Posts

Showing posts from January, 2010

jQuery function in javascript loop -

i got div's i'm editing 'jeditable' works perfectly! want give users alert ask them if want edit post. <script type="text/javascript" src="jquery-1.9.1.js"></script> <script type="text/javascript" src="jquery.jeditable.js"></script> <script type="text/javascript"> $(document).ready(function jeditable() { $("div[title='article']").click (function() { var edit; edit = confirm("editing article?"); if (edit == true) { $('.edit').editable('x2.php', { cancel : 'cancel', submit : 'ok', onblur: 'ignore', }); } else { alert("canceling edit.."); } }); }); </script> 1)when alert pops , cancel it, nothing happens (inten

Wrong result using sum at MySQL -

i have view lot of data. can got results using subqueries (data ok , optimized): +------------+ | attendance | +------------+ | 319 | | 102 | | 598 | | 113 | | 6 | | 279 | | 366 | | 146 | | 669 | | 205 | | 123 | +------------+ the next time user update data, shows this: +------------+ | attendance | +------------+ | 319 | | 102 | | 598 | | 113 | | 7 | | 279 | | 253 | | 146 | | 669 | | 561 | | 123 | +------------+ which ok, 'cause user update information 1 before has 6 attendance. but problem comes when use data temptable , make: select sum(attendance) total ( /* subquery returning above table */) cause returns (in first place 1 user having 6 attendance): +-------+ | total | +-------+ | 3169 | +-------+ and 7: +-------+ | total | +-------+ | 3128 | +-------+ when should 3170!!! ideas? edit 1: p

android - How to test the backing array used in Java Sting? -

while developing android application, attention caught backing array . multiple strings can share same char[] because strings immutable. substring(int) method returns string shares backing array of source string. optimization: fewer character arrays need allocated, , less copying necessary. can lead unwanted heap retention. taking short substring of long string means long shared char[] won't garbage until both strings garbage. typically happens when parsing small substrings out of large input. avoid necessary, call new string(longstring.substring(...)). string copy constructor ensures backing array no larger necessary. then have read many resources on web. know strings no longer shares same backing array since jdk7u6 , pointed mark rotteveel . then started trying play with, , test existence of shared backing array in code: string str = "1234567890"; system.out.println("str.substring(1): " + (str == str.substring(1))); system.out.println(&quo

core data - Adding individual float values per UITableViewCell to get grand totals? -

i having major problem getting started finding answer question? have uitableview being populated user generated content , being persisted coredata. good. can't find way in apple docs following: how add each dollar value in cell grand total displayed somewhere user? in case can thrown in uilabel in footer of each section don't care. can't figure out how each individual cell dollar amount entered there , add next dollar amount in next cell in section , on. any ideas on how add totals cells grand total? the elegant solution problem using key paths. you not go cells , data out. go data model , calculate there. remember, mvc dictates should separate model , view. suppose have subclass of nsmanagedobject nsnumber attribute "amount" fetched via core data. can simple calculations this: float sum = [[fetchedobjects valueforkeypath:@"@sum.amount"] floatvalue]; this described in key-value coding programming guide under collection operators

android - A boolean value defined in XML. How to reference in Java? -

i'm trying write code reference bool.xml file , reference current value inside bool. <bool name="enableqaurl">true</bool> with want able reference in code, if it's set true , if false else. simple if , else statement. any code references or feedback appreciated. resources res = getresources(); boolean enableqaurl = res.getboolean(r.bool.enableqaurl); source : http://developer.android.com/guide/topics/resources/more-resources.html

post - MVC Model not posting -

when click login button never model posted server. if accept formcollection see values. how can make automatically bind model instead of searching form collection? from have read there few common problems this: 1 - view not specify model using (@model myapp.models.name) 2 - model not use properties 3 - of required fields missing controller [httpget] public actionresult password() { return view(new authviewmodel()); } [httppost] public actionresult password(authviewmodel password) { if (password == null || string.isnullorempty(password.password)) { viewbag.error = constants.errormessages.userpassword_passblank; return view(new authviewmodel()); } //success return redirect("/"); } model public class authviewmodel { public string password { get; set; } } view @model mvcapplication1.models.authviewmodel @{ viewbag.title = "password"; } <h2>password</h2> @using (html.beginform()) { <d

c++ - pthread_cond_timedwait returns error 138 -

i can't find information on google, post here hoping can help... my problem windows pthread function pthread_cond_timedwait() . when indicated time elapsed, function should return value etimedout. instead in code, conditional variable not signaled, returns value 138 , earlier expected timeout, immediately. so questions are: error 138? , why timeout not elapsed? code use thread is: int retcode = 0; timeb tb; ftime(&tb); struct timespec timeout; timeout.tv_sec = tb.time + 8; timeout.tv_nsec = tb.millitm * 1000 * 1000; pthread_mutex_lock(&mutex_); retcode = pthread_cond_timedwait(&cond_, &mutex_, &timeout); pthread_mutex_unlock(&mutex_); if (retcode == etimedout) { addlog("timed-out. sending request...", log_debug); } else // happened { std::stringstream ss; ss << "thread interrupted (error " << retcode << ")"; addlog(ss.str().c_str(), log_debug); } is there wrong absolute timeout comp

c++ - Why is Boost Graph Library's `source()` a global function? -

i understand in generic programming, algorithms decoupled containers. make no sense implement generic algorithm instance method (the same algorithm should work on multiple concrete classes; don't want make them inherit 1 abc since exponentially increase number of classes). but in case of source() function in boost graph library , don't understand why global function , not instance method of graph class. as far tell reading bgl source code , source(e, g) needs know implementation details of graph , edge objects passed it; it's not enough know interfaces . so source() not generic algorithm. in other words, needs know concrete class of graph instance. why not put in same class instance method? wouldn't lot cleaner / less confusing making global function needs customized each class it's called upon? update the relevant source code: // dwa 09/25/00 - needed more explicit reverse_graph work. template <class directed, class vertex, class ou

css - How to fix the shadow on my menu, Fiddle example shown -

thanks ahead of time everyone. have been working on menu in css , html , can't figure out how make shadow appear around whole menu item + sub-menu instead of part drops down. should covering it, it's not: my code here: http://jsfiddle.net/clare12345/nq4rv/1/ . #listitems:hover { box-shadow: 2px 4px 8px #888888; } #menu ul li:hover ul li { display:block; box-shadow: 2px 4px 8px #888888; } <div id="menu"> <ul> <li><div id="listitems"><div id="menuheader">steps:</div><a href="#nogo">section one</a> <div id="smalltext">description text here</div> <ul> <li><a href="#nogo">a</a></li> <li><a href="#nogo">b</a></li> </ul> </div> i tried putting shadow

App Engine NDB query with multiple inequalities? -

the 2 answers on here involve restructuring database accommodate limitation, unsure how in case. i have list of thousands of contacts, each many many properties. i'm making page has ability filter on multiple properties @ once. for example: age < 15, date added > 15 days ago, location == santa cruz, etc. potentially ton of inequality filters required. how 1 achieve in gae? according the docs (for python) , limitations: datastore enforces restrictions on queries. violating these cause raise exceptions. for example, combining many filters, using inequalities multiple properties, or combining inequality sort order on different property disallowed . filters referencing multiple properties require secondary indexes configured. if check in few months, may change. gae keeps changing pretty quickly. for now, though, you'll have make multiple queries , combine them in code.

python - SciPy step response plot seems to break for some values -

Image
i'm using scipy instead of matlab in control systems class plot step responses of lti systems. it's worked great far, i've run issue specific system. code: from numpy import min scipy import linspace scipy.signal import lti, step matplotlib import pyplot p # create lti transfer function coefficients tf = lti([64], [1, 16, 64]) # step response (redo better resolution) t, s = step(tf) t, s = step(tf, t = linspace(min(t), t[-1], 200)) # plotting stuff p.plot(t, s) p.xlabel('time / s') p.ylabel('displacement / m') p.show() the code as-is displays flat line. if modify final coefficient of denominator 64.00000001 (i.e., tf = lti([64], [1, 16, 64.0000001]) ) works should, showing underdamped step response. setting coefficient 63.9999999 works. changing coefficients have explicit decimal places (i.e., tf = lti([64.0], [1.0, 16.0, 64.0]) ) doesn't affect anything, guess it's not case of integer division messing things up. is bug in scipy, or doi

ember.js - How do you assign a static data- attribute to an ember view? -

i need assign static data- attribute ember.view, how set in view object instead of in {{view }} tag. app.messagesformview = ember.view.extend({ tagname: 'div', classnames: ['modal', 'fade'], didinsertelement: function() { this.$().modal('show') }, willdestroyelement: function() { this.$().modal('hide') }, }) unfortunately, don't have enough reputation comment on ola's answer, believe better way not use string (text in quotation marks) denote data attribute property name. instead, write property name in camelcase , ember automatically bind hyphenated attributebinding. example: app.messagesformview = ember.view.extend({ tagname: 'div', attributebindings: ['data-backdrop'], databackdrop: 'static', // binds data-backdrop. awesome! }); i hope makes sense!

php - Doctrine Mongo ODM UniqueIndex is replicated -

i'm playing uniqueindex picked doc of doctrine odm , seems have misanderstood of aims do. indeed have keyword document mapped doctrine odm : namespace app\document; use doctrine\odm\mongodb\mapping\annotations odm; /** * @odm\document * @odm\uniqueindex(keys={"name"="asc", "lang"="asc"}) */ class keyword { /** @odm\id(strategy="auto") */ protected $id; /** @odm\string */ protected $name; /** @odm\string */ protected $lang; .... as can see document has uniqueindex on 2 keys (name , lang) i have simple script persist document .... .... $keyword=new \app\document\keyword(); $keyword->setcreatedate(new \datetime()); $keyword->setlang("fr"); $keyword->setlastparsedate(new \datetime()); $keyword->setname("test"); $dm->persist($keyword); $dm->flush(); now when find mongo shell, data same pair name/lang replicated

Numeric Data Validation in C++ -

i have looked everywhere can't seem find , implement input validation takes in integers, have code running fine problem since ive added validation code, requires user enter twice before accepts second input, want user have enter in once validation program recognizes not int , displays appropriate message, id appreciative of help! here's code: cout<<"please enter first value: \n"; cin>>a; //error checker check if input number while(!(cin >> a)) { cin.clear(); std::cin.ignore(numeric_limits<streamsize>::max(), '\n'); cout << "invalid input. please try again: "<<endl; } you trying cin>>a once before while loop , again in while loop condition. remove initial extraction. cout<<"please enter first value: \n"; // cin>>a; <- remove //error checker check if input number while(!(cin >> a))

css - Why do i have unwanted margin on top of my html page? -

i keep getting unwanted top margin , cant remove it, tried everything, affected 1 of other projects well, find solution. please heres html: <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>joy designert</title> <link href="style1.css" rel="stylesheet" type="text/css" /> </head> <body topmargin=0 marginheight=0> <div id="wrapper"> <div id="topbanner"><div class="container"><h2>top banner content</h2></div></div> <div id="nav"><div class="container">navigation text<?include ("navigation.php");?></div></div> <div id=&quo

java - TimerTask() not doing what was supposed to, only printing one time -

public static void main(string[] args) { timer ttt = new timer(); timertask test = new timertask() { @override public void run() { system.out.println("in"); } }; ttt.schedule(test, 1000); } this supposed print "in" every second printing 1 time. tips? thank you what you're using one-shot version of schedule . use overloaded version accepts interval period: ttt.schedule(test, 0, 1000); aside: newer executorservice preferred on java.util.timer . timer has 1 executing thread, long-running task can delay other tasks. executorservice can operate using thread pool. discussed more here

ruby - How to create a Rails-like before filter in Sinatra? -

class foo def do_before ... end def do_something ... is there way run do_before method before each other method in foo class (like do_something )? it seems sinatra before block runs before each http request, has nothing class. edit: michael pointed out in comments, similar functionality rails offers in controller. however, both rails , sinatra offer similar functionality. as iain pointed out in comments, example specify not specific rails/sinatra. i'm assuming want before filter ones in rails , sinatra offers: sinatra's modular apps: class foo < sinatra::base before "do something" end '/' "hello world" end end class bar < sinatra::base before "do else" end '/' "hello world" end end in config.rb file, require 'foo.rb' require 'bar.rb' map '/foo' run foo end map '/bar' run bar end this nearest ana

filenames - Refining a Folder Creation and move based on File Names Bash Script [SOLVED] -

i appologize in advance have looked , tried many of solutions problem out there none of them have worked perfectly. writing script create folder based on name of file move files of same name it. code have works errors. keeps throwing error folder exists after first pass. have tried if else doesn't seem handling right. if 1 me , tell me i'm doing wrong appreciate it. first part of script remove white space , replace _, works perfectly. #!/bin/bash # main_dir=/pghwh1/photos cd $main_dir find . -name '* *' | while read fname new_fname=`echo $fname | tr " " "_"` if [ -e $new_fname ] echo "file $new_fname exists. not replacing $fname" else echo "creating new file $new_fname replace $fname" mv "$fname" $new_fname fi done find . -type f | while read file; f=$(basename "$file") f1=${f%.*} if [ -d "$f1" ]; mv "$f" "$

javascript - Uncaught TypeError: Cannot set property 'innerHTML' of null -

i have been having trouble code. have tried best stay book book seems wrong. the following code should display rss feed ever radio button has been selected. can see website on http://w3.cnm.edu/~bnoble/cis1210/afds/travel/traveldeals.html . thanks in advance help! <html> <head> <title>travel deals rss feed</title> <script> var rssrequest = false; function getrequestobject() { try { rssrequest = new xmlhttprequest(); } catch (requesterror) { try { rssrequest = new activexobject(); } catch (requesterror) { try { rssrequest = new activexobject("micorsoft.xmlhttp"); } catch (requesterror) {

java - How can I optimize this String search/replace method? -

i implementing own web server. following method searches server side includes , builds html page appropriately. public string getssi(string content) throws ioexception { string beginstring = "<!--#include virtual=\""; string endstring = "\"-->"; int beginindex = content.indexof(beginstring); while (beginindex != -1) { int endindex = content.indexof(endstring, beginindex); string includepath = content.substring(beginindex+beginstring.length(), endindex); file includefile = new file(base_dir+includepath); byte[] bytes = new byte[(int) includefile.length()]; fileinputstream in = new fileinputstream(includefile); in.read(bytes); in.close(); string includecontent = new string(bytes); includecontent = getssi(includecontent); content = content.replaceall(beginstring+includepath+endstring, includecontent); beginindex = content.indexof(begi

html - H1 Bottom Border Underline -

i having issue trying underline h1 border-bottom, extends behind picture (to left). underline extend end of page. here code: html: <div id="content"> <img src="http://imageshack.us..."/> <h1>about me</h1 <p>info me....</p> <h2>contact info</h2> <p>phone:my number</p> <p>email: email</p> </div> css: #content { padding: 5px 10px 5px 0px; margin: 10px 10px 10px 0px; } #content img { float: left; margin: 0px 10px 10px 0px; } #content h1 { font-size: 26px; margin: 15px 0px 5px 0px; border-bottom: 5px solid black; } note: novice coder - if not possible or there other ways let me know! the reason happening because haven't set width on h1 . naturally going extend entire page width. solve this, add width property, , should go. code looks now #content h1 { font-size: 26px; margin: 15px 0px 5px 0px; borde

haskell - How best to type "Any monad transformer stack containing m" -

i'd write function fixproxy :: (monad m, proxy p) => (b -> m b) -> b -> () -> p a' () b m r fixproxy f () = runidentityp $ v <- respond a' <- lift (f a) fixproxy f a' v which works you'd think until try run proxy >>> :t \g -> runrvart . runwritert . runproxy $ fixproxy g 0 >-> tolistd (num a, randomsource m s, monadrandom (writert [a] (rvart n)), data.random.lift.lift n m) => (a -> writert [a] (rvart n) a) -> s -> m (a, [a]) where use rvart intentionally highlight existence of lift class in rvar . lift represents existence of natural transformation n :~> m ought encapsulate i'm looking for, function like: fixproxy :: (monad m, monad n, lift m n, proxy p) => (b -> m b) -> b -> () -> p a' () b n r is lift right answer (which require many orphan instances) or there more standard natural transformation mptc use? note practical solution, described

sql - SSIS derived column very slow (date manipulation) -

setup : have large ssis package sorts through lot of different flat files , throws them tables fit file definitions t... except date. dates come on in format: "mm/dd/yyyy hh:mm:ss.ffffff." of course, dbtimestamp , needs converted "yyyy-mm-dd hh:mm:ss.ffffff" . on given file have @ least 2 dates; created , updated. on have more. problem : of 26 files parse, 1 particularly larger other. in cases can 40+ mb. seemed running fine before, running through derived column component derives 3 dates extremely slow. takes around 30 minutes parse ~90,600 rows. i'm watching data flow executing , bottleneck looks derived column. report error rows if happen exist , there none, know it's not choking on rows... can't figure out taking long. cpu shoots 100% while executing (no big surprise) memory stays low @ 12%. here's exact transformation happens on each of 3 dates each line: (dt_dbtimestamp)(substring(column,7,4) + "-" + subst

java - Simplified MIPS CPU using high level programming languages -

i'm trying design of analyzer/simulator simplified mips cpu using high level programming language preferably java. considered mips cpu adopts cdc 6600 scoreboard scheme dynamically schedule instruction scheduling , using cache load , store instruction cache hit , cache miss. need start advice simulation. should use event queue simulation? if how? a simple risc processor can simulated executing 1 instruction @ time. true pipelined cpu. since want model superscalar processor, several instructions in flight @ same time, event based simulator best way correctly model instruction completes when, , how in-flight instructions compete processor resources.

microsoft metro - WinJS ScrollView Pinch Zoom not working -

winjs scrollview pinch zoom not working this code : <div id="container"> <img src="images/logo.png" /> </div> #container { width:1000px; height:600px; overflow:scroll; -ms-content-zooming:zoom; -ms-content-zoom-limit-max:1000%; -ms-content-zoom-limit-min:20%; }

iphone - How to Refersh the UI view from subview custom cell? -

Image
my xib ddesign i have design screen this,in run time have screen in have view name , plus , minus button,in run time have name 1,name 2 , name 3 etc . when click plus button increase value 1 ... , show count label,then when click minus button wan decrease count label value. my click event code in custom cell class, _(ibaction)click:sender { nsuinteger no =2; second-class *sc = [[secondclass alloc] init]; [sc numberofitem:no]; } when click button in custom cell,i want change count label value in main class, main class coding is -(void)nuberofitem:no { nslog(@"number : %d",no); //its show correct value localtextbox.text = no; nslog(@"text box value : %@",localtextbox.text); //but in label shows null value } not able change count lable value don't know how thing can know me please. the button (custom or otherwise) shouldn't telling rest of application other "i tapped!". set button it's target view controller ,

syntax - Tictactoe c program error with main function -

i'm creating simple tictactoe game in c. keep getting error in main function, don't know expected expression wants before else statement. how program works symbols both players, begin game. error: tictac.c: in function ‘main’: tictac.c:31: error: expected expression before ‘else’ tictac.c: @ top level: tictac.c:49: warning: conflicting types ‘print’ tictac.c:30: warning: previous implicit declaration of ‘print’ here tictac.c:63: error: conflicting types ‘check’ tictac.c:63: note: argument type has default promotion can’t match empty parameter name list declaration tictac.c:29: error: previous implicit declaration of ‘check’ here tictac.c:89: warning: conflicting types ‘move’ tictac.c:28: warning: previous implicit declaration of ‘move’ here code: char board[3][3]; int main(void) { int first; char player1, player2; printf("player 1: choose symbol: \n"); player1 = getchar(); printf("player 2: choose symbol: \n"); play

What are the consequences of creating a branch from a subfolder of trunk in SVN? -

i thought when branch, branch whole trunk, in company i've seen people branch subfolders of trunk , deeper- there practical consequences of besides confusion when try find right directory in trunk merge into? the problem not branching.. merging: never merge such "subtree" folder. why? subversion store merge-info subtree folder. , happens, nobody can use merge -reintegrate anymore. look here more information : avoid subtree merges , subtree mergeinfo, perform merges on root of branches, not on subdirectories or files this means long have subtree merge-infos hanging around in trunk can not use -reintegrate option, should use, because in way merging much easier.

How to differentiate two HTML elements with same tagname and same text -

i know there method in jsoup tells me element same tag name, text , class (if any) different other element same tag name, text , same class (if any). clarification consider following html snippet : <html> <body> <div>here am</div><div>first time</div> <div>here am</div><div>again</div> </body> </html> now in above code how can separate 2 elements div tag , text here am . note here 2 elements have no id. the above example simple actual scenario may more complex. if kindly suggest me generalized answer grateful. thank you. give id making unique document. can done as <div id="first">here am</div> <div id="second">here am</div>

actionscript 3 - On mouseover how to highlight an object's point so that I can draw connector from highlighted point -

i want develop similar features in http://www.cacoo.com connector.please me urjent. you can google as3 transform library , find lot. for example (i can post 2 urls because of limitation of stackoverflow): https://github.com/ryantan/free-transform-manager-as3 http://www.senocular.com/demo/transformtoolas3/transformtool.html you can more google.

windows - Execute RDP connection on multiple server -

we have thousand of windows server in our network. kind of work need log in on 100+ servers. doing manually. entering server name , giving credentials. possible create batch file/script so, work can automated. create text file or csv , run script. script can open mstsc session , put credential in mstsc. can define username , password in script. consider using remote desktop manager - remotedesktopmanager.com, allows create several predefined remote desktopts, save different rdp settings them, , switch between desktops in more convenient way. also when connect via usual mstsc, can save separate rdp file , ask remember credentials when conecting first time, , store separate rdp files way.

jquery - Array of selectors: for loop vs. $.each -

given following array of selectors (each of display: none in our css) , loop: var arr = ['#home', '#news', '#tidy']; (i=0;i<=arr.length;i++){ $(arr[i]).toggle(); } what equivalent using $.each ( , presumably $(this) )? edit ok understand using join: var s = arr.join(); $(s).toggle(); i did not realize "toggle many other jquery methods calls each method internally there no need use each" +1 @undefined, however... the question original put forth because when i: $.each(arr, function(){ $(this).text("my id " + + "."); }); i undefined (!) errors. (ok fair there .toggle , .insertafter etc., i'm attempting simplify) why above not equivalent to: $('#home').text('my id #home.'); $('#news').text('my id #news.'); $('#tidy').text('my id #tidy.'); ? edit 2 ok syntax issue - $(this) requires prepending '' + : $('' + this).text('my

php - Jquery functions conflict with other plugin jquery function -

i using same jquery function in 2 different wordpress plugins. both plugins working fine individually, problem if activate both script working 1 plugin other 1 not working(2nd plugin not working). can give me solution , tell me problem is? 1) don't include jquery twice 2) make use of $ = jquery.noconflict() if necessary

MongoDB Shell: find by BinData -

i have document in mongodb { "_id" : objectid("51723a2f2b9b90e9eb190c45"), "d" : bindata(0,"c9f0f895fb98ab9159f51fd0297e236d") } the field "d" indexed, how can find value in mongo shell? e.g. db.test.find( {"d": bindata(0,"c9f0f895fb98ab9159f51fd0297e236d") } ) not working, idea? bindata base64 representation of binary string.must instantiated. db.test.find( {"d": new bindata(0,"c9f0f895fb98ab9159f51fd0297e236d") } )

javascript - Checking if window size has changes and performance/optimalization -

today i'm implementing slider plugin , have 1 question it: i want make responsive, achive (depending on current implementation) should add function detect if browser window size has changed - , here's question - overall performance? or maybe should re-think solution , try build pure css? the browser resize temporary , don't see big hassle slight hiccup in phase. since refer jquery, can add $(window).resize(function() { ... }); add withing document ready, , call 1 on load. do $(window).resize(); as far performance, correct every little addon have effect on performance, when active. when window not resized, teh event not fired.

tsql - How to user previous resultset into next query in SQL Server -

i want generate access token if username , password match in users table. how can use previous returned value next insert query? have marked missing value ###i don't know###. create procedure [dbo].[getaccesstoken] @userid varchar(50), @password varchar(50) select id users userid = @userid , password = @password if @@rowcount != 0 begin set @token = newid(); insert accesstokens (token, userid) values(convert(varchar(255), @token), ###i don't know###) end return 0 end please me. thanks, in advance. simply pass @userid second parameter insert insert accesstokens (token, userid) values(convert(varchar(255), @token), @userid)

ios - UITextView - strange text clipping -

Image
i've placed uitextview uitableviewcell , sized how want. can see size has been set correctly (by setting text view's background color). . . text within text view has strange clipping. how can avoid this? update: i ended placing uitextview onto empty view in brand new view controller , still noticed problem. next step create new project , start adding things in 1 one. started single view controller , view uitextview - ok. added library convenience methods view placement - broken. this issue caused library adds convenience methods uiview placement. example contains methods like: view.x = somefloat view.width = somewidth i suspect there namespace collision internal method used uitextview, i'm not sure method caused problem yet.

c++ - Testing wall clock time based algorithms -

i'm maintaining algorithm uses wall clock time make various decisions (eg. solutions quick calculate taking long , need scrapped). when trying test algorithm, results can different each time due number of variables such machine load, operating system scheduling, io etc. what standard approach testing such system? cpu instructions executed 1 idea had, i'm not sure how practical on modern multi-core x86 processor. the fall plan add increments internal counter , change limits of algorithm try , match performance of existing wall clock version. involve lot of trial , error i'd know if there easier way before start going down path. the simple crude option "abstract away" wall time retrieve logic. say, use class walltime gettime method , use throughout application. there 2 "providers" of time class can use. 1 rt clock in system. the other returns values pre-recorded list. you record first pass through algorithm , store values retur

java - Iterating a list with hibernate query -

i have usertable uid username password 1 stephen 1542s 2 james 8452b store procedure name: sp_gridview query: select * usertable list list=null; list=hibernatetemplate. getsessionfactory().opensession() .createsqlquery("call sp_gridview").list(); for(int i=0; i<list.size(); i++) { system.out.println(list.get(i)); } here not using generics because, not needed requirements. try iterate above list but, show result hash code. output: [ljava.lang.object;@3c668d12. how iterate list , value without hashcode. it seems you're getting object back, , object.tostring() called when trying print prints that. solve it, can cast actual type of object specific tostring() method. such: system.out.println((string)list.get(i));

html - How to make a fluid sidebar? -

i'm creating sidebar css code: .sidebar { position: absolute; z-index: 100; top: 0; left: 0; width: 30%; height: 100%; border-right: 1px solid #333; } but sidebar width doesn't scale when change browser width. how can make sidebar fluid? thanks. look @ height in body in css part. here working example you: your html: <div id="content"> <p>this design uses defined body height of 100% allows setting contained left , right divs @ 100% height.</p> </div> <div id="sidebar"> <p>this design uses defined body height of 100% allows setting contained left , right divs @ 100% height.</p> </div> your css: body { margin:0; padding:0; width:100%; /* key! */ } #sidebar { position:absolute; right:0; top:0; padding:0; width:30%; height:100%; /* works if parent container assigned height value */ color:#333; background:#eaeaea; border:1px solid #333; } #content { margin-righ

ruby on rails - Restore Gemfile.lock from gitignore -

in rails app, gemfile.lock ignored tracking through .gitignore but want file committed , tracked. how do that? first remove entry gemfile.lock .gitignore, add .gitignore , commit. add , commit gemfile.lock. long these done in 2 separate commits, other team members able track gemfile.lock file.

c# - NancyFx and TinyIoC provide single instance to module -

iv got simlpe question. im using nancy windows form (passed through constructor (autoresolve)). if let nancy resolve automatically every module creates new instance of form, not want. thought maybe register form instance in tinyioc , use instance instead of creating new 1 each time. has proved not simple implement idea is. thanks in advance you should in bootstrapper something like: public class mybootstrapper: defaultnancybootstrapper { configureapplicationcontainer (tinyioccontainer container) { //the .assingleton() instructs tinyioc make 1 of those. container.register<imessagedeliverer>().assingleton(); base.configureapplicationcontainer (container); } }

Understanding the semantics of C pointer casts when applied to literals -

is there documentation specifying meaning of pointer cast applied literal in c? for example: int *my_pointer = (int *) 9 is compiler-dependent or part of standard? edit: deleted misleading note based on comment below, thanks. int *my_pointer = (int *) 9 this not point literal 9 . converts literal 9 pointer int . c says conversion integer pointer type implementation-defined. int *my_pointer = &(int) {9}; this does. makes my_pointer points int object of value 9 .

java - How to convert byte string to byte[] -

Image
i stuck casting issue converting byte string byte array. i.e have string " [b@1a758cb ". base64 encrypted string of main string "gunjan". here decryption want convert encrypted byte string byte[]. but string.getbyte[] not working me. string.getbytes[] gives bytes of byte string. how can ?? have iterate on each character in byte string , convert them byte[] ?? edited i using apache coded 3.1 jar base64 conversion. here code getting encrypted text.. string in = "gunjan"; byte[] bytestr = in.getbytes(); byte[] base64encoded = base64.encodebase64(bytestr); here value of base64encoded [b@1a758cb can see console log in image.. first of all, don't have problem here, since decoded string value (gunjan) equal original value (gunjan). you're confused printed intermediate byte arrays. noted in comments, strings [@bxxxx result of calling tostring() on byte array. desn't display value of bytes, type of array ( [@b ) followe

PHP echo display - Missing first Row from Mysql -

i'm not sure why happening. have read explanations on here can't seem find myself. on both series , episodes lists site missing first row when echoing results. fix great. here's coding episode page <?php include '../connect/dbseries.php' ?> <?php $result2 = mysql_query("select seriesid, seasonindex, sortname, thumbfilename, currentbannerfilename, posterbannerfilename, summary, imdb_id, episodename, episodeindex, compositeid series seriesid = '$_get[id]' order seasonindex, episodeindex asc;"); if (!$result2) { echo 'could not

php - adddate(curdate(), -(day(curdate())-1)) and concat(last_day(curdate()),' 23:59:59') -

what mysql script means time between ? adddate(curdate(), -(day(curdate())-1)) , concat(last_day(curdate()),' 23:59:59') day(curdate())-1 current day of month, less 1. today (aug 15, 2013), value 14. subtract 14 days august 15 , have august 1. in other words, adddate(curdate(), -(day(curdate())-1)) gives first day of month. last_day(curdate()) gives last day of month. if call today return august 31, 2013. append 23:59:59 , have last second of last day of month. in other words, if called on august 15, 2013, values come out 2013-08-01 , 2013-08-31 23:59:59 . if range applied against datetime value, means "anything in month of august 2013". this pretty way check date/time values within month because avoids using function on mysql column holds date/time. if column has index, index (probably) used optimization. 1 approach see this: where date_format(mydatetime, '%y%m') = date_format(curdate(), '%y%m') this reads little be

Command line argument to string in C -

is there way in c store whole command line options , arguments in single string. mean if command line ./a.out -n 67 89 78 -i 9 string str should able print whole command line. now, able print values in different vector forms. #include <stdio.h> #include <getopt.h> #include <string.h> int main(int argc, char* argv[]) { int opt; for(i=0;i<argc;i++){ printf("whole argv %s\n", argv[i]); } while((opt = getopt(argc, argv, "n:i")) != -1) { switch (opt){ case 'n': printf("i %s\n", optarg); break; case 'i': printf("i %s\n", optarg); break; } } return 0; } i want this, optarg printing first argument , want arguments printed, want parse after storing in string. simply write function this: char * combineargv(int argc, char * * argv) { int totalsize = 0; (int = 0; < argc; i++) { totalsize += strlen(argv

wpf - Why can't I update my ObservableCollection with Filtered CollectionView attached during unit testing? -

i've got observablecollection in viewmodel need modify in code on background thread (using task object). i've got icollectionview attached collection. when modify collection @ run-time, code runs fine. in unit testing error, "this type of collectionview not support changes sourcecollection thread different dispatcher thread." i create collection thusly (on ui thread @ run-time): cashdeliverydepots = new observablecollection<cashdeliverydepot>(); filteredcashdeliverydepots = collectionviewsource.getdefaultview(cashdeliverydepots); and modify using code (which running on non-ui thread @ run-time): currentdispatcher.invoke(() => { foreach (var depot in depots) { cashdeliverydepots.add(depot); } }); the currentdispatcher class executes code according whether or not there application dispatcher. internal static class currentdispatcher { internal static void invoke(action action) {

best way to process images already on S3 (rails) -

i have set of images on amazon s3, , i'd automatically generate thumbnails them serve on site. i've considered cloudinary, seems i'd have copy on images cloudinary servers first. want keep them on s3. i've considered dragonfly, seems dragonfly works files i'd upload after installing dragonfly. have uploaded files. what's solution me? i'm in rails environment (rails 3.2). thanks! if it's 'set of images' it's not structured. you're better off reorganizing way store , manage images. try paperclip . class modelname < activerecord::base attr_accessible :image #more here has_attached_file :image, :styles => { :large => "450x450>", :medium => "300x300>", :thumb => "150x150>" }, :storage => :s3, :s3_credentials => "#{rails.root}/config/s3.yml", :path => "people/:style/:id/:filename", :s3_protocol => "https"

SQL Server 2008: delete duplicate rows -

i have duplicate rows in table, how can delete them based on single column's value? eg uniqueid, col2, col3 ... 1, john, simpson 2, sally, roberts 1, johnny, simpson delete duplicate uniqueids 1, john, simpson 2, sally, roberts you can delete cte: with cte (select *,row_number() over(partition uniqueid order col2)'rowrank' table) delete cte rowrank > 1 the row_number() function assigns number each row. partition by used start numbering on each item in group, in case each value of uniqueid start numbering @ 1 , go there. order by determines order numbers go in. since each uniqueid gets numbered starting @ 1, record row_number() greater 1 has duplicate uniqueid to understanding of how row_number() function works, try out: select *,row_number() over(partition uniqueid order col2)'rowrank' table order uniqueid you can adjust logic of row_number() function adjust record you'll keep or remove. for instance,

vb.net - how to create a picturebox in vb 2008 and move it? -

i want ask important question in vb2008 : i'm working on 2d level designer put images , collision rectangles in place program generate right code. problem : make button , in click event add new picture box , when add have move mouse , have "move" code know it's new picture box can't write code before picture box add.(if doesn't understand can explain situation again) for more clear code : private sub button2_click(byval sender system.object, byval e system.eventargs) handles button2.click dim integer newpicturebox.image = image.fromfile("c:\users\hp\desktop\ground.bmp") newpicturebox.name = "image" & (i) newpicturebox.visible = true newpicturebox.top = 200 newpicturebox.width = 100 newpicturebox.height = 50 newpicturebox.left = 100 + gotoright newpicturebox.sizemode = pictureboxsizemode.autosize 'add control form controls.add(newpicturebox) gotoright = gotoright + newpictureb

c++ - C# wcf service plugin model -

i planning project management system companies proprietary server technology. system consist of 3 main components: service runs on servers want control, central management server sends commands/gets data services, , client application connects central management server. these components written in c#, , communicate via wcf. the challenge face enabling plugin-in support service running on servers. of tutorials/examples i've found 10 years old, , none deal implications of wcf. here example of functionality need: another developer @ company (who doesn't have access source of system) wants able disk space c:\ drive on 1 of servers using client app of management system. create dll copied server, , added config file service. should able disk space server no further changes system. a nice-to-have, although i'm not sure possible, support plugins written in either c#, c++, or delphi. i looking place start, tutorials/examples, , general concept of how system (and w

database performance - Drawbacks of using manually created temporary tables in MySQL -

i have many queries use manually created temporary tables in mysql. want understand if there drawbacks associated this. i ask because use temporary tables queries fetch data shown on home screen of web application in form of multiple widgets. in organization significant number of users, involves creation , deletion of temporary tables numerous times. how affect mysql database server ? execution plans can't optimal when add/use/remove tables when talk databases in general. takes time generate execution plan, db unable create 1 when use described approach.

casting - C# - is operator - Check castability for all conversions available -

edited after reading further, modified question more specific. as per microsoft documentation : an expression evaluates true if provided expression non-null, , provided object can cast provided type without causing exception thrown. otherwise, expression evaluates false. here issue below. var test = (int32)(int16)1; // non-null , not cause exception. var test2 = (int16)1 int32; // evaluates false. the documentation states: note operator considers reference conversions, boxing conversions, , unboxing conversions. other conversions, such user-defined conversions, not considered. so, i'd assume doesn't work above because user-defined conversion. how check see if castable type including non-reference/boxing/unboxing conversions? note: found issue when writing unit tests casttoordefault extension works on types, including non-reference types (as compared as ). refactored answer based on mike precup's linked code i cleaned answer bec