Posts

Showing posts from May, 2015

jquery - convert json to another json format -

i new json. having little trouble inconverting json 1 format format. json converted. { "message": "successfully advisor data has been fetched.", "success": true, "data": { "dataheaders": ["carrier","b2b", "em"], "dataarray": { "dhl": ["dhl", "45", "5","5"], "fedex": ["fedex","40", "7","6"], "ups" : ["ups","30", "10","3"], "tnt" : ["tnt","30", "10","3"], } } } i require json converted format. [ { "key":"carrier", "values":[ { "x":"dhl", "y":45 }, { "x":"fedex", "y...

css - How to "inspect element" on scrollbar? -

with webkit, possible modify scrollbar styles. however, cannot "inspect element" on scrollbar when debugging in chrome. there workaround this? the scrollbar part of body element, not able 'inspect' non-html element. to see css styles applied scrollbar, inspect element scrollbar belongs to.

ruby on rails - Template is missing error -

i started programming ruby on rails , have problem. this controller def new_card @card = card.new end def create_card @card = card.new(params[:card]) if @card.save flash[:notice] = "card created" redirect_to :action => "card_information", :id => @card.id else render new_card_path end end def card_information @card = card.find(params[:id]) end these view files: (create_card) = form_for @card, :url => create_card_path |f| .row .span3 = f.label "card name" = f.text_field :title %br/ .row .span3 = f.submit "submit", :class => "btn btn-primary" card_information .row .span12 %h3 = @card.title and routes: match 'card_information/:id' => 'home#card_information' match 'create_card' => 'home#create_card' when try launch create card page have template missing error page showing up

bit manipulation - StringBuilder initialization in Java -

i needed use this method , , after looking @ source code, noticed stringbuilder initialization not familar me (i use no-argument constructor stringbuilder , i.e. new stringbuilder() ). in method: stringbuilder sb = new stringbuilder(items.size() << 3); from javadoc: java.lang.stringbuilder.stringbuilder(int capacity) constructs string builder no characters in , initial capacity specified capacity argument. why bit shift needed here? source code: /** creates backslash escaped string, joining items. */ public static string join(list<?> items, char separator) { stringbuilder sb = new stringbuilder(items.size() << 3); boolean first=true; (object o : items) { string item = o.tostring(); if (first) { first = false; } else { sb.append(separator); } (int i=0; i<item.length(); i++) { char ch = item.charat(i); if (ch=='\\' || ch == separator) { sb.ap...

sql - Get DISTINCT record using INNER JOIN -

i have follwong query on multi tables select distinct b.boxbarcode [box barcode], (select case when b.imagescount null 0 else b.imagescount end) [total images], s.stagename [current stage] ,d.docuementtypename [document type], u.username [start user],uu.username [finished user] [dbo].[operations] o inner join dbo.lkup_stages s on o.stageid=s.id inner join dbo.lkup_users u on u.id=o.startuserid left join dbo.lkup_users uu on uu.id=o.finisheduserid inner join boxes b on b.id=o.boxid inner join lkup_documenttypes d on d.id = b.doctypeid b.isexportfinished = 0 when select count boxes table isexportfinished = 0 got count 42 records, when run above qoury got 71 records, want 42 records in boxes table retrived. you doing one-to-many join, i.e. @ least 1 of tables have multiple rows match join criteria. step 1 find table(s) give "duplicates". once have done may able fix ...

class - C++ Getting an object -

lets have following class: static int counter = 0; class account { public: int id; int favnumber; account(int favnum) { this->id = ++counter; this->favnumber = favnum; } }; account user1(4); account user2(9); now both accounts user1 , user2 have different id unique. there way knowing id of account field of object "favnumber", if how should implemented? something getfieldbyid(int id) you may use std::map : #include <map> class account { // make attributes private. better practice int id; int favnumber; static int s_counter; //^^^^^^^^^^^^^^^^^^^^^ better move static private member of account public: account(int favnum) { this->id = ++s_counter; this->favnumber = favnum; } // getters int getfavnumber() const { return favnumber; } int getid() const { return id; } }; int account::s_counter = 0; // ^^^^^^^^^^^^^^^^^^^^^^^^ don't forget initialize account user1(4); ...

c# - Bitmap graphics: when saving on disk no drawed strings - works when memorystream -

i creating png picture, using bitmap object, using drawing.graphics . create bitmap, insert background image , draw strings. now, when save image on disk, files not have strings! i doing in asp.net mvc, controllers signature: [acceptverbs(httpverbs.get)] public string getnewsletterpicture(string headline, string tagline) when don't save image on disk , instead returns filestreamresult memorystream , image looks perfectly. so there problem when save image disk, strings "forgotten" somehow. any ideas? my code : colorconverter converter = new colorconverter(); color textcolor = (color)converter.convertfromstring("#ff58595b"); int width = 598; int height = 77; int offset = 40; int shadowoffset = 1; var bmp = new bitmap(width, height); using (graphics g = graphics.fromimage(bmp)) { g.clear(color.lightgray); image backgroundimg = new bitmap(server.ma...

android - What is the difference between setBackgroundResource and setBackgroundDrawable -

could tell me difference between setbackgroundresource(resourceid) , setbackgrounddrawable(getresource().getdrawable(drawableid)) in android? you can have @ android source code view class , find out there little difference! public void setbackgroundresource(int resid) { if (resid != 0 && resid == mbackgroundresource) { return; } drawable d= null; if (resid != 0) { d = mresources.getdrawable(resid); } setbackground(d); mbackgroundresource = resid; } and setbackground() calls through setbackgrounddrawable() ... public void setbackground(drawable background) { //noinspection deprecation setbackgrounddrawable(background); }

Paypal IPN working in IPN simulator but fail in sandbox environment -

it weird. set ipn url sandbox accounts , server able receive notifications post paypal sandbox yesterday. today checked both logs application , web server, no ipn received paypal sandbox after completed transactions other days. i logged sandbox site check if there ipn created, ipns there status showed retrying. double checked web server logs, nothing paypal except 1 sent simulator. i sure ipn url correct because didn't change @ all. tried use ipn simulator paypal developer site , working, receive notifications simulator. that's not want! wrong paypal sandbox ipn recently? please help, thank you. same problem test environment here, yesterday went fine, today no ipn requests @ all paypal sandbox status empty https://www.paypal-notify.com/eventnotification/search?eventsearchtype=productipn

asp.net mvc - jQuery event becoming unattached on load of partial view -

i using jquery fileupload plug-in ( https://github.com/blueimp/jquery-file-upload ) mvc4 app. the file upload functionality (upload , table of uploaded files) contained in partial view. so have number of views contain file upload partial view. when file uploaded, save action of attachment controller fired. handles storing of file , retrieves updated list of files particular area of site. view returned fileupload jquery , injects html div in parent page (#_attachments). all works fine in renders correctly. issue having after file upload performed , partial view reloaded via jquery, fileupload no longer works. it appears may due event no longer being attached #fileupload control. have tried using 'on' method doesn't seem work either. partial view script $(function () { $('#fileupload').fileupload({ url: "/attachment/save", done: function (e, data) { // "data.result" contain response da...

matlab - ActiveX control of Word. Select text and images -

this have done far: word = actxserver('word.application'); document = word.documents.open('c:\documents , settings\kz7213\desktop\test.docx'); selection = word.selection; selection.typetext('big finale'); selection.style='heading 1'; selection.typeparagraph; fig1 = figure('visible','off'); plot([1 2 3 4 5],[4 1 3 5 7]); print -dmeta selection.paste; selection.style='heading 1'; selection.insertcaption('figure','test figure 1'); %not working selection.style='captionstyle'; selection.typeparagraph; how can select previous entered text such "big finale" edit it, or select figure pasted selection. paste command in order make caption image? possible solution in vba ms word: 'to find text selection.find.execute findtext:="big finale", wrap:=wdwrapalways 'to select inline shape activedocument.inlineshapes(1).select alternative solution find inli...

web applications - Build an ASP.Net web app with offline functionality -

i'm in process of building asp.net (3.5) web app , wondering if knew of way there offline functionality. this needed people able 'install' web app on device (using 'add home screen' function on iphone example) , use app when offline; usage limited (there no need server calls @ point either). can done .aspx page? edit- .manifest added: cache manifest index.aspx /logo.png /main.css /main.js edit no.2- we have working offline, in fashion; works when in safari don't want in safari, want standalone app. when try run 'can't connect server error'. possible .aspx page? edit no.3 - we've got work using .html page still not yet .aspx edit no.4- it's working, although we're unsure why! added index.aspx 'network' section of cache.manifest last week (which didn't work last week!) may have helped once know sure i'll update happened! thanks help! for offline html5 applications asp.net, see link , lin...

android - NullPointerException in getView Of Adapter extends BaseAdapter -

i populating listview search in tabwidget.my list contain image , textview.without tabwidget works fines in tabwidget gives error .i have error in getview locat is 08-07 16:24:44.300: e/androidruntime(20166): fatal exception: main 08-07 16:24:44.300: e/androidruntime(20166): java.lang.nullpointerexception 08-07 16:24:44.300: e/androidruntime(20166): @ com.example.project.searchdictionaryactivity$mycustomadapter.getview(searchdictionaryactivity.java:392) 08-07 16:24:44.300: e/androidruntime(20166): @ android.widget.abslistview.obtainview(abslistview.java:2485) 08-07 16:24:44.300: e/androidruntime(20166): @ android.widget.listview.measureheightofchildren(listview.java:1250) 08-07 16:24:44.300: e/androidruntime(20166): @ android.widget.listview.onmeasure(listview.java:1161) 08-07 16:24:44.300: e/androidruntime(20166): @ android.view.view.measure(view.java:12842) 08-07 16:24:44.300: e/androidruntime(20166): @ android.view.viewgroup.measurechildwithmargins(viewgroup...

database - How to create a DB file in sqlite3 using a .schema file -

our client has provided file named db.schema. there command can use run file create .db file in sqlite3? can without having type in queries mentioned in db.schema file? please help! thanks! if file contains sql commands in correct format, sqlite3 command-line tool, , run this: sqlite3 mydatabase.db < db.schema many sqlite administration tools have functions import such file.

php - Date issue: always shows 01 Jan rather than converting to desired Date -

this question has answer here: php date format converting 4 answers i new php programming , facing strange problem, through different forums able learn how convert dates of different formats our desired formats, today not possible , given 01 jan no matter gave in variable, strange working great. code following: i using combination of date , strtotime php functions, as: $coll_date_1[$i] = $row->coll_date_1; //this 08-08 i.e 8 aug $coll_date_1[$i] = date('d m',strtotime($coll_date_1[$i])); //this return 01 jan the 1st line assigns value database variable, , 2nd line function convert them desired format. know doing silly mistake, cant seem pin point is... that happens because 08-08 not valid date format. you try adding "fake" year in front of it, 2000-08-08 , or current year, 2013-08-08 , , do $coll_date_1[$i] = 'year-...

php - How to JOIN 2 tables in MYSQL with same ID on multiple rows -

i'm having hard time figuring out. hope can me figure out. for example. have video site , in video site can submit video posts name of people play in video. don't want add 1 name can more. i'd have video.php page , in page can submit video title of video , names of people play in it. table: post ------------------------------------------- -- video_id ---- video_name ---- video_cast -- ------------------------------------------- 1 vid-1 1 2 vid-2 2 3 vid-2 2 table: cast ----------------------------------------- -- cast_id ---- cast_name ---- cast_video -- ----------------------------------------- 1 john 1 2 erik 2 3 ela 2 now if on homepage , see new post. if click on it. send video_id information in header can fetch video.php . page: video.php ...

java.lang.StackOverflowError: android.view.View.isLayoutDirectionInherited -

hi getting stackoverflow error while trying add view in layout. code: parentofallingmt.addview(layoutinflater.inflate( r.layout.layout_dstbutton, parentofallingmt, true)); here parentofallingmt linear layout , want layout_dstbutton child @ index 1. prior adding layout_dstbutton , added parentofallingmt.addview(layoutinflater.inflate( r.layout.gmt_option_list_dst_on, null, false)); which adding properly. following logcat output: 08-06 07:23:44.843: e/androidruntime(19513): java.lang.stackoverflowerror 08-06 07:23:44.843: e/androidruntime(19513): @ android.view.view.islayoutdirectioninherited(view.java:11756) 08-06 07:23:44.843: e/androidruntime(19513): @ android.view.viewgroup.resetresolvedlayoutdirection(viewgroup.java:5379) 08-06 07:23:44.843: e/androidruntime(19513): @ android.view.viewgroup.resetresolvedlayoutdirection(viewgroup.java:5380) 08-06 07:23:44.843: e/androidruntime(19513): @ android.view.viewgroup.resetresolvedlayoutdirecti...

ios - Putting links in contact in UIWebView and display on different view controller -

i have view controller in have created simple contact app using apple's addressbook, have created view controller has web view create , displays contacts , phonenumber when user click on generate button. need that, on generate contacts should hyperlinks, , when click on contact should display details of contact have done in 1st view controller. know have use delete of webview not sure how implement it, far have written. -(bool) webview:(uiwebview *)webview shouldstartloadwithrequest:(nsurlrequest *)request navigationtype:(uiwebviewnavigationtype)navigationtype { viewcontroller *latestview = [[viewcontroller alloc] initwithnibname:@"viewcontroller" bundle:nil]; [self.navigationcontroller pushviewcontroller:latestview animated:yes]; return yes; } this function generates , displays contacts in webview, in want know how add hyperlink along contact details - (ibaction)createfileaction:(id)sender { nsstring *tweet, *phonenumbers=@"", *te...

html - Force "#" links to function normally with .htaccess and <base> tags -

i'm using .htaccess achieve "pretty" urls on website. result, forced include <base> tag in headers. trying use ajax, , causes href="#" links return index page. (for example, clicking on <a href="#">link</a> on website.com/games/ returns website.com/# rather doing nothing - # link should.) how can work around this? suggestions appreciated - perhaps alternative stopping style sheets breaking .htaccess rather <base> .

forms - Ajax call back: Return variable as input value -

after ajax call need echo out variable value of hidden field. html <form ajax1> <input name="place" value="milan"> <input name=submit onclick="return submitform1()"> </form> <form ajax2> <input type="hidden" value="$place"> <input name="filter"> <input name=submit onclick="return submitform2()"> </form> <div id="result"></div> ajax call function submitform1() { var form1 = document.myform1; var datastring1 = $(form2).serialize(); $.ajax({ type:'get', url:'query.php', cache: false, data: datastring1, success: function(data){ $('#results').html(data); } }); return false; } php <? $place= $_get['place'] //do stuffs ?> it works perfectly, need add function echo out $place in value=" " of form ajax2 any appreciated

html - How to keep a link tag a different color when on that page? -

i want tag of page on in different color rest of links. example: my links white, on hover change red underline. want page on red underline. how can this? create separate style active tabs. give tab active specific style (via class or id in css)

python - Counting unique values in a pandas grouped object -

i have table in pandas/python , doing following: grouped_data = df_comments_cols['article_id'].groupby(df_comments_cols['user_id']) now count number of articles per user following: ct_grouped_data = grouped_data.count() the above counts number of article ids per user. however, there multiple of same article ids per user (in sense user has interacted article more once) , wish count unique article ids per user - there quick way this? thanks in advance. i think might looking nunique , can call on groupby objects so: in [63]: df = dataframe({'a': randn(1000, 1)}) in [64]: df['user_id'] = randint(100, 1000, size=len(df)) in [65]: df['article_id'] = randint(100, size=len(df)) in [66]: gb = df.article_id.groupby(df.user_id) in [67]: gb.nunique() out[67]: user_id 100 2 101 1 102 1 104 2 105 1 106 2 107 1 110 1 111 4 112 2 113 1 114 2 ...

c# - Initializing a List into a static method -

i have 6 operators trying push operator class. need initialise list of new operators can used effectively. i've got myself in quite mess , having fair few syntax problems, appreciated in creating list. public static list<comparisonoperator> createcomparisonoperators() { this.condition1select.items.clear(); this.condition2select.items.clear(); this.condition3select.items.clear(); this.condition4select.items.clear(); foreach (comparisonoperator op in ops) { this.condition1select.items.add(op); this.condition2select.items.add(op); this.condition3select.items.add(op); this.condition4select.items.add(op); } return new list<comparisonoperator>(); } the this statement means refer current instance. static methods don't have instance , can't use this statement. need make list static, too. comparisonoperator enumeration ops needs...

c# - Error handling of user input in a List<int> -

i have following code: list<int> moneys = new list<int>(); console.writeline("please enter cost of choice"); int money = int.parse(console.readline()); moneys.add(money); from if enter text program stops working , unhandled exception message appears. wondering how handle exception, if possible program doesn't stop working? you should use tryparse method. not throw exception if input not valid. this int money; if(int.tryparse(console.readline(), out money)) moneys.add(money);

sql - Conditional querying to return timestamp if NOT todays date , else return time -

i have sql query want retrieve timestamp records table. the query must return time without time zone if todays date = timestamp in record. if record's timestamp::date not equals todays date return timestamp. examples: 2013-08-07 18:00:18.692+01 2013-08-09 20:13:09.927+01 expected result: 18:00:18.692 2013-08-09 20:13:09.927+01 from 2 timestamps able retrieve time 1st todays date retrieve both date , time second not todays date this formatting issue, might better handle in application code. can in sql. create table t ( ts timestamp not null ); insert t values ('2013-01-01 08:00'); insert t values (current_timestamp); the time , timestamp data types aren't compatible in way want return them, casting text makes sense. select case when ts::date = current_date ts::time::text else ts::text end t; ts -- 2013-01-01 08:00:00 16:34:52.339

java - Complex query in Morphia -

in method java, pass parameter collection mongodb complex query one: {"$or": [{"$and": [{"contextid": "akka"}, {"messageid": "pippo"}]}, {"$and": [{"domain": "niguarda"}, {"hostname": {"$ne": "hostserver"}}]} ] } the string contains query variable , passed parameter in query string. i tried pass query parameter method criteria (querydb.criteria(" {"$or": [ {"$and": [{"contextid": "akka"}, {"messageid": "pippo"}]}, {"$and": [{"domain": "niguarda"}, {"hostname": {"$ne": "hostserver"}}]}] }" ) but not work. any suggestions? what you're trying query q = dao.createquery(); q.or( q.and(new criteria[]{ dao.createquery().filter("contextid").equal("akka"),...

javascript - HTML5 video source will not successfully change in IE -

i'm going nuts on problem. have script changes sources of <video> tag, reloads , plays it. problem can't work on version of internet explorer. i have array of video sources called sequence.sources , containing: sequence.sources = ['video.webm', 'video.mp4', 'video.ogv']; the sequences object loaded array, that's dynamic aspect of all. function use change video sources follows: var videoelem = document.getelementbyid('video'); // remove sources while (videoelem.firstchild) { videoelem.removechild(video.firstchild); } // add new sources (var = 0; < sequence.sources.length; i++) { var srcelem = document.createelement('source'); srcelem.setattribute('src', sequence.sources[i]); videoelem.appendchild(srcelem); } // initiate video videoelem.load(); videoelem.play(); this works on browsers ie. do? i've tried modifying src attribute of <video> tag directly, doesn't seem work. i...

java - SWTException in SWTBot-Test: Why is it thrown in Tycho+Surefire? -

i swtexception:invalid thread access of swtbot-test. turn green when started eclipse, problem must inside pom.xml guess. how solve this? i use following arguments , dependencies in pom.xml of test-fragment: <!-- language: lang-xml --> <build> <plugins> <plugin> <groupid>org.eclipse.tycho</groupid> <artifactid>tycho-surefire-plugin</artifactid> <version>${tycho.version}</version> <configuration> <testfailureignore>true</testfailureignore> <failifnotests>false</failifnotests> <forkedprocesstimeoutinseconds>300</forkedprocesstimeoutinseconds> <useuiharness>true</useuiharness> <useuithread>false</useuithread> <showeclipselog>true</showeclipselog> <dependencies> <dependency> <type>eclipse-plugin</type> <artifactid>my.host.ui.bundle</artifactid> ...

css - Vertical centring image with display table-cell not working -

im trying vertically centre image using css display table-cell. why code not working? looks should according css-tricks.css http://css-tricks.com/centering-in-the-unknown/ http://jsfiddle.net/sne4y/1/ .cont { background-color: grey; position: fixed; height: 100%; width: 100%; display: table; } img { display: table-cell; vertical-align: middle; } <div class="cont"> <img src="http://www.quarktet.com/icon-small.jpg" /> </div> the img tag doesn't need display: table-cell; , vertical-align: middle; parent does. so need: .cont { background-color: grey; position: fixed; height: 100%; width: 100%; display: table-cell; vertical-align: middle; } img { } <div class="cont"> <img src="http://www.quarktet.com/icon-small.jpg" /> </div> also, appears position: fixed giving problems, well, , had remove work here: http://jsfiddle.net...

spam - How do we 'whitelist' our website for Facebook? -

how 'whitelist' our website - when people click on link our website (www.ineed.co.uk) comes 'facebook thinks site unsafe ...' if debug site can see : inferred property 'og:url' property should explicitly provided, if value can inferred other tags. inferred property 'og:title' property should explicitly provided, if value can inferred other tags. inferred property 'og:description' property should explicitly provided, if value can inferred other tags. inferred property 'og:image' property should explicitly provided, if value can inferred other tags. fix tags in head of website , d fine.

asp.net - Why does asp:Textbox sometimes add "text" to the CSS class in the rendered html? -

this markup: <asp:textbox id="txtaddress" cssclass="s175" runat="server" maxlength="30" placeholder="street"></asp:textbox> is rendered as: <input name="ctl00$leftcolumncontent$txtaddress" type="text" maxlength="30" id="leftcolumncontent_txtaddress" class="s175 text" placeholder="street"> but on project, markup: (exactly same) <asp:textbox id="txtaddress" cssclass="s175" runat="server" maxlength="30" placeholder="street"></asp:textbox> causes happen: <input name="ctl00$contentplaceholder1$txtaddress" type="text" maxlength="30" id="contentplaceholder1_txtaddress" class="s175" placeholder="street"> why "text" class not getting applied? it's class="s175" vs class="s175 text" . ...

c# - Call method every time a controller method is ending -

i have static class called notificationmanager , every time controller method called, want store modelerrors in notificationmanager. however, inside notificationmanager, can't access modelstate because not inside actual controller. is there way automatically call method once controller method finished, without having write in every single controller method? note: need use values in view. override onactionexecuted in controller. still have viewdata[] protected override void onactionexecuted(actionexecutedcontext filtercontext) { //do stuff base.onactionexecuted(filtercontext); }

performance - Is doing this: var[property] more resource intensive than var.property? -

i'm refactor long algorithm can adapted property instead of fixed one. so, instead of having var.x have var[property], property can x, y, alpha, etc. but, question appeared, performance wise, present impact?. thanks! in relative terms yes it's slower, whether matters depends on deep specifics of application , usage patterns.

php - Directory index forbidden by Options directive error in Cakephp -

getting directory index forbidden options directive error when trying upload images not getting every time, not know exact senario, have check error_logs of apache. .htaccess in webroot `<ifmodule mod_rewrite.c> rewriteengine on rewriterule ^$ webroot/ [l] rewriterule (.*) webroot/$1 [l] </ifmodule>` i fixed using +indexes in < directory > don't know why i'm getting error images only, of ~700 kb , ~1500 x 1700 in size.

r - Behavior of do.call() in the presence of arguments without defaults -

this question follow-up previous answer raised puzzle. reproducible example previous answer: models <- list( lm(runif(10)~rnorm(10)),lm(runif(10)~rnorm(10)),lm(runif(10)~rnorm(10)) ) lm1 <- lm(runif(10)~rnorm(10)) library(functional) # works do.call( curry(anova, object=lm1), models ) # do.call( anova, models ) the question why do.call(anova, models) work fine, @roland points out? the signature anova anova(object, ...) anova calls usemethod , should* call anova.lm should call anova.lmlist , first line objects <- list(object, ...) , object doesn't exist in formulation. the thing can surmise do.call might not fill in ellipses fills in arguments without defaults , leaves ellipsis catch? if so, documented, it's new me! * clue--how usemethod know call anova.lm if first argument unspecified? there's no anova.list method or anova.default or similar... in regular function call ... captures arguments position, partial match , full mat...

java - NullPointerException when using GMapsV2Direction class -

i've been trying fix run-time error last few days no avail, not sure why it's throwing nullpointerexception when creates nodelist when getdirection method called. i'm new android programming if can offer me little guidance appreciated, thank you! edit: judging debugger latlng co-ordinates , direction type being passed through getdocument() method, document isn't being returned getdocument() method. public document getdocument(latlng start, latlng end, string mode) { string url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude + "&sensor=false&units=metric&mode=driving"; try { httpclient httpclient = new defaulthttpclient(); httpcontext localcontext = new basichttpcontext(); httppost httppost = new httppo...

javascript - Covert JS object into flat array with parent names -

i have object this: data: { connection: { type: 0, connected: false }, acceleration: { x: 0, y: 0, z: 0, watchid: 0, haserror: false } }, converting flat array this: "connected": false "haserror": false "type": 0 "watchid": 0 "x": 0 "y": 0 "z": 0 is easy task (recurrence friend!). but there way in javascript called full parents , i.e. this: "connection.connected": false "acceleration.haserror": false "connection.type": 0 "acceleration.watchid": 0 "acceleration.x": 0 "acceleration.y": 0 "acceleration.z": 0 or expecting much? another variant: function flatten(o) { var prefix = arguments[1] || "", out = arguments[2] || {}, name; (name in o) { if (o.hasownproperty(name)) { typeof o[name] === "object" ? ...

c - recvfrom not receiving depending on ai_family used -

i'm trying head around socket programming , have encountered unexpected (for me) behaviour. when try send data "localhost" , set addrinfo.ai_family af_inet message send isn't coming through client process host process (recvfrom() doesn't return). if set af_inet6 fine. same af_unspec in case picks ipv6 addrinfo (first in list). both host , client use same ai_family of course. i've tried code copy pasted beej's guide network programming had same result. i'm using dgram sockets. i tried connecting different pc got opposite results, ipv4 worked fine, ipv6 did not. gather may due me using '6to4 gateway'. have no idea means. the problem related own machine code work on ipv4 on machine tested on. can't if it's sending or receiving problem. what prevent me sending or receiving data to/from localhost using af_inet sockets? i'm on windows7 64bit machine compiling mingw. if makes difference i'm running same program host , ...

How to create a trigger in SQL Server that fires only right before the transaction will be committed -

so ran issue goes follows: - have table a. - have table b has foreign key table a. - have trigger on table ensures every item in table has @ least 1 row in table b pointing (through foreign key). - trigger runs "insert" commands. issue when insert table a, trigger raises error because table b doesn't have row foreign key new row in table yet. row on table b inserted end of transaction trigger not give me chance. solution problem? there way tell trigger run after last command in transaction executed? if need trigger fire on table a, not know if there corresponding rows in table b, should use "instead of" trigger. allow check table b before inserting rows table a. if there match in table b, proceed insert a, otherwise, add row b , a, or skip data doesnt match , return error application. http://msdn.microsoft.com/en-us/library/ms175521(v=sql.105).aspx

c++ - std::bad_alloc assigning a pointer from address of a reference -

for whatever reason, ended code looked this typedef std::vector<double> vector; void f(vector const& v) { vector const* p; p = &v; } this throws bad_alloc exception @ point of assignment. why? matter f called on non-cast vector? c++03 compiled on gcc 4.1. ** edit ** inside code running inside google mock see exception. tried tear code out , compile separately , worked fine. looking further ** further edit ** problem assignment happened in last line of constructor of object member of object. next object in initializer list of parent object exception coming from, gdb made happening on last line of previous object's constructor assignment taking place. downvotes remind me how misguided question was. there no possible way code can raise std::bad_alloc exception (or other exception, matter), since doing assigning pointer value pointer variable. std::bad_alloc raised new , new[] operators when memory allocation fails, , there no such memory al...

mysql - How can I Update column value to Old value plus New value from other table using Trigger? -

how can update column value old value plus new value other table using trigger if value has have entry? wanted following. notice bold , italicized part. delimiter$$ create trigger trigger_name after insert on table_one each row begin insert table_two(clmn_id, clmn_one) values(new.clmn_id_fk,new.clmn_a) on duplicate key update clmn_one = values( clmn_one + new.clmn_a ); end$$ delimiter; try removing keyword values on duplicate key: delimiter$$ create trigger trigger_name after insert on table_one each row begin insert table_two(clmn_id, clmn_one) values(new.clmn_id_fk,new.clmn_a) on duplicate key update fine_amount = clmn_one + new.clmn_a; end$$ delimiter;

Binary search in an ordered list in java -

im looking way implement code in java works same way binary search in ordered arraylist ordered list thanks the algorithm should same both arraylist , list , given both ordered.

Tornado + SQLAlchemy non-blocking DB calls -

i'm relatively new application development here goes nothing. i've been working on project employs use of tornado server , sqlalchemy's orm database management/access (using postgres in end). at outset of project hadn't considered possibility using sqlalchemy prevent me taking advantage of tornado's async features (since sqlalchemy's database calls apparently 'block' thread). do have suggestions how implement async-compatible setup tornado+sqla+postgres? take @ aiopg - https://github.com/aio-libs/aiopg it python 3.4 asyncio adapter postgres includes sqlalchemy support. haven't tried myself yet, found while looking async libraries postgres , tornado. using momoko, supplies raw psycopg2 layer. remember latest version of tornado supports asyncio, asyncio libraries work tornado.

cocoa touch - How do you change button text dynamically when button is subview of a custom cell in iOS? -

i making ios app , has table view prototype cells. configure cells in cellforrowatindexpath method , works fine, come trouble when want change text in button after created. want changes button text when tap button. tried do: [button settitle:@"change" forstate:uicontrolstatenormal]; inside of clickmethod runs when click the button, changes text in last cell no matter button press. tried above doesn't work because have multiple instances of same button.(one in every row) know how can change text of button click on only. code creates button: - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath: (nsindexpath *)indexpath { cell = [tableview dequeuereusablecellwithidentifier:@"cell" forindexpath:indexpath]; //configure cell button = [uibutton buttonwithtype:uibuttontyperoundedrect]; [button addtarget:self action:@selector(clickmethod:) forcontrolevents:uicontroleventtouchupinside]; [button settitle:@"button" forstate:u...

BasicHttpBinding Error - Xamarin -

problem not calling wcf function using basichttpbinding , showing error. no host route error comes on visual studio. unhandled exception: system.net.webexception: error: connectfailure (no route host) using system; using system.collections.generic; using system.linq; using monotouch.foundation; using monotouch.uikit; using helloworld_app4.localhost; namespace helloworld_app4 { public class application { // main entry point of application. static void main(string[] args) { // if want use different application delegate class "appdelegate" // can specify here. localhost.service1 obj = new localhost.service1(); obj.getdata(32, true); uiapplication.main(args, null, "appdelegate"); } } } what license have got? if have indie license wont allowed access web/wcf services , have rely on rest services. i found out hard way switched ot using asp.net web...

verilog - What division algorithm should be used for dividing small integers in hardware? -

i need multiply integer ranging 0-1023 1023 , divide result number ranging 1-1023 in hardware (verilog/fpga implementation). multiplication straight forward since can away shifting 10 bits (and if needed i'll subtract 1023). division little interesting though. area/power arent't critical me (i'm in fpga resources there). latency (within reason) isn't big deal long can pipeline deisgn. there several choices different trade offs, i'm wondering if there's "obvious" or "no brainer" algorithm situation this. given limited range of operands , abundance of resources have (bram etc) i'm wondering if there isn't obvious do. if can work fixed point precision rather integers may possible change : divide result number ranging 1-1023 to multiplication number ranging 1 - 1/1023, ie pre-compute divide , store coefficient multiply.

java - JAXB enoding issue when marshalling to System.out -

Image
i'm trying print console java bean, unmarshalled http response. have issues encoding. here's part of response: <?xml version="1.0" encoding="utf-8" standalone="yes"?> <response> <errormsg>Ä°Ã…Ÿleminizi ...</errormsg> </response> my method is: public void printtoconsole() { try { jaxbcontext context = jaxbcontext.newinstance(response.class); marshaller marshaller = context.createmarshaller(); marshaller.setproperty(marshaller.jaxb_formatted_output, boolean.true); marshaller.setproperty(marshaller.jaxb_encoding, "utf-8"); marshaller.marshal(this, system.out); } catch (jaxbexception e) { e.printstacktrace(); } } by viewing bean values debugger, they're shown correctly in debugger's pop-up(eclipse ide) thanks the problem using default console settings, not able print utf-8 characters properly. make sure co...

uitableview - iOS neither init or initWithCoder are been called -

i add tableview viewcontroller , need initialize properties. neither -(id)init or - (id)initwithcoder:(nscoder*)adecoder been called. my header file: @interface myviewcontroller : uiviewcontroller <uitableviewdelegate,uitableviewdatasource> any of knows why or how can either init methods call? i appreciate help the uiviewcontroller reference states initwithnibname:bundle: designated initializer. that's 1 should override if you're doing stuff during initialization. update: right, pointed out simon, override initwithcoder: if you're using storyboard (though assume op not, said initwithcoder: not getting called).

ruby on rails - Heroku errors [was working yesterday] -

i keep getting these error's in heroku logs every time i've tried deploy today. app working fine last night, i'm not sure what's changed since since haven't done new. song_controller.rb class songscontroller < applicationcontroller before_filter :authenticate_user!, only: [:create ,:edit, :update, :destroy, :vote_for_song] before_action :set_song, only: [:show, :edit, :update, :destroy, :vote_for_song] def extract_video @song = song.find(params[:id]) @song.youtubeaddy.extract_video_id end def vote_for @song = song.find(params[:id]) current_user.vote_for(@song) @song.plusminus = @song.votes_for @song.save respond_to |format| format.js { render 'update_votes' } end end def vote_against @song = song.find(params[:id]) current_user.vote_against(@song) respond_to |format| format.js { render 'update_votes' } end end def new_songs @songs = song.order(...