Posts

Showing posts from June, 2015

Conditional JSON serialization using C# -

i have class serialize json in c# , post restful web service. have requirment if 1 field filled out field not present. service errors if both fields serialized json object. class looks this: [datacontract(name = "test-object")] public class testobject { [datamember(name = "name")] public string name { get; set; } // if string-value not null or whitespace not serialize bool-value [datamember(name = "bool-value")] public bool boolvalue { get; set; } // if string-value null or whitespace not serialize [datamember(name = "string-value")] public string stringvalue { get; set; } } as noted in comments, if stringvalue has value don't put boolvalue in json object. if stringvalue blank, don't put in stringvalue instead put in boolvalue. i found how xml serialization, cannot find way works json serialization. there conditional json serialization on c#? it appears using datacontractjsonse

c# - Lucene.Net Query with two MUST Clauses Returning Incorrect Results -

i've created query 2 must clauses (and 0 should clauses) returning results satisfy 1 of clauses. far can tell, incorrect behavior. an example of such query before searching {+(text:wba) +(attribute:10)} the incorrect results being returned have 'wba' term in 'text' field, not have '10' term in 'attribute' field. when @ index in luke, go search tab, , run search +text:wba +attribute:10 i no results, expect. here's simplified version of code run search: public static scoredoc[] search( string searchphrase, int maxresults, ienumerable<string> attributes ) { var topquery = new booleanquery(); var textquery = new booleanquery(); using( var nganalyzer = new ngramanalyzer( version.lucene_30, 3, 9 ) ) { using( var stanalyzer = new standardanalyzer( version.lucene_30, new hashset<string>() ) ) { var ngparser = new queryparser( version.lucene_30, indexmanager.textfieldname, nganalyzer );

android - Resources$NotFoundException: Resource ID #0x0 issue -

this problem annoying me since have no clue might causing it. have few reports of error, samsung devices running android 2.3.5 , 2.3.6 (98%). below stack trace: android.content.res.resources$notfoundexception: resource id #0x0 @ android.content.res.resources.getvalue(resources.java:892) @ android.content.res.resources.getdrawable(resources.java:580) @ android.widget.textview$handleview.setorientation(textview.java:8355) @ android.widget.textview$handleview.<init>(textview.java:8324) @ android.widget.textview$insertionpointcursorcontroller.<init>(textview.java:8631) @ android.widget.textview.getinsertioncontroller(textview.java:9218) @ android.widget.textview.ontouchevent(textview.java:7137) @ android.view.view.dispatchtouchevent(view.java:3885) @ android.view.viewgroup.dispatchtouchevent(viewgroup.java:869) @ android.view.viewgroup.dispatchtouchevent(viewgroup.java:869) @ android.view.viewgroup.dispatchtouchevent(viewgroup.j

No Shipping Options Available - Opencart 1.5.6 fedex -

i'm attempting set opencart store client. i'm getting following error on shipping page. "warning: no shipping options available. please contact assistance!" research suggests error happens when there mismatch between weight-class store , plugin, or similar. i've tried every combination of configuration settings can think of without result. i'm not familiar enough opencart debug issue. need start looking? firstly have enable shipping status , values admin panel shipping tab.after can in front end.

javascript - Call same ajax from different element clicks with different data -

i'm trying call same ajax function different elements different data. for eg: i've these 2 links <a href="#!" id="link1" data-source="google">google</a> <a href="#!" id="link2" data-source="facebook">facebook</a> and ajax call like: $("#link1).click(function() { $.post( '/myphpscript/', { data:$("#link1).attr('data-source') }, // data want send script function (data) { } }); i know can call same ajax different elements this: $('#link1, #link2').click(some_function); but how select data based on clicking element? use instance of this , also, give links common class , use simple selector: $(".ajaxlinks").click(function() { $.post('/myphpscript/', { data:$(this).attr('data-source') }, function (data) { }); });

Python - Wrong directory when execute from terminal -

if run ide dir path ok, when execute termianl, geeting exception: code: def __init__(self): dir = os.path.abspath(os.path.join(__file__, os.pardir)) self.locator_file_path = dir+'/locators/locator_'+self.get_class_name_lower()+'.json' open(self.locator_file_path) json_data: exception: e ====================================================================== error: test_verify_page (test_verify_page.testverifypage) ---------------------------------------------------------------------- traceback (most recent call last): file "test_verify_page.py", line 9, in test_verify_page sign_inpage = signinpage() file "c:\python27\lib\site-packages\page_objects\sign_in_page.py", line 47, in __init__ open(self.locator_file_path) json_data: ioerror: [errno 2] no such file or directory: 'c:\\python27\\lib\\site-packages\\page_objects/locators/locator_signinpage.json' ---------------------------------------------

mysql - Query with two NOT IN subqueries -

is possible have query 2 not in on 2 subqueries: select u.feedbackid user_feedback u u.feedbackid not in ( select feedbackid user_feedback_sent) , not in (select feedbackid user_feedback_received) the query throws error on second not in saying incorrect syntax. you're missing column name shuold not in second subquery. works need: select u.feedbackid user_feedback u u.feedbackid not in (select a.feedbackid user_feedback_sent a) , u.feedbackid not in (select b.feedbackid user_feedback_received b) identation practice implement when writing sql code. hope helps

javascript - Testing Angular app with Protractor inside iframe hosted by non-Angular app? -

in process of migrating legacy app angular have setup legacy app loads new in iframe. want test integration protractor. legacy app not angular app. we'd able test if legacy app had angular, doesn't, protractor has trouble switching context iframe angular app lives. how should done? edit: protractor fails follows. after iframe comes , doing browser.switchto().frame(...); protractor unable find controls inside iframe. we've tested case outside iframe , protractor finds buttons , links , fields fine in angular app. when same page loaded in iframe acts though weren't there. once had similar situation, upside down - there non-angular page opened on click: non-angular page opened after click i hope same idea work here also. set ignoresynchronization false right before switching frame. set ignoresynchronization true in aftereach() function: browser.ignoresynchronization = false; // switch frame

ios - Swift : [MyApp.MyClass retain]: message sent to deallocated instance -

i getting following crash app. [myapp.myclass retain] i not know issue @ honest you. this occuring in swift class. need know why is occurring , general way fix this. here swift code in general (there more it, don't need post all. class myclass : nsobject, apidelegate, uialertviewdelegate { var apiclient : api? func initmyclass (authkey : nsstring?) { apiclient = api(authkey: authkey, debugmode:false) apiclient?.delegate = self } as rob said, looks culprit methods begin init not initializers. seems swift strange these method around memory management. anyway, in own code, renamed of these methods begin setup instead of init , , haven't received "retain message sent deallocated instance" error again. xcode should provide warning prevent error.

angularjs - How create select from object in Angular? -

how easy create select list object js? object: 0: {userswork: "600", name: "salaria"}, 1: {userswork: "700", name: "bavaria"} i need create: <select> <option value="600">salaria</option> <option value="700">bavaria</option> </select> i tried using ng-option : <option ng-show="specializationselect == {{value.usersspecializationidspecialization}}" value="{{value.usersworkspaceiduser}}" ng-repeat="(key, value) in options">{{value.detailtousersname}}</option> use ng-options <select ng-options="person.userswork person.name (objid, person) in persons"></select> assuming data array object in $scope.persons (sub out whatever)

android - Null Object Reference error when adding refresh listener to SwipeRefreshLayout for a WebView -

when add line of code swipelayout.setonrefreshlistener(this); i error void android.support.v4.widget.swiperefreshlayout.setonrefreshlistener (android.support.v4.widget.swiperefreshlayout$onrefreshlistener)' on null object reference mainactivity import android.app.activity; import android.os.bundle; import android.os.handler; import android.view.keyevent; import android.view.window; import android.webkit.websettings; import android.webkit.webview; import android.webkit.webviewclient; import android.support.v4.widget.swiperefreshlayout; public class mainactivity extends activity implements swiperefreshlayout.onrefreshlistener { private webview mwebview; private swiperefreshlayout swipelayout; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); getwindow().requestfeature(window.feature_no_title); setcontentview(r.layout.main); mwebview = new webview(this); mwebview.load

Ruby's HTTP Client improperly parsing certain URLs -

it quite possible there answer following question, if so, unable recognize it. here's thing: making ruby program sweeping dictionary list of entries. need because want sweep each entry in search of specific words, that's beside point. problem program has trouble downloading data encoded links, has never occured before. by encoded, mean encoding replacing non-ascii characters etc., link this: http://www.dict.cc/deutsch-englisch/a+%5bauch+a%5d+%5bbuchstabe%5d.html looks this: http://www.dict.cc/deutsch-englisch/a+%5bauch+a%5d+%5bbuchstabe%5d.html the funny thing while above not work, of links work, instance: /deutsch-englisch/a+an+b+anpassen.html i have tested random links , work, , regex matches supposed match. here's function using: def getdataoverhttpget(link, proxy = nil) link = uri.unescape(link) # added http = httpclient.new(:agent_name => 'mozilla/5.0 (windows nt 6.1; wow64; rv:12.0) gecko/20100101 firefox/25.0') http.p

enterprise - Magento Category Custom Design Page Layout not changing -

Image
i have turned off caching, not matter when edit admin -> catalog -> categories. click on custom design , edit page layout, , layout 1 - 3 columns. none of changes show up. i've tried default site , specific site per category no updates reflecting front-end. can edit custom layout update area , use like: <reference name="root"> <action method="settemplate"><template>page/1column.phtml</template></action> </reference> or can edit local.xml file , force categories specific layout: <catalog_category_default> <reference name="root"> <action method="settemplate"><template>page/1column.phtml</template></action> </reference> </catalog_category_default> <catalog_category_layered> <reference name="root"> <action method="settemplate"><template>page/1column.phtml<

css - Setting text-decoration: none but link is still underlined -

i'm deisgning simple button , don't want text link have underline. set text-decoration "none" in css below, still underlined. how can rid of that? .button { border-style: solid; border-width: 2px; border-color: #63d3ff; background-color: #000e4d; text-align:center; display: inline-block; padding-top: 10px; padding-right: 15px; padding-bottom: 10px; padding-left: 15px; color:white; } .button { text-decoration: none; } the html is: <a href="#" class="button">save choice</a> your css work links inside element class button , this: <span class="button"><a href="#">save choice</a></span> but in html, link has class, in case, css should this: a.button { text-decoration: none; }

uiviewcontroller - Swift popToRoot not working -

Image
this highlighted line should poptoroot proceed, after successful registration should redirect root view controller. reason it's not working me, literally nothing happens, not error. i tried self.navigationcontroller?.poptorootviewcontrolleranimated(true) you don't appear using navigation controller @ all, i'd wager self.navigationcontroller nil . you use unwind segue. in root view controller, add method so: @ibaction func unwindtoroot(segue: uistoryboardsegue) { print("successfully unwound") } then in scoreboard scene want unwind, can control -drag button "exit outlet": when let go, can pick unwind action: this achieves "pop root" sort of functionality, not contingent upon using navigation controller. if want perform unwind programmatically, rather doing segue button exit outlet, view controller icon exit outlet: then, select segue in document outline , give segue unique storyboard id: then can

igraph - Removal of N Random nodes from the graph in R -

i new r/igraph. remove n nodes randomly graph. however, not find right way that. have generated erdos-renyi graph of igraph package 400 vertices. igraph provides deletion of vertices, not in random way. example: delete.vertices(graph, v) . i referred this documentation. i searched web , previous questions on stack overflow, not right answer. can please tell or refer me documentation on how remove n (lets n = 100) random nodes? basically need generate vector of random numbers ranging 1 400: random.deletes <- runif(n=100, min=1, max=400) and apply it: my.new.graph <- delete.vertices(graph, random.deletes) of course, both can done @ once you'd lose track of deleted nodes: my.new.graph <- delete.vertices(graph, runif(n=100, min=1, max=400))

javascript - Google Maps: Get click or marker (x,y) pixel coordinates inside marker click listener -

i trying display completely custom info windows on map markers on marker click . have implemented this answer div show on map-canvas click... not able replicate on marker click. is possible markers pixel position inside of marker click function, , suppress normal infowindow show desired custom infowindow? i tried this: google.maps.event.addlistener(marker, 'click', function(args) { var x=args.pixel.x+$('#map').offset().left; //we clicked here var y=args.pixel.y; info.style.left=x+'px'; info.style.top=y+'px'; info.style.display='block'; }); but in console, see: uncaught typeerror: cannot read property 'x' of undefined a marker click event returns mouseclickevent the documented property of mouseclickevent is: latlng latlng latitude/longitude below cursor when event occurred. to convert pixel position use fromlatlngtocontainerpixel method of mapcanva

how to send Data from matlab GUI to arduino? -

i'm doing remote control using matlab gui have no experience in matlab code, not implemented : 1- arduino code ( transmitter ) : int matlabdata; const int apin=13; const int bpin=12; #include <virtualwire.h> char *controller; void setup() { serial.begin(9600); pinmode(apin,output); vw_set_ptt_inverted(true); // vw_set_tx_pin(bpin); vw_setup(4000);// speed of data transfer kbps } void get_action(){ if(serial.available()>0) // if there data read matlabdata=serial.read(); // read data if(matlabdata==1){ //forward controller="f"; serial.println("forward"); } if(matlabdata==2){ //backward controller="b"; serial.println("backward"); } if(matlabdata==3){ //right controller="r"; serial.println("right"); } if(matlabdata==4){ //left controller="l"; serial.println("left"); } if(matlabdata==5) { //stop controller="s"; serial.println(&

javascript - Web Audio API AudioParam.value not logging -

i trying figure out how read current value of audioparam. when audioparam being modified audionode through audionode.connect(audioparam), doesn't seem effect audioparam.value. here example: have oscillator (source) connected gainnode (gain). have oscillator (mod) routed gainnode (modamp). modamp connected gain.gain. have meter gain.gain, changing textbox display gain.gain.value when play oscillator, gain audibly moving , down, meter stays constant original setting. how can real-time reading of audioparam? http://jsfiddle.net/eliotw/3o0d0ovs/4/ (please note have run script every time want run oscillator) //create audio context window.audiocontext = window.audiocontext || window.webkitaudiocontext; var context = new window.audiocontext(); //create source , gain, connect them var source = context.createoscillator(); var gain = context.creategain(); source.connect(gain); //create modulator , gain , connect them var mod = context.createoscillator(); var modamp = context.cre

awt - Editable Java Drawing2D Texts and Images -

for gym exercise machine, need modify continuously texts , images inside jpanel. drawimage() , drawstring() worked fine, 'dumb'. have repaint everytime. the pseudo-code following: public class cscreen extends jpanel { public cscreen() { repaint(); } public void paint(graphics g) { bufferedimage img=...some image...; int ximg= ...variable location...; int yimg= ...variable location...; g.drawimage(img,ximg,yimg,...); graphics2d g2 = (graphics2d) g; g2.setfont(...); g2.setcolor(...); string txt = ...some text...; int xtxt= ...variable location...; int ytxt= ...variable location...; g2.drawstring(txt,xtxt,ytxt,...); } } is there way deal text , images, if objects, not pixels drawn? please, help, appreciated.

ios - Connecting Multiple Storyboards in Swift -

i in process of building ios app using swift , have been advised use storyboard each feature each feature have 10 views. starting main storyboard, provide advice on how transition between storyboards using swift? alternatively, there better using multiple storyboards if want avoid confusion of 50+ view main storyboard? here ended working: let secondvc:uiviewcontroller = uistoryboard(name: "secondstoryboard", bundle:nil).instantiateviewcontrollerwithidentifier("numbertwo") uiviewcontroller @ibaction func changestoryboardbuttonclicked(sender: anyobject) { presentviewcontroller(secondvc, animated: false, completion: nil) } when app needs move new controller that's in different storyboard, have instantiate new storyboard, instantiate initial view controller there. let sb = uistoryboard(name: "somestoryboardname", bundle: nil) let vc2 = sb.instantiateinitialviewcontroller() uiviewcontroller // or whatever class of initial vc

winforms - C# WebBrowser object not loading Uri -

i believe i've researched here , elsewhere enough justify posting new question. situation similar not identical others' reported problems. as proof of concept building app hits google streetview , staticmaps api's , displays images of them in c# windows form (.net 3.5 time being). form has webbrowser object, 4 textboxes (street, city, state, zip) address input , "go" button. here's code (and other reputable posts/sites, should need): using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms; namespace googlemapstest { public partial class form1 : form { public form1() { initializecomponent(); } private void button1_click(object sender, eventargs e) { webstreetview = new webbrowser(); uri urlstring = new uri("https://maps.googleapis.com/maps/api/streetview?size=300x300&locat

vba - Excel; trying to find events in a column across multiple sheets -

i have on 100 worksheets identical. trying make 1 new sheet scans other sheets. scan 1 column (h) , find event (both >.05 , <-.05). need copy entire row , place new worksheet. ok haven't touched vba in years, come googling different steps needed achieved. used random data ranging cell a1 h30 usin few example sheets; you'll need adapt code needs, should more enough started! sub lookforvaluesinh() dim ws_count integer ws_count = activeworkbook.worksheets.count dim ws worksheet set ws = thisworkbook.sheets.add(after:=thisworkbook.sheets(thisworkbook.sheets.count)) ws.name = "results" = 1 ws_count dim row_count integer row_count = 30 r = 1 row_count worksheets(1).select if cells(r, 8) >.05 worksheets(1).rows(r).copy ws.activate ws.paste activecell.offset(1).select end if next r next end su

Add certain rows in a column that satisfy condition in R? -

i using r , want add values within column if rows satisfy condition. if have data frame data below: team mp win atl 14 .4 atl 25 .4 atl 14 .4 bos 14 .55 bos 20 .55 bos 9 .55 how store values of mp atl (14+25+14 = 53)and bos (14+20+9=43)? edit: if want add new variable multiplies win mp / sums (where sums sum of mp each team ). atl variables, want values .4*14/53 , .4*25/53, , bos want .55*14/43, .55*20/43, .55*9/43 i think produce you're looking for: edit in light of akrun 's excellent answer, here's more compact solution: dat$cumsums <- ave(dat$mp, dat$team, fun=sum) dat$newvar <- with(dat, win * (mp/cumsums)) previous solution cumsums <- by(data = dat$mp, indices = dat$team, fun = sum) cumsums.df <- data.frame(team = names(cumsums), cumsums = as.numeric(cumsums)) dat <- merge(x=dat, y=cumsums.df, = "team") dat$newvar <- with(dat, win * (mp/cumsums)) results dat team mp win cumsums

Issues with displaying dynamic OpenGL VBO -

i have been working vbos in opengl, , apparently don't understand i'm doing wrong here. want display vbo text in updated each frame. goal time fps counter, other applications viable. down actual code: can work fine if set vbos in initialization function , draw in rendering function. if try , edit in draw function, however, nothing displays. while debugging have found of vectors containing data correct (i updated vbo same text , vectors indeed identical), issue must handling of vbos, , not data inside of them. here initialization/rendering commands: glgenbuffers(1, &pntvbo); glbindbuffer(gl_array_buffer, pntvbo); glbufferdata(gl_array_buffer, newpoints.size() * sizeof(vec3f), &newpoints[0], gl_stream_draw); glgenbuffers(1, &indvbo); glbindbuffer(gl_element_array_buffer, indvbo); glbufferdata(gl_element_array_buffer, newindex.size() * sizeof(unsigned int), &newindex[0], gl_stream_draw); i tried this, no success: glbindbuffer(gl_array_buffer, pntvbo

java - connection string for android to sqlserver -

i've started developing android application connects sqlserver db, i've connected db connection string : connurl = "jdbc:jtds:sqlserver://" + _ip+ ":" + _port + ";" + "databasename=" + _db + ";usentlmv2=true;integratedsecurity=true"; but works if try on device connected same network in server connected because ip put in connection string 192.168.1.7. should make work if try in network ? i've tried replacing ip address ip address got what ip wont connect. that's because you're behind nat , address isn't reachable outside world. need move server real ip address, or poke hole in nat , allow address rerouting. but that's ok, because should never directly connect db anyway- not have allow db server reached public internet, have put login info in public app. totally insecure. should have webservice between , db. webservice should 1 password, , should data db , return in json or xml format.

roboto - Android TextView custom typeset causes gravity to stop working -

Image
update this appears happening roboto-italic.ttf. if you're running issue, try font family. i'm running odd issue when applying typeset textview. app name, "contact" in linearlayout android:gravity="center" set, causes centered nicely seen in "before" image below. when set typeface, causes gravity stop working reason. how i'm setting typeface: tvappname.settypeface( typeface.createfromasset(getactivity().getassets(),"fonts/roboto-italic.ttf")); any idea why might happening? i've tried setting gravity programmatically, didn't help. commenting 1 line causes text go being centered. before after the roboto-italic.ttf file google's website seems broken or incompatible in way. work-around use normal roboto font specify italic 2nd argument : typeface tf = typeface.createfromasset(getactivity().getassets(), "fonts/roboto-normal.ttf")); tvappname.settypeface(tf, typeface.italic);

sparql - How to get such data as abstraction, location and link for image in Dbpedia? -

i trying data museum not successfull. code. know name of museum, want data museum prefix dbpedia: <http://dbpedia.org/resource/> prefix dbpedia-owl: <http://dbpedia.org/ontology/> prefix dbpprop: <http://dbpedia.org/property/> select ?abstract ?location { ?architectural_structure rdf:type dbpedia-owl:museum . ?architectural_structure dbpedia-owl:location dbpedia:taganrog . ?architectural_structure dbpprop:name dbpedia:chekhov_shop . } the dbpprop:name have selected ( dbpedia:chekhov_shop ) in fact string. if @ dbpedia page has been defined the chekhov shop . therefore, suggestion filter query based on name displayed: prefix dbpedia: <http://dbpedia.org/resource/> prefix dbpedia-owl: <http://dbpedia.org/ontology/> prefix dbpprop: <http://dbpedia.org/property/> select * { ?architectural_structure rdf:type dbpedia-owl:museum . ?architectural_structure dbpedia-owl:location dbpedia:taganrog . ?architectural_structure dbpprop:

java - can't added my object to to ArrayList -

i tried add object arraylist ? ican't whyyyyyy ? arraylist<patient> emer; patient p = new patient(); p.setname(jtextfield1.gettext()); p.setsurname(jtextfield2.gettext()); p.setgender(jradiobutton1.gettext()); } p.setbooldtype(jcombobox1.getselecteditem() + ""); p.setentarnceday(jcombobox2.getselecteditem() + "/" + jcombobox3.getselecteditem() + "/" + jcombobox4.getselecteditem()); p.setfee(integer.parseint(jtextfield8.gettext())); emer.add(p); you haven't initialized emer , getting "local variable not initialized" error. arraylist<patient> emer; what need initialize emer new array list instance. arraylist<patient> emer = new arraylist<patient>(); or better yet: list<patient> emer = new arraylist<patient>();

java - Jackson Circular Dependencies -

i have circular dependency struggling solve right take these 2 classes - boiler plate code removed demo purposes class 1 @entity @table(name = "t_credential") @cache(usage = cacheconcurrencystrategy.read_write) @jsonidentityinfo(generator=objectidgenerators.intsequencegenerator.class, property="@id") public class credential implements serializable { @id @generatedvalue(strategy = generationtype.auto) private long id; //removed @jsonignore want disable fields if no credentials available //also fetch in eager fashion instead of lazily loading @onetomany(mappedby = "credential",fetch=fetchtype.eager) private set<usertask> usertasks = new hashset<>(); .... ..... class 2 @entity @table(name = "t_usertask") @cache(usage = cacheconcurrencystrategy.read_write) @jsonidentityinfo(generator=objectidgenerators.intsequencegenerator.class, property="@id") public class usertask imple

OpenLayers 2 - 'immediate' measurement -

i trying create measurement control in openlayers, using openlayers.control.measure function, return features area in real time, when moving mouse around. have been doing lot of reading , many achieved using immediate property of openlayers.control.measure control, can't seem work. when using immediate property, area of feature when create new vertexes... not when moving mouse around. appreciate can't seem find doing wrong. here code using: <!doctype html> <html> <head> <script src="scripts/jquery-213/jquery-2.1.3.min.js"></script> <script src="http://maps.google.com/maps/api/js?sensor=false&v=3.2"> </script> <script src="scripts/openlayers-2.10/openlayers.js"></script> <style type="text/css"> body { height: 100%; width: 100%; z-index: 1; } #map { height: 100%; min-height: 300px; width: 100%; position: absolute; top: 0; left: 0; margin:

Java Error: Could not find or load main class -

package src.sheet1.question1; class onefourtwoone { public static void main(string[] args) { assert args.length == 1; int x = integer.parseint(args[0]); system.out.print(x); while(x != 1) { x = next(x); system.out.print(" " + x); }; } static int next(int x) { return ((x % 2) == 0) ? (x / 2) : (3*x + 1); } } when input :java onefourtwoone in terminal, here occurs error: error: not find or load main class onefourtwoone how can run it? java cannot run class because in package. java expects package name matched path file. create directory structure looks this: src +-sheet1 +-question1 +-onefourtwoone.java and compile class onefourtwoone.class . switch parent directory of src , , execute command java src.sheet1.question1.onefourtwoone

Android default font -

want app use default font phone using, how do that? no matter font settings on phone, font on app remains same. try magic: tv.settypeface(typeface.createfromfile("/system/fonts/" + sp1.getselecteditem().tostring() + ".ttf"));

Using complex th:attr fields with Thymeleaf -

i have thymeleaf template rather complex data- attribute, so: <div data-dojo-props="required: true, placeholder:'foo bar baz', more: stuff" ...> i'd have thymeleaf provide placeholder, so: <div th:data-dojo-props="placeholder:'#{foo.bar.baz}'" ...> it doesn't work, of course. i'm supposed use th:attr so: <div th:attr="data-dojo-props=placeholder:'#{foo.bar.baz}'" ...> which doesn't work. add : or ' within th:attr , template breaks. tried escaping them, e.g. \: , \' , , tried using html entities, e.g. &38; , didn't work. so tried th:prependattr , th:appendattr : <div th:prependattr="data-dojo-props=placeholder:'" th:attr="data-dojo-props=#{foo.bar.baz}" th:appendattr="data-dojo-props='" ...> but can't handle : , ' , nor escaping them: <div th:prependattr="data-dojo-props=placeholder&am

css - jQuery crossfade images and hide them with display:none -

i need fade div background-image in same container fixed dimension. fadein , out need , work quite well, because want possibility click on each visible image, , that's impossible working opacity, if it's effect i'd have.. kind of crossfading between images. html <div class="image_container"> <div id="image1"></div> <div id="image2" style="display:none"></div> </div> my simplified js $( ).click(function() { $( "#image1" ).fadeout(); $( "#image2" ).fadein(); } by placing images in absolute position on top of each other, can use jquery fade between them this: <div class="image_container"> <div id="image1"></div> <div id="image2" style="display:none"></div> </div> <script type="text/javascrtip"> $(".image_container").click(function(){

dynamic array of a nested class with an array in it? Can it be done? -

this code compiles crashes instantly. i've tried on devcppportable . trying make class can store lot of complex data (i.e. object has multiple property sets , each set carries multiple figures). each object created have unique number of property sets , internal property values. able shape class upon declaration not allocate bunch of unused space. possible? #include<iostream> using namespace std; class { public: int amount; struct b { int max; int* prop; b() {} void set(int&); ~b(){delete prop;} }; b* property; a(int amt, int max0, int max1=0, int max2=0); ~a(){delete property;} }; int main() { object(2, 3, 5); return 0; } a::a(int amt, int max0, int max1, int max2) { amount = amt; property = new b[amt]; switch(amt) { case 3: property[2].set(max2); case 2: property[1].set(max1);

html - Javascript double-click does not work in IE9 and IE11 -

in javascript code, single-click opens link in new tab , double-click opens light-box. works ok in browsers except in ie9 , ie11. in first code, both single-click , double-click work single-click, ie gives message, "allow pop-up?" want ie open link in new tab w/o message other browsers. in second code, single-click works want second click of double- click in ie gets ignored , ends working single-click. can done remove issue - either in first code or in second code - perhaps missing? first code: $('div[id^="jzl_"].short').click(function(e) { var $this = $(this); var currentid = e.target.id; if ($this.hasclass('clicked')) { $this.removeclass('clicked'); $.colorbox({ href : "getinfo1.php?id=" + c

c++ - Implementation of scheduling algorithm -

i have assignment need develop simulation of process scheduler. got of setup stuck @ figuring out logic schedule processes. right have struct created holds processes pid, cycle count , memory requirement. , have used vector hold 100 processes can sort them if want , remove processes schedule them. for 5 processors created int array guessing processors should have cycle count , memory limits? in case struct maybe? and how assign processes these 5 processors? can me figure out? need implement simple fcfs algorithm. void init_process_list(vector<process> &p_list) { generator generate; // random number generator class process p; for(int = 0; < process_count; i++) { p.process_id = i; p.cpu_cycles = generate.rand_num_between(cycle_lbound, cycle_ubound); p.mem_footprint = generate.rand_num_between(mem_lbound, mem_ubound); p_list.push_back(p); } } // initialize processor array void init_processor_list(int *processor_lis

python - Superimpose on FITS image on another with PyWCSGrid2 -

i've got 2 .fits images. 1 image of stars , galaxies. other significance map want plot on it, contour. pywcsgrid2 python module in, i've tried overlay 1 on other while , can't them both show @ same time. ideas why isn't working? import matplotlib.pyplot plt import sys import pyfits import pywcsgrid2 mpl_toolkits.axes_grid1.axes_divider import make_axes_locatable imagename=str("example1.fits") def setup_axes(): ax = pywcsgrid2.subplot(111, header=f_radio[0].header) return ax # image1 data = f_radio[0].data #*1000 ax = setup_axes() # prepare figure & axes fig = plt.figure(1) #get contour source: f_contour_image = pyfits.open("image2.fits") data_contour = f_contour_image[0].data # draw contour cont = ax.contour(data_contour, [5, 6, 7, 8, 9], colors=["r","r","r", "r", "r"], alpha=0.5) # draw image im = ax.imshow(data, cmap=plt.cm.gray, origin="lower", interpo

shell - I want to delete a batch from file -

i have file , contents : |t1234 010000000000 02123456878 05122345600000000000000 07445678920000000000000 09000000000123000000000 10000000000000000000000 .t1234 |t798 013457829 0298365799 05600002222222222222222 09348977722220000000000 10000057000004578933333 .t798 here 1 complete batch means start |t , end .t. in file have 2 batches. i want edit file delete batch record 10(position1-2),if position 3 till position 20 0 delete batch. please let me know how can achieve writing shell script or syncsort or sed or awk . i still little unclear want, think have enough give outline on bash solution. part unclear on line contained first 2 characters of 10 , remaining 0 's, looks last line in each batch. not knowing how wanted batch (with matching 10 ) handled, have written remaining wanted batch(es) out file called newbatch.txt in current working directory. the basic outline of script read each batch temporary array. if during read, 10 , 0 's match found, sets

angularjs - Regular Expression for alphnumeric with first alphabet and at least one alphabet and one number -

i'm trying generate regular expression can satisfy following conditions: it should alphanumeric only. it should contains @ least 1 alphabet , @ least 1 number. it should allow small letters. it's length should between 3 , 16 inclusive. the first character should alphabet. ex:- abc - invalid (should have @ least 1 number also) ab9 - valid 9ab - invalid (should start alphabet) ab9 - invalid (no capital letters allowed) aa - invalid (length should @ least 3) abcdefghijklmnop99 - invalid (length should @ least 16) i tried following solution it's not working expected /^(?=.*[a-z])[a-z0-9]{3,16}$/ i want use regex in ng-pattern check text input user. i'd use: /^[a-z](?=.*\d)[a-z\d]{2,15}$/ or, if want unicode compatible: /^\p{ll}(?=.*\p{n})[\p{ll}\p{n}]{2,15}$/

How to parse html in node.js using jquery 2.1.3? -

i trying use node.js jquery 2.1.3 , jsdom 4.0.4 web scraping. running problems running jquery module. code // load http module create http server. var $ = require('jquery')(require("jsdom").jsdom().parentwindow); var http = require('http'); var request = require("request"); // configure our http server respond hello world requests. var server = http.createserver(function (req, res) { res.writehead(200, {"content-type": "text/plain"}); var uri = "http://www.forever21.com/shop/ca/en/men-tees-tanks"; request({ uri: uri, }, function(error, response, body) { if (error) { return console.error(error); } var f = $(body); res.write(body); res.end(); }); }); // listen on port 8000, ip defaults 127.0.0.1 server.listen(8000); // put friendly message on terminal console.log("server running @ http://127.0.0.1:8000/"); and err

postgresql - What units is timeout in Rails database.yml? -

in database.yml, timeout in seconds or milliseconds? , it, timeout entire database connection including wait time connection or else? the timeout in milliseconds. entire time rails app wait database response. practice add reconnect option in file application try reconnecting server before giving in case of lost connection.

linux - getting filenames from directory in shell script -

i iterate loop on file present in directory using shell script. further, display contents each file. passing directory command line argument. i have simple loop follows: for file in $1 cat $file done if run sh script.sh test where test directory, content of first file only. could please me in this? couple of alternatives: compact modification of sma's code: for file in $1/* [[ -f $file ]] && cat $file done or use find: find $1 -type f -exec cat \{\} \;

algorithm - Count lexographically sorted substrings -

given string s of length n. string s made of lower case english alphabets. need counthow many substrings of s sorted. given string s, need count number of sorted substrings of s. a string s lexicographically sorted if s[i] ≤ s[i+1] 1 ≤ ≤ n-1 (consider 1-based indexing). example : let string s="bba" answer 4 explanation : substrings of 'bba' are: b, b, a, bb, ba, bba out of these 6 substrings, 4 ('b', 'b', 'a' , 'bb') substrings sorted. answer 4. my current solution no better brute force . check each substring , check if sorted or not. string length can 1000000 o(n^2) approach won't work out. can better solution problem ? make 2 indexes - left , right. set them both first symbol index of string. increment right while s[right] ≤ s[right+1] . when next symbol violates order, have substring ss = s[left..right] , substrings of ss sorted too. find number through ss length: k = right - left + 1 you have k on

Error While generating pig-eclipse files (Building Apache Pig from Source) -

ran following commands successfully. git clone -b spark https://github.com/apache/pig ant -dhadoopversion=23 however gives me error while generating eclipse files ant clean eclipse-files error stack below [ivy:resolve] :::::::::::::::::::::::::::::::::::::::::::::: [ivy:resolve] :: unresolved dependencies :: [ivy:resolve] :::::::::::::::::::::::::::::::::::::::::::::: [ivy:resolve] :: org.apache.hadoop#hadoop-yarn-common;1.0.4: not found [ivy:resolve] :: org.apache.hadoop#hadoop-yarn-client;1.0.4: not found [ivy:resolve] :: org.apache.hadoop#hadoop-yarn-api;1.0.4: not found [ivy:resolve] :::::::::::::::::::::::::::::::::::::::::::::: [ivy:resolve] [ivy:resolve] :: use verbose or debug message level more details full stack trace link https://gist.github.com/krishnakalyan3/b1a5c024c81ac5d211d6 current trunk generates eclipse files. eclipse has problems. opened pig-4520 discuss.

list - How do I create an error message using pickAFile() in Jython? -

i creating program various calculations list of numbers. how can show error message if presses "cancel" while choosing file pickafile() ? when cancel it, error message for line in file line. the error message is: >"the error was:stream closed > i/o operation failed. > > tried read file, , couldn't. sure file exists? > if exist, did specify correct directory/folder?" here's code: def selectfilecalculatestatistics(): fullpathname = pickafile() file = open(fullpathname, "r") listnumbers = readlistnumbers(file) min = calculateminimum(listnumbers) max = calculatemaximum(listnumbers) mean = calculatemean(listnumbers) standarddeviation = calculatestandarddeviation(listnumbers, mean) print("the minimum number list is: " + str(min)) print("the maximum number list is: \n" + str(max)) print("the mean number list is: " + str(round(mean, 2))) print("the standard devi

javascript - How to comment ejs code ( JS node) -

Image
i have code in ejs file. <table> <% for(var i=0; < data.length; i++) { %> <tr> <td><%= data[i].id %></td> <td><%= data[i].name %></td> </tr> <% } %> </table> when comment way, <!-- <table> --> <!-- <% for(var i=0; < data.length; i++) { %> --> <!-- <tr> --> <!-- <td><%= data[i].id %></td> --> <!-- <td><%= data[i].name %></td> --> <!-- </tr> --> <!-- <% } %> --> <!-- </table> --> i still have error in line 2. here stack of error referenceerror: c:\users\toumi\desktop\workspaces\eclipse\todolist\views\x.ejs:2 1| <!-- <table> --> >> 2| <!-- <% for(var i=0; < data.length; i++) { %> --> 3| <!-- <tr> --> 4| <!-- <td><%= data[i].id %></td> --> 5| <!-- <

php - Keep getting Fatal error: Function name must be a string in -

i'm not seeing quite seems there's nothing defining function here. i've tried can see php limited @ point- month or , can't seem it: error says: fatal error: function name must string in /home/ad67852/public_html/ft-adshot.com/login.php on line 35...... } else { mysql_query("update members set lastlogin = '".time()."' userid='userid'"); $_session("ulogin"); $_session['ulogin'] = true; $_session("uname"); $_session['uname'] = $userid; $_session("pw"); $_session['pw'] = $password; //header("location: /members/index.php"); i wondered if time () not defined or nothing tried has worked far! thanks in advance appreciate solving one, robert $time=time(); mysql_query("update members set `lastlogin` = '".$time."' `userid`='userid'"); $_session['ulogin']; $_

Logging data from a subprocess (python,linux) -

i'm running 2 scripts in parallel follows: import subprocess time import sleep subprocess.popen(["python3", 'tsn.py']) subprocess.popen(["python3", 'lsn.py']) the above code in file called multi.py both 'tsn.py' , 'lsn.py' logging data separate text files using file.write(). if run .py files individually log data fine, when run multi.py data logged prints on screen fine, doesn't logged in text files (i.e file.write() doesn't execute ). issue , how work around that? thanks. edit: lsn.py looks this. tsn.py same from socket import * import time servername_sen = '192.168.0.151' serverport_sen = 8080 clientsocket_sen = socket(af_inet,sock_stream) clientsocket_sen.connect((servername_sen,serverport_sen)) get='getd' status='off' logvar = 0 file = open('lsn_log.txt', 'a') while 1: time.sleep(0.5) clientsocket_sen.send(get.encode('utf-8')) print('lsn bp