Posts

Showing posts from February, 2013

java - assigning an array to a specific index of another array -

how can assign array "spider" array "visualone" @ index [n][i]? (the last line of code stuck) time! public class tester1 { public static void main(string[] args) { char[] spider = new char[]{'^','@','^'}; int = 0; int rows = 12; int columns = 12; int spoutlength = 12; int climbheight = 7; int framespaces = 3; char[][] visualone = new char[climbheight][spoutlength]; (int n=0;n<(visualone[0].length);n++){ system.out.println(); (i=0; i<visualone.length; i++){ visualone[n][i]={spider}; } } } use: visualone[n] = spider; copy reference of spider nth row of visualone.

Ruby on Windows: Cannot install mysql2 gem - Failed to build gem native extension -

i tried follow posts here , there but i'm near enough reach truth answer problem. is there else i'm missing here? d:\projects\ruby\cms>gem install mysql2 --platform=ruby -- '--with-mysql-dir="c:\mysql-connector-c-6.1.3-winx64"' temporarily enhancing path include devkit... building native extensions. take while... error: error installing mysql2: error: failed build gem native extension. c:/railsinstaller/ruby1.9.3/bin/ruby.exe extconf.rb --with-mysql-dir="c:\mysql-connector-c-6.1.3-winx64" checking ruby/thread.h... no checking rb_thread_blocking_region()... yes checking rb_wait_for_single_fd()... yes checking rb_hash_dup()... yes checking rb_intern3()... yes ----- using --with-mysql-dir=c:\mysql-connector-c-6.1.3-winx64 ----- checking main() in -llibmysql... yes checking mysql.h... yes checking errmsg.h... yes checking mysqld_error.h... yes ----- setting rpath /lib ----- creating makefile make generating mysql2-i386-mingw32.d

event handling - Corona SDK - Cancel timer from within Widget Candy button onPress handler -

i trying cancel timer within onpress event handler of widget candy button. however, timerid nil though have defined local variable within file scope. new lua development assuming issue has variable scope having difficulty figuring out way access timer variable without making true global variable (i.e. declaring without "local" keyword). see code snippet below. local countdowntimer = timer.performwithdelay(1000, handlecountdowntimer, countdown); local answerbutton1 = wcandy.newbutton { x = "center", y = "55%", width = "75%", name = "mybutton1", theme = "theme_1", border = {"normal",6,1, .12,.12,0,.4, .72,.72,.72,.6}, presscolor = {1,1,1,.25}, caption = "touch me!", textalign = "center", fontsize = "40", onpress = function( eventdata ) timer.cancel(countdowntimer); -- "countdowntimer" nil!!! local b

SQL value at min query without join -

quite have solve following problem. suppose have 3 columns: col a, col b, col c. col contain date need group on. col b contains value need find minimum each group in col a. , col c contains data find minimum occurred, pull value col c corresponding min in col b. i commonly solve problem, writing join statement. know better solution, without join? problem seem common me image make sense create dedicated sql command. finding value of function @ point of minimum (from math point of view) regards, update. i apologize not posting example of mean. here table: location quantity street new york 2 broad new york 3 main pittsburgh 1 grove pittsburgh 5 school austin 7 hayes austin 2 barn i group "location" , choose min in "quantity" each group. find "street" corresponding each min value. here how final o

class - Problems with random # generators in c# (EDITED) -

edited i have in main, set objects , call player class. sorry lack of comments in code. player myplayer; myplayer = new player(); hiders[] myhiders = new hiders[4]; (i = 0; < 4; i++) { myhiders[i] = new hiders(); } while (foundall == false) { myplayer.move(); (i = 0; < 4; i++) { myhiders[i].displaydistance(myplayer.x, myplayer.y); } (i = 0; < 4; i++) { myhiders[i].checkcapture(myplayer.x, myplayer.y); } foundall = true; (i = 0; < 4; i++) { if (myhiders[i].found == false) { foundall = false; } } } console.writeline("you win!"); and these classes class player { public int x; public int y; public void move() { string buffer; console.writeline("where move?"); buffer = console.readline(

Should you always use with when printing to files in python -

from have seen, there 2 ways print file: method 1 file = open('myfile.txt', 'a') file.write('sup') # later on file.write('yo') # @ end file.close() method 2 with open('myfile.txt', 'a') f: f.write('sup') # later on open('myfile.txt', 'a') f: f.write('yo') the problem first method, if program end abruptly, file not close , not saved. because of this, using , reopening file everytime want print it. however, realize may bad idea considering append file every 5 seconds. there major performance hit in reopening file "with" before printing every time? , if so, how should handle abrupt endings result in file not being closed using first method. in first method, want flush changes file system after done set of writes. i.e.: file.flush() for simple had in example, yes should use with open... interacting files.

c# - Load one control after another in aspx page -

i have asp.net page loading content using javascript. loading content third party. and have image should loaded after javascript generates content in but happens image showing before content loaded div, bit in appropriate. please suggest me method other way around. i have put code sample this. in aspx page. <body> <div id="bodydiv" runat="server"> <script src="//platform.linkedin.com/in.js" type="text/javascript"></script> <script type="in/companyprofile" data-id="xxxxx" data-format="inline"></script> <a id="closelink" href="http://www.xyz.com" class="closedbutton" runat="server"> <img id="closeimg" runat="server" src="images/remove.png" /></a> </div></body> what method should use load image after content javascript loaded. thanks ! your image loading p

jquery - Slideshow CSS background -

i looking way background image on css flip through set of images(3-4). whether solution through jquery, css or whatever, willing implement it. i new coding, here have far. my css .global-header { min-height:600px; background-image: url("assets/bgimages/head_sandwichman.jpg"); background-size: cover; text-align: center; and html <header class="container global-header"> <div class="inner-w"> <div class='rmm' data-menu-style = "minimal"> <ul> <li><a href="index.html">home</a></li> <li><a href="menu.html">menu</a></li> <li><a href="findus.html">find us</a></li> <li><a href="about.html">about</a></li> </ul> </div> <div class="large-logo-wrap"> <img src="

node.js - NodeJS, MongoDB: Database read/write strategy for performance -

this first attempt @ web application db access i'm not sure accepted way of doing db write/read. in basic terms, application have 1 user updating field in db (a number) , many other users read (through rest api). updating of number not frequent (maybe once per minute) reads can more that, 100/minute. understand low rate of db write/reads wouldn't matter direct read db, want know strategies typically used in web applications. for example, better maintain number variable in memory , serve reads, don't need access db each time, , write db (and re-fetch value memory) when there update field. or better read db each read entry. i apologize if question vague. put nodejs , monogdb tags because that's i'm using in app. thank you.

JSON.NET DeserializeXmlNode to XML Attributes -

how can convert json xml using json.net this: {data : [{s1 :3, s2 :4}, {s1 :1, s2:9}]} to <data s1="3" s2="4" /><data s1="1" s2="9" /> once you've parsed object, pass function this. ienumerable<xelement> getattributeddataelements(jobject obj, string membername) { return jobject o in obj[membername].asjenumerable() select createnode(membername, o); } xelement createnode(string membername, jobject obj) { return new xelement(membername, jproperty m in obj.asjenumerable() select createnode(m) ); } xobject createnode(jproperty member) { var value = member.value; switch (value.type) { case jtokentype.string: case jtokentype.integer: return new xattribute(member.name, value); default: // assuming others objects return createnode(member.name, (jobject)value); } }

python - How to calculate time difference easily in hour-minute-second format -

i want calculate time differences 1 one in following. how in easy way ? 00:00:01.97-00:00:01.43 = 0.44 (unit:second) data 00:00:01.43 00:00:01.97 00:00:02.50 00:00:03.04 00:00:03.54 00:00:04.04 00:00:04.57 00:00:05.11 00:00:05.61 00:00:06.14 00:00:06.64 00:00:07.14 00:00:07.64 00:00:08.18 00:00:08.68 00:00:09.18 00:00:09.21 here's 1 way it: from datetime import datetime import itertools data = """00:00:01.43 00:00:01.97 00:00:02.50 00:00:03.04 00:00:03.54 00:00:04.04 00:00:04.57 00:00:05.11 00:00:05.61 00:00:06.14 00:00:06.64 00:00:07.14 00:00:07.64 00:00:08.18 00:00:08.68 00:00:09.18 00:00:09.21""" def pairs(iterable): a, b = itertools.tee(iterable) next(b, none) return itertools.izip(a, b) format = "%h:%m:%s.%f" before, after in pairs(data.split()): before_dt = datetime.strptime(before, format) after_dt = datetime.strptime(after, format) difference = (after_dt - before_dt).t

c - Bind to a veth interface -

trying bind code veth interface . need create raw_socket this. creating veth interface using ip link add veth10 type veth peer veth10p can me code connecting 1 end of veth connection (i.e. veth10 in example). you need interface index first - under linux can use struct ifreq , ioctl . have written own arp request not need can observe code understand working interfaces (name -> index) https://github.com/petrbel/pvu2/blob/master/arp-request/arp.c#l59 hope helped little

c# - What's the issue with this WPF binding -

what's issue wpf binding <textbox name="tagnumbertextbox" style="{staticresource textboxstyle}" width="200" charactercasing="upper" text="{binding tags, path=[0]}"/> i getting error on text="{binding tags, path=[0]}" the property 'path' set more once. however expecting issue because of wcf service binding. wcf service not being invoked. wpf screen has datacontext has 1 of property tags observable collection. trying bind first element of collection. when create binding of form {binding foo} , foo component property path. shorthand form can omit path= component. therefore {binding tags, path=[0]} setting path both tags , [0] . i suspect wanting {binding path=tags[0]} - or in shorthand form {binding tags[0]}

html5 - Media queries not working properly in nodejs -

the media queries of html code works in desktop. when integrated nodejs media queries not responding in desktops. works in devices android , iphone. want fix because windows phone not responding media queries desktop after nodejs integration. for example: @media (max-width: 768px) { css code } works in iphones , androids expected.but ignored in desktop , windows phones, when used nodejs. can please me this. make sure when integrate stuff node, html still loading css file properly. node server-side, media-queries client-side. thing integration node can is: not serve files client-side. most probably: client not loading css file. check browser's console , should see error message(s).

android - i want to upadate the password through a alert dialog by setting user timings? -

Image
i want update password through alert dialog setting user timings?suppose want set time after 1miniute, after 1 minute want reset passsword through alert,how can send notification after time when app open.

javascript - retaining checkbox and POP Up to add more -

i have made form in person puts details. after completing form , submitting it, want popup should ask "do want add more?","yes or no ?". if yes chosen, values filled in form should retained , rest should appear blank. on no page should freshened blank. able retain values of drop down items , text fields,but not able retain values of check box items. check box code : <label>hotel facilities</label> </td><td class="row1"> :</td> <td class="row1" width="70%"> <div style=" font-weight:normal; color: #4b4b4b;font-size: 12px; width:260px; background:#d2d2d2; max-height:300px; overflow:scroll;overflow-x:hidden;"> <?php $dcs=mysql_query("select * `tblfacility` `type`='rm'"); while($dc=mysql_fetch_array($dcs)){?> <input type="checkbox" n

How to create a temporary table in ORACLE with READ ONLY access -

i using create global temporary table script create temporary table in oracle db showing sql error: ora-01031: insufficient privileges . want create temp table read access. plz me out in this. what trying achieve is: we have create table in destination database greenplum. in source database(oracle) getting select query user example: "select * abc join def d on a.col1=d.col1" creating temp table(in case of oracle) on top of example "create global temporary table table101 (select * abc join def d on a.col1=d.col1)". then using temp table required information information_schema example "select * all_tab_columns table_name='table101' ".by column_name,data_type,character_maximum_length etc information. using information can "create table statement" using javascript . then store create table statement in variable & run in execute row script(step in pentaho data integration tool) create table in destination db. problem have rea

ios - Setting an background image over an image set for a UIImageView - Objective C -

i setting images uiimage programmatically. want add play button on view. think of facebook in how there play button on image. trying figure out on do. here setting of uiimage : uiimage *img = [uiimage imagenamed:[nsstring stringwithformat:@"%d.jpg", indexpath.row]]; cell.photoview.image = img; suggestions, thoughts? you can add playbutton either uibutton or uiimageview , add subview photoview . [cell.photoview addsubview:urplaybuttonview];

PHP opendir(), sorting by date -

i have script retrieves files directory , need sort files date. latest photos uploaded top of list. please advise anyone? <? $slozka = "./gallery/holiday/"; //select folder want list files $thumb= "thumb"; //the name of folder thumbnails $vypis = opendir($slozka); //open folder $celkem = '0'; //beginning number of photos while (false!==($file = readdir($vypis))) //reading files { if($file!="."&&$file!=".."&&!is_dir($file)&&$file!=$thumb) //search through folder { $celkem++; //count number of pictures $filetitle = $file; $nahrada = array("_", ".jpg", ".png", ".gif"); $filetitle = str_replace($nahrada, " ", "$filetitle"); if (file_exists($slozka.$thumb.'/'.$file)) { //if there preview , display .. echo "<li><a href=\"gallery/holiday/".$file."

html - Why can't I change list-style in css (OpenCart)? -

i'm not able affect list-style in website through css. "bullets" disappeared lists of sudden , there nothing in css file disable them. for example here product page: http://www.azores-store.com/rollup/rollup-85cm/roll-up-premium-85 the list starts "nykyaikainen muotoilu". if @ source code of page can see ul , li tags don't have attributes, defaults. now if @ css file: http://www.azores-store.com/catalog/view/theme/adefault2/stylesheet/stylesheet.css there's nothing disable bullets lists. have tried referring list class has no effect. i'm confused here... in advance help! because of padding removal. default, lists have 40px padding-left value. if remove ul, ul li{/* list-style: none; */} css, , give ul padding-left value, see disc.

c# - How to position a TextBlock always at the bottom of the view -

i want put textblock @ bottom of view inform users something. each of views height different, user use scrollviewer scroll view. want no matter how long view is, textblock @ bottom of view, user need not scroll scrollbar bottom of view see message . can help? add 2 grids. 1 purpose add view , second information text below. <grid> <grid.rowdefinitions> <rowdefinition height="*"/> <rowdefinition height="30"/> </grid.rowdefinitions> <!-- main grid in scrollviewer--> <scrollviewer> <grid grid.row="0" > </grid> </scrollviewer> <!-- information text @ bottom --> <grid grid.row="1"> <textblock text="your message" horizontalalignment="center" verticalalignment="bottom"/> </grid> </grid>

ArgumentError: wrong number of arguments in Ruby -

trying solve problem, class person def initialize(name) @name=name end def greet(other_name) puts "hi #{other_name}, name #{name}" end end initialize("ak") greet("aks") but getting error like: argumenterror: wrong number of arguments calling `initialize` (1 0) i don't understand asking here, if argument why error (1 0). can me understand problem. look @ code: class person attr_reader :name def initialize( name ) puts "initializing person instance #{object_id}" @name = name end def greet( name ) puts "hi #{name}, i'm #{name()}" end end when wrote initialize without explicit receiver: initialize( "ak" ) it matter of luck message recognized. has responded: method( :initialize ).owner #=> basicobject basicobject , foremother of object instances, herself responded call, scolding wrong number of arguments, bec

google maps - How to implement GMSMarker drag drop on GMSMapView? -

i set marker on google map when drag it's of map drag. i want drag marker when click , drag on it's and drag map when click , drag outside marker. this code self.camera = [gmscameraposition camerawithlatitude:-33.86 longitude:151.20 zoom:6 bearing:0 viewingangle:0]; self.map = [gmsmapview mapwithframe:self.mapview.bounds camera:self.camera]; self.map.mylocationenabled = yes; self.map.delegate = self; gmsmarker *marker = [[gmsmarker alloc] init]; marker.position = self.camera.target; marker.draggable = yes; marker.title = @"sydney"; marker.snippet = @"australia"; marker.map = self.map; marker.icon = [gmsmarker markerimagewithcolor:[uicolor bluecolor]]; marker.appearanimation = kgmsmarkeranimationpop; [self.mapview addsubview:self.map]; and event on drag drop - (void) mapview:(gmsmapview *)mapview didbegindraggingmarker:(gmsmarker *)marker { } - (void) mapview:(gmsmapview *)mapview didenddraggingmarker:(gmsmarker *)marker { } - (void) m

php - 30 seconds response time just in GET request, why? -

i trying add rss feeds on wordpress site. plug-in called wp rss multi-importer, , based on simplepie . i've tested my feed url in simplepie demo website , works. fast. however, request page contains feed takes 30 seconds! , fails sometimes. doesn't happen on other pages. if don't mind, attached website page i'm testing out here . edit: forgot website hosted in computer running in wamp. if have ftp/cpanel than, add set_time_limit(0); @ top of wp-config.php . this set the maximum execution time . 0 means unlimited , if want specify custom timeout, add numbers in seconds, eg:- set_time_limit(60); means 60seconds . more information ..

android - Fragments and Activities -

i have main activity hosting 3 fragments. want pass data activity(which hosts form) 1 of fragment in main activity. main activity uses viewpager host 3 fragments. how possible? that depends on data want pass, guess packing data bundle instance job. when create intent launch activity, can set arguments on it. , later use arguments when creating fragments. take @ this(from intent class): public intent putextra (string name, bundle value) public bundle getextras ()

javascript - BxSlider in small res issue - wrong slide loading after control left/right -

i have simple bx-slider here . after shrink browser window small size 360 slides in recentsoldcarousel act strange. when click on left/right control can see correct slide , after slide blink , - wrong slide loading. here code: $('#recentsoldcarousel .carousel-inner').bxslider({ slidewidth: 247, minslides: 1, maxslides: 3, moveslides: 3, pager: false, slidemargin: 10, startslide: 0, touchenabled: true, onetoonetouch: true, preventdefaultswipex: true, preventdefaultswipey: true, autodirection: 'next', }); i'm newbe in jquery if can me gratefull.

ios - how to know if UIButton titlelable.text changed -

i want know how can fire function when button title change ? tried use command nothing work : [button addtarget:self action:@selector(function:) forcontrol:uicontroleventvaluechange]; you can use observer in viewcontroller has outlet button: first add observer (in viewdidload example) [self.button addobserver:self forkeypath:@"titlelabel.text" options:nskeyvalueobservingoptionnew context:null]; override default observer method on viewcontroller - (void)observevalueforkeypath:(nsstring *)keypath ofobject:(id)object change:(nsdictionary *)change context:(void *)context { if ([keypath isequaltostring:@"titlelabel.text"]) { // value changed uibutton *button = object; nsstring *title = button.titlelabel.text; } } remove observer in dealloc function [self.button removeobse

Mule MySQL Connector -

i'm trying connect mule mysql database, using tutorial (very new in mule): http://www.mulesoft.org/connectors/mysql-connector i've come way down, step 6 (test listitems). if go url specified, i'm getting error: failed route event via endpoint: defaultoutboundendpoint{endpointuri=jdbc://selectall, connector=eejdbcconnector { name=database lifecycle=start this=5b3808ad numberofconcurrenttransactedreceivers=4 createmultipletransactedreceivers=false connected=true supportedprotocols=[jdbc] serviceoverrides=<none> } , name='endpoint.jdbc.selectall', mep=request_response, properties={querytimeout=-1}, transactionconfig=transaction{factory=null, action=indifferent, timeout=0}, deleteunacceptedmessages=false, initialstate=started, responsetimeout=10000, endpointencoding=utf-8, disabletransporttransformer=false}. message payload of type: string i've been searching quite long time now, can't find solution. maybe guys can me out? th

How to print the name of sub-directory in python? -

this question has answer here: python - how find files , skip directories in os.listdir 4 answers i want name of sub-directories in python, eg : folder hav sub folders a,b,c,d ect... i want name of folders inside folders a,b,c, ... os.listdir() should trick.

syntax - How to escape quotation marks when initializing a unix/shell command in python? -

i using target.write command write line line4 = "do echo "$i|$( geoiplookup -f /usr/share/geoip/geoip.dat $i | cut -d' ' -f4 -n | sed -e 's/,$//' -e '/^$/d' )" >> $output;".format(name) but face error : file "m.py", line 8 target.write('output=/var/www/html/result/{0}/rips.txt;\necho > $output;\nfor in $( cat /var/www/html/result/{0}/pwips.txt );\ndo echo "$i|$( geoiplookup -f /usr/share/geoip/geoip.dat $i | cut -d' ' -f4 -n | sed -e 's/,$//' -e '/^$/d' )" >> $output;;\ndone'.format(name)) ^ syntaxerror: invalid syntax also removed code | sed -e 's/,$//' -e '/^$/d' but got the file without ' strings after -d ? any ?

iphone - Custom Toolbar in navigation control in ios doesnot show button text (add button + and edit button text in this case) -

//adding right bar add button uibarbuttonitem *addbarbutton=[[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemadd target:self action:@selector(insertdata)]; //self.navigationitem.rightbarbuttonitem=addbarbutton; uitoolbar *toolbar=[[uitoolbar alloc] initwithframe:cgrectmake(160.0,20, 150, 30)]; toolbar.barstyle= style toolbar.tintcolor=[uicolor clearcolor]; toolbar.backgroundcolor=[uicolor clearcolor]; nsarray *items=[nsarray arraywithobjects:addbarbutton,self.editbuttonitem,nil]; [toolbar setitems:items]; uibarbuttonitem *baritem=[[uibarbuttonitem alloc] self.navigationitem.rightbarbuttonitem=baritem; self.navigationcontroller.toolbarhidden=yes; you have bug in code. either remove line or give other color. toolbar.tintcolor=[uicolor clearcolor]; or change to toolbar.tintcolor=[uicolor bluecolor]; that solves problem.

c++ - Read a line from the console -

i reading several string such name , surname , student number , grades, first 3 have done follows: cout<<"enter student's first name: "<<endl; string name; cin>>name; cout<<"enter student's last name: "<<endl; string surname; cin>>surname; cout<<"enter student's unique student number: "<<endl; string studentno; cin>>studentno; how grades enter in following manner : " 90 78 65 33 22" , want read entire line of grade string variable. these string used construct student object. how achieve this, tried using getline() not work. my attempt: int main(){ cout<<"enter student's first name: "<<endl; string name; cin>>name; cout<<"enter student's last name: "<<endl;

sql - connect_by_root equivalent in postgres -

how can covert connect_by_root query of oracle in postgres. ex: oracle query. select fg_id, connect_by_root fg_id fg_classifier_id fg start parent_fg_id null connect prior fg_id = parent_fg_id you use recursive common table expression "carries" root through recursion levels: with recursive fg_tree ( select fg_id, fg_id fg_clasifier_id -- <<< "root" fg parent_fg_id null -- <<< "start with" part union select c.fg_id, p.fg_clasifier_id fg c join fg_tree p on p.fg_id = c.parent_fg_id -- <<< "connect by" part ) select * fg_tree; more details on recursive common table expressions in manual: http://www.postgresql.org/docs/current/static/queries-with.html

sql - perl execution permission error -

i have 1 perl script using script connect sqlserver database , execute stored procedure in case perl scrip give 1 error scrip use dbi; $host = 'server'; $database = 'db'; $user = 'usr'; $auth = 'pssword'; # dbd::ado $dsn = "provider=sqloledb;trusted connection=yes;"; $dsn .= "server=$host;database=$database"; $dbh = dbi->connect("dbi:ado:$dsn", $user, $auth, { raiseerror => 1, autocommit => 1} ) || die "database connection not made: $dbi::errstr"; $sql = "exec [dbo].[get_status] '2013-10-31','00',320,'mbm40cashflw'"; $sth = $dbh->prepare($sql); $sth->execute(); $sth->finish(); $dbh->disconnect(); above script use dbi:ado driver. give full grand permissions in stored procedure errors dbd::ado::st execute failed: can't execute statement 'exec [dbo].[sap.get_status_load_data] '2013-10-31','00!',320,'mbmy_fcl_s40cashflw'

iOS download font error when have weak network such as flight-mode -

from ios6 can dynamic download font apple. downloaded example code downloadfont demo . , found weird. firstly, using wifi network, downloaded font in list , show correct font word successfully. secondly, shut down network flight-mode. return project. thirdly, selected 1 font such "dfwawasc-w5", found log in console of xcode that 2014-03-10 17:14:36.840 downloadfont[2946:1807] still couldn't match <ctfontdescriptor: 0x16547750>{attributes = <cfbasichash 0x165588e0 [0x3a073ae0]>{type = mutable dict, count = 1, entries => 1 : <cfstring 0x3a0efd24 [0x3a073ae0]>{contents = "nsfontnameattribute"} = <cfstring 0x9bfbc [0x3a073ae0]>{contents = "dfwawasc-w5"} } >} and text didn't use "dfwawasc-w5" font system font. select other font had downloaded before such "stlibian-sc-regular" , show correct font. after reselect font "dfwawasc-w5" didn't show correctly, got correct font &q

c++ - How can I preserve the order of multiplications and divisions? -

on 32 bit embedded c++ application, need perform following computation: calc(int millivolts, int ticks) { return millivolts * 32767 * 65536 / 1000 / ticks; } now, since int on platform has 32 bits , millivolts has range of [-1000:1000], millivolts * 32767 * 65536 part cause integer overflow. avoid this, have split factor 65536 1024, 32 , and reordered follows: calc(int millivolts, int ticks) { return millivolts*32767*32/1000*1024/ticks*2; } this way, long order of multiplications , divisions preserved compiler, function compute correctly. kerninghan , ritchie state in section 2.12 of "the c programming language" (i don't have copy of c++ standard handy): c, languages not specify order in operands of operator evaluated. if understand correctly, compiler free change chosen expression not work intended. how can write function in such way guaranteed work? edit: several answers below suggest using floating point calculations avoid issue. not op

Business layer, Service layer and 3-tier architecture -

i want obtain 3-tier architecture: ui<-bll<-dal. my dal "super" object can handle different db tecnologies sql server, mysql, ecc.. and think business logic layer: /// <summary> /// customer entity /// </summary> public class account { public string username; public string email; } public class accountservice<t> t : account { ientitymanager entitymanager; public accountservice(ientitymanager entitymanager) { this.entitymanager = entitymanager; } public void register(t account, string confirmpw, string verificationemailbody) { // validate parameters... // check email uniqueness... // write account db... if (entitymanager.save<t>(account)) { // send verification email whit guid } } public void verify(string guid) { t account = entitymanager.get<t>(new p

PostgreSQL connection timeout -

i using desktop application postgresql database server. when not using application 10 20 minutes continuously, database connection dropped . , using postgresqljdbc database connection. please me on database connection time out. thanks. sounds connected via stateful connection tracking router/firewall has short connection tracking timeout. sounds need enable keepalives. take @ tcp_keepalives_interval , tcp_keepalives_idle parameters . you can request keepalives client-side in jdbc driver; see pgjdbc docs.

android - Fullscreen/Immersive mode lost when application come back to foreground -

i'm trying add immersive mode on android application using opengl es. work, when put application background , come in, application lose full screen status (navigation bar back). here method put application fullscreen/immersive mode (i call oncreate in mainactivity): private void setfullscreen() { int uioptions = this.getwindow().getdecorview().getsystemuivisibility(); if (build.version.sdk_int >= 14) { uioptions ^= view.system_ui_flag_hide_navigation; } if (build.version.sdk_int >= 16) { uioptions ^= view.system_ui_flag_fullscreen; } if (build.version.sdk_int >= 18) { uioptions ^= view.system_ui_flag_immersive_sticky; } this.getwindow().getdecorview().setsystemuivisibility(uioptions); } how can handle that? thanks! call setfullscreen() in onresume() method instead of oncreate() .

How to use rails bundler behind a authenticated proxy? -

i new ruby , getting started learn ruby on rails. behind authenticated proxy network. i researched on internet, answers didn't work me. password has special characters i have exported http_proxy in ruby shell export http_proxy=ht tp://foo:b\@r\@192.168.1.1:8080 when issued bundle update below error :/railsinstaller/ruby1.9.3/lib/ruby/1.9.1/uri/generic.rb:213:in `initialize': scheme http not accept registry part: foo:b@r@192.168.1.1:8080 (or bad hostname?) (uri::invalidurierror) c:/railsinstaller/ruby1.9.3/lib/ruby/1.9.1/uri/http.rb:84:in `initialize' c:/railsinstaller/ruby1.9.3/lib/ruby/1.9.1/uri/common.rb:214:in `new' c:/railsinstaller/ruby1.9.3/lib/ruby/1.9.1/uri/common.rb:214:in `parse' i tried remove \ before 2 in both places, didn't work. i have put content in .gemrc file in folder create first_app yet didn't work. anyone has used rails behind authenticated proxy, please me?

Automaticallyut MSTest all test methods in a solution in Command Line -

the mstest allows run tests in specify assemblies test through /testcontainer or metalist through /testmetadata; there way automatically run tests in solution, whithout specifing name of dlls/meta files? thanks. it's not want hear, answer no, default limited /testcontainer or /testmetadata options specifying tests run. you run mstest multiple times each dll in project contains tests. run process analyzes dlls tests , build list of dlls contain tests , run script calls mstest each of dlls.

gradle - Add external library into android studio 0.5.1 project -

i'm using external library svprogresshud in android studio project module. fine until upgraded android studio 0.5.1. shows follow error message: error:(7, 17) package org.lcsky not exist here settings.gradle: include ':app',':svprogresshud' my build.gradle in project folder: buildscript { repositories { mavencentral() } dependencies { classpath 'com.android.tools.build:gradle:0.9.+' } } allprojects { repositories { mavencentral() } } my build.gradle in svprogresshud module: apply plugin: 'android' android { compilesdkversion 19 buildtoolsversion "19.0.0" defaultconfig { minsdkversion 8 targetsdkversion 19 versioncode 1 versionname "1.0" } buildtypes { release { runproguard false proguardfiles getdefaultproguardfile('proguard-android.txt'), 'proguard-rules.txt'

c# - How to create an Generic Interface with two methods with the same name but different signature? -

i receive error when trying create generic interface have 2 method same name different signature. idea doing wrong , how fix it? type 'xxx.interfaces.irepository' defines member called 'delete' same parameter types public interface irepository<t> : irepositoryreadonly<t> { void add(t entity); void update(t entity); void delete(t id); void delete(t entity); void save(); } your methods don't have different signatures. names of method-parameters not matter, type . how going specify in calling code method want call? is id of type t , or should of type int ? public interface irepository<t> : irepositoryreadonly<t> { void add(t entity); void update(t entity); void delete(int id); void delete(t entity); void save(); }

php - Strict Standards: Only variables should be passed by reference (qdig gallery) -

the code qdig gallery is: $excl_imgs[] = end($logo_arrray = explode('/', $header['css_logo_url'])); $excl_imgs[] = end($bg_img_array = explode('/', $header['css_bg_img_url'])); which gives above error (strict standards). how fix this? do instead , error should go away: $logo_arrray = explode('/', $header['css_logo_url']); $bg_img_array = explode('/', $header['css_bg_img_url']); $excl_imgs[] = end($logo_arrray); $excl_imgs[] = end($bg_img_array); you should try , fix strict standards warning , not hide them.

xaml - Traversing elements of Stackpanel -

i new c#/xaml development , have started creating basic windows phone 8 application. want elements (controls) added in stackpanel child stackpanel using stackpanel.children.add(name_of_the_control). want elements or controls added in stackpanel not know how it. have searched on net not helpful link. please me process of how achieve it. you can access controls added stackpanel it's children property, example : foreach(var control in stackpanel.children) { //here can each element of stackpanel in control variable //further example : if(control radiobutton) { var radio = (radiobutton)control; //do radiobutton } else if(control textblock) { var textblok = (textblock)control; //do textblock } //add other possible type of control want manipulate }

sql - Stored Procedures for IBM DB2 -

i new stored procedures. need pick stored procedures db2(which new to). code wrote not working: create procedure sp_test ( id number ) begin if number < 0 raise value error; end if; select * student_tb taskid = 'number'; end; / and script (another file) calls stored procedure: begin sp_test('15'); end; i not sure wrong. hope can advise. thank you. i'm not expert in db2, i'm pretty sure have call stored procs in db2. call sp_test('15'); or execute (call sp_test('15')); the syntax might little different stored procedures return result set. docs db2 on target platform should explain difference.

ios - Creating private cocoapods repo outside github -

we working on projects use both open-source libraries , our private libraries can't go public. public mean, can't hosted outside our company servers. use cocoapods of them. while using open-source libs pretty easy, question if can use private repository on our private servers host our private libs? i've found link http://guides.cocoapods.org/making/private-cocoapods.html , , there no information weather has github or can server, looking solution on other pages , has repo on github. true? it not have repo on github. see private pods guide more info.

javascript - what does this expression means in Regular Expression -

var nameregex = /^[a-za-z ]*$/; what line mean in regular expression ? used checking name,but don't know how doing? it's not jquery. it's vanilla javascript , more powerful engine. in case, it's regex literal, made intent of checking name contains uppercase or lowercase letters, or spaces.

php - Ajax response is OK but not displaying -

in 1 of web application have "mark favorite icon". when 1 clicks on button. disappears , ajax request called jquery('.favr').click(function() { var user_ids = jquery(this).attr('id'); var current_ids = '<?php echo $cui ?>'; jquery.ajax({ url: '<?php bloginfo('url') ?>/', type: 'post', data: {'ajaxreturn': '102', 'logedid': current_ids,'ids':user_ids}, success: function(result) { jquery('.favh').html(result); } }); }); which inserts user id in database , returns response icon "remove favorite". working ok. ajax response <i data-tooltip="" data-selector="tooltip0d27op" title="remove favori

iphone - how to read and write data to nfc tag in ios Application -

i implement nfc in application(nfc implementation possible using mobile wallet iphone https://itunes.apple.com/us/app/itaptag/id694873763?mt=8 @ appstore) , can 1 please provide me sample code read , write data nfc tag iphone application thanks in advance

grant SQLPermission and permission to connect to the database in policy file java -

how grant sqlpermission codebase in java? trying connect database (mysql) using jdbc. the helpful information found @ sqlpermission not clear enough. do have grant socket permission along it? policy file have used grant { permission java.net.socketpermission "*", "listen, connect, accept"; permission java.sql.sqlpermission "setlog"; permission java.sql.sqlpermission "callabort"; permission java.sql.sqlpermission "setsyncfactory"; permission java.sql.sqlpermission "setnetworktimeout"; }; statck trace: exception in thread "abandoned connection cleanup thread" java.security.accesscontrolexception: access denied ("java.lang.runtimepermission" "setcontextclassloader") when add permission java.lang.runtimepermission "setcontextclassloader"; policy file there no exception connection , statement not created null.on debugging application jumps directly return flag; at

c++ - Qt: Include .pri to use library - incorrect includes -

i'm trying use qtserialport ( http://qt-project.org/wiki/qtserialport ) qt 4.8. it's not part of version, have install manually. avoid manually install it, wanted include .pri file shipped qtserialport. got copy doing "git clone https://git.gitorious.org/qt/qtserialport.git ". using in *.pro file with: include(qtserialport/src/serialport/serialport-lib.pri) but compiling fails bc. of includes like: #include <qtserialport/qserialportglobal.h> so guess these includes resolve /usr/include etc. there way fix without changing includes "foo.h" manually? so guess these includes resolve /usr/include etc. there way fix without changing includes "foo.h" manually? yes, sure. first, need write config += serialport per documentation. you specify includepath qtserialport clone on system. you still need library built, assume aware of it.

c# - Does HttpCookie.HttpOnly property allow connection over https? -

when set cookie httponly property true, server restrict cookie on https, or allow connection on both http , https ? it allows both. httponly determines whether or not cookie can accessed through client-side script. has nothing ssl. msdn : setting httponly property true not prevent attacker access network channel accessing cookie directly. consider using secure sockets layer (ssl) protect against this. you can use requiressl="true" entry in web.config secure authentication cookies . can use secure property secure individual cookie.

hdfs - Filed to start data node in Hadoop Cluster -

i trying installing cdh 4.6 in cluster of 3 nodes. 1 data node out of 3 not able start @ all. tried searching , solving possible ways, failed. please me in solving this. below log. 5:49:10.708 pm fatal org.apache.hadoop.hdfs.server.datanode.datanode exception in securemain java.io.ioexception: path component: '/' world-writable. permissions 0777. please fix or select different socket path. @ org.apache.hadoop.net.unix.domainsocket.validatesocketpathsecurity0(native method) @ org.apache.hadoop.net.unix.domainsocket.bindandlisten(domainsocket.java:191) @ org.apache.hadoop.hdfs.net.domainpeerserver.<init>(domainpeerserver.java:42) @ org.apache.hadoop.hdfs.server.datanode.datanode.getdomainpeerserver(datanode.java:603) @ org.apache.hadoop.hdfs.server.datanode.datanode.initdataxceiver(datanode.java:570) @ org.apache.hadoop.hdfs.server.datanode.datanode.startdatanode(datanode.java:741) @ org.apache.hadoop.hdfs.server.datanode.datanode.<

sql - How to make batch insert with ColdFusion having more than 1000 records? -

i having spreadsheet contains around 3000 records. need insert these data new table. in case using batch insert mechanism quite good. so tried simple example , <cfquery datasource="cse"> insert names values <cfloop from="1" to="3000" index="i"> ('#i#') <cfif lt 3000>, </cfif> </cfloop> </cfquery> but sql server 2008 allows 1000 batch insert @ time getting error. so how make separate batches each containing 999 records @ time , can execute @ time? you can use bulk insert statement should cope extremely large datasets. the data need in csv, , you'll have create variable file location. <cfquery datasource="cse"> bulk insert names '#variables.scsvlocation#' </cfquery> if have reason not use bulk insert , want break down loops of 999, have work out how many 'records' in dataset, divide 999 amou

c# - why does my app complaints about a missing SQL parameter when i already supplied it? -

i have stored procedure takes 18 parameters , 1 parameter annoys me. have passed blob value of type varbinary(max) image. default pass null image. though i've passed parameter , when ran it, has given me following error procedure or function 'uspsvupdtcourse' expects parameter '@pbookimage', not supplied. but can see in first image have passed parameter first image-c# code throw exception second image- sql store procedure is there away fix or need further details, stored procedure on going thing, not logic error , else.. : ( in stored procedure check input param looks @pbookimage varbinary(max) = null this accept null parameter in sp

jquery - getting to grips with javascript callbacks - undefined callback data -

my javascript skills limited , i'm having problem structure of series of functions think need callbacks. i've been reading number of posts , tutorials it's not sticking...yet.. on page have pop modal contains image. if user clicks edit button it's edited in aviary. once that's completed image properties saved database , images within modal box - , underlying form - should updated edited image. my series of events starts modal opening: $('#editimagelink2').click(function(event) { aviaryonclick('image2', $(this).data('mode'), function(image) { #do final bits here }); }); modal pops if user clicks edit button next function starts editor: function aviaryonclick(source, mode) { editedimage = doaviary(source); if (editedimage) { return true; } else { return false; } } so - aviary pops expected. when user saves edited image i'm starting have trouble: the doaviary function looks this: function do

c# - Many-to-many table as model with extra column -

i have code-first mvc4 c# application these 2 models public class classroom { public int id { get; set; } public string classname { get; set; } public virtual icollection<pupil> pupils { get; set; } } public class pupil { public int id { get; set; } public string pupilname { get; set; } public virtual icollection<classroom> classrooms { get; set; } } this part of context modelbuilder.entity<location>() .hasmany(l => l.classrooms) .withmany(o => o.pupils) .map(m => m.mapleftkey("pupilid") .maprightkey("classroomid") .totable("pupilclassroommm")); therefore there many-to-many table called "pupilclassroommm". this worked fine, want add column pupilclassroommm-table. tried make model, add-migration doesn't it. public class pupilclassroommm { [key, column(order = 0)] public int classroomid { get; set; } [key, column(order = 1)] public in

How to run batch file(.bat) from Jmeter -

i'm new work jmeter , want run batch file ,i have tried run batch file bsf sampler using command exec("c:\windows\system32\wscript.exe../stopwas.bat") and displayed error message "there no script engine file extension .bat" also have tried run batch file os process sampler , wrote command : command :cmd stopwas.bat also failed can me issue? for os process sampler guess need provide command parameter /c or /k . so: command: cmd command parameters: /c c:\somefolder\someotherfolder\stopwas.bat mention have use full path .bat file. another option executing via beanshell sampler runtime.getruntime().exec("c:/windows/system32/cmd.exe /c c:/somefolder/someotherfolder/stopwas.bat");