Posts

Showing posts from March, 2012

timer - Best way to schedule tasks in vb.net -

i need execute commandline on hour , half past hour. there better ways this? maybe ones don't involve checking hour every second. timer 1 second interval: private sub timer1_tick(byval sender system.object, byval e system.eventargs) handles timer1.tick integer = 0 24 if timestring = & ":00:00" & or timestring = "0" & & ":00:00 or if timestring = & "30:00:" & or timestring = "0" & & ":30:00 end if next end sub step 1 - calculate time next hour or half hour mark; step 2 - set timer's elapsed period equal time calculated in step 1; step 3 - when timer ticks, reset elapsed time 30 minutes , work need do. if process has run on hour / half hour recalculate time needed in step3 rather setting 30 minutes (this compensate drifting). here code calculate milliseconds midnight; should able work there private function millisecondstomidnigh

importerror - Python Circular Import - Works locally but not on server -

background information python 2.7.1 (r271:86832) on server , locally using virtualenv dependencies same local python 64 bit server python 32 bit using django actual problem we hit circular import problem on our server wasn't caught during testing. doing trivial circular import example shows circular imports indeed erroring locally. we stuck prints @ top of each file gets imported. local behaviour: priority.__init__.py sync.tasks.keywords.py priority.reasons.py priority.__init__.py (<- circular import works??) priority.reasons.py server behaviour: priority.__init__.py sync.tasks.keywords.py priority.__init__.py (<- circular import works??) traceback (most recent call last): ... sync.tasks.keywords import check_keywords importerror: cannot import name check_keywords i'm baffled. code same. i'm double baffled fact import chain different before erroring well. so... tips on start looking? i suggest break circular import

jquery - Animate click toggle -

i animate div when click (click toggle in example).i want animate initial position when click again. (i try variable , if, not work. perhaps there easier way? or there mistake?) please check answer here: http://jsfiddle.net/uxvxh/2/ html: <div id="logo"></div> css: #logo { position:fixed; bottom:-40px;left: 5%; width:70px; height:80px; background:blue; cursor:pointer; } jquery: $(function(){ /* click simple $("#logo").click(function() { $("#logo").animate({bottom: "0"}, 1200) }); */ /*click toggle ?*/ var hidden = true; $("#logo").click(function() { if (hidden) { $("#logo").animate({bottom: "0"}, 1200); } else { $("#logo").animate({bottom: "-40"}, 1200); } state = !hidden; }); }) your example working did little mistake change state hidden variable. var

c# 4.0 - Dynamic ViewModel Generation in asp.net mvc 3 -

i attempting ambitious on asp.net mvc 3 backed c sharp 4.0 . without further trash talk point . i have build web application in can make simple forms ( cms type application) . the usual approach take design form in cshtml , , viewmodel. the viewmodel takes care of validation rules , error messages etc. have allow user create form . i sat write down on piece of paper on how go . able generate form , based on user inputs , have reached deadend , how create viewmodel @ runtime ? for example if in database , konw form called "registration" , has control "textbox" , take string , required public class registrationviewmodel { [required(errormessage="cant let go buddy")] public string name {get;set;} } i wish type views such viewmodels , not sure how dynamically construct c# class based on data have inside database. i not sure if c# has constructs achieve purpose , new .net platform . i want know if there approach can generate viewmodels

c# - Asp.Net - Export two Gridviews to excel or pdf -

i have page shows 2 grids side side; "expenses" , "income". want user able export excel or pdf or print it's shown on web page, side side. how can it? what's best practice? thanks. probably reporting services (ssrs) in case sql server

iphone - Writing orignal image with exif to Document Directory folder from ALAsset object -

i want save alasset imagearray directly document directory exif tried png conversion, jpeg conversion nothing worked creating new image either jpg or png (loss of exif) i have seen time save nsdata directly folder preserve exif dont know how i getting metadata alasset object result nsdictionary *metadata = [[result defaultrepresentation] metadata]; another assets array list of images alassetsgroupenumerationresultsblock assetenumerator = ^(alasset *result, nsuinteger index, bool *stop) { if(result != null) { [assets addobject:result]; ; nslog(@"assets %i",[assets count]); self.progressview.progress = (float)index / ([assets count]-1); } saving images document directory folder -(void)saveimagestodocumentdirectory{ nslog(@"assets count %i",[assets count]); for(int i=0;i<[assets count];i++) { currentimage = [uiimage imagewithcgimage:[[[assets objectatindex:i] def

ios - Align two different text on single line in iphone sdk -

Image
i have uilabel , uibutton , text changing dynamic except uilabel , want show them single label , should center align on single line both work differently show in picture underline text "the gluten free foodie" has clickable feature unlike text found by . don't know how accomplish task if text of button in picture "the gluten free foodie" come long how can move label left show in picture. in advance. try this: nsstring *text1 = @"found "; //text of uilabel cgsize constraint1 = cgsizemake(320, 2000); //suppose total width of superview 320 cgsize size1 = [text1 sizewithfont:[uifont fontwithname:@"arialmt" size:12.0] constrainedtosize:constraint1 linebreakmode:uilinebreakmodewordwrap]; //font used in "found by" label nsstring *text2 = @"the gluten free foodie"; //text of uibutton cgsize constraint2 = cgsizemake(320, 2000); cgsize size2 = [text2 sizewithfont:[uifont fontwithname:@"arial-boldmt"

spring - Handle Connection and Read Timeouts for RestClient calls in android -

i have restservice interface many rest calls using throughout application. i setting timeouts handling connection , read-timeouts clienthttprequestfactory httpfactory = myrestservice.getresttemplate().getrequestfactory(); if(httpfactory!=null) { if(httpfactory instanceof simpleclienthttprequestfactory) { ((simpleclienthttprequestfactory)httpfactory).setconnecttimeout(10*1000); ((simpleclienthttprequestfactory)httpfactory).setreadtimeout(30*1000); } else if(httpfactory instanceof httpcomponentsclienthttprequestfactory) { ((httpcomponentsclienthttprequestfactory)httpfactory).setconnecttimeout(10*1000); ((httpcomponentsclienthttprequestfactory)httpfactory).setreadtimeout(30*1000); } } but stuck handling timeout situation. thought of using method not coming loop when rest call fails. myrestservice.getresttemplate().seterrorhandler(new responseerrorhandler() {

mono - Covariance broken in C# arrays? -

consider following generic interface itest covariant type parameter t , generic class test implementing interface, , class a , subclass b : interface itest<out t> {     t prop{ get;} } class test<t> : itest<t> {     public t prop{ { return default(t);     }} } class {     } class b: {     } the following code compiles no errors throws runtime exception system.arraytypemismatchexception : itest<a>[] = new itest<a>[1]; a[0] = new test<b>(); //<-- throws runtime exception but code works fine: itest<a> r = new test<b>(); this has tested on mono 2.10.2 ( unity3d 4.1 ). think somehow related broken covariance in arrays (see http://blogs.msdn.com/b/ericlippert/archive/2007/10/17/covariance-and-contravariance-in-c-part-two-array-covariance.aspx ). i not clear why type-check happening when array slot assigned not taking covariance account. i have compiled , tested given code in vs2010 using .net

c# - SendKeys.Send function not working -

i want press shift + tab on event , using system.windows.forms.sendkeys.send purpose not working , tried below ways call function. system.windows.forms.application.doevents(); sendkeys.send("{+(tab)}"); system.windows.forms.application.doevents(); sendkeys.send("+{tab}"); system.windows.forms.application.doevents(); sendkeys.send("{+}{tab}"); system.windows.forms.application.doevents(); sendkeys.send("+{tab 1}"); can tell me right way ? the proper syntax is: sendkeys.send("+{tab}"); in light of comment trying implement pressing shift+tab cycle between control fields, note can done more reliably without emulating keys. avoids issues where, instance, window has focus. following method emulate behavior of shift_tab, cycling through tab stops in reverse order: void emulateshifttab() { // form elements can focused var tabcontrols = thi

c# - How to Pick up values from datagrid ,search the database and update new values? -

i have datagrid , in have many rows. want pick 2 columns 1 row 1 column search database row value , second column update row new value. please help. my code giving syntax error incorrect syntax near keyword 'values' my code { using (sqlconnection con = new system.data.sqlclient.sqlconnection("data source=rex;initial catalog=personaldetails;integrated security=true")) { con.open(); (int = 0; <= datagridview2.rows.count - 1; i++) { string insertdata = "update test set availableqty = " + "values (@qty) itemcode = " + "values (@itemcode) "; sqlcommand cmd = new sqlcommand(insertdata, con); cmd.parameters.addwithvalue("@itemcode", datagridview2.rows[i].cells[0].value ?? dbnull.value); cmd.parameters.addwithvalue("@qty", datagridview2.rows[i].cells[4].value

c++ - Single template instantiation for separate objects -

consider following: /* t.h */ template <class t> void too() { std::cout << " template: " << typeid(t).name() << " size: " << sizeof(t) << std::endl; } /* a.h */ extern void fooa(); /* a.cpp */ struct local { int a[2]; } void fooa() { local l; std::cout << "<foo a>:\n" << " real: " << typeid(l).name() << " size: " << sizeof(l) << std::endl; too<local>(); } /* b.h */ extern void foob(); /* b.cpp */ struct local { int a[4]; }; void foob() { local l; std::cout << "<foo b>:\n" << " real: " << typeid(l).name() \ << " size: " << sizeof(l) << std::endl; too<local>(); } /* main.cpp */ int main() { fooa(); foob(); return 0; } compiling , running results in: <foo

java - How to parse this queryString which is a resultant of JSON response -

i have parsed json response , got string below : string querystring = "aqb=1&v1=somev1data&v25=somev25data&url=http://www.someurl.com/configure/getvalues/request1=req1passed&data2=somedatapassed&ce=utf-8&arb=1"; when split above querystring output should : aqb=1 v1=somev1data v25=somev25data url=http://www.someurl.com/configure/getvalues/request1=req1passed&data2=somedatapassed ce=utf-8 arb=1 note : querystring changes , url parameters changes. aqb,v1.....v30,p1....p30,ce,pre,pe,url,arb predefined variable names. it not possible unless url parameter url-encoded, "&" characters escaped in order not interpreted field separators. the string should encoded this: string querystring = "aqb=1&v1=somev1data&v25=somev25data&url=http%3a%2f%2fwww.someurl.com%2fconfigure%2fgetvalues%2frequest1%3dreq1passed%26data2%3dsomedatapassed&ce=utf-8&arb=1"; as formatted in question, string cannot pa

javascript - HighCharts Time-based Quarterly Data - xAxis Label Issue -

we displaying dynamic data on our site. user can select different types of time periods such monthly, quarterly, annual, decennial, etc. our issue comes in trying show quarterly data cleanly on xaxis. can use formatter show tool-tip correctly "q1 2008". want have xaxis similar. partially there think doing fat-finger error here. example on jsfiddle . the code trying work in xaxis label [formatter][2] : xaxis: { alternategridcolor: '#fafafa', labels: { style: { fontsize: '9px', width: '175px' }, formatter: function () { var s; if (highcharts.dateformat('%b', this.value) == 'jan') { s = s + "q1" }; if (highcharts.dateformat('%b', this.value) == 'apr') { s = s + "q2&

c# - How to avoid the 0-byte file on Webclient download error -

when using following code download file: webclient wc = new webclient(); wc.downloadfilecompleted += new system.componentmodel.asynccompletedeventhandler(wc_downloadfilecompleted); wc.downloadfileasync("http://path/file, "localpath/file"); and error occurs during download (no internet connection, file not found, etc.) allocates 0-byte file in localpath/file can quite annoying. is there way avoid in clean way? (i probe 0 byte files on download error , delete it, dont think recommended solution) if reverse engineer code webclient.downloadfile see filestream instantiated before download begins. why file created if download fails. there's no way ammend code should cosnider different approach. there many ways approach problem. consider using webclient.downloaddata rather webclient.downloadfile , creating or writing file when download complete , sure have data want. webclient client = new webclient(); client.downloaddatacompleted += (sender, e

Can't hover the child menu while creating css menu -

i trying create simple css menu following structure: <section id="navigation-bar" class="container"> <nav class="pull-left"> <ul class="multicolumnmenu"> <li> <a href="#">menu 1</a> <div class="column-menu"> <ul> <li> sub menu 1 </li> <li> sub menu 2 </li> <li> sub menu 3 </li> <li> sub menu 4 </li> <li> sub menu 5 </li> </ul> </div> </li> ... </ul> </nav> </section> i trigger menu css .multicolumnmenu > li:hover .column-menu{ display: block; } the menu shows can't hover on it.

oracle - SQL join allowing only one match from each table -

i have 2 tables. 1 table has coupons allocated each customer , other table has redemption information each customer. need left coupons redeemed each campaign , if upc overlaps 2 campaigns counted both (but not counted twice within 1 campaign). here's idea of redemtion table | customer_id | upc | redeem_date_id | |-------------|------|----------------| | 1234 | 3456 | 42 | | 1234 | 3456 | 43 | | 1234 | 3456 | 44 | | 1234 | 3456 | 49 | and table coupons allocated looks | customer_id | campaign_id | upc | print_date_id | expire_date_id | |-------------|-------------|------|---------------|----------------| | 1234 | 1 | 3456 | 35 | 45 | | 1234 | 1 | 3456 | 40 | 50 | | 1234 | 2 | 3456 | 41 | 51 | in example customer has more redemptions allocated coupons (because could'v

java - Non-English characters appear as ? marks -

in servlet application i'm passing french text url parameter. firefox works fine, ie9 shows me ? marks. why , how can solve that? is there web browser charset problem? have try set <meta charset='utf-8'> ?

osx snow leopard - Unable to install rvm on mac OSX 10.6.8 -

i've been unsuccessfully trying install rvm on snow leopard, everysingle way tried ended in same way: $ \curl -l https://get.rvm.io | bash -s stable --ruby=1.9.3 % total % received % xferd average speed time time time current dload upload total spent left speed 100 13707 100 13707 0 0 8880 0 0:00:01 0:00:01 --:--:-- 33350 please read , follow further instructions. press enter continue. downloading rvm wayneeseguin branch stable % total % received % xferd average speed time time time current dload upload total spent left speed 100 1062k 100 1062k 0 0 198k 0 0:00:05 0:00:05 --:--:-- 288k tar: unrecognized option `--strip-components' pour en savoir davantage, faites: `tar --help'. not extract rvm sources. thanks help this happen tar version fink , try ls -l /sw/bin/gtar - in case not use fink remove rm -rf /s

vb.net - Make a form that behaves like a message box in vb 2010 -

my app based on visual basic 2010/2012 (all codes same both languages). want open registration form above parent form such responding registration form becomes necessary user message box. can suggest me code. , please don't suggest complex one. irritates. :) thanks in advance. open registration form using showdialog() dim f frmregistration = new frmregistration() f.showdialog() the showdialog method used display modal dialog box . modal dialog box blocks execution of code following call until dialog box closed.

Sybase ASE - INSERT INTO statment i stored procedure, problems in formating string -

i have following problem formatting @p_f_field variable correct, error: could not execute statement. incorrect syntax near ‘+’ sybase error code=102, sqlstate=”42000” severity level=15, state=181, transaction state=1 line 7 my stored procedure: create proc dbo.sp_m_efi_dw_full_dsa_table_load_im ( -- parameter examples: @p_skm_name varchar(4096), @p_usr_name varchar(4096), @p_t_name_dsa varchar(4096), @p_t_name_bas varchar(4096), @p_f_name varchar(4096), @p_f_field varchar(4096) ) begin declare @sql varchar(4096) if @p_skm_name not null begin if @p_usr_name not null begin set @sql='truncate table '+@p_skm_name+'.'+@p_usr_name+'.'+@p_t_name_dsa exec (@sql) end end set @sql='insert '+@p_skm_name+'.'+@p_usr_name+'.'+@p_t_name_dsa+' '+@p_f_name+ ' values '+@p_f_field exec (@sql) end my call stored procedure: execute bas_efi.dbo.sp_m_efi_dw_full_dsa_table_load_im @p_skm_name = 'b_ef', @p_usr_name

Custom Android TabHost Slow Fragments -

i use actionbarsherlock , slidingmenu. my mainactivity not access db , no parsing of ever. static. tabs generated dynamicly depending on "section" choose slidingmenu. after 2 click app becomes awefully slow. below main view. <tabhost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" > <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <tabwidget android:id="@android:id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" /> <framelayout android:id="@+id/content_frame"

MDX Calculate SUm at a fixed level in hierarchy -

i have hieracy defined level1 level5 , beneath id. create calculated member makes sum @ level4. currentmember.parent works @ level5 not @ id level. what better way ? ok, found it, ancestors can specify @ leve want it. with member measures.temp sum(ancestors([master product].[product tree].currentmember,[master product].[product tree].[ibs level 4]), [measures].[qty master product]) select non empty { [measures].[qty master product], [measures].[qty cross product], measures.temp } on columns, non empty { [master product].[product tree].[ibs level 5] } on rows [its cross sales] ( [complex].[by country].[complex].&[3], [dates].[calender].[date].&[2013-03-17t00:00:00] )

c++ - Initializer but incomplete type? -

the following code gives me 2 errors when compile #include <iostream> #include <fstream> #include <cstring> #include "translator.h" using namespace std; void dictionary::translate(char out_s[], const char s[]) { int i; char englishword[max_num_words][max_word_len]; (i=0;i < numentries; i++) { if (strcmp(englishword[i], s)==0) break; } if (i<numentries) strcpy(out_s,elvishword[i]); } char translator::toelvish(const char elvish_line[],const char english_line[]) { int j=0; char temp_eng_words[2000][50]; //char temp_elv_words[2000][50]; not sure if need std::string str = english_line; std:: istringstream stm(str); string word; while( stm >> word) // read white-space delimited tokens 1 one { int k=0; strcpy (temp_eng_words[k],word.c_str()); k++; } (int i=0; i<2000;i++) // error: out_s not declared in scope { di

CSS menu transitions not working -

i'm trying add transition effects onto css dropdown menu, wherever put transition code in doesn't seem work. transition: 2s ease-in; i'm trying transition fade in , out on hover of parent li of actual dropdown ul event doesn't happen suddenly. jsfiddle: http://jsfiddle.net/jazparkyn/6jshy/5/ you cannot transition display property. try using opacity dropdown menus. nav ul ul { opacity: 0; visibility: hidden; transition: .5s ease-in; -o-transition: .5s ease-in; -ms-transition: .5s ease-in; -moz-transition: .5s ease-in; -webkit-transition: .5s ease-in; } nav ul li:hover > ul { visibility: visible; opacity: 1; } see demo .

Slow response from Neo4j Embedded Server for several seconds when it starts -

i running neo4j server in embedded mode. facing performance related issue while server getting several seconds after fine. where shutting server down there no log says database returning inconsistent state it's fine shutdown , startup of neo4j server. even loaded reference node getting property out of it. still slow seconds.

c# - .ics files not opening in Chrome Mobile for Apple Devices -

i'm getting error 102 (): unknown file type. when trying download .ics file asp.net application. file looks this: begin:vcalendar prodid:-//test version:2.0 method:publish begin:vevent uid:uid class:public dtstart:20130506t173000 dtend:20130506t190000 description;encoding=quoted-printable: $2500? summary:smoking cessation may priority:0 location:armc theater end:vevent end:vcalendar my response code in c# this: httpcontext.current.response.clear(); httpcontext.current.response.addheader("content-disposition", string.format("attachment;filename={0}.ics", "example")); httpcontext.current.response.contenttype = "text/calendar"; httpcontext.current.response.write(calendardata.tostring()); httpcontext.current.response.end(); any suggestions? everything i've read says it's not possible through chrome mobile. if find answer, i'd interested well. if it's help, know it's possible through safari mobile. ans

c# - NullReferenceException with Auto-Generated Tables -

i have problem exception nullreferenceexception ... class auto generated ef , contains list of icollection , list supposed initialized in constructor when trying add items list shows exception. internal partial class customer : person { partial void objectpropertychanged(string propertyname); public customer() { this.accounts = new hashset<account>(); this.customerupdates = new hashset<customerupdate>(); } public virtual icollection<account> accounts { get; set; } public virtual icollection<customerupdate> customerupdates { get; set; } } the exception thrown when trying add item collection. "this.accounts.add()" internal partial class customer : person, icustomer { internal customer(guid userid, string firstname, string surname) : base(userid, firstname, surname) { } //list of customer accounts ienumerable<iaccount> icustomer.accounts { { return accounts.asenum

jQuery / Javascript - else if statement not reaching else if -

i'm relatively new jquery / javascript i've come across looks simple snag solve, , can't see what's wrong. sorry if ends being simple i've searched loads no end. i'm trying various divs fade in or out depending on whether 'visible' or not. divs 'pages' want advance when 'next' arrow clicked. here's jquery: $(document).ready(function(){ $("#page1 > div").hide(); $("#page2 > div").hide(); $("#page3 > div").hide(); $("#page1 > div").fadein(800); $("#nextarrow").click(function(){ if($("#page1").is(":visible")){ $("#page1 > div").fadeout(800); $("#page2 > div").fadein(800); } else if($("#page2").is(":visible")){ $("#page2 > div").fadeout(800); $("#page3 > div").fadein(800); } else { a

railo - ColdFusion - Collection loop in cfscript -

i have tag based syntax works in railo. <cfloop collection="#myarray#" item="j" index="i"></cfloop> the above allows me access index 'i' , item itself, 'j'. i want same in cfscript, used: for ( in myarray) {} however, 'i' gives me item ...how can access index value? as work-around, have had manually count index so: j = 1; ( in myarray) { j++; } but feels dirty. in syntax of cfscript allow true alternative cfloop's collection? i have tried google searching of never decent result. there way rewrite in loop allow me access index too? thanks, mikey. it's not possible in coldfusion , i'm afraid, other work-around using, or using indexed loop. however in railo, there (rather awful tag/script hybrid syntax): <cfscript> loop array=[5,4,3,2,1] index="i" item="v" { writeoutput("[#i#][#v#]<br>"); } </cfscript> so

How to take care of duplicates while copying files to a folder in python -

i writing script in python consolidate images in different folders single folder. there possibility of multiple image files same names. how handle in python? need rename "image_name_0001", "image_name_0002" this. you can maintain dict count of names have been seen far , use os.rename() rename file new name. for example: dic = {} list_of_files = ["a","a","b","c","b","d","a"] f in list_of_files: if f in dic: dic[f] += 1 new_name = "{0}_{1:03d}".format(f,dic[f]) print new_name else: dic[f] = 0 print f output: a a_001 b c b_001 d a_002

iphone - Supporting old iOS versions and devices -

i need ios app compatible previous ios versions, @ least 4.0, , prior devices (iphone 4s, 4, 3gs... , ipad devices). found posts dealing ios versions backwards compatibility have years (for example, how build against older ios versions latest xcode downloads? ), , don´t know if deprecated or still way proceed, @ least concerning app building. regarding programming issues, guess should check documentation know if sdk features/libraries/frameworks want use supported ios versions want compatible... , having such information, how check programmatically ios version device running, in order provide feature or not? on other hand, regarding ios versions , devices running them: find apple document listing ios versions supports each existing device? hardware-dependent issues should take account while developing app? thanks edit: target architecture(s) hardware consideration i've take account? knowing that, example, iphone 3gs able run, , running, ios 6.1.3, can assume device suppor

python - "Underlying C/C++ object has been deleted" -

i'm having exception running simple application in python 2.7 qt. code: # *-* coding: utf-8 *-* __author__ = 'luismasuelli' import sys pyqt4 import qtgui class streamwidget(qtgui.qwidget): def __init__(self): super(streamwidget, self).__init__(self) self.initialize() def initialize(self): self.setwindowtitle("stream capture test") self.resize(400, 300) self.center() self.show() def center(self): qr = self.framegeometry() cp = qtgui.qdesktopwidget().availablegeometry().center() qr.movecenter(cp) self.move(qr.topleft()) def main(): app = qtgui.qapplication(sys.argv) window = streamwidget() sys.exit(app.exec_()) main() sh*t: runtimeerror: underlying c/c++ object has been deleted (at super() call line) what error , how can solve it? appreciated. got error! passed parameter (self) without noticing it. i'm noob @ , seems parameter p

c++ - reading from file, gcount() is always 0 even after several file.get() -

i'm trying read file using file.get() seems stuck in first line. input file like: 1234,56 7891,01 ....... this code: char* n1 = new char[5]; char* n2 = new char[3]; std::ifstream data("input_file"); while (i < 4) { data.get(n1, 5); printf("%ld\n", data.gcount()); data.get(n2, 3); printf("%ld\n", data.gcount()); //read newline data.get(&ch, 2); printf("%ld\n", data.gcount()); printf("n1= %s, n2 = %s\n", n1, n2+1); } output: 0 0 0 n1= 1234, n2 = 56 0 0 0 n1= 1234, n2 = 56 0 0 0 n1= 1234, n2 = 56 i'm not able make sense of this. get(char*, streamsize) gets stuck encounters newline delimiter. need use getline() advance next line. also, second get() reads 2 characters stream (i.e read ",5" instead of ",56" first line.

ruby on rails - How to appending a Form_For block to a Target div with in coffe.erb file? -

here want accomplish: let user enter home address via form return results ajax call on page have button on each result allows me save attribute of home @home object via remote call. i appending results of ajax call <div id="search-results"> . within div have link looks <a href="#9090090"> home id </a> . when user clicks link want create new instance of home model :alt_home_id => 9090090 (which href attribute text of link). these links being appended in coffee.erb file: if results.home_id? targetdiv.append '<a href="#9090090"> home id </a>' i tried doing this: searchresults.append '<%= form_for property.new, |f| %> <%= f.text_field :alt_home_id %> <%= f.submit %><% end %>' without line breaks of course. this gives me error of unexpected keyword_do_block is best way create 1 new object 1 attribute being created. have considered writing ajax call grab id , creat

c - TCP Checksum Calculation Changing - tcp offloading is disabled -

i manipulating tcp packets using netfilter, have recalculate tcp , ip checksums working expected. wireshark reports checksums correct on way out of server (which matches client thinks should well), when reach client checksum replaced 0xaa6a. in post routing hook, calculating tcp checksum follows... after manipulating addresses/ports. tcp_header->check = 0; tcp_header->check = tcp_v4_check(tcp_len, ip_header->saddr, ip_header->daddr, csum_partial((char *)tcp_header, tcp_len, 0)); the ip checksum fine using ip_send_check(ip_header); the server not have tcp offloading enabled rx or tx , not support it, unsupported error when attempting enable or disable. offload parameters eth0: rx-checksumming: off tx-checksumming: off scatter-gather: off tcp-segmentation-offload: off udp-fragmentation-offload: off generic-segmentation-offload: off generic-receive-offload: on large-receive-offload: off rx-vlan-offload: off tx-vlan-offload: off ntuple-filters: of

SQLite Database on Android Not Storing Int Properly -

i creating android application keep track of recipes. able store , retrieve recipes, is_favorite value not working correctly. when send boolean value (based on whether checkbox checked or not), correctly sent helper.insert function: public recipe insert(string name, boolean isfavorite, string servingsize, string time, string instructions) { contentvalues values = new contentvalues(); values.put("name", name); values.put("is_favorite", (isfavorite) ? 1 : 0); values.put("serving_size", servingsize); values.put("time", time); values.put("instructions", instructions); long id = databasehelper.getwritabledatabase().insert(database_table, null, values); } when @ values , is_favorite 1 if isfavorite true , 0 if isfavorite false, want. but when helper.getbyid(int id) recipe created, returns 0 is_favorite column, no matter value put in there. query pretty sta

loops - Iterating over a 2 dimensional python list -

this question has answer here: iterating through multidimensional array in python 6 answers i have created 2 dimension array like: rows =3 columns= 2 mylist = [[0 x in range(columns)] x in range(rows)] in range(rows): j in range(columns): mylist[i][j] = '%s,%s'%(i,j) print mylist printing list gives output: [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ] where each list item string of format 'row,column' now given list, want iterate through in order: '0,0' '1,0' '2,0' '0,1' '1,1' '2,1' that iterate through 1st column 2nd column , on. how do loop ? this question pertains pure python list while question marked same pertains numpy arrays. different use zip , itertools.chain . like: >>> itertools import cha

javascript - JSFiddle - Use POST request error -

i've looked @ several other questions same error, don't seem quite match i'm doing. i'm working angularjs app & trying pagination within jsfiddle . when click on link, error: {"error": "please use post request"} most sources need change form method. no using or post, not sure hangup happening. tried setting breakpoints, didn't much. help appreciated! note- same error message: need select "run" & click on link when first link jsfiddle works because frame shows http://fiddle.jshell.net/enigmarm/l7csd/6/show/ . when click run posts form http://fiddle.jshell.net/_display/ render page. going http://fiddle.jshell.net/_display/ in browser (ie: using get) give error. you have href="" means clicking regets page using verb instead of post created rendered page. don't put href="" on or stop requesting page.

python - create view similar to another one -

i have make changes in django project , though i'm familiar python, i'm not django. this situation: i have table field "active". need let users sort table based on value of field (yes/no). i looked views.py , realized there view sorts table based on id: users = user.objects.all().order_by('id') my questions are: how can make view sort table based on url parameter? do have create view or can use same kind of modifications? you can use same view. def myview(request): get_param = request.get.get('my_param', 'id') #some more processing users = user.objects.order_by(get_param) #note - dont need `all()` #rest of code here.

pyqt application performing updates -

i have pyqt application ready release. it's first attempt on gui thing bare me. works pretty , have 1 more thing wrap up. love software updates itself: check url new version; new version found; notify user of updates (click) → update . the problem don't know how perform update. check, find new version, download , must close application , execute installer of new version. if close can't execute else, if execute installer can't close application. based on user choices program downloads , installs third party software needs same thing: close before install program, restart after install program. after downloading installer newer version, can use atexit.register() os.exec*() run installer, e.g. atexit.register(os.execl, "installer.exe", "installer.exe") . make installer start when application exit. application exit after os.exec*() call, no race condition occur.

Updating Activerecord queries to rails 3.2 format : find(:all) to all -

i updating active record queries of rails project. have not been able find out how update when query is foo.find(:all, :stuff, :id, :thing, @bar) i know how handle regular. find(:all) or .find(:all, :conditions => {} ( find(:first) , find(:all) deprecated ) have not found on if, example, model user, find users use: user.all and specific conditions, use: user.where(neck: "long")

Google Chrome JavaScript Fade: style.opacity and setTimeout -

i have javascript script fade element. the gist this: function fade() { if (cat.style.opacity > 0) { // decrease opacity cat.style.opacity -= 0.1; // call fade again in fraction of second settimeout( fade, 60 ); } else { cat.style.visibility = "hidden"; } } ( full code here http://xahlee.info/js/js_fadeout.html , javascript code here: http://xahlee.info/js/js_fadeout.js ) in google chrome, doesn't fade completely. seems loop stuck , style.opacity never reaches 0. on stackoverflow, seems google chrome bug post year ago, never confirmed. seems strange, major bug. know why doesn't work in google chrome? this appears precision issue. can around pretty using .tofixed precision need. cat.style.opacity = (cat.style.opacity - 0.1).tofixed(2); http://jsfiddle.net/ggpqc/

sql - how do I use a string returned as an ajax response to assign to a php variable -

i select option drop down menu(id="field"), , on basis of value wish generate drop down menu, use ajax retrieve value of field1 input. function is: function showbranches(degree) { var xmlhttp=false; if (window.xmlhttprequest) {// code ie7+, firefox, chrome, opera, safari xmlhttp=new xmlhttprequest(); } else {// code ie6, ie5 xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.open("post","sors/sendegree.php?degree="+degree,true); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readystate==4 && xmlhttp.status == 200) { document.getelementbyid('br').innerhtml=xmlhttp.responsetext; } } xmlhttp.send(null); } code in sendegree.php file simply <?php echo $_request['degree']; ?> now try receive string returned ajax code php variable using statement: <?php $state="<span id=\"br\"></span>"; echo $state; ?>

Unable to call servlet from javascript -

i calling servlet using code: document.location.href= '${pagecontext.request.contextpath}/dropdown'; while function called using onload when page gets loaded, getting following http 404 error: $%7bpagecontext.request.contextpath%7d

python - Djangonic way to get second order DB-info in Django? -

i'm messing around first django site , far it's going good. facing challenge of getting information db. model looks this: class countries(models.model): country = models.charfield(max_length=100) def __unicode__(self): return self.country class organisationtypes(models.model): organisation_type = models.charfield(max_length=100) def __unicode__(self): return self.organisation_type class organisations(models.model): organisation_name = models.charfield(max_length=200) organisation_type = models.foreignkey(organisationtypes) country_of_origin = models.foreignkey(countries) def __unicode__(self): return self.organisation_name class locations(models.model): organisation = models.foreignkey(organisations) country_of_location = models.foreignkey(countries) tel_nr = models.charfield(max_length=15) address = models.charfield(max_length=100) def __unicode__(self): return '%s - %s - %s - %s&#

android - Disable some tabs when using ViewPagerIndicator -

i trying create wizard type of functionality in android app, couple of steps need followed. each of steps represented in own fragment , fragments placed in fragmentpager. using viewpagerindicator [1] well. what i'm interested in somehow have of steps "disabled" (so not allowing user scroll corresponding fragments, although tab headers visible ). user able navigate step 1's tab @ beginning, (after validation) tabs 1 , 2, 1, 2 , 3 , on... any ideas best way implement this? [1] - http://viewpagerindicator.com/ thanks have try add fragments when user pass validation? after validation in fragmenttab1, add fragmenttab2 pageadapter , notifydatasetchange after every new addition. if pageadapter class of library doesnt it, you'll need rewrite methods or create own pageadapter.

android - ERROR: attempt to index global object a nil value: corona SDK -

i'm getting error: runtime error ...n-stylr\documents\corona projects\happy_day\game.lau:50: attempt index global 'city1' (a nil value) my code follows: function scene:createscene(event) local screengroup = self.view local background = display.newimage("background1.jpg") local city1 = display.newimage("bild.png") city1:setreferencepoint(display.bottomleftreferencepoint) city1.x = 0 city1.y = 640 city1.speed = 1 local city2 = display.newimage("bild.png") city2:setreferencepoint(display.bottomleftreferencepoint) city2.x = 1136 city2.y = 640 city2.speed = 1 local city3 = display.newimage("build2.png") city3:setreferencepoint(display.bottomleftreferencepoint) city3.x = 0 city3.y = 640 city3.speed = 2 local city4 = display.newimage("build2.png") city4:setreferencepoint(display.bottomleftreferencepoint) city4.x = 1136 city4.y = 640 city4.speed = 2 end function scene:enterscene(event) runtime:addeventlistener(&quo

jsf 2 - display growl when page is loaded primefaces jsf2 -

i have commandbutton : <p:commandbutton value="enregistrer" action="#{reglementclientmb.ajouter}" process="@this @form" update="@form" > <f:setpropertyactionlistener target="#{reglementclientmb.est_ajouter}" value="false" /> </p:commandbutton> the action method return page , want display 1 p:growl when next page loaded i tested put constructor of managed bean growl displayed below data in page facescontext.getcurrentinstance().addmessage( null, new facesmessage(facesmessage.severity_info, "" + "confirmation", "réglement crée avec sucée")); requestcontext.getcurrentinstance().update("messages"); how can achieve this thank in advance the bean's constructor may late job if <p:growl> rendered before be

Push a git local repository to github -

i new in git. learning git. while pushing repo in github got errors below. $ git push origin master ssh: connect host github.com port 22: bad file number fatal: not read remote repository. please make sure have correct access rights , repository exists. what can solution ?? thanks foysal

python - numpy.arange divide by zero errror -

i have used numpy's arange funciton make following range: a = n.arange(0,5,1/2) this variable works fine itself, when try putting anywhere in script error says zerodivisionerror: division 0 first, step evaluates 0 (on python 2.x is). second, may want check np.linspace if want use non-integer step. docstring: arange([start,] stop[, step,], dtype=none) return evenly spaced values within given interval. [...] when using non-integer step, such 0.1, results not consistent. better use ``linspace`` these cases. in [1]: import numpy np in [2]: 1/2 out[2]: 0 in [3]: 1/2. out[3]: 0.5 in [4]: np.arange(0, 5, 1/2.) # use float out[4]: array([ 0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])

indexing - Simple MySQL WHERE query not using Index -

quick answer: query condition needs same type column use index. trying search char column numeric condition. i have table 15 million rows. have column called 'ticket' can occur multiple times wouldn't occur many times . . . less 10. have created index on column explain command says when using simple 'where ticket =' query not using index. confuses me asking question here. create table company1.rtable ( `adate` date default null, `fromd` date default null, `pno` int(10) default null, `ticket` char(11) default null, `r` int(11) unsigned not null default '0', `line` tinyint(3) unsigned default null, `nnum` char(11) not null, `pkey` char(7) default null, `modnum` char(4) default null, `dnum` smallint(5) unsigned not null, `rdnum` smallint(5) unsigned default null, `ptype` int(10) default null, `lnum` decimal(9,2) default null, `lineamount` decimal(9,2) default null, `amount` decimal(9,2) default null, `amount1` decima

batch file - I dont run mi script junit by .bat -

i read other questions a: "how run junit testcases command line?" , "how run junit test command line java [duplicate]" still can not run script file .bat: java -cp c:\users\psanchez\documents\eclipse\plugins\org.junit_4.10.0.v4_10_0_v20120426-0900\junit.jar org.junit.runner.junitcore c:\users\psanchez\eclipseworks\buscarjava\bin\serarch bjava.class what happens when try run it? it's hard what's wrong based on you've given us.

php - Edit Value in MySQL Database -

i trying edit value of integer in database through php, here code using $query = "update bremners stud_name = john set stud_goal = stud_goal + 1"; bremners table , in table there column name of person (stud_name) tried making if stud_name = john change int represents number of goals john has, column has number of goals stud_goal. tried increasing value 1. try this: $query = "update bremners set stud_goal = stud_goal + 1 stud_name = 'john'"; in php start this: <?php $mysqli = new mysqli("localhost", "root", "", "test"); $name = "bill"; $increment = 1; if ($stmt = $mysqli->prepare("update bremners set stud_goal = stud_goal + ? stud_name = ?")) { $stmt->bind_param("is", $increment, $name); $stmt->execute(); printf("%d row affected.\n", $stmt->affected_rows); $stmt->close(); } $mysqli->close(); ?> if need change mu

css - How to show tags on tumblr when you hover over a picture? -

i got new theme ( http://soeststhemes.tumblr.com/casual ) unfortunately doesn't show tags. i'd show tags when hover on image, know how on html? in blog: http://yixing.tumblr.com/ tags shows @ side when hover mouse on it since theme doesn't have tags, you're going have add them in. take @ this useful guide tumblr has on creating custom themes. first, need html structure. simple section tags: div box appearing if post has tags, link each tag separated space. must pasted after each instance of <div class="entry"> shows types of posts. {block:hastags} <div id="tags"> {block:tags}<a href="{tagurl}">{tag}</a>&nbsp;{/block:tags} </div> {/block:hastags} now css makes appear , disappear upon hovering post, formatting it. should placed before {customcss} in html code, along theme's css. added lines make section more fluid theme. #tags { /* positions tags section */ po

c# - Reading text into a richtextbox -

i have problem, wanna read out text file richtextbox , use method, load textbox : private void richtextbox1_textchanged(object sender, eventargs e) { richtextbox1.text = file.readalltext(@"c:\users\textfile1.txt", encoding.default); } the problem is, shows me text if press letter on keyboard, "a" or "b". searched in google, couldn't find similar. hope can me here ;) btw: using visual studio express 2012 you use textchanged event display text file , try put same code form load or other event want

In Enterprise Architect, how to add print lines to the UML diagram? -

Image
i want see how uml diagram divided printing, can rearrange diagram better fitting entire blocks page. i want following interms of dividing diagram printing. after seeing how print, want rearrange blocks. ctrl+a mark , paste complete paint best option viewing... windows photo viewer open diagram's properties dialog , on "diagram" tab there option "show page border (current diagram)".

scheme - Accessing a variable field within a node -

hi new racket using binary tree structure. using following structure (define-struct human(age hight)) i have created following object/variable/human (define james(make-human 10 50)) if have node in binary tree structure (define-struct node (left human right)) how can compare different object's hight (say michael) james given james within node, example: (define (insert-human-into-tree human node) (cond [(empty? node)(make-node empty human empty)] [(<= human-hight( **node-human-hight**)) i need know how access hight field of human object within node ( node-human-hight ). use accessor procedures in struct, example: (define-struct human(age hight)) (define james (make-human 10 50)) (define-struct node (left human right)) (define anode (make-node null james null)) ; access human in node, , height of human (human-hight (node-human anode)) => 50 ... , it's spelled "height", not "hight". so, answer question, compa

How to code PHP function that displays a specific div from external file if div called by getElementById has no value? -

thank answering question quickly. did more digging , found solution grabbing data external file , specific div , posting document using php domdocument. i'm looking improve code adding if condition grab data different div if 1 called getelementbyid has data. here code got far. external html source. <div id="tab1_header" class="cushycms"><h2>meeting - 12:00pm 3:00pm</h2></div> my php file calling source looks this. <?php $source = "user_data.htm"; $dom = new domdocument(); $dom->loadhtmlfile($source); $dom->preservewhitespace = false; $tab1_header = $dom->getelementbyid('tab1_header'); ?> <html> <head> <title></title> </head> <body> <div><h2><?php echo $tab1_header->nodevalue; ?></h2></div> </body> </html> the following function output message if div id can't found but... if(!tab1_header) {

Python: Loops for simultaneous operation, Two or possibly more? -

this question closely relates how run 2 python loops concurrently? i'll put in clearer manner: questioner asks in above link, like for in [1,2,3], j in [3,2,1]: print i,j cmp(i,j) #do_something(i,j) but l1: in [1,2,3] , j in [3,2,1]: doesnt work q1. amusing happened here: in [1,2,3], j in [3,2,1]: print i,j [1, 2, 3] 0 false 0 q2. how make l1 work? not multithreading or parallelism really. (it's 2 concurrent tasks not loop inside loop) , compare result of two. here lists numbers. case not numbers: for in f_iterate1() , j in f_iterate2(): update: abarnert below right, had j defined somewhere. is: >>> in [1,2,3], j in [3,2,1]: print i,j traceback (most recent call last): file "<pyshell#142>", line 1, in <module> in [1,2,3], j in [3,2,1]: nameerror: name 'j' not defined and not looking zip 2 iteration functions! process them simultaneously in loop situation. , question still rema

asp.net - System.AccessViolationException in .NET 4.0 while connecting to SQL Database -

i have created following code dim connectionstring string = configurationmanager.connectionstrings("default").connectionstring dim con new sqlconnection(connectionstring) con.open() response.write("connection opened<br/>") con.close() response.write("connection closed<br/>") in web application project target .net framework 4.0 giving system.accessviolationexception cannot understand why. if change target framework .net 3.0 code runs fine. below detailed exception system.accessviolationexception unhandled hresult=-2147467261 message=attempted read or write protected memory. indication other memory corrupt. source=system.data stacktrace: @ sniaddprovider(sni_conn* , providernum , void* ) @ sninativemethodwrapper.sniaddprovider(safehandle pconn, providerenum providerenum, uint32& info) @ system.data.sqlclient.tdsparser.consumepreloginhandshake(boolean encrypt, boolean trustservercert, boolean inte