Posts

Showing posts from January, 2011

Java ArrayList merge without duplicates based on a value -

i have class called sample , class has property arraylist<area> , , area contains arraylist<elements> public class sample { private arraylist<area> sampleareas; public arraylist<element> getmergeddata() { ... } ... } public class area { private arraylist<element> areaelements ... } public class element { private string name; private float value; ... } i need getmergeddata() sample class merges every arraylist<elements> each of it's area, keeping element bigger value. ex: area 1: ("element k" => 1.0, "element c" => 0.5, "element as" => 15.0) area 2: ("element k" => 10.1, "element c" => 5.5, "element as" => 2.9, "element o" => 1.5) area 3: ("element c" => 2.8, "element as" => 0.5, "element o" => 5.8) area 4: ("element k" => 3.25, "e

c# - ASP.NET application crashes when CPU configuration is changed from AnyCPU to x86 -

i have asp.net application 2 modules: a server module, runs windows service. a web module installed on iis. the above works (have been working) last several years. problem has happened when have move application new windows 2008 server. what have done is: changed target anycpu x86 on server module, tested on bp machine , worked. moved server , web module win 2008 server. installed service , ran it, far good. from web site, ran query failed null pointer exception , this: at system.runtime.remoting.proxies.realproxy.handlereturnmessage(imessage reqmsg, imessage retmsg) this head started spinning. code talk service similar this: <application name="shr"> <client url="tcp://localhost:8039"> <wellknown type="package.dal.mydao, mypackage" url="tcp://localhost:8039/shr/mydao.rem"/> </client> <channels> <channel ref="tcp client">

sql server - Data Warehouse design - Handling NULL and empty values in the OLTP -

i creating dw oltp creaking somewhat. a problem i'm faced there isn't data integrity in oltp database. example suburb field. this suburb field free text field on oltp ui means we've got values in field, plus we've got empty strings , we've got null values. how handle this? scenarios i've come are: import data (not ideal) in etl process, treat empty string same null , replace word 'unknown' in dw import both empty strings , null's empty strings in dw just fyi, i'm using microsoft bi stack (sql server, ssis, ssas, ssrs) the short answer is, depends on null , empty strings mean in source system. this general question (handling null ) has been discussed lot, e.g. here , here , here etc. think important point remember data warehouse database; may have specific type of schema , designed 1 purpose, it's still database , general advice on null still applies. (as side note, prefer talk "reporting database" r

java - cloning or unmodifiableCollection -

during university classes on java learned concept of privacy leak, public getter returns reference private mutable object. the example gave follows: (forgive me if syntax isn't quite right, i'm working memory) private hashset<*> priv = new hashset<*> public collection<*> getpriv () { return this.priv; } now problem object's client has opportunity corrupt private hashset, intentionally or otherwise. on course, suggested solution use following: public collection<*> getpriv () { return collections.unmodifiablecollection (this.priv); } this seems solution me, because not internal state of object protected external modification, attempt modify returned unmodifiablecollection trigger exception. problem though, works collections. there doesn't seem equivalents other mutable java classes. most books on java i've read since suggest following: public collection<*> getpriv () { return this.priv.clone (); } t

Cmake very simple set failure -

i trying start using cmake simplest helloworld example, in ubuntu 12.04, cmake 2.8.7. first tried 1 from: http://www.elpauer.org/stuff/learning_cmake.pdf project( helloworld ) set( srcfiles helloworld.cpp ) add_executable( helloworld ${srcfiles} ) i have source file called "helloworld.cpp" side of cmakelists.txt. created directory called "configure", went inside , called "cmake ..". following: -- c compiler identification gnu -- cxx compiler identification gnu -- check working c compiler: /usr/bin/gcc -- check working c compiler: /usr/bin/gcc -- works -- detecting c compiler abi info -- detecting c compiler abi info - done -- check working cxx compiler: /usr/bin/c++ -- check working cxx compiler: /usr/bin/c++ -- works -- detecting cxx compiler abi info -- detecting cxx compiler abi info - done cmake error @ cmakelists.txt:3 (add_executable): add_executable called incorrect number of arguments -- configuring incomplete, errors occurred!

java - how to slow down one method without affecting the rest of the program? -

i'm making game in java , want create character moves randomly. 1 made spastic. want add delay between random numbers generated. i'm beginner don't judge code lol public class monster extends entity{ private world world; image monster; public monster(int x, int y, world world) { super(x, y, world); w = 32; h = 32; this.world = world; } public void render(gamecontainer gc, graphics g) throws slickexception{ super.render(gc, g); monster = new image("gfx/world/monster.png"); g.drawimage(monster, x, y); } public void update(gamecontainer gc, int delta) throws slickexception{ super.update(gc, delta); random move = new random(); int number; for(int counter=1; counter<=1;counter++){ number = move.nextint(4); system.out.println(number); if(number == 0){ setdy(-1); }else if(number == 1){ setdx(-1); }else if(number == 2){

curl - How can I echo a scraped div in PHP? -

how echo , scrape div class? tried doesn't work. using curl establish connection. how echo it? want how on actual page. $document = new domdocument(); $document->loadhtml($html); $selector = new domxpath($document); $anchors = $selector->query("/html/body//div[@class='resultitem']"); //a url want retrieve foreach($anchors $a) { echo $a; } neighbor, made snippet below, uses logic, , tweaks display specified class webpage in get_contents function. maybe can plug in values , try it? (note: put error checking in there see few bugs. can helpful use tweak. ) <?php error_reporting(e_all); ini_set('display_errors', '1'); $url = "http://www.tizag.com/csst/cssid.php"; $class_to_scrape="display"; $html = file_get_contents($url); $document = new domdocument(); $document->loadhtml($html); $selector = new domxpath($document); $anchors = $selector->query("/html/body//div[@

Trying to set color to my text in android -

i trying set color text in android. every time launch application shuts down. here have in color.xml file: <?xml version="1.0" encoding="utf-8"?> <resources xmlns:android="http://schemas.android.com/apk/res/android"> <color name="background_color">#006400</color> <color name="app_text_color">#ffe4c4</color> here have in mainactivity class: int textcolor = getresources().getcolor(r.color.app_text_color); textview hellotext = (textview)findviewbyid(r.string.hello_world); hellotext.settextcolor(textcolor); here layout file: <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@di

node.js - How to get a HTML page in nodejs? -

test.html <html> <head> <title>test page</title> </head> <body> body</body> </html> how modify this: var http = require('http'); http.createserver(function (req, res) { res.writehead(200, {'content-type': 'text/plain'}); res.end('hello world\n'); }).listen(1337, '127.0.0.1'); console.log('server running @ http://127.0.0.1:1337/'); to return test.html above? here's example of simple streaming static server var basepath = '/files' http.createserver(function (req, res) { if (req.method !== 'get') { res.writehead(400); res.end(); return; } var s = fs.createreadstream(path.join(basepath, req.path)); s.on('error', function () { res.writehead(404); res.end(); }); s.once('fd', function () { res.writehead(200); }); s.pipe(res); }); in practice should use express.static: http:

How to disply timdstamp column with specific format in Spring Data JPA -

i using spring data jpa , have table below: public class apk { @temporal(temporaltype.timestamp) @column private java.util.date creationtime; } my dbms mysql5.x , above column defined datetime type in it. call findal() method in repository class extends paginandsortingrepository. public interface apksrepository extends paginandsortingrepository<apk, long>{ } public class apksserviceimpl implements apksservice { public pagingres<apk> findall(pageinfo pageinfo){ paginres<apk> result = new pagingres<apk>(); page page = apksrepos.findall(pageinfo.topagerequest()); result.frompage(page); return result; } } public class pageinfo { private int page; private int rp; private string sortname; private string sortorder; private string query; private string qtype; //getters , setters public pagerequest topagerequest() { sort.direction direction = sort.direction.asc; if (sortorder!=

php - How to catch filetypes in malformed URLs -

just wondering how can extract or match specific file type, since there lot of malformed urls , directories. so need regex match real ones. http://domain.com/1/image.jpg <-match .jpg http://domain.com/1/image_1.jpg/.gif <-match first .jpg http://domain.com/1/image_1.jpg/image.png <-match first .jpg http://domain.com/1/image_1.jpg <-match .jpg http://domain.com/1/image.jpg.jpeg <-match first .jpg http://domain.com/1/.jpg <-not match http://domain.com/.jpg.jpg <- not match /1/.jpg <-not match /.jpg.png <-match first jpg /image.jpg.png <-match first jpg i'm trying piece of code: preg_match_all('([a-za-z0-9.-_](jpg))i', $url, $matches); any ideas? preg_match('(^(http://domain.com/\w.*?\.jpg))i', $url, $matches); this match start of string first .jpg . filename part must start letter, number, or _ .

g wan - Index as servlet, rest as static content -

i picked g-wan while , i'm trying figure out how make index use specific servlet while having static content available. i moved index.html index_old.html wouldn't have conflicts. i placed following handler. xbuf_t *read_xbuf = (xbuf_t*)get_env(argv, read_xbuf); xbuf_replfrto(read_xbuf, read_xbuf->ptr, read_xbuf->ptr + 16, "/", "/?hello"); after restarting gwan, saw hello, ansi c! desired. however, noticed other contents no longer loaded, 404 page different! so, had thought, seemed doing string substitution, rather precise matching. xbuf_t *read_xbuf = (xbuf_t*)get_env(argv, read_xbuf); xbuf_replfrto(read_xbuf, read_xbuf->ptr, read_xbuf->ptr + 16, "/", "/?"); now, when hitting / , saw 404, , /hello , saw servlet again. so, not seem solution looking for. again, want / hit specific servlet of designation, , other requests not effected 1 rule. thanks, it appears similar solution presented in

C++ multi-threaded data management -

i looking conceptual advice regarding managing large quantity of data in computer vision project of mine. having trouble a) conceptualizing , b) implementing concept of coordinating large stream of data coming both input program cameras , generated code. so data have handle on separable 5 separate 'streams' i'll call them: raw frames (direct input camera) target images (sub-frames, taken previous image stream) timestamps (for raw frames) vehicle attitude data (gps, body angles, etc. wireless serial port connection vehicle) attitude data timestamps the general flow, if sequentially, be: frame = grabinputframe(); targetsvector = searchfortargets(frame); vehicledata = getdatafromvehicle(); each target in targetvector ( targetdata = processdata(target, vehicledata); updatetargetlog(targetdata); } so here's deal: i'm trying means of threads, since algorithms processor intensive , not sequentially related (i mean don't need color data gps coords

Python: unpacking into array elements -

why behavior of unpacking change when try make destination array element? >>> def foobar(): return (1,2) >>> a,b = foobar() >>> (a,b) (1, 2) >>> = b = [0, 0] # make , b lists >>> a[0], b[0] = foobar() >>> (a, b) ([2, 0], [2, 0]) in first case, behavior expect. in second case, both assignments use last value in tuple returned (i.e. '2'). why? when a = b = [0, 0] , you're making both a , b point same list. because mutable, if change either, change both. use instead: a, b = [0, 0], [0, 0]

oop - java - design patterns - inheritance with static variables -

i have person class extends record class , i'd define database table name, columns, , column types static variables in person class. i'd following can't because can't modify objects when not in method(i think? java noob here). class person extends record{ protected static final string dbtable = "people"; protected static linkedhashmap<string, string> dbcolumns = new linkedhashmap<string, string>(); dbcolumns.put("id","integer"); dbcolumns.put("name", "text"); } i following looks messy , not readable if table has several columns class person extends record{ protected static final string dbtable = "people"; protected static final string[] dbcolumns= {"id","name"}; protected static final string[] dbcolumntypes= {"integer","text"}; } i don't want define these in constructor because want static method in parent class(rec

ruby - How to pull data from remote server database in rails? -

i using tiny_tds connecting remote database, used mysql , sql server. other gem available can access vendor database? you're not understanding how database access works. we use driver talk database. database vendors have different protocols used connect, driver handles that. above layer we'd have api talks driver. that'd dbi, knows how talk different drivers. still have write using query language of database dbi gives advantages. it's pain convert 1 database another, because queries change , inconsistencies between "standards" show up. above layer we'd have activerecord or sequel, orms, , dbm agnostic. allow use consistent language define our connections databases, create queries , handle interactions. if want talk different database manager, install driver, change connection string, , rest should work. this huge time savings , "very thing". can use sqlite proof-of-concepts, , postgresql, mysql, or oracle production system, w

Use case for using array as ruby hash key -

ruby allows using array hash key shown below: hash1 = {1 => "one", [2] => 'two', [3,4] => ['three', 'four']} i not clear on common use case be. if people can share real-world scenarios useful, appreciate it. a great example why you'd want store arrays hash keys memoizing. this example of how array hash key useful: def initialize(*args) @memoizer ||= {} return @memoizer[args] if @memoizer[args] # args in initializer, # create new instance future. @memoizer[args] = some_calculation(args) end

actionscript 3 - FDT - Where is new Flash Project? -

up until point have been doing of coding in sublime text 2, , compiling flash pro cs6. have gotten pretty actionscript 3. have been uing mvc design pattern , used external libraries admobs , electroserver. real reason why got fdt , wanted because wanted play source file downloaded in document class mxml. in every tutorial though see them say, "oh click new flash project". problem though there no choice "flash project" there actionscript project , fdt project or fla. in flash ide use 1 .fla "shell" publish from, , have .fla assets embedded in as3 swf. i'm sure that's not way set files in fdt, dont know right way it, or right way start. maybe not finding right page, seems documentation on site pretty weak. there tutorials somewhere me start compiling projects? thanks a tutorial people transitioning flash ide fdt helpful too. i wrong, ide, can't compile fla. instead of this, provides approach build projects. have start "n

persistence - Query entity class with multiple joins using criteria api -

how select rows in table using docid column value , retrieve values in appointment table values in patient table. query should in criteria api. entity class follows 2 joins. @entity @table(name="appointment") public class appintment implements serializable { private static final long serialversionuid = 1l; @id @column(unique=true, nullable=false, length=20) private string appid; @temporal(temporaltype.date) @column(name="app_date", nullable=false) private date appdate; //bi-directional many-to-one association doctors @manytoone @joincolumn(name="docid", nullable=false) private doctor doctor; //bi-directional many-to-one association patients @manytoone @joincolumn(name="userid", nullable=false) private patient patient; }

How to get same result in C or C++ same as toLowerCase in Java or string.lower() in Python? -

i need c or c++ function(or library) works string.tolowercase() in java. i know can use tolower() english, need function (or library) can cover global language. (actually, needs cover 9 languages listed below.) language list dutch english french german italian portuguese russian spanish ukrainian add, these characters in first line below input , second line expected result line 1: aÁÀÂÄĂĀÃÅÆbcĆČÇdeÉÈÊËĚĘfghℏiÍÌÎÏjklŁmnŃŇÑoÓÒÔÖÕØŒpqrŘsŚŠŞtŢuÚÙÛÜŪvwxyÝzŹŽΑΔΕΘΛΜΝΠΡΣΣΦΩАБВГҐДЕЁЄЖЗИЙІЇКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ line 2: aáàâäăāãåæbcćčçdeéèêëěęfghℏiíìîïjklłmnńňñoóòôöõøœpqrřsśšştţuúùûüūvwxyýzźžαδεθλμνπρσςφωабвгґдеёєжзийіїклмнопрстуфхцчшщъыьэюя i verified results java tolowercase() , python string.lower() , both correct. is there way translate lowercase letter in c or c++? and important thing letters read file encoded 'utf-8'! please me. english not good, please use simple english as can. i think find need in boost libraries - see http://www.boost.o

php - PNG file saved using CURL is corrupt -

i'm using following code so thread , file outputted corrupt png file. can't view in image editor. image i'm trying grab can found @ this direct link . <?php function getimg($url) { $headers[] = 'accept: image/gif, image/png, image/x-bitmap, image/jpeg, image/pjpeg'; $headers[] = 'connection: keep-alive'; $headers[] = 'content-type: application/x-www-form-urlencoded;charset=utf-8'; $user_agent = 'mozilla/5.0 (windows nt 6.1; wow64) applewebkit/537.31 (khtml, gecko) chrome/26.0.1410.64 safari/537.31'; $process = curl_init($url); curl_setopt($process, curlopt_httpheader, $headers); curl_setopt($process, curlopt_header, 0); curl_setopt($process, curlopt_useragent, $user_agent); curl_setopt($process, curlopt_timeout, 30); curl_setopt($process, curlopt_returntransfer, 1);

android - Data in arrays isn't persisted -

in android activitity, using 2 different arrays. first, declaring them, , in oncreate() method, instantiating them. however, when populate them , change orientation, getting instantiated again in , data lost. public class mainactivity extends activity { private jsonarray first; private jsonarray second; protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); interestedsections = new jsonarray(); productsbought = new jsonarray(); } //... } i tried add if (savedinstancestate != null) before initializing arrays, initialize them first time only, when change orientation, being null . can in order persist data in arrays throughout whole application lifecycle please? check out answer oncreate called when screen rotated: activity restart on rotation android edit: if want quick , dirty way make work, have static initialized boolean , set true oncreate.

java - How to parse an xml and get the content of specific element -

my xml string got message queue ==> <?xml version='1.0' encoding='utf-8'?><soapenv:envelope xmlns:soapenv="http://www.w3.org/2003 /05/soap-envelope"><soapenv:body><ns1:postpublicationresponse xmlns:ns1="http://www.openoandm.org/xml/isbm/"><ns1:messag eid>urn:uuid:7d361fb0-bc54-48bd-bbd1-6e34960ef3f8</ns1:messageid><ns1:messagecontent><messagecontent xmlns="http://www.o penoandm.org/xml/isbm/"><hi>k786</hi></messagecontent></ns1:messagecontent></ns1:postpublicationresponse></soapenv:body> </soapenv:envelope> now have writtent function trying content of element messagecontent i.e <hi>k786</hi> getting null value always. function parse above xml is: private string parsequeuemessage(string message) throws parserconfigurationexception, saxexception, ioexception, xpathexpressionexception { string resultmsg = &quo

rspec integration / request specs vs controller specs with an emphasis on JSON api -

i have adopted app has test coverage of tests of mixed quality. majority of app working against json api. going write request specs authenticating , sending post's authentication data wasn't trivial. testing json api, controller specs more appropriate? for example, match 'api/login-mobile' => 'api#login_mobile', :as => :login_mobile, :defaults => {:format => 'json' } this seem trivial @ require integration spec capybara. in addition, capybara wouldn't send session data natively , require page.driver.post ..... i integration tests testing ui interactions seems bad model testing json api. missing something? or there tutorial doing integration / requeset tests? looking @ discourse right , pretty tests controllers .... if integration / request specs bees knees, why make decision? thx in advance i integration-style tests, this post . interacting api endpoint via json higher-level controller, use feature , scenario

java - Outputting a group ring values using two for loops -

i'm learning java , seem weak in knowledge of loops. i supposed call printsquare(1, 5); . output want is: 12345 23451 34512 45123 51234 i tried out: public void printsquare(int min,int max){ for(int i=min;i<=max;i++){ for(int j=i;j<=max;j++){ system.out.print(j); } system.out.println(); } } which gives me: 12345 2345 345 45 5 i tried inserting 2 more loops not seem work. i appreciate if don't give me full answer, because not way learn. prefer clues on how accomplish this. you should add 1 more loop nested i loop, outside j loop. it should min i-1 .

Audio streaming in ios using AVPlayer -

i trying develop small app should stream audio particular link. using avplayer dont know why not working. tried google nothing seems relevant there. kindly help.. thank you - (void)viewdidload { [super viewdidload]; nsurl *url = [nsurl urlwithstring:@"http://108.166.161.206:8826/stream.mp3"]; self->playeritem = [avplayeritem playeritemwithurl:url]; self->player = [avplayer playerwithplayeritem:playeritem]; self->player = [avplayer playerwithurl:url]; [player play]; } don`t know why first init player playeritem , after init nsurl. anyways, here way go: -(void) viewdidload{ player = [[avplayer alloc] initwithurl: [nsurl urlwithstring:@"http://xxx/yourfile.mp3"]]; [player addobserver:self forkeypath@"status" options:0 context:nil]; } - (void) observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change

How to use FRED Rest service with c# -

i try use fred hammock use provided rest service. unfortunately have no idea how use it. did far: string url = "http://wit.istc.cnr.it/stlab-tools/fred/api"; hammock.restclient client = new hammock.restclient(); client.addheader("accept", "image/png -f text=miles davis american jazz musician"); //client.addheader("accept", "text=miles davis american jazz musician"); client.authority = url; hammock.restrequest req = new hammock.restrequest(); req.path = url; hammock.restresponse response = client.request(req); string _result = client.request(req).content; you're making post request never specify that. from juniper.net , extract make post request: public void makeqrest() { try { string auth = "http://wit.istc.cnr.it/stlab-tools/fred/api"; string body = "text=miles davis american jazz musician"; iwebcredentials credentials = new hammock.authentication.basic.basica

c# - Does multiple query block on single connection(SqlConnection)? -

i have sample data access method design below calls recursively: public static void deleterecord(sqlconnection connection, string childids, string parentsheetname) { using (var adapter = new sqldataadapter("...", connection)) { //fill datatable string newids = "..."; string newparentname = "..."; const string query = "delete table " + "where ids in (@ids) , parent = @parent"; //here's recursion takes place deleterecord(connection, newids, newparentname); using (var command = new sqlcommand(query, connection)) { var parameters = new[] { new sqlparameter(...), new sqlparameter(...) } command.parameters.addrange(parameters); command.executenonquery(); } } my questions are: (as practice) okay pass connection parameter? is okay put deleterecord me

php - Permutating Result Set of My Query, Something is wrong -

i have 4 tables: persons jobs titles departments persons table id | title_id | person | phone | email | dept_id | job_id ---+----------+--------+-------+-------+---------+------- 1 | 1 | some1 | 12345 | s@a.c | 2 | 3 ... other tables' structures same following id | ******** ---+--------- assume there 5 records in table titles, 5 records in table departments , 5 job records in table jobs. and let's suitable records defined $search string = 6 in table persons; when execute query below, result set has 5 x 5 x 5 x 6 = 750 records , of them repetitive. results doing permutation. $query = sprintf( "select * persons p, titles t, departments d, jobs j p.person %s or p.phone %s or p.email %s , p.id=t.id , p.id=j.id ,

c# - Thread that talk with UI? -

i have code: private void buttonstart_click(object sender, eventargs e) { task.factory.startnew(() => generalistacartelle()) .continuewith(t => generalistacartellecompletata() , cancellationtoken.none , taskcontinuationoptions.none , taskscheduler.fromcurrentsynchronizationcontext()); } private void generalistacartelle() { try { ... operation .... } catch (exception err) { txterrors.appendtext(err.message); } } generalistacartellecompletata() { ... process finished... } and txterrors in "main" thread (the ui). when catch error, asynch thread cannot write ui control, , invalid cross-thread exception . can dialogate ui inside thread? if targetting winform application then: try { ... operation .... } catch (exception err) { if (txterrors.invokerequired) { txterrors.begininvoke(new methodinvoker( delegate { tx

WebConnector with Auto-Run checked, inserting Duplicate Invoice to the QuickBooks with Rails 3.2.9 -

i using web connector add invoice quickbooks v13. have added provided logic add invoice if invoice not added quickbooks. when have set autorun option of web connector automatically call api. if have 1 invoice add, first run working fine. second call webconnector, search result invoice in quickbooks sends record statuscode="0" means exist still once again added same invoice quickbooks. not able restrict adding of same invoice multiple time following rails code insert invoice quickbooks. using qbwc gem in rails application send qbxml request , parse response def api if request.get? render :nothing => true return end if params["envelope"]["body"].keys.first =="authenticate" add_invoice #add invoice method called search/add invoice end req = request rails.logger.info "=== #{ params["envelope"]["body"].keys.first} ===" res = qbwc::soapwrapper.route_request(req) rails.lo

java.lang.NumberFormatException: For input string: "9813023219" -

i'm using serial event pass rfid tags read arduino processing. in serial event parsing , converting variable integer. working part, 1 rfid card keeps throwing error. void serialevent(serial thisport) { string instring = thisport.readstring(); if(instring != null) { serial connect1 = (serial) connections.get(0); if(thisport == connect1 ) { chair chair = (chair) chairs.get(0); if(instring.contains("uid value:")) { int p2 = instring.indexof(":"); string pstring = instring.substring(p2+1); string pstring2 = pstring.substring (0,10); //println(pstring2); pstring2.trim(); println("string length: " + pstring2.length()); chair.setrfid(pstring2); println(pstring2); } } } } void setrfid(string r) { try{ this.rfid = integer.parseint(r); } catch (exception e) { e.printstacktrace();

c# - Identify rgb and cmyk color from pdf -

i have pdf consists of different color text , background color. how identify colors used in pdf cmyk or rgb format? stringbuilder sb_sourcepdf = new stringbuilder(); pdfreader reader_firstpdf = new pdfreader(pdf_of_firstfile); document document = new document(); pdfparser parser = new pdfparser(new fileinputstream(pdf_of_firstfile)); parser.parse(); pddocument docum = parser.getpddocument(); pdfstreamengine engine = new pdfstreamengine(); pdpage page = (pdpage)docum.getdocumentcatalog().getallpages().get(0); engine.processstream(page, page.findresources(), page.getcontents().getstream()); pdgraphicsstate graphicstate = engine.getgraphicsstate(); string colorname = graphicstate.getstrokingcolor().getcolorspace().getname(); graphicstate.gettextstate().getfont(); int r = graphicstate.getnonstrokingcolor().getjavacolor().getred(); int g = graphicstate.getnonstrokingcolor().getjavacolor().getgreen(); int b = graphicstate.getnonstrokingcolor().getjavacolor().getblue(); int rgb = g

Reverse LISP list in place -

i write function reverses elements of list, should happen in place (that is, don't create new reversed list). something like: >> (setq l ' (a b c d)) ((a b c d) >> (rev l) (d c b a) >> l (d c b a) what flags should follow achieve this? it's not difficult implement (ignoring fault cases). keys use (setf cdr) reuse given cons cell , not lose reference prior cdr. (defun nreverse2 (list) (recurse reving ((list list) (rslt '())) (if (not (consp list)) rslt (let ((rest (cdr list))) (setf (cdr list) rslt) (reving rest list))))) (defmacro recurse (name args &rest body) `(labels ((,name ,(mapcar #'car args) ,@body)) (,name ,@(mapcar #'cadr args)))) [edit] mentioned in comment, in-place (and w/o regard consing): (defun reverse-in-place (l) (let ((result l)) (recurse reving ((l l) (r (reverse l)) (cond ((not (consp l)) result) (else (setf (car l) (ca

ios - comparing image from ui to sqlite database image -

i want make application in ios has image in imageview , database thousand of images used comparing image in image view for. eg: suppose have celebrity's image in imageview.. have compare image sqlite database , show appropriate image/list of image matching it. this raw idea, have still not started working on can not show code is there open source library in ios can use achieving this??? or can guide me links it. thanks no open source library found, created own logic using opencv , storing images in database. used pagination concept solve large amount of data processed thank you

linux - How to print current time (with milliseconds) using C++ / C++11 -

currently use code string now() { time_t t = time(0); char buffer[9] = {0}; strftime(buffer, 9, "%h:%m:%s", localtime(&t)); return string(buffer); } to format time. need add milliseconds, output has format: 16:56:12.321 you can use boost's posix time . you can use boost::posix_time::microsec_clock::local_time() current time microseconds-resolution clock: boost::posix_time::ptime = boost::posix_time::microsec_clock::local_time(); then can compute time offset in current day (since duration output in form <hours>:<minutes>:<seconds>.<milliseconds> , i'm assuming calculated current day offset; if not, feel free use starting point duration/time interval): boost::posix_time::time_duration td = now.time_of_day(); then can use .hours() , .minutes() , .seconds() accessors corresponding values. unfortunately, there doesn't seem .milliseconds() accessor, there .total_milliseconds() one; can little

Call a shell script using a different ruby within a rails app -

i have rails application runs on ruby 1.9 , shell script (podcast producer) depends on ruby 1.8. i need call shell script within application. ruby version manager use rvm , app runs within passenger. obvious reasons takes wrong ruby shell script (means, loads rvm , bundler env , tries start within same environment, application runs in). first line of shell script: #!/usr/bin/env ruby -i/usr/lib/podcastproducer call in app `/usr/bin/podcast` how solve this? you can use rvm-shell (included in rvm installation) override current ruby/rvm version in environment , explicitly use system's default ruby version (assuming have not installed alternate ruby version system default, can check running /usr/bin/ruby -v ). you should able use rvm-shell within ruby script follows: `rvm-shell system -c '/usr/bin/podcast'` the system argument instructs rvm use system's default ruby version.

vb.net - Strange behaviour of the If() statement -

today stumbled upon strange behaviour of vb.net if() statement. maybe can explain why working does, or maybe can confirm bug. so, have sql database table "testtable" int column "nullablecolumn" can contain null. i'd read out content of column. so declare variable of type nullable(of integer) matter, open sqlclient.sqldatareader "select nullablecolumn testtable" , use following code content of column: dim content nullable(of integer) ... using reader sqlclient.sqldatareader = ... content = if(reader.isdbnull(reader.getordinal("nullablecolumn")), nothing, reader.getint32(reader.getordinal("nullablecolumn"))) end using but after variable content has value 0, not nothing have expected. when debugging looks alright, so reader.getordinal("nullablecolumn") delivers correct ordinal position of column (which 0) reader.isdbnull(0) , reader.isdbnull(reader.getordinal("nullablecolumn")) deliver t

.net - Filter Rally defect on Last Updated Date -

i using below code retrieve defect data rally. currently, defect being filtered formatted id. is there way through can filter result last updated date? eg: string querystring = @"(lastupdatedate < 4\5\2013)"; static void main(string[] args) { rallyserviceservice service = new rallyserviceservice(); string rallyuser = "username"; string rallypassword = "password"; service.url = "https://rally1.rallydev.com/slm/webservice/1.41/rallyservice"; system.net.networkcredential credential = new system.net.networkcredential(rallyuser, rallypassword); uri uri = new uri(service.url); system.net.icredentials credentials = credential.getcredential(uri, "basic"); service.credentials = credentials; service.preauthenticate = true; service.cookiecontainer = new system.net.cookiecontainer(); // find defect //string querystring = @"(lastupda

ADO.NET Entity Framework on Vs2012 + WCF = Error -

first of all, reading question. i developing solution using vs 2012 using ado.net entity framework (5 think, latest version). working fine until introduce wcf service business layer (this assignment school, cannot scrap wcf business layer). the issue when request data database. when have method returns string database, works fine (since primitive). when returns entity object (such account), goes hell. exception: (yeah, vague). an error occurred while receiving http response http://localhost:8733/services/accountsmanager. due service endpoint binding not using http protocol. due http request context being aborted server (possibly due service shutting down). see server logs more details. what tried: tried modifying entites.tt file add [datacontract] [datamember] attribute. because in older versions of ef, seemed doing on own. not know if neccessary since allows me compile , not complain not serializable. this how looks @ first: namespace commonlayer { using system; usin

c++ - non datatype template parameter, more specialization generated? -

my code is: #include <iostream> using namespace std; template <typename t, int x> class test { private: t container[x]; public: void printsize(); }; template <typename t, int x> void test<t,x>::printsize() { cout <<"container size = "<<x <<endl; } int main() { cout << "hello world!" << endl; test<int, 20> t; test<int, 30> t1; t.printsize(); t1.printsize(); return 0; } question: how many specialization generated?. if understand correctly , generates 2 specializations 1 <int, 20> , <int, 30> . kindly correct if understanding wrong? is there way see/check number of specializations generated reverse engineering? 1) yes, 2 instantiations generated compiler , linker might merge functions identical generated code (using whole program optimization e.g.), cute way reduce code bloat. 2) see question explained how gcc can

What data structure is used to implement facebook like's post and comments? -

this question has answer here: facebook “like” data structure 4 answers this 1 of java interview questions... i asked data structure use implement facebook post, , comments? i love hear view of members.... this more task database (notice how complex below is, compared this (because of below taken care of proper database proper indexing)), but... note i'm assuming posts can liked , comments post. posts: posts can a map of post id post object . if want see list of posts user made, you'll need a map of user id set of post ids . likes: you want number of likes per post , see whether user liked post, a map of post id set of user ids of it. if want see things user likes, you'll need data structure - a map of user id set of post ids liked. comments: comments can a map of comment id comment object . connected post id stored in co

xamarin.ios - MonoTouch App on Latest Alpha 4.1.0 (build 45) -

yesterday have updated latest version of xamarin.ios, problem i'm experiencing existing apps, not working anymore datasources, example have simple tableview custom datasource, run fine no exception, when executed getcell or rowsinsection example not called. have idea why? there maybe change apply on code make working? i have found it, on older version uitableviewdatasource worked fine without it, adding override fixed it. public override int numberofsections (uitableview tableview) { return 1; }

asp.net - GridView update causes "incorrect syntax near 'nvarchar'" error -

i have major problem when trying use update in gridview . code below, once click 'edit', option change 'kpi' name , 'current target'. but, once click 'update', error message: incorrect sysntax near 'nvarchar' here markup: <p> <br /> <asp:dropdownlist id="groupselection" runat="server" datasourceid="group" datatextfield="fcstgroup" datavaluefield="fcstgroup"> </asp:dropdownlist> </p> <p> <asp:gridview id="gridview2" runat="server" datasourceid="sqldatasource1"> <columns> <asp:commandfield showeditbutton="true" /> </columns> </asp:gridview> </p> <p> <asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:wfmconnectionstring3 %>"

ocr - ICR for machine printed text? -

i know icr used handwritten(hand printed) data recognition can leverage icr extract distorted(bad quality) machine printed text chance ? if not best way solve following problem i have unstructured document may run 2 or more pages, in document there few date field handwritten.now want convert text file. have tried fullpage ocr(omnipage , abbyy etc) tools have icr modules convert text file. @ full page ocr when encounter handwritten date puts junk character instead of using icr module there. don't want go form processing tools parascript , a2ia position based , work structured document. or can use icr convert machine printed text , handwritten(anyway work hand return date in case) here aim text file output unstructured document few hand written text(like dates,numbers ) i have tried fullpage ocr(omnipage , abbyy etc) tools have icr modules that incorrect, explains poor result. if tried retail versions of omnipage , abbyy finereader, these software packag

node.js - Strange trailing character received from res.end -

here's backend code: res.statuscode = 400 res.setheader 'content-type', 'text/plain' res.end 'invalid api endpoint.' when curl terminal, get: invalid api endpoint.% the "%" sign shows inverted colors. why "%" sign there? this marks partial line, since response send not have trailing newline. man zshoptions prompt_sp <d> attempt preserve partial line (i.e. line did not end newline) otherwise covered command prompt due prompt_cr option. works out‐ putting cursor-control characters, including series of spaces, should make terminal wrap next line when partial line present (note success‐ ful if terminal has automatic margins, typical). when partial line preserved, default see inverse+bold character @ end of partial line: "%" normal user or "#" root. if set, shell pa