Posts

Showing posts from April, 2011

javascript - modifying a multiple selects validation with jquery -

what i've got far: jsfiddle what want is: add class "invalid" <select> if not selected in it's row remove class if 3 selects in row selected if <select> s in 1 row selected submit form if 1 <select> selected add "invalid" class other 2 selects in same row this html , js included in fiddle link above : <form id="productoptions" name="product-options"> <div class="selects s1"> <select name="selectss1" id="size1" class="product-select-options-size"> <option>-size</option> <option>small</option> <option>medium</option> <option>large</option> <option>x-large</option> </select> <select name="selectsc1" id="color1" class="product-select-options-color"> <option>-color</option> <opti...

xcode - Reading file line by line in iOS SDK -

i have texfile follows: line1 line2 line3 line4 line5 .... i want read file 2 arrays of string line1, line3, line 5,... go array1 , line 2, line 4, line 6,... go array2 . each element of arrays stores 1 line. step 1) read file ( [nsstring stringwithcontentsoffile:encoding:error:] ) step 2) split string ( [nsstring componentsseparatedbycharactersinset:[nscharacterset newlinecharacterset]] ) step 3) iterate on array , insert 2 arrays

Heap corruption while freeing allocated memory in C -

in attempt free memory after malloc command prevent memory leaks, running heap corruption problem during runtime. debug telling me application trying write memory after end of heap buffer has been reached. here have simplified isolate problem. #include <stdio.h> #include <stdlib.h> #include <math.h> main(){ int i,j,n; int temp[4]; int **a; printf("amount of intervals entered: "); scanf("%d", &n); //allocate memory 2d array of size (n x 4) = (int**) malloc(n*sizeof(int*)); (i=0;i<4;i++){ a[i] = (int*) malloc(4*sizeof(int)); } if (!a){ printf("malloc failed %d\n",__line__); exit(0); } printf("please enter intervals line @ time followed return: \n"); for(i=0;i<n;i++){ scanf("%d %d %d %d",&a[i][0], &a[i][1], &a[i][2], &a[i][3]); } for(i=0;i<n;i++){ printf("%d, %d, %d, %d\n", a[i][0], a[i][1], a[i][2], a[i][3]); } // free allocated memory (i=0;...

mySQL to PostgreSQL concat first name and last name for name search (Ruby on Rails) -

hey i'm trying figure out how convert statement works in mysql postgresql , curious if knows solution. here statement works in mysql: def self.by_name(keywords) if keywords find(:all, :conditions => ["concat(first_name," ",last_name) like?", "%#{keywords}%"]) end end here statement found on this site had similar problem, doesn't work me, in, if search contact.by_name("bobby"), there no results. def self.by_name(keywords) if keywords find(:all, :conditions => ["textcat(textcat(first_name,text ' '),last_name) like?", "%#{keywords}%"]) end end the idea search "bobby", "fishcer", or "bobby fischer" , match either first name, last name, or both first , last name. thanks! you can use concatenation operator ( || ) paste together: :conditions => [ "coalesce(first_name, '') || ' ' || coalesce(las...

spring - How springSecurityFilterChain Skips Authentication for already logged in requests -

i have been working on spring security, , working well. went debugging how works. filters configured springsecurityfilterchain via http namespace. 1 of them authentication filter providing authentication. found when new login request comes(no previous session) authentication filter invoked, when request comes logged in user, i.e, session existing, authenticationfilter not invoked. coudn't find , how 'springsecurity' skips authentication logged in requests. please me understand this. thanks i think sessionmanagementfilter takes care of this: if (!securitycontextrepository.containscontext(request)) { authentication authentication = securitycontextholder.getcontext().getauthentication(); if (authentication != null && !authenticationtrustresolver.isanonymous(authentication)) { // user has been authenticated during current request, call session strategy try { sessionauthenticationstrategy.onau...

download image using php form -

i need download particular image page using submit button, using form , php submit action, here html , php code html code <form name="logo" action="" method="post"> <input type="hidden" name="lgpath" value="images/logo/<?php echo $selpro['lgpat'];?>"> <img src="images/cmplogo/<?php echo $selpro['lgpat'];?>"> <div><input type="submit" value="<?php echo $selpro['lgname'];?>" name="dwnlg" id="dwnlg"></div></div> </form> php code <?php if($_post['dwnlg']) { $lgpath=$_post['lgpath']; header('content-disposition: attachment; filename="'.$lgpath.'"'); } ?> i gave path download image header it's downloaded current page file, how can solve it? try following code download...

sql server - How to group the rows and move them into new column in the same table? -

Image
i want group rows , move them new column in same table. here ilustration: and query i've made far: select month([date]) bulan, [type] tipe, sum([net qty]) total_karton, cast(sum([cm1 (rp)]) decimal) total_uang tbl_weeklyflash_id datediff(month,[date],current_timestamp) between 0 , 2 group month([date]), [type] order month([date]), [type] how that? you want pivot - there's example @ http://www.mssqltips.com/sqlservertip/1019/crosstab-queries-using-pivot-in-sql-server-2005/

blocking the activities once they are executed in android -

i working on application contain register activity it's first page on tabs. want once user register whenever user starts application should run main menu screen , should never display register screen till user uninstall application , reinstall again. you can use sharedpreferences. example: sharedpreferences mprefs = getsharedpreferences("mypreferences", context.mode_private); sharedpreferences.editor editor = mprefs.edit(); editor.putboolean("firsttime", true); editor.commit(); so can check if firsttime true doing this: sharedpreferences mprefs = getsharedpreferences("mypreferences", context.mode_private); if(mprefs.getboolean(firsttime, false){ //show screen }

c# - Catch "switching workspaces" event in MVVM -

i have application build mvvm pattern josh smith ( http://msdn.microsoft.com/en-us/magazine/dd419663.aspx ). when have several workspaces opened in app, want catch event of switching workspaces/tabs can save content of current workspace first. have looked throught workspaceviewmodel , viewmodelbase, don't know how add eventhandler. i have found solution in post, had tweak little bit : what proper way handle multiple datagrids in tab control cells leave edit mode when tabs changed? basically have added eventhandler on previewmousedown of tabcontrol generating different workspaces. private void tabcontrol_previewmousedown(object sender, mousebuttoneventargs e) { mainwindow_vm dc = (mainwindow_vm)this.datacontext; if (isundertabheader(e.originalsource dependencyobject)) //do need done before switching workspace // in case, switch focus dummy control objectcontext save everything, focused textbox } private bool isunderta...

jsf 2 - JSF Initialize Map Object -

i'm starting first steps in jsf. i've read link http://docs.oracle.com/javaee/6/tutorial/doc/bnawq.html#bnaww in regards map initialization. the problem is, want populate map values residing in file. how can that? i've tried not using faces-config.xml , calling support method in bean's constructor, select list box isn't populated. my bean class: @managedbean public class adgrouplistbean { private static final string with_access = "d:\\workspace\\accesscontrol\\permissions.txt"; private static final string without_access = "d:\\workspace\\accesscontrol\\nopermissions.txt"; private map<string,string> withaccess, withoutaccess; private ldapqueries queries; public adgrouplistbean(){ withaccess = new linkedhashmap<string, string>(); withoutaccess = new linkedhashmap<string, string>(); queries = new ldapqueries(); initlist(with_access, withaccess); initlist(without_access, withoutaccess);...

Rails partial not rendering with JavaScript -

i'm trying render partial in app, reason not render. think has asset pipeline , fact not correctly implementing javascript want use in partial. test partial simple sentence works fine. can direct me in proper use of javascript in app? here jsfiddle of trying show: http://jsfiddle.net/yzqg4/ problematic partial: <%= javascript_include_tag "highcharts", "exporting", "jquery-1.4.2.min", "rails" %> <script type="text/javascript" charset="utf-8"> $(function() { var chart; $(document).ready(function() { chart = new highcharts.chart({ chart: { renderto: 'panel_contents', type: 'column' }, xaxis: { categories: ['automotive', 'agency', 'contractor', 'country club', 'other'] }, yaxis: { min: 0, tit...

javascript - JQuery PriceFormat and OnChange -

i'm using jquery priceformat plugin (http://jquerypriceformat.com/). my code following: $('#valor').priceformat({ prefix: 'r$ ', centsseparator: ',', thousandsseparator: '.', limit: 8, centslimit: 2 }); however, want capable of changing value of input while users type value. example, input i'm using priceformat in, product price. but, there input called taxes, example, dinamically changed price (let's tax 1% of price). want capable of changing tax value while user change product price. how can this? i have solved issued binding keyup event function this: function calculartaxa(){ //code of function here } $("#valor").bind('keyup', calculartaxa); hope someone. ;d

html - Why isn't this image showing? -

Image
i made header image, reason can't appear css. here's screenshot: the header in same image directory index.html file. background image appearing, not header. typed header twice in html div test in 2 different spots see if working, reason not showing up, don't lol. thanks. #header { background-image:url('../emailheader.png'); width:100%; height:100%; background-repeat:no-repeat; } <div id="header"></div> here's example of it. not sure why doesn't work. demo you need provide height or dependent on height of inner content, 0 #header { background-image:url('http://i.imgur.com/nctiy.png'); width:100%; background-repeat:no-repeat; height:200px; }

iphone - How to add UISearchBar in to my tableView programmatically? -

now have 2 mutable array, 1.songsname mutablearray; 2.songurl mutablearray; on songsname mutablearray contains huge collection of songs name list,the names coming url, , songurl mutablearray contains corresponding url of songsname am using xmlparser retrieve url content,custom cell used displaying content,in custom cell contains 1 label display song name , 1 play button play song want use search bar in tableview now, please me write code if use search bar in tableview , scrolling time search bar scroll table-view cell, bad see in so answer and use uisearch bar tableview and see uisearchdisplaycontroller class refernce in cellforrowatindexpat , in umberofrowsinsection should test witch tableview displayed , return desired values. if(tableview == self.searchdisplaycontroller.searchresultstableview){ // search view population } else { // data view population }

ruby on rails - RailsRestore Session Data with Session_ID -

during checkout process data stored in session variables until payment had been successful @ stage data saved database. our latest integration new payment gateway client directed gateway , directed back. the problem when user redirected payment gateway, new session created , data "lost". if have session_id of client before sending him payment gateway, , pass session_id through process, there anyway can restore previous session session_id. this is: application.config.session_store :cookie_store, :key => ' thanks in advance

Android ProgessBar while loading WebView -

in application, have webview loads url internet. now, due slow networks page takes long time load , user sees blank screen. i want show progressbar while webview gets loaded , hide progessbar when webview gets loaded completely. i know how use progressbar , asynctask s, here problem. this code use load webview . mwebview = (webview) findviewbyid(r.id.webview); mwebview.getsettings().setjavascriptenabled(true); mwebview.setwebviewclient(new hellowebviewclient()); mwebview.loadurl(web_url); and custom webviewclient class private class hellowebviewclient extends webviewclient { @override public boolean shouldoverrideurlloading(webview view, string url) { view.loadurl(url); return true; } } now, if try show progressbar using asynctask s guess have give code load url in doinbackground() function of asynctask , show progress through onprogressupdate() function. but, how load url inside doinbackground() doinbackground...

Android change background of tabs -

does know how can edit tabs background have red gradient background when not selected , when selected dark red gradient? change text color white? you can use code tabhost.tabspec spec; tabhost tabhost = gettabhost(); spec = tabhost.newtabspec("1").setindicator("tab host 1", res.getdrawable(r.drawable.xxx)).setcontent(intent_name); tabhost.addtab(spec); tabhost.setcurrenttab(2); settabcolor(tabhost); tabhost.setontabchangedlistener(new ontabchangelistener() { @override public void ontabchanged(string tabid) { settabcolor(tabhost); } }); } public static void settabcolor(tabhost tabhost) { (int = 0; < tabhost.gettabwidget().getchildcount(); i++) { tabhost.gettabwidget().getchildat(i).setbackgroundcolor(color.parsecolor("#000000")); // unselected } tabhost.gettabwidget().getchildat(tabhost.getcurrenttab()).setbackgroundcolor(color.parsecolor("#74df00")); // selected }

xcode - Compilation warning: no rule to process file of type sourcecode.c.c for architecture i386 -

i'm trying build libcurl static library ios xcode 4.2 + sdk 5.0 on osx 10.6.8 apple llvm compiler 3.0 or llvm gcc 4.2. it compiled (with both compilers) has many warnings this: warning: no rule process file '$(project_dir)/../../../../projectname/libs/curl-7.26.0/src/tool_bname.c' of type sourcecode.c.c architecture i386 i checked target->compile sources . has .c files needs , don't have .h files. i tried change compile sources c no take effect. i'm not understand how fix , why type of c sources sourcecode.c.c

Why is it better to use class name instead of objects to access class methods or variables in Java? -

i reading code conventions java http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-137265.html#587 . in that, have mentioned should avoid use of objects access class variable or method , should use class name instead. avoid using object access class (static) variable or method. use class name instead. example: classmethod(); //ok aclass.classmethod(); //ok anobject.classmethod(); //avoid! is there particular reason in terms or performance or else? by class variables assume mean static variables. the use of static variables/methods through instance variables should avoided because it's confusing reader. since can use instances access instance variables, reading code calls static methods through instance can confuse reader what's going on. image case, thread.sleep , static method: thread.sleep(1000); since method static , calling through class name, it's intuitive reader deduce effect put current...

asp.net - How to measure WebSockets and WebService latency -

i have 2 applications web socket , web service created in .net/web form , running locally there online tool or there simple code can measure latency? dev tools in chrome has timing/logging functionnalities may sufficient?

Ember.js: Whats the difference between Router / Route and StateManager / State? -

it seems older examples of routing use statemanager , newer examples use concept of router . difference , why use 1 on other? router , route subclasses of statemanager , state, routing specific code added directly statemanager code, in last few weeks effort has been made extract out. basically use router core flow of app deals urls , forth, if need use additional state managers in other places in application, can use statemanager/state without routing code being included when it's not needed.

Access Replace Function -

i have following access query: select [city] [patient] replace([patient].[city],' ',' ') 'san d*' i'm relatively used work data type mismatch in criteria expression. any ideas? edit anyone willing test sql against own data? is city stored string? if stored number (perhaps fkey table) make sense you're using string operations on it. edit: note self: stop forgetting null values.

c++ - Send UDP packet to a public IP using Boost.asio -

i want send udp packets static ip 122.***.***.*** udp server listens on port 1213. udp::resolver resolver(io_servicesend); udp::resolver::query query(udp::v4(),"122.***.***.***","1213"); udp::endpoint receiver_endpoint = *resolver.resolve(query); udp::socket socket(io_servicesend); socket.open(udp::v4()); boost::shared_ptr<std::string> message(new std::string("transfer")); socket.send_to(boost::asio::buffer(*message), receiver_endpoint); but fails. because sending private port rather sending nat's port. tcp works perfectly. can 1 explain me theory or post link. and server code is udptunnel::udptunnel(boost::asio::io_service& io_service) :socket_(io_service, udp::endpoint(udp::v4(), 1213)) { start_receive(); } void udptunnel::start_receive() { socket_.async_receive_from( boost::asio::buffer(recv_buffer_), remote_endpoint_, boost::bind(&udptunnel::handle_receive, this, ...

How to pass array of argument to batch file? -

i having batch file called formalbuild.bat ,it take parameter name called componentname. for ex. build different components below. formalbuild.bat servicecomponent formalbuild.bat datamodelcomponent formalbuild.bat ... ... formalbuild.bat somexyzcomponent is possible create array of component name , pass 1 one component batch file build? as component name changes, use for loop or better for/f loop. for %%c in (servicecomponent datamodelcomponent somexyzcomponent ) ( call formalbuild.bat %%c ) if list of components long split them multiple lines for %%c in (servicecomponent datamodelcomponent component3 ... component_n somexyzcomponent ) ( call formalbuild.bat %%c )

php - reverse htmlspecialchars -

this may seem simple problem couldn't find in archives. how 1 reverse effects of htmlspecialchars? i tried this: $trans_tbl = get_html_translation_table (html_entities); $trans_tbl = array_flip ($trans_tbl); $html = strtr ($html, $trans_tbl); but didn't work. there simple way this? use htmlspecialchars_decode() <?php $str = "<p>this -&gt; &quot;</p>\n"; echo htmlspecialchars_decode($str); // note here quotes aren't converted echo htmlspecialchars_decode($str, ent_noquotes); ?> reference - php official doc

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

i trying reposotries using c# code process svncommand = null; var psi = new processstartinfo("svnadmin"); psi.redirectstandardoutput = true; psi.redirectstandarderror = true; psi.useshellexecute = false; psi.arguments= @"dump c:\repositories\myrepo > c:\temp\myrepodumpfile.dump"; using (svncommand = process.start(psi)) { var myoutput = svncommand.standardoutput; var myerror = svncommand.standarderror; debug.write("output :" + environment.newline + environment.newline + myoutput.readtoend() + environment.newline + "error :" + environment.newline + environment.newline + myerror.readtoend()); svncommand.close(); } when use dump command commandline svnadmin dump c:\repositories\myrepo > c:\temp\myrepodumpfile.dump it works fine when try ...

.net - Adding restrictions to xsd generated from wcf -

so i'm doing research on how format wsdl , xsd generated wcf, adding annotations/documentation wsdl , xsds along adding restrictions various parameters. so far i've been able add documentation both wsdl , xsds creating attributes implement iwsdlexportextension interface along ioperationbehavior interface. for general idea of modifying schemas see: http://thorarin.net/blog/post/2010/08/08/controlling-wsdl-minoccurs-with-wcf.aspx for general idea of adding annotations wsdl see: http://msdn.microsoft.com/en-us/library/ms731731(v=vs.110).aspx however run trouble when trying add restrictions elements(by adding simple types) in xsd. from here can either exception occur stating can't set elements type because has read-only type associated it, or can try using read-only type add restriction, nothing happens. here's code generating exception (system.xml.schema.xmlschemaexception: type attribute cannot present either simpletype or complextype.) : var com...

ios - Passing data between tabs in Xcode 4.3 -

i trying pass data 1 tab in xcode 4.3 struggling work. following video tutorial on youtube , goes fine until end. uses older version of xcode (i using xcode 4.3.1) cant find way achieve does. here video: http://www.youtube.com/watch?v=4wowsgstzo0 between 5:40 , 6:30 opens mainwindow.xib , control drags app delegate 2 views wants share data between , completes work. can't find way achieve in version of xcode using storyboards, can point me in right direction? depending on kind of data trying pass around, can store in app delegate , pull there out of each view controller. you can access app delegate anywhere in application this: [[uiapplication sharedapplication] delegate].whateverproperty you need import app delegate header file files this.

c++ - Calling Function Overwrites Value -

i have several configuration flags implementing structs. create object. call method of object flag, triggers comparison between 2 flags. however, time, 1 of flags has been overwritten somehow. to clarify, here's simplified version of code should illustrate i'm seeing: class flag_type { unsigned int flag; /*more stuff*/ }; flag_type flag1 flag_type flag2 class myobject { public: void method1(const flag_type& flag_arg) { //conditionals, , then: const flag_type flag_args[2] = {flag_arg,flag_arg}; method2(flag_args); } void method2(const flag_type flag_args[2]) { //conditionals, , then: method3(flag_args[0]); } void method3(const flag_type& flag_arg) { //actually in superclass //stuff if (flag_arg==flag1) { /*stuff*/ } //stuff } }; int main(int argc, const char* argv[]) { //in functions called main: myobject...

asp.net mvc - repository pattern in asp. net mvc3 -

i have started teaching myself c# , asp.net. trying build simple blog application. confused repository pattern usage. have seen few tutorials , implementation varies. for blog application, have 2 database tables (models) - blogs , comments. currently, have idbcontext looks this: public interface idbcontext { iqueryable<blog> findallblogs(); iqueryable<blog> findblogsinmonth(int month); blog getblog(int id); void add(blog blog); void update(blog blog); void delete(blog blog); void add(comment comment); //void remove(comment comment); } and have repository looks this: public class blogrepository : idbcontext { private blogdb db = new blogdb(); public iqueryable<blog> findallblogs() { return db.blogs.orderbydescending(b => b.publishdate); } public blog getblog(int id) { return db.blogs.single(b =>...

node.js - upgraded node to v0.8 and started receiving an error for sys/util -

i upgraded node v0.6.12 0.80 , started receiving error below - have removed sys module import still getting error. helpful hints helpful. not suing stylus either. path.exists called `fs.exists`. sys.js:1 throw new error( error: "sys" module called "util". @ sys.js:1:69 @ nativemodule.compile (node.js:602:5) @ function.nativemodule.require (node.js:570:18) @ function.module._load (module.js:297:25) @ module.require (module.js:362:17) @ require (module.js:378:17) @ object.<anonymous> (/node/node_modules/stylus/lib/token.js:12:15) @ module._compile (module.js:449:26) @ object.module._extensions..js (module.js:467:10) @ module.load (module.js:356:32) upgrade node v0.8.1. solve problem

objective c - UI splt vew capabilty -

there id try in app know if can done. with ui splitview, know if change left view...the right view changes example have left view containing cat names. each time change cat name in left view controller see image of cat in right. ii wonderng if t possble how name of cat gets passed in n previous screen. , when change left contoller different characteristics of particular cat eye colur, colur etc etc thanks the left view typically has navigation controller, means can drill down through various levels of information , choices until 1 needs use right side detail.

How to get CherryPy's cherryd serving static files -

i want start server, point @ directory , have serve static files. thought cherryd good/easy that. i've read cherryd usage , portion of online docs, posts here static files , cherrypy, i've yet find information bare configuration file cherryd. i've been able piece following: [global] server.socket_host: "127.0.0.1" server.socket_port: 8000 log.error_file = '/users/chb/code/app/test/log/cherrypy.error.log' [/] tools.staticdir.on: true tools.staticdir.root: '/users/chb/code/app' tools.staticdir.dir: '.' i tried alternate configuration: [global] server.socket_host: "127.0.0.1" server.socket_port: 8000 log.error_file = '/users/chb/code/app/test/log/cherrypy.error.log' [/] tools.staticdir.root: '/users/chb/code/app' [/index.html] tools.staticfile.on: true tools.staticfile.filename: '/users/chb/code/app/index.html' the latter adheres more docs (see below). visiting 127.0.0.1:8000 gets me 404. w...

objective c - Display UIMenuController in editingDidBegin of a UITextField -

i want display uimenucontroller right after textfield has become active. i'm doing right is: - (ibaction)textfieldeditingdidbegin:(uitextfield *)sender { // textfield menu item uimenucontroller *menu = [uimenucontroller sharedmenucontroller]; [menu settargetrect:sender.frame inview:self.view]; [menu setmenuvisible:yes animated:yes]; } the method gets called not display menu... if touch+hold gesture on textfield comes regularly. i hope there's simple solution that, thanks i found solution question. you can make uimenucontroller appear when start editing text field method: - (void)textfielddidbeginediting:(uitextfield *)textfield { double delayinseconds = 0.1; dispatch_time_t poptime = dispatch_time(dispatch_time_now, delayinseconds * nsec_per_sec); dispatch_after(poptime, dispatch_get_main_queue(), ^(void){ uimenucontroller *menu = [uimenucontroller sharedmenucontroller]; [menu settargetrect:textfield.frame in...

javascript - making a gviz chart with AngularJS -

i'm trying make gviz pie chart example here example https://google-developers.appspot.com/chart/interactive/docs/quick_start in angularjs. what services need write? the example code above uses a google ajax library load gviz library a gviz datatable. a gviz pie chart document.getelementbyid it seems i'll need write own service each of these, except $document . true? seems awful lot of boiler plate =/ (side question, why wrapping these service thing?) can take stab @ datatable service might like? i'm not sure how access google.visualization.datatable() 'translate' line. var data = new google.visualization.datatable(); i'd have give closer look, would want create 1 directive. looks cool charting package. if want ideas on wrapping components in directives @ angularjs wiki page (version 1.0.0 ones) on github , there offshoot group angular-ui i'm involved in wrapping , creating reusable angular components.

Is there any way to get the range of colors used in ImageMagick's -fuzz option? -

i'm trying hack image search uses color "distance," (or "tolerance", or "variance") similar what's done in imagemagick's -fuzz option: http://www.imagemagick.org/usage/color_basics/#fuzz_distance . what i'm hoping a range or array of rgb values single initial pixel can use match against comparison points in database. obviously what's happening -fuzz euclidean distance formula describing sphere in rgb cube, i'm not sure find mathematics or how use imagemagick (or other library) accomplish this. thoughts? as stated here in magemagick's forums , color b within fuzz range r of color a if euclidian distance lower r: sqrt((b.r - a.r)^2 + (b.g - a.g)^2 + (b.b - a.b)^2) < r r , g , b stand colors' respective red, blue , green values. if don't have transparency, that's it. if need consider transparency, have multiply colors respective alpha channel value before using them in formula. in 3...

Slow compound mysql update query -

we're doing update query between 2 database tables , ridiculously slow. in: take 30 days perform query. one table, lab.list, contains 940,000 records, other, mind.list 3,700,000 (3.7 million) update sets field when 2 between conditions met. query: update lab.list l , mind.list m set l.locid = m.locid l.longip between m.startipnum , m.endipnum , l.date between "20100301" , "20100401" , l.locid = 0 as now, query performing 1 update every 8 seconds. we tried mind.list table in same database, doesn't matter query time. update lab.list l, lab.mind m set l.locid = m.locid longip between m.startipnum , m.endipnum , date between "20100301" , "20100401" , l.locid = 0; is there way speed query? imho should make 2 subsets of databases: mind.list.longip between m.startipnum , m.endipnum lab.list.date between "20100301" , "20100401" and update values these subsets. somewhere along line think made mistake, whe...

c++ - pthread synchronization on two different conditions -

i have worker thread processing queue of work items. work items might not processable right now, worker thread might push them queue. void* workerfunc(void* arg) { workitem* item = null; while(true) { { scoped_lock(&queuemutex); while(workerrunning && workqueue.empty()) pthread_cond_wait(&queuecondition, &queuemutex); if(!workerrunning) break; item = workqueue.front(); workqueue.pop(); } // process item, may take while (therefore no lock here), // may considered unprocessable if(unprocessable) { scoped_lock(&queuemutex); workqueue.push(item); } } return null; } now need following: time time, need scan through work queue remove items not needed anymore (from same thread enqueues work items). cannot use queuemutex this, because might miss item being processed, need way pause ...

php - Records disappearing in PDO mssql transaction loop -

i have following code (more or less) import anywhere 500.000 4.000.000 rows: $ssql = "insert table (a,b,c) values(?,?,?)" $osqlstmnt = $pdo->prepare($ssql); $osqlstmnt->setattribute(pdo::sqlsrv_attr_encoding, pdo::sqlsrv_encoding_system); if (!$osqlstmnt) { echo $pdo->errorinfo(); // handle errors } $pdo->begintransaction(); $ilinecounter = 1; while (($sline = fgets ($ocsv, 8000)) !== false) { $aline = explode('|', $sline); //fgetscsv did not work if ($ilinecounter % 100 == 0) { lo("inserting row " . $ilinecounter); $pdo->commit(); sleep(0.15); $pdo->begintransaction(); } try { $osqlstmnt->execute($aline); $isuccesulinserts++; } catch (exception $e) { print_r($e); $ifailedinserts++; } $ilinecounter++; } $pdo->commit(); as can see, perform commit every 100 lines, , added sl...

php - List with percentage -

i'm trying make percentage of test answers. i have mysql db 3 tables table tests id | name ---+-------- 1 | test 1 2 | test 2 table questions tests' questions id | name | test_id ---+------------+-------- 1 | question 1 | 1 2 | question 2 | 1 3 | question 3 | 1 4 | question 4 | 1 5 | question 1 | 2 6 | question 2 | 2 7 | question 3 | 2 8 | question 4 | 2 table answers put answers tests id | question_id ---+------------- 1 | 1 2 | 2 3 | 5 4 | 6 5 | 7 6 | 8 how can list percents of done questions within test. in case this: name | percentage -------+----------- test 1 | 50 test 2 | 100 try select t.name, cast((count(a.id) / count(q.id)) * 100 unsigned) percentage tests t left outer join questions q on q.test_id = t.id left outer join answers on a.question_id = q.id group t.name see sqlfiddle example

Google docs list API PHP -

i want add list of google docs on website(not google site) don't want copy-paste link of docs 1 one. code of website in php. unable find php guide google docs list api version 3.0; php guide available version 1.0 (deprecated) version should use? other options? should use drive? there's library php available. http://code.google.com/p/google-api-php-client/ after grab that, check out documentation on how use drive api .

javascript - Slider images don't work in internet explorer, but works in the other ones -

http://teothemes.com/wp/ the slider not showing on internet explorer, after refresh times starts working. that's not acceptable behaviour, can't understand issue is. it works fine on other browsers, firefox, safari, chrome...so it's ie it seems js scripts not being loaded initially remove console.log() lines (or comment them out) in js files, should work in ie.

javascript - extJS: set 'config options' on field by JS -

why can't set ' config options ' methode set set({value: 'new value',disabled:true}); how can set 'properties' field var name = { fieldlabel:'name', value: 'test', id:'id-name', xtype: 'textfield', }; this.form= new ext.formpanel({ items:[name], buttons: [{ text : 'set value', handler: function() { ext.getcmp('id-name').set({value: 'new value',disabled:true}); }] }); resetting component properties using object not part of design of extjs. config used in object creation , when first used in constructor applied object using special methods extjs class system core generate getters , setters , initialize component them. not possible trying , desired result. in example above, textfield initialized config overriding default values of component during creation , generates getters , setters attributes, value, id, , fieldlabel ne...

c++ - UnsatisfiedLinkError for native cpp function in Android app (ndk) -

i trying run easy android ndk app in cpp, unsatisfiedlink error generate() function. any appreciated. quite fluent in c++, java little bit rusty. have been trying lot of tips web concerning naming, far no luck. here files: native.cpp: #include <string.h> #include <jni.h> jstring java_com_optimuse_app_optimuseappactivity_generate(jnienv* env, jobject thiz){ return env->newstringutf("hello jni !"); } android.mk: local_path := $(call my-dir) include $(clear_vars) local_module := native local_src_files := native.cpp include $(build_shared_library) i compile ndk-build , goes well, provides me libnative.so, located in project directory. use eclipse rest. optimuseappactivity.java: package com.optimuse.app; import android.app.activity; import android.widget.textview; import android.os.bundle; public class optimuseappactivity extends activity { @override public void oncreate(bundle savedinstancestate) { super.oncreate...

c# - Mapping a collection to a subselect with Fluent nHibernate -

i've got class looks like: public class competitor { public virtual int competitorid { get; set; } public virtual string firstname { get; set; } public virtual string lastname { get; set; } public virtual ienumerable<string> sportscompeted { get; set; } } sportscompeted list of sportids (strings) resolved so: select distinct sportid results competitorid = xxx how go mapping that? looking @ hasmany can specify where clause, don't think that's quite i'm looking in case? i'm using fluent mappings, omitted brevity. you should able .element() . like: hasmany(x => x.sportscompeted) .keycolumn("competitorid") .element("sportid") // can define element type second parameter .table("results"); more info: mapping collection of strings nhibernate fluent nhibernate automapping of list<string>? edit: let's have result , sport entities instead: public class sport...

javascript - Spring Framework to Optimize SQL connection? -

so on webproject succesfully connects , reads sql database. code connects looks this. //from here var connection = new activexobject("adodb.connection") ; var connectionstring="data source=<server>;initial catalog=<catalog>;user id=<user>; password=<password>;provider=sqloledb"; connection.open(connectionstring); var rs = new activexobject("adodb.recordset"); //to here rs.open("select * table", connection); rs.movefirst while(!rs.eof) { document.write(rs.fields(1)); rs.movenext; } rs.close; connection.close; simple , effective , have working fine. first 4 (marked here here) run horribly slow , have reconnect every time need read or write sql database... lot project. every time run code (which on every other webpage creating in project) have sit , wait code run. i have been told/ required project, configure design using javascript , spring framework. apparently there either a) way hold connection don't h...

android - null keyevent and actionid = 0 in onEditorAction() (Jelly Bean / Nexus 7) -

i have edit text functions search box in application. in jelly bean on nexus 7 when type text box listening on , hit enter keyevent = null , actionid = 0 passed oneditoraction() method. has else encountered this? i'm thinking might bug. in second if statement below null pointer because actionid = 0 , keyevent = null; // search field logic. @override public boolean oneditoraction(textview v, int actionid, keyevent event) { log.d(tag, "oneditoraction"); if (event != null && event.getaction() != keyevent.action_down) return false; if (actionid == editorinfo.ime_action_search || event.getkeycode() == keyevent.keycode_enter) { .....do stuff(); } } ended adding in null check keyevent. commonsware pointing out happens on 3.0+. seems more workaround solution, works. // search field logic. @override public boolean oneditoraction(textview v, int actionid, keyevent event) { log.d(tag, "oneditoract...

sql server - SQL UPDATE statement combining multiple rows into one column -

i'm working airline data, have query this select invoices.pnr, segments.depart, segments.arrival, segments.departdatetime invoices inner join segments s on i.invoice_id = s.invoice_id` pnr = 'aaaaaa' this returns pnr depart arrival departdatetime aaaaaa dfw mci 7/2/2012 7:30 aaaaaa mci lax 7/2/2012 11:30 aaaaaa lax dfw 7/4/2012 2:30 pm i have column in invoices called routing want show 'dfw-mci-lax-dfw' possible using sql method ? segments listed in order, dfw-mci first mci-lax lax-dfw. edit: if update database dfw-mci-mci-lax-lax-dfw acceptable. can strip out duplicate entries on view layer. i can write in coldfusion, looping , thousands of database updates takes forever. mass update every 100 records, i'd avoid using other sql altogether here's how can value. agree @automatic whether should update database data. since have recalculate every time of rows change. ;with x ( select i.pnr, i.invoice_id, s.de...

php - Logical operations between strings -

suppose have strings, how should transform them in order able use logical operations on them in php? possible? example: want "x=1"&&"x=0" to return false . introduction i noticed have both logical operator && , assignment operator in string = , want evaluate assignment has logical operator in string. don't know how got here very wrong education purpose tag along breakdown "x=1" && "x=0" = false ^ ^ ^ | | | | | x == 1 | | | | , | | x == 0 the above expression false because x can not equal 0 , 1 @ same time to able have such evaluation in php need write own function eg logicalstring can evaluate expression logicalstring("x=1") or logicalstring("x=0") assumption $x = 1; // imagine value of x example 1 && // start evaluation && if (logicalstring("x...

ruby - Import into local scope -

consider # sun.rb class sunshine def bright? return true end end def greeting(greeter) puts "hello, sun #{greeter}" end # main.rb def abc my_load "sun.rb" greeting("abc") return sunshine.new end s = abc puts s.bright? greeting("adrian") ... can have such my_load here greeting("abc") call succeeds, latter greeting("adrian") causes nomethoderror; puts s.bright? call succeeds. so, synthetically speaking: such classes,methods sun.rb in scope of caller of my_load , additionally garbage collected when not referenced anymore? first off, stand-alone (called on main object) method call cause nameerror exception if doesn't exist. nomethoderror if call method on object. nothing #=> nameerror class a; end a.nothing #=> nomethoderror this because when call nothing on main , doesn't know if method or variable. however: nothing() #=> nomethoderror because () knows meth...

python - Setting up django on a virtual machine -

i have virtual machine running peppermint os 2 (basically ubuntu). i've been trying follow following tutorial: http://jeffbaier.com/articles/installing-django-on-an-ubuntu-linux-server/ and far has worked out tutorial has stated. apache httpd.conf file looks following: servername localhost maxrequestsperchild 1 sethandler python-program pythonhandler django.core.handlers.modpython setenv django_settings_module myproject.settings pythonpath "['/home/<my_user_name>/django_projects'] + sys.path" sethandler none sethandler none sethandler none sethandler none whenever try , and go "localhost/", shows me /var/www/ folder (the index.html file says "it works!") , not django startpage should come up. contents of /var/www "admin_media" , "media" what need do? thank you. try mod_wsgi or uwsgi , it's easier config, robust, , faster. you @ django doc - use django ...

python - How to send POST request? -

i found script online: import httplib, urllib params = urllib.urlencode({'number': 12524, 'type': 'issue', 'action': 'show'}) headers = {"content-type": "application/x-www-form-urlencoded", "accept": "text/plain"} conn = httplib.httpconnection("bugs.python.org") conn.request("post", "", params, headers) response = conn.getresponse() print response.status, response.reason 302 found data = response.read() data 'redirecting <a href="http://bugs.python.org/issue12524">http://bugs.python.org/issue12524</a>' conn.close() but don't understand how use php or inside params variable or how use it. can please have little trying work? if want handle http using python, highly recommend requests: http humans . post quickstart adapted question is: >>> import requests >>> r = requests.post("http://bugs.pyt...

ios - Crash (EXC_BAD_ACCESS) when using CCCrypt -

below code encrypt string, nsstring *token = @"us=foo;pw=bar;pwalg=false;"; nsstring *key = @"testtest"; const void *vplaintext; size_t plaintextbuffersize; plaintextbuffersize = [token length]; vplaintext = (const void *) [token utf8string]; cccryptorstatus ccstatus; uint8_t *bufferptr = null; size_t bufferptrsize = 0; size_t *movedbytes; bufferptrsize = (plaintextbuffersize + kccblocksize3des) & ~(kccblocksize3des - 1); bufferptr = malloc( bufferptrsize * sizeof(uint8_t)); memset((void *)bufferptr, 0x0, bufferptrsize); // memset((void *) iv, 0x0, (size_t) sizeof(iv)); nsstring *initvec = @"init vec"; const void *vkey = (const void *) [key utf8string]; const void *vinitvec = (const void *) [initvec utf8string]; ccstatus = cccrypt(kccencrypt, kccalgorithmdes, kccoptionecbmode, vkey, //"123456789012345678901234", //key kcckeysizedes, nul...

python - how to get matplotlib physical (not data) scale -

Image
i have simple code: import numpy np import matplotlib.pyplot plt matplotlib.backends.backend_pdf import pdfpages matplotlib.patches import ellipse plotfilename="test.pdf" pdf = pdfpages(plotfilename) fig=plt.figure(1) ax1=fig.add_subplot(111) plt.xlim([0,10]) plt.ylim([0,10]) ax1.plot([0,10],[0,10]) e=0.0 theta=0 maj_ax=2 min_ax=maj_ax*np.sqrt(1-e**2) const=1 ax1.add_artist(ellipse((5, 5), maj_ax, const*min_ax, angle=theta, facecolor="green", edgecolor="black",zorder=2, alpha=0.5)) plt.grid() pdf.savefig(fig) pdf.close() plt.close() here how looks: as see code, should circle, isn't! have narrowed problem down const term in line 16. don't want use ax1.axis("equal") because data don't have same scales on vertical , horizontal. 1 tell me how can ask matplotlib tell me aspect ratio using can set const term correctly have circle in end? in other words want know ratio of horizontal vertical axis "physical" length (f...

actionscript 3 - Using NFC Reader with Adobe AIR -

i've got acs acr122u nfc reader , smart card. i've tried googling can't seem find native extensions allow me read/write via nfc. would of have resources read on? this can used android , air.

CSS absolute positioning dilemma -

i'm experienced css 1 has me confused - apologies if simple fix. i attempting theme drupal webform has multiple fieldsets. idea stack fieldsets on top of each other. simple css issue of positioning relatively , absolutely - goes wrong containing div collapses instead of maintaining it's shape. you can see problem @ http://164.177.146.240/eventbooking5/node/6 . set background-color of fieldsets green. containing border has red border , positioned relatively. when fieldsets positioned absolutely, stack expect containing div collapses , compromises rest of sites styling i appreciate help. maybe put height onto containing div using css? or use javascript grab height of tallest fieldset , make containing div height? or dynamically each fieldset starting first 1 when move onto anotjher fieldset javascript gets it's height , sets container div height , on.

javascript - Accessing d3.js element attributes from the datum? -

i'm trying access cx & cy attributes of specific svg circles have drawn screen using d3.js's .data() function, can out? code that's trying access below. d3.selectall(".mynode").each( function(d, i){ if(d.someid == targetid){ console.log( d.attr("cx") ); // trying demo point, doesn't work } } i'm quite new d3.js & javascript, i'm not sure if i'm approaching front anyways or perhaps may have missed inbuilt solution? your code trying svg attribute item of data, when want attribute svg dom element, in: console.log(d3.selectall(".mynode").attr("cx")); this give attribute first non-null element of selection; can filter selection dom element looking for: console.log(d3.selectall(".mynode").filter(_conditions_).attr("cx")); or, if you'd access attributes of selected elements, use this in each function: d3.selectall(".mynode").each( function(d, i)...

android - Combine multiple drawables -

i have multiple drawables , want combine 1 drawable (for example, 4 squares create 1 big square, windows logo :)). how can this? you can using tablelayout or linearlayout s. however, if want create single image usin within imageview have create bitmap manually; not hard: bitmap square1 = bitmapfactory.decoderesource(getresources(), r.drawable.square1); bitmap square2 = bitmapfactory.decoderesource(getresources(), r.drawable.square2); bitmap square3 = bitmapfactory.decoderesource(getresources(), r.drawable.square3); bitmap square4 = bitmapfactory.decoderesource(getresources(), r.drawable.square4); bitmap big = bitmap.createbitmap(square1.getwidth() * 2, square1.getheight() * 2, bitmap.config.argb_8888); canvas canvas = new canvas(big); canvas.drawbitmap(square1, 0, 0, null); canvas.drawbitmap(square2, square1.getwidth(), 0, null); canvas.drawbitmap(square3, 0, square1.getheight(), null); canvas.drawbitmap(square4, square1.getwidth(), square1.getheight(), null); i ha...