Posts

Showing posts from April, 2014

javascript - Google Line Chart Adding Array of Objects -

Image
i have array of objects i've created parsing json string: var measurementdata = @html.raw(jsonconvert.serializeobject(this.model.item1)); var stringifieddata = json.stringify(measurementdata); var parseddata = json.parse(stringifieddata); this gives me number of objects, depending on model, looking this: now question is, how add these google line chart without having hardcode datatable? this i've got now, works somewhat: var data = new google.visualization.datatable(); data.addcolumn('string', 'timestamp'); data.addcolumn('number', selectedmeasurements); data.addrows([ [parseddata[index[0]].timestamp, parseddata[index[0]][selectedmeasurements]], [parseddata[index[1]].timestamp, parseddata[index[1]][selectedmeasurements]] ]); chart.draw(data, options, { isstacked: true, vaxis: { viewwindowmode: 'explicit',

What is the best way to copy memory for X indexes to many locations within a single array in C? -

what best way copy memory x indexes many locations within single array in c? the problem trying solved emulated memory cpu emulator. original hardware has type of memory mirroring, , attempting replicate via code. say have array: int memory[100] = {0}; and have 10 indexes mirrored @ different locations. example if memory[0] changed, index 0, 10, 20, 30... should change value or if memory[3] changed, index 3, 13, 23, 33 should mirrored. likewise if mirrored location changed other mirror locations should reflect this, such if index 23 changed, 3, 13, 23, 33... etc should reflect this. another requirement way specify start , ends of mirrored locations are. example index 10-19 mirrored @ index 30-39, again @ 70-79 leaving unmodified space in between segments of mirrored indexes. would using memcpy fastest/most efficient way of achieving if this, or sort of iterating loop , pointer math better efficiency? how pointer math done calculate start address copy destination? ar

c++ - GetPixel is WAY too slow -

i have bunch of squares , each has specific identity/symbol need identify. far have like: #include <iostream> #include <windows.h> using namespace std; int main() { hdc dc = getdc(0); colorref color; int sum, x, y; while (true) { sum = 0; sleep(100); (x = 512; x < 521; x++) { (y = 550; y < 565; y++) { color = getpixel(dc, x, y); sum = getrvalue(color) + getbvalue(color) + getgvalue(color); } } cout << "sum: " << sum << endl; } return 0; } obviously scans 1 block far. problem somehow though it's on 100 pixels, takes insanely long time. can't imagine going on. takes on second, maybe 2 seconds, each repetition. can do? there has faster way this. if can't query individual pixels, there way region of screen? zone not inside program's window.

php - How to test file upload with laravel and phpunit? -

i'm trying run functional test on laravel controller. test image processing, want fake image uploading. how do this? found few examples online none seem work me. here's have: public function testresizemethod() { $this->preparecleandb(); $this->_createaccessablecompany(); $local_file = __dir__ . '/test-files/large-avatar.jpg'; $uploadedfile = new symfony\component\httpfoundation\file\uploadedfile( $local_file, 'large-avatar.jpg', 'image/jpeg', null, null, true ); $values = array( 'company_id' => $this->company->id ); $response = $this->action( 'post', 'filestoragecontroller@store', $values, ['file' => $uploadedfile] ); $readable_response = $this->getreadableresponseobject($response); } but controller doesn't passed check: elseif (!input::hasfile('fi

Can't get javafx and webview to handle google javascript -

i having issues getting javafx listen on google results. i'm sure it's due javascript live results can't find way around it. document doc = engine.getdocument(); nodelist elements = doc.getelementsbytagname("a"); for(int i=0; < elements.getlength();i++){ ((eventtarget) elements.item(i)).addeventlistener("click", listener, false); } in chrome browser i'm able right click result , inspect. dom shows fine. how have javafx replicate chrome browser can do? i able so: class1 javafx webview application class2 bridge between javascript , java in class1 created method so. can used upon clicking button. private void setjslisteners(){ class2 bridge = new class2(); jsobject hrefwindow = (jsobject) engine.executescript("window"); hrefwindow.setmember("java", bridge); engine.executescript("var links = document.getelementsbytagname(\"a\");" + "for (var = 0; < l

haskell - Partial application of functions and currying, how to make a better code instead of a lot of maps? -

i beginner @ haskell , trying grasp it. i having following problem: i have function gets 5 parameters, lets f x y w z = x - y - w - z - and apply while changing variable x 1 10 whereas y , w , z , a same. implementation achieved following think there must better way. let's use: x 1 10 y = 1 w = 2 z = 3 = 4 accordingly managed apply function following: map ($ 4) $ map ($ 3) $ map ($ 2) $ map ($ 1) (map f [1..10]) i think there must better way apply lot of missing parameters partially applied functions without having use many maps. all suggestions far good. here's another, might seem bit weird @ first, turns out quite handy in lots of other situations. some type-forming operators, [] , operator maps type of elements, e.g. int type of lists of elements, [int] , have property of being applicative . lists, means there way, denoted operator, <*> , pronounced "apply", turn lists of functions , lists of arguments lists of res

java - Is this code snippet about semaphore necessary? -

here's code java concurrency in practice , showing how make execute block when work queue full using semaphore bound task injection rate. semaphore equal pool size plus number of queued tasks want allow. public class boundedexecutor { private final executor exec; private final semaphore semaphore; public boundedexecutor(executor exec, int bound) { this.exec = exec; this.semaphore = new semaphore(bound); } public void submittask(final runnable command) throws interruptedexception { semaphore.acquire(); try { exec.execute(new runnable() { public void run() { try { command.run(); } { semaphore.release(); } } }); } catch (rejectedexecutionexception e) { semaphore.release(); } } } my question about catch (rejectedexecutio

c# - Retrieve information from SVN Repository contains special characters -

i using sharpsvn connect , retrieve information visual svn server c#. but on svn server, repository have folder name c# , when read folder, exception occurred: additional information: url 'https://< svnserver >/svn/it/02_shopfloor/c' non-existent in revision 13 i debug , found uri still be: {https://< svnserver >/svn/it/02_shopfloor/c#} system.uri how access svn repositories contain special characters? i had used following nothing changed: if (lists[i].path.contains("#")) { path = lists[i].path.replace("#", "\\#"); } else { path = lists[i].path; } reposss[i] = new uri("https://< svnserver >/svn/it/02_shopfloor/" + path); svnclient.getlist(reposss[i], out listsinfo); //exception occur @ here the # schema operator in url. need escape character using uri escape rules. there helper functions on system.uri class , specific scenarios on svntools. escaped character %23 23 h

oracle - sql query- group by and then join -

i have 2 tables follow: 1)passenger - passenger_id,passenger_name , passenger_city 2)flight - flight_id,flight_name , passenger_id. the question is: list passenger details flight id, has travelled in more 1 flight. (this function display passenger details flight id's has travelled in more 1 flight.) i used query: select * passenger_1038299 passengerid in(select passengerid flight_1038299 group passengerid having count(passengerid)>1); but doesnt give me flight_ids. please tell how retrieve flight id well. , sorry stupid question new sql. join flight table passenger's flights select * passenger_1038299 p join flight_1038299 f on f.passenger_id = p.passenger_id p.passengerid in( select passengerid flight_1038299 group passengerid having count(passengerid)>1 ); i use exists check multiples. index on passenger_id may run faster query above. select * passenger_1038299 p join flight_1038299 f on f

MYSQL Diff From MAX -

Image
i'm trying query motogp result here's sqlfiddle i want add 2 more columns pos (1, 2, 3, 4, ...) gap (rider laptime - 1st pos laptime) desired result: 1 | marquez | 2799.627 | 2799.627 2 | rossi |2803.143 | 3.516 my current query: select `rider`, sum(laptime), count(`lapno`), max(`topspeed`) ts (select `lapno`,`rider`, (t1+t2+t3+t4) laptime , `topspeed` `a_lap_time` t_laptime) group a.rider order count(`lapno`) desc, sum(laptime) asc please advise, thank you this result | rider | laptime | gap | lapno | ts | |-----------------|----------|--------|-------|-------| | marc marquez | 2799.627 | 0 | 30 | 329.3 | | valentino rossi | 2803.143 | 3.516 | 30 | 319.7 | produced by: select `rider`, laptime, laptime - minlaptime gap, lapno, ts ( select `rider`, laptime, lapno, ts, @lap := if(@lap = 0.0, laptime, @lap) minlaptime ( select `rider`, sum(laptime) lapt

javascript - Handlebars angular JS parse error in ng-select -

i have ng-repeat div, , inside div have select control. code produces parse error: <select name="qty" ng-model="qty"> <option ng-repeat="v in [1,2,3,4,5,6,7,8,9,10]" value="{{v}}" ng-selected="v=={{item["menuitem.qty"]}}"> {{v}} </option> </select> in f12 console prints ng-selected="{{item[" menuitem.qty"]}}"="" so, see there issue handlebars , array, cannot figure out wrong here. change ng-selected="v=={{item["menuitem.qty"]}}" to ng-selected="v=={{item['menuitem.qty']}}"

C++ function that conditionally returns different types -

i'm attempting write template function return different types based on string passed in. template<typename t> t test(string type) { int integer = 42; float floateger = 42.42; if (type == "int") return integer; if (type == "float") return floateger; } int main() { int integer = test("int"); cout << "integer: " << integer << endl; } when run following error: error: no matching function call 'test(const char [4]) how can implement such thing? my end goal write function return objects of different classes depending on string passed it. know isn't right approach @ all. correct way this? you can't that, @ least not way. in order able return different types have first return reference , second possible returned types have inherit declared return type. for example: class base { }; class derived1 : public base { }; class derived2

Multiply permutations of two vectors in R -

i've got 2 vectors of length 4 , want multiplication of permutations of vector: a=(a1,a2,a3,a4) b=(b1,b2,b3,b4) i want: a1*b1;a1*b2;a1*b3...a4*b4 as list known order or data.frame row.names=a , colnames=b use outer(a,b,'*') return matrix x<-c(1:4) y<-c(10:14) outer(x,y,'*') returns [,1] [,2] [,3] [,4] [,5] [1,] 10 11 12 13 14 [2,] 20 22 24 26 28 [3,] 30 33 36 39 42 [4,] 40 44 48 52 56 and if want result in list can z<-outer(x,y,'*') z.list<-as.list(t(z)) head(z.list) returns [[1]] [1] 10 [[2]] [1] 11 [[3]] [1] 12 [[4]] [1] 13 [[5]] [1] 14 [[6]] [1] 20 which x1*y1, x1*y2, x1* y3, x1*y4, x2*y1 ,... (if want x1*y1, x2*y1, ... replace t(z) z )

Google Maps does not work in c# winforms -

i have problem location of google maps in c# winforms application. i message "you seem using unsupported browser." internet explorer - compatibility view removed google.it , google.com problem persists. the code used follows: private void btn_localizza_click(object sender, eventargs e) { string street = txt_indirizzoaz.text; string city = cbo_comuneaz.text; string state = cbo_statoaz.text; string zip = cbo_capaz.text; try { stringbuilder add = new stringbuilder("http://maps.google.com/maps?q="); add.append(street); add.append(city); add.append(state); add.append(zip); webbrowser1.navigate(add.tostring()); if (street != string.empty) {add.append(street + "," + "+");} if (city != string.empty) {add.append(city + "," + "+");} if (state != string.empty) {add.append(state + "," + "+");} if (zip != string.empty)

css - How to open two page in one submit in html? -

hei, want ask html. how open 2 page in 1 click on form action ? try 2 action never work, here use make form: <form action = "http://www.google.com" method = "get" target = "_blank"> that use open google when submit, how open 2 site or page in 1 submit ? i try not work <form action = "https://www.google.com" action="https://www.facebook.com" method = "get" target = "_blank"> im sorry im newbie please me find out. thank much in form add action property have provide link 1 of html page. then submit button add onclick property , provide link page opened in new window. form action="/link/of/your/first/html/page"<br/> <!--content--> input type="submit" onclick="window.open('/link/of/second/html/page','other_window') hope full.

php - One to One relation in Doctrine updates only one field - Integrity constraint violation: 1062 Duplicate entry -

it follow-up previous post relations while updating entity in symfony2 - one-to-one , one-to-many doesn't work while i've managed solve issue one-to-many, although dirty fix in controller, same isn't working one-to-one, following error: sqlstate[23000]: integrity constraint violation: 1062 duplicate entry '16' key 'uniq_3bae0aa753c674ee' the code: class offer { /** * @var event * * @orm\onetoone(targetentity="event", inversedby="offer") * @orm\joincolumn(name="event_id", referencedcolumnname="id") */ private $event; } class event { /** * @var offer * * @orm\onetoone(targetentity="offer", mappedby="event") * @orm\joincolumn(name="offer_id", referencedcolumnname="id", ondelete="set null") */ private $offer; } plus, on last post has been suggested me add following code on setevent (precisely "$event->setoffer($this);" part:

php - Pass value by reference to COM object function -

i have com object, contains function: [id(1)] hresult tst1([out] long * l, [out, retval] long * e ); create object , use in php , pass parameter reference: $i=5; $f = new com('app.myobj'); $f->tst1(&$i); got error: call-time pass-by-reference has been deprecated if pass $i without & (that should define "by reference") have same value of i equals 5 after tst1() execution $i=5; $f = new com('app.myobj'); $f->tst1($i); but inside of com object function changes passed value stdmethodimp csomeobject::tst1(long* e) { *e=3; return s_ok; } how pass reference in php while calling com object function?

ios - Delegate Method is not getting called -

i trying pass selected cell text categoryviewcontroller describeviewcontroller. not call method in describeviewcontroller method. categoryviewcontroller.h #import <uikit/uikit.h> @protocol categoryviewcontrollerdelegate <nsobject> - (void)didselectrow:(nsstring *)celldatastring; @end @interface categoryviewcontroller : uiviewcontroller<uitableviewdelegate, uitableviewdatasource> @property (weak, nonatomic) id<categoryviewcontrollerdelegate> delegate; @end categoryviewcontroller.m - (void)tableview:(uitableview *)tableview didselectrowatindexpath:(nsindexpath *)indexpath { uitableviewcell *cell = [categorytableview cellforrowatindexpath:indexpath]; nsstring *celltext = cell.textlabel.text; [self.delegate didselectrow:celltext]; [[self navigationcontroller] popviewcontrolleranimated:yes]; } describeviewcontroller.h #import <uikit/uikit.h> #import "categoryviewcontroller.h" @interface describeviewcontroller : pro

git - GitHub ignorefiles -

Image
i using github more year, right cannot handle ignoring files. i’m trying ignore files generated ide, , ignore .pyc files. keep appearing in changes. tried put: experience/.idea experience/.idea/* take @ screenshot: there 2 parts this: be sure you're using right directory matching scheme, since want block directory. that, want change experience/.idea/** experience/.idea/ . be sure git isn't tracking of files anymore removing them stage via git rm --cached <paths-to-ignore> .

python - ipython notebook not opening on windows 7 -

i'm trying open ipython notebook after downloading part of anaconda, using windows 7. i can open ipython in it's own python terminal not in browser. when run ìpython notebook in command prompt huge error log below. a lot of other questions not being able load ipython include obvious missing package indicator i've not been able spot of use in log. any ideas might going wrong or can fix it? z:\anaconda>ipython notebook [i 14:27:59.766 notebookapp] using mathjax cdn: https://cdn.mathjax.org/mathjax/latest/mathjax.js traceback (most recent call last): file "z:\anaconda\lib\site-packages\ipython\utils\traitlets.py", line 407, in __get__ value = obj._trait_values[self.name] keyerror: 'ip' during handling of above exception, exception occurred: traceback (most recent call last): file "z:\anaconda\scripts\ipython-script.py", line 5, in <module> sys.exit(start_ipython()) file "z:\anaconda\lib\site-packages\ipytho

jsf 2 - Primefaces calendar date pattern pm and am changed -

i have p:calendar : <p:calendar showbuttonpanel="true" showon="button" timezone="#{settingsbl.gettimezoneidset()}" mask="true" pattern="#{searchbl.determinedatetimepatternforfield(cc.attrs.curmaskelement)}" /> if click on button current date locale de_de value 22.10.15 15:40:37 set. after submitting form calendar shows value 22.10.15 15:40:37 corrent. pattern dd.mm.yy hh:mm:ss . if switch locale en_us , click current date button, calendar input gets 10/22/15 3:43:18 pm . if submit or click on calendar input field (gets focus) value gets 1/0/22 1:53:43 1 . pattern m/d/yy h:mm:ss a . calendar bug? i determine pattern locale this: dateformat di = dateformat.getdateinstance(dateformat.short, currentlocale); if (di instanceof simpledateformat) { final simpledateformat sdf = (simpledateformat) di; this.datepattern = sdf.topattern(); } i using primefaces 5.2.14.

c# - Capturing hex data packets with regular expressions -

i'm trying figure out best way capture data packets present in string contains otherwise unwanted characters. data packets in hex, typically grouped bytes white space in-between. packets vary in length , delimited @ beginning , end "10" , "10 03" respectively. thus, bit of text packet in may this: gibberish 10 01 23 ab cd ef 10 03 gibberish i can regex capture string of hex bytes enough, without accounting delimiters multiple hex packets can become one, or unwanted characters @ beginning or end happen hex can lumped in packet. how can regex account delimiters? can think of ways around without using regular expressions, doesn't seem efficient. generally, gibberish @ beginning referring memory address. contiguous string, without white-space. hence, use \s+ capture that. since hex data delimited 10 @ beginning , 10 03 @ end, use them: ^\s+ (10 (?:[0-9a-f]{2} )+10 03) a demo at regex101 . ps: you'll have use regexoptions.ignoreca

Programmatically set text color to primary android textview -

how can set text color of textview ?android:textcolorprimary programmatically? i've tried code below sets text color white both textcolorprimary , textcolorprimaryinverse (both of them not white, have checked through xml). typedvalue typedvalue = new typedvalue(); resources.theme theme = getactivity().gettheme(); theme.resolveattribute(android.r.attr.textcolorprimaryinverse, typedvalue, true); int primarycolor = typedvalue.data; mtextview.settextcolor(primarycolor); finally used following code primary text color of theme - // primary text color of theme typedvalue typedvalue = new typedvalue(); resources.theme theme = getactivity().gettheme(); theme.resolveattribute(android.r.attr.textcolorprimary, typedvalue, true); typedarray arr = getactivity().obtainstyledattributes(typedvalue.data, new int[]{ android.r.attr.textcolorprimary}); int primarycolor = arr.getcolor(0, -1);

seo - error 301 versus 410 when page deleted -

before when deleted page, them redirected (301) page category page, in google webmastertool, said had many "soft 404" changed , send 410 error , display links similar page, in webmastertool, said found increase of "404 not found" ?? of course see increase of 404 errors because happening! warn notice unintended problems. right increase indeed intended ignore it. warning disappear.

java - Parallelization of map reduce -

i have 2 independent mapreduce jobs in single java program. how can make them run in parallel. system configuration hadoop 2.7.1 3 node 16 physical cores instead of using job.waitforcompletion(true) use job.submit() method submitting job. later submit job , return immediately. job.waitforcompletion(true) submit job , waits completion. then should use iscomplete() checking completion status of jobs. remember non-blocking call , might want put while loop while sleep time. job job1 = new job("job1"); job job2 = new job("job2"); .... // code configure both job objects. //now submit both jobs. job1.submit(); job2.submit(); // wait completion. while(!job1.iscomplete() && !job2.iscomplete()) { thread.sleep(10000); }

java - detect hashtag and handles in a text under Android -

i'm writing app twitter like. i'm display tweets detect url link. i'm using code below: import android.text.html; tweet.settext(html.fromhtml(str_tweets)); using this, text displayed showing html tag , "allow" click on it. i'm trying same detecting hashtag # , handles @ the goal display profile when click @ , associated post when click on # i don't know best way make or smarter one. any idea ? api twitter allowing ?? thanks

How to read json data with JavaScript or jQuery -

i'm getting response when executing upload button page (i'm using jquery file upload). readystate: 4 responsetext: {"files":[{"name":"my_picture.jpg","size":79362,"type":"image\/jpeg","url":"https:\/\/www.mysite.com\/lib\/plugins\/jquery-file-upload-9.11.2\/server\/php\/files\/55_ads_1_preuzmi.jpg","mediumurl":"https:\/\/www.mysite.com\/lib\/plugins\/jquery-file-upload-9.11.2\/server\/php\/files\/medium\/55_ads_1_preuzmi.jpg","thumbnailurl":"https:\/\/www.mysite.com\/lib\/plugins\/jquery-file-upload-9.11.2\/server\/php\/files\/thumbnail\/55_ads_1_preuzmi.jpg","deleteurl":"https:\/\/www.mysite.com\/lib\/plugins\/jquery-file-upload-9.11.2\/server\/php\/index.php?file=55_ads_1_preuzmi.jpg","deletetype":"delete"}]} responsejson: [object object] status: 200 statustext: ok i want grab name key value, nothing else not n

java - Permission denied when uploading a video to Facebook in Android -

i'm writing android app upload , share video on facebook. code below: public void dosharevideo(view view) { list<string> permissionneeds = arrays.aslist("publish_actions","publish_pages"); //this loginmanager helps eliminate adding loginbutton ui loginmanager manager = loginmanager.getinstance(); manager.loginwithpublishpermissions(this, permissionneeds); uri videofileuri = uri.parse("file:///storage/emulated/0/movies/untitled.mp4"); sharevideo video = new sharevideo.builder() .setlocalurl(videofileuri) .build(); sharevideocontent content = new sharevideocontent.builder() .setvideo(video) .setcontenttitle("video shared android apps") .build(); shareapi.share(content, new facebookcallback<sharer.result>() { @override public void onsuccess(sharer.result resu

java - EL expression for class -

i don't understand how represent class in el expressions. i have el function takes class parameter (namely enum class) return possible enum values. i want invoke el expression. e.g. ${mytld:enumer(com.example.enums.myenum)} however: the above syntax passes null argument using myenum.class throws exception such expression cannot evaluated how express class in el without possibly passing string representation? the below works <function> <description> returns list of enum values given enum class </description> <name>enumer</name> <function-class>com.example.functions</function-class> <function-signature>list enumer(java.lang.string)</function-signature> </function> ${tld:enumer('com.example.myenum')} what like <function-signature>list enumer(java.lang.class)</function-signature> you can't represent class in plain el. can @ pass thro

javascript - Why won't this clearInterval work? -

i'm making race 2 images move right random number of px's won't stop clear interval, alert "stop" works. i'm using red , green picture changing z-indexes stoplight user start , stop race. <script type="text/javascript"> var ship = 0; var ufo = 0; function random() { var rand = math.floor((math.random() * 15) + 1); var rand2 = math.floor((math.random() * 15) + 1); ship = ship + rand; ufo = ufo + rand2; document.getelementbyid("ufo").style.left = ufo + 'px'; document.getelementbyid("spaceship").style.left = ship + 'px'; } function start() { if(document.getelementbyid("red").style.zindex == 1) { document.getelementbyid("red").style.zindex = "0"; alert("go"); var timer = setinterval(function() {random()},1000); } else { document.getelementbyid("green").style.zindex = &qu

zebra - ZPL: how to set max width of a "text field" -

given list of small strings (1 3 words each), print them in 2 columns using zpl zebra printers. example, if list ["a", "b", "c", "d", "e"] , label this: b c d e however, if strings little bit longer, able truncate them columns don't overlap. example, if list ["string 1", "string 2", "long string 3", "string 4", "string 5"] , label should this: string 1 string 2 long str string 4 string 5 i see 2 possible approaches this: 1) using zpl command have not been able find yet 2) calculating width of strings in pixels. in case need know font used zpl. i'm using command text printing: ^a0,n,30,30 ^fdtext^fs it looks ^tb solution: ^a0n,30,30 ^tbn,250,29 ^fdtext should go here^fs

Convert javascript value to binary to be placed into mysql -

i have column in mysql table of type binary ( password ). within object: { password: request.password }; each value in object string . how convert value password binary placed mysql row? +------------+--------------+------+-----+-------------------+-------+ | field | type | null | key | default | | +------------+--------------+------+-----+-------------------+-------+ | password | binary(16) | no | pri | | | +------------+--------------+------+-----+-------------------+-------+ use var password = "abc"; var result = ""; function converttobinarystring(decimal){ return (decimal >>> 0).tostring(2); } password.split('').foreach(function(char){ result += converttobinarystring(char.charcodeat(0)) }) console.log(result) // 110000111000101100011

android - Buttons aren't shown in the LinearLayout -

Image
i want looks (this screenshot graphical layout editor): so created layout: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <linearlayout android:id="@+id/controls" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <button android:id="@+id/clearbutton" android:layout_width="wrap_content" android:layout_height="match_parent" android:text="@string/clearbuttontext" android:layout_weight="1" /> <edittext android:id="@+id/searchte

json - JSONParser doesn't work in Android -

this type of json object coming android device : {"successful":true,"value":{"materials":[{"materialid":999999,"type":1,"stockno":1,"weight":1}]}} i'm trying parse : public string parsematerial(jsonobject object){ try{ jsonarray objectarray = object.getjsonarray("value"); } catch(jsonexception e){ log.d("jsonparser=>error", e.getmessage()); } } what in logcat : d/jsonparser=>error: value:{"materials":[{"materialid":999999,"type":1,"stockno":1,"weight":1}]} what doing wrong here? why program fall in catch block? thanks. cause value not json array

javascript - Accessing children using children in jQuery -

can 1 me having 2 span on click of 1 span tag p tag should show here html file <span class="span1" ng-click="show()">span_1 <p class="p1" ng-show="var1">p_1</p> </span> <span class="span1" ng-click="show()">span_2 <p class="p2" ng-show="var1">p_2</p> </span> and corresponding jquery var app = angular.module('myapp', []); app.controller('myctrl', function($scope) { $scope.var1 = false; $("span").click(function(){ $(this).children().toggle(); }) }); is there children() tag in angularjs ? plunker http://plnkr.co/edit/unyqby6llrqhab8183nf?p=preview please have of plunker <!doctype html> <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquer

Write hex numbers stored as strings to hex file directly in Java? -

i'm writing small assembler in java converts arm assembly code hex file executed virtual arm cpu on fpga. for example sub r0, r15, r15 add r2, r0, #5 add r3, r0, #12 sub r7, r3, #9 will translated machine(hex) code as e04f000f e2802005 e280300c e2437009 which stored strings line line in string array output in code. so how can write machine code hex file exactly literally is? instead of being encoded text. so when open output file tools hexeditor show encoding (without newline sign of course...) e0 4f 00 0f e2 80 20 05 e2 80 30 0c e2 43 70 09 currently tried: outputstream os = new fileoutputstream("hexcode.hex"); (string s : output) { int value = integer.decode(s); os.write(value); } os.close(); but gives me errors exception in thread "main" java.lang.numberformatexception: input string:"e04f000f" @ java.lang.numberformatexception.forinputstring(

c++ - Build SuperTuxKart on Mac OS X(failed to create symbolic link 'lib/libpng.pc': No such file or directory) -

i'm trying build open source game called supertuxkart on mac os x 10.10, following official instruction here . however, when typed "cmake .. -duse_cpp2011=1" or "cmake .. -gxcode", got error message: failed create symbolic link 'lib/libpng.pc': no such file or directory failed create symbolic link 'lib/libpng-config': no such file or directory . it seems package has "lib/libpng/libpng.p" , "lib/libpng/libpng.pc" in "cmake_build" directory not 'lib/libpng.pc' , 'lib/libpng-config'. is reason? problem caused bugs in cmake script provided package or cause didn't install libpng properly? how fix it? cmake_library_path used when searching libraries e.g. using find_library() command. if have libraries in non-standard locations, may useful set variable directory (e.g. /sw/lib on mac os x). if need several directories, separate them platform specific separators (e.g. ":"

arrays - How do I find a String list's length in Java? -

i'm new java, , i'm i'm not using lists properly, i'm saving loads of user input responses elements of string list (as side question, want string list or array list task?), , later want print out these elements @ end of program. however, want automatically through loop, don't know length of list make loop job. tried for(int j = 0; j <= (results.length-1); j++){ where "results" name of string list, it's giving me error "cannot find symbol." there way length of string list in java? , using list thing properly, or should trying array list instead? appreciated. if, length, mean total number of elements contained in list, can use size() method. returns integer specifies number of elements present in list. as for loop, can this: for (int j = 0; j < results.size(); j++) { //write loop logic here }

velocity - How to construct dynamic variable NAMES? -

i want loop on data, , create dynamic maps can later push more data into. example: #foreach ($item in ["bob","john","andy"]) #set(${item}_map = {}) #end so later can this: $!bob_map.put("${foreach.count}", "${some_data}") i do: #foreach ($item in ["bob","john","andy"]) <div id="${item}_map" ></div> #end so later can in js: <script> var map; function initmap() { map = new google.maps.map(document.getelementbyid('bob_map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); } </script>

java - How to pass parameter to injected class from another class in CDI? -

i new cdi, tried find solution question, but, couln't found any. question suppose have 1 class being injected(a) from, value(topass) getting injected, want pass same value(topass) class b, getting injected class a. public class { string topass = "abcd"; // value not hardcoded @inject private b b; } public class b { private string topass; public b(string topass) { topass = topass; } } can please me in this? note: cannot initialize topass variable of b in same way have initialized in a, there restriction it. in spring have done easily, but, wanted in cdi. you have options: 1. set topass variable b @postconstruct method of bean a : @postconstruct public void init() { b.settopass(topass); } or 2. create producer topass variable , inject bean a , b . producer: @produces @topass public string producetopass() { ... return topass; } injection: @inject @topass string topass; or 3. if b

c# - AST walker doesn't seem to work fine -

i using roslyn , have created ast walker in order detect when nodes traversed. the source trying parse following: var source = string.format(@" using system; using system.collections; using system.linq; using system.text; namespace helloworld {{ class {0} : {1} {{ static void main(string[] args) {{ console.writeline(""hello, world!""); }} }} }}", "myclass", "mybaseclass"); and walker: namespace mystuff { using system; using microsoft.codeanalysis; using microsoft.codeanalysis.csharp; using microsoft.codeanalysis.csharp.syntax; public class mywalker : csharpsyntaxwalker { public mywalker(syntaxnode node) : base(syntaxwalkerdepth.structuredtrivia) { this.root = node; } public syntaxnode root { get; private set; } public void star

How can I add in-store credit to my Ruby On Rails app -

i want add store credit app fiverr or other online marketplaces have users can have credit or money in accounts. there gem or recommended steps me build this? credit little intense because have balance actual money. when world, need make sure app works properly. nonetheless, you'd have set model , other things working. the 2 aspects require storage (a model) , payment (mechanics accept money). these permit app accept payments, , have way store them (giving balance work with). the setup not overly complicated; you'll have payments model literally store money user has sent - you'll able balance through user model: storage #app/models/user.rb class user < activerecord::base #columns id | username | email | etc etc etc has_many :payments def balance payments.sum(:value) #-> @user.balance -> "25" end end #app/models/payment.rb class payment < activerecord::base #columns id | user_id | value | currency | t

spring - Pass query parameters through a route -

camel learner here. there ability store incoming query parameters , set various headers/query parameters various routes? want build proxy-like service authentication option. example : 1) receive http on http://foo.bar/path?login=admin&password=admin&action=delete 2) i'd use <to uri="direct:auth"/> send request http://auth.foo.bar/login?login=admin&password=admin , receive authentication token answer 3) then, perform action token : going http://action.foo.bar/perform?authtoken=sometoken&action=delete finally - there option "cut" "action" param before going auth route , append before going action . thanks. you'll want use camel jetty component receive http request , camel http4 component make requests other web services. the jetty component take query parameters client's call , put them in headers of in exchange same names http query. you can set query parameters used other http calls settin

c++ Access violation reading location while erasing from list -

i have following c++ code: typedef std::list< volume >::iterator pvolume; typedef std::list< pvolume >::iterator ppvolume; void node::delvolume( pvolume _volume ) { for( ppvolume = m_volumes.begin( ); != m_volumes.end( ); ) if( (*it) == _volume ) { = m_volumes.erase( ); break; } else it++; } it gets error unhandled exception @ 0x009a3c79 in delone3d.exe: 0xc0000005: access violation reading location 0xfeeefef2. exactly when erasing. debug shows neither "it" nor "_volume" null pointer. what other reasons may occur for? the code show correct, seems there's problem elsewhere in application. memory pattern 0xfeeefef2 (a few addresses above 0xfeeefeee ) indicates freed dynamic memory, see here . you can massively simplify code, way: // std::list, in example m_volumes.remove(_volume); // std::vector , std::deque auto itr = std::remove(m_volumes.beg

javascript - Google Chrome inactivity redirect -

i have chrome opening in kiosk mode - added --kiosk flag chrome shortcut works expected. the kiosk allows browsing of our intranet , internet . realise can use javascript redirect pages on our intranet, internet? don't want people fpr example browsing youtube , walking away. we have browser re-direct www.mydomain.com after x minutes of inactivity. i have tried kiosk here require swipe left/right gestures don't seem work page navigation (already contacted developer via github). any suggestions? i managed find answer question on another site . ended using chrome extension called idle reset . hopefully helps else.

ruby - How can I pass extra details from simpleForm elements to my controller in rails -

i'm using simpleform in rails , have 2 fields presented user choose location (a rich association) pre-filtered set of locations. each choice needs saved in join table along type of location is. how can create form send info controller can tell me 'type' of location being selected. _new_flow_form.html <%= simple_form_for @new_flow,:url => {:action => "company_create_flow", :controller => 'flows'}, :html => { :class => 'form-horizontal', :multipart => true } |f| %> <%= f.label 'workflow title', :class => 'control-label' %> <%= f.text_field :title, :class => 'form-control' %> <%= f.association :locations, collection: location.where(:company_id => @company.id, :source => 'true'), :label => 'source location' %> <%= f.association :locations, collection: location.where(:company_id => @compa

c - How to avoid blocking read() from named pipe after it closes -

i have 2 processes created named pipe. writer process writes message using write(), , reader process reads message read(). noticed read() blocks when writer closes pipe. possible let writer process sends eof before closing pipe reader not blocked? not... it's not possible send eof because eof nothing maps sent on channel. eof condition (yes, it's condition, not receive or send on channel) means there's no more data read(2) , it's got process making read(2) return 0 characters read. many reads in eof condition, return value of 0 meaning there's no more data. by way, pipes block readers when there's no data available, but, writer still there send more data, there's no eof condition. design, pipes block readers when there's no data available (but writer still has pipe open) , block writers when there's no more space put data in fifo (this happens when there readers fifo open, none of them reading) see it's feature, not bug

r - knitr: can I cite an article in a figure caption using the fig.cap chunk option? -

Image
i'd cite article in figure caption. i've tried using rmarkdown/pandoc [@citekey] , latex \\citep{citekey} forms in fig.cap chunk option without luck. here reproducible example: --- output: rmarkdown::tufte_handout references: - id: nobody06 title: 'my article' author: - family: nobody given: jr issued: year: 2006 --- text [@nobody06]. ```{r figure, fig.cap="a figure [@nobody06]"} library(ggplot2) qplot(1:10, rnorm(10)) ``` # references this produces correct citation in text block either [@nobody06] (when use rmarkdown form) or (?) (when use latex form) in figure caption. here screencap: . i have tried reference in .bib , .bibtex file follows, same results: @misc{nobody06, author = "nobody jr", title = "my article", year = "2006" } after updating dev versions of rmarkdown ( rstudio/rmarkdown@c22ee06 ) , knitr ( yihui/knitr@b510ced ) (?) both in text block , figur