Posts

Showing posts from August, 2011

Access violation with C++ -

i bit rusty c languages, , have been asked write quick little application take string stdin , replace every instance of letter 'a' letter 'c'. feel logic spot on (largely reading posts on site, might add), keep getting access violation errors. here code: #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> using namespace std; int main() { printf("enter string:\n"); string txt; scanf("%s", &txt); txt.replace(txt.begin(), txt.end(), 'a', 'c'); txt.replace(txt.begin(), txt.end(), 'a', 'c'); printf("%s", txt); return 0; } i can use insight. thank much! scanf doesn't know std::string is. c++ code should this: #include <string> #include <iostream> #include <algorithm> using namespace std; int main() { cout << "enter string:" << endl; string txt; cin >

routing - Rails router: Avoiding long helpers -

consider following snippet router.rb resource :user namespace :settings resource :access_filter end 'settings' end this generates url's want ( user/settings/access_filter ), produces undesired directory structure , long url helpers. in case, helper becomes new_user_settings_access_filter , prefer have new_access_filter . , rails expects accessfilterscontroller reside in module named settings . i way keep flat directory structure, flat url helper structure, "nested" url structure. long no parameters neccessary, don't think controllers , views needs know access filters nested under user model , retain opportunity move them options/access_filter without breaking site. sugggestions on how there appreciated. if want prefix path, avoid nesting , hassle involved using separate scope . organizationally, seems make sense well, since want decouple access filter routes user. scope "user/settings" resource :access_fil

javascript - how to build a visual representation of a wall and tiles with java script? -

so i've been set task interview i'm struggling finish it. task : build html page can input dimensions (height , width) of set of tiles , input dimensions (height , width) of wall. the page return number of tiles needed fill wall, give visual representation of wall tiles on it. so far i've managed easy math work out tiles have no clue start show wall. <form > tile dimensions<br /> width: <input type="text" id="tile_width" />cm height: <input type="text" id="tile_height" />cm <br /> wall dimensions<br /> width: <input type="text" id="wall_width" />cm height:<input type="text" id="wall_height" />cm </form> <button onclick="tilecalc()" >calculate</button> <script language="javascript" type="text/javascript"> function tilecalc() { var tilewidth = document.get

java - Scanner only reading 1st token of a string -

new java language, the following bit of code. whole string isn't written file. first token written file. explanations ? import java.io.filewriter; import java.io.ioexception; import java.util.scanner; public class fichiertextewrite { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub try { system.out.println("entrez le nom d'un fichier :"); scanner in = new scanner(system.in); string filename = in.next(); filewriter fwrite = new filewriter(filename); system.out.println("entrez une phrase memoriser"); fwrite.write(in.next()); system.out.println("writing on file complete "); fwrite.close(); }catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } } i have tried nextline() method didn't se

joomla wrong base href results in wrong CSS template -

i have installed joomla 3.x , modules. one of modules display articles categories of articles, when navigate article , css stylesheets not load. when view source, discovered url css stylesheet in page above becomes: <base href="http://cambridge.mywebcommunity.org/index.php/10-%e7%88%b1%e7%ab%8b%e6%96%b9%e5%8a%a8%e5%90%91%e6%9b%b4%e6%96%b0/3-welcome-to-your-blog" /> ... instead of original put in, here: <base href="http://cambridge.mywebcommunity.org/" /> this happens css stylesheet module. css url loads this: <link rel="stylesheet" href="http://cambridge.mywebcommunity.org/10-爱立方动向更新/modules/mod_news_pro_gk5/interface/css/style.css" type="text/css" /> ... instead of original css url put in: <link rel="stylesheet" href="http://cambridge.mywebcommunity.org/modules/mod_news_pro_gk5/interface/css/style.css" type="text/css" /> so have figured out issue urls no

jquery - How to launch existing HTML content in a Bootstrap Modal dynamically, without having modal html for each link? -

i've read few articles on loading remote content modals or dynamic content, , have read #531 issue https://github.com/twitter/bootstrap/issues/531 can't quite find want, perhaps because i'm thinking problem in wrong way. i have list of content, each item showing different product , details it. want able click 'view details' link each product, , have same content populate in modal, use css display small additional information (my question how retrieve different content dynamically, think given how little data need, it's not worth request). the html list item: <ul> <li class="span4 product"> <div class="inner"> <img src="xxxxx" alt="product xxxxx" /> <div class="control-group"> <label class="control-label">product type:</label> <span class="field">really cool product<

io - How performance of reads/writes to regular file varies when linux kernel memory load becomes high? -

it seems writes/reads regular files can't not made non-blocking. found following references support: from linux programming interface: linux , unix system programming handbook: "--- nonblocking mode can used devices (e.g., terminals , pseudoterminals), pipes, fifos, , sockets. (because file descriptors pipes , sockets not obtained using open(), must enable flag using fcntl() f_setfl operation described in section 5.3.) o_nonblock ignored regular files, because kernel buffer cache ensures i/o on regular files not block, described in section 13.1. however, o_nonblock have effect regular files when mandatory file locking employed (section 55.4). ---" from advanced programming in unix environment 2nd ed: "--- said system calls related disk i/o not considered slow, though read or write of disk file can block caller temporarily. ---" from http://www.remlab.net/op/nonblock.shtml : "--- regular files readable , writeable. stated in releva

dart - Creating a Rikulo custom view and give his children correct position -

why has absolute position? i'm trying make panel title, title behind child nodes of panel, because children in absolute position. how can build custom views if not respect layout? want control in childs place. don't approach clear mind? here simple code example: class mypanel extends view { string title; mypanel() { } @override element render_() => new element.html('<div class="v-shadow"><div class="v-title">$title</div><div class="v-inner" id="$uuid-inner"></div></div>'); } this result screenshot, title dashed blue border http://i.stack.imgur.com/pprrd.png yes, absolute position designed on purpose. in short, ensures views in rikulo 100% controllable. more philosophy behind it, please refer here , here . unlike css, position controlled application (in dart) or use of the layout manager , such linear layout , anchor layout. of course, can provide own layout to

java - Naming a variable with a variable -

i'm working on assignment uses oop. program create bunch of different lemurs based on user puts in. share similar traits parent class , own unique traits in own class. part of program allow user decide number of objects (or lemurs) created. want create objects in progressive manner, l1, l2, l3... etc. here's have far. wanted use lemcounter keep track of lemur number , attach object name, every time new object created. //main section of code static int numlems, typelems, loop, lemcounter; static string alllems[]; public static void main(string[] args) { //ask number of lemurs asknl(); //initalize length of array total number of lemurs alllems = new string[numlems]; //ask lemurs user wants generate //set lemur counter , lemur string nothing lemcounter = 0; for(int = 0; < numlems; i++){ //run method asks lemur want asktl(); //run method check lemur user wanted checktl(); //use lemcounter keep tra

javascript - SceneNode (layers), Deep Zoom Composer and Seadragon Ajax -

i'm using deepzoom composer layer different images on top of other, each layer on top being smaller. (similar http://msdn.microsoft.com/en-us/expression/cc745977.aspx ) is there easy way using seadragon ajax 0.8.9 zoom each layered image on top (with container showing exact 1:1 ratio of top layered image), instead of manually creating control overlay , assigning click behaviour zoom/pan layered area on overall composition? update: i've tried use sparseimagescenegraph.xml values set zoomto to: <x>0.0663816754801515</x> <y>0.0850837639496624</y> <width>0.0322681051707401</width> <height>0.0322681051707415</height> <zorder>2</zorder> using viewer.viewport.zoomto(30.990353933356293, new seadragon.point(0.0663816754801515, 0.0850837639496624)); but off 2nd level image. also tried: var x = 0.066381675480155; var y = 0.085083763949665; var w = 0.0322681051707403; var h = 0.0322681051707407; var rect = n

submit - Spring 3 -- form with 2 buttons, sending 2 parameters to controller method -

i have spring 3 mvc form 2 parameters i'm trying send controller method, , i'm getting 404 error. twist on problem form has 2 submit buttons, , submit button clicked dictates value of 1 of parameters. here form. <form:form action="/approve/${bulletin.id}" method="post"> <table> <tr> <td colspan="2"><b>from:</b> <c:out value="${bulletin.name}" /></td> </tr> <tr> <td colspan="2"><b>subject:</b> <c:out value="${bulletin.subject}" /></td> </tr> <tr> <td colspan="2"><b>date:</b> <c:out value="${bulletin.date}" /> <br></td> </tr> <tr> <td colspan=

jquery - how to set a table cell to a value when next sibling td's checkbox is checked -

this code: ... <td class="paymentstatus">@model.paymentstatus</td> <td><input type="checkbox" class="checkbox"/></td> </tr> what i'm wanting when checkbox checked set paymentstatus td text "payment checked" i tried this: $(".checkbox").change(function () { if ($(this).is(":checked")) { $(this).closest('.paymentstatus').text("payment checked"); } }); doesn't work. know why , how fix? you need use closest parent td , sibling(td.paymentstatus) set text. demo $(".checkbox").change(function () { if ($(this).is(":checked")) { $(this).closest('td') .siblings('td.paymentstatus') .text("payment checked"); } });

jquery - create notification when user insert new order into database in php -

i developed website purchasing online. problem how can create notification alert @ admin page when new order inserted mysql. notification appear icon number @ admin page on website, when admin open website know new order had made customer. i know have use javascript ajax have not idea how begin. i have example code: refreshinterval = 500 refreshtimeout = settimeout(getnotificationcounts, refreshinterval); function getnotifications() { $.ajax({ url: 'path_to_your_php', type: 'post', data: //put example user_id cvan handled sesion datatype: 'json', success: function (data) { alert('you have' + data.total + ' new messages') refreshtimeout = settimeout(getnotificationcounts, refreshinterval); } }); } there 2 alternatives problem. looking persistent http connection. if don't mind browser support of solution, use websockets. part of html5 api not supported browsers , it's new

objective c - Appending some data to a plist -

Image
i'm creating app allows log board game plays. i'm storing logs in plist , i'm trying figure out how append plist. think understand logic i'm having trouble putting code. my plist looks so: right i'm trying believe overwrite plist file instead of appending //get path root directory nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory,nsuserdomainmask, yes); nslog(@"paths: %@",paths); //get path documents directory nsstring *documentspath = [paths objectatindex:0]; nslog(@"documentspath: %@",documentspath); //get path logs.plist file nsstring *plistpath = [documentspath stringbyappendingpathcomponent:@"logs.plist"]; //create dictionary values nsdictionary *plistdict = [nsdictionary dictionarywithobjects:[nsarray arraywithobjects:mylogtitle, name, players, mynotes, nil] forkeys:[nsarray arraywithobjects:@"log title",@"name",@"players","notes", nil]]; //write out

MATLAB - Contour plot with only 2 colours? -

i plotting contour plots in matlab using vectors. using contourf command filled contour. thing data discrete (only has values 0 & 1) still matlab interpolates color in contour plot, don't want. want 2 colors plot - 0 defining black, 1 defining white. these colors should represent actual data being plotted. you need specify levels in contourf : %# create contours colors indicating 0 , 1 contourf(x,y,z,[0 1]) %# set colormap black/white colormap([0 0 0;1 1 1])

Slow execution of Exe in Azure -

i facing problem of slow execution of exe in azure platform following steps: read data sql azure server& csv files & display in on html5 pages. write data on csv files. executing external fortron exe, reads data csv files generated in step 23. fortron exe after calculations write data on .txt file. read text file data generated in step 5 & display on html5 pages. issue: in point # 3, when invoking fortron exe using process start method, – on local machines in take 17~18 secs on cloud server taking 34~35 secs. rest other activities taking same time on local cloud server. regarding step 3: size local machine using (e.g. number of cores), since you're running exe may doing number-crunching. compare the machine size allocated in windows azure? using small (shared core) or small (single core)? plus size cpu local machine have? if you're not comparing like-kind configurations, you'll have performance differences. same goes ram (an sm

java - Creating new instance of object in loop to add in list -

i trying add object (javabean) list. mywebservicerequest mywebservice = new mywebservicerequest(); myrequesttype type= new myrequesttype (); for(int i=0; i< 9; i++){ type.seta(somedynamicvalue); type.setb(somedynamicvalue); mywebservice.add(type); } this creates 1 object of (type), add same object 9 times same data. mywebservicerequest mywebservice = new mywebservicerequest(); for(int i=0; i< 9; i++){ myrequesttype type= new myrequesttype (); type.seta(somedynamicvalue); type.setb(somedynamicvalue); mywebservice.add(type); } this creates multiple objects, add 9 diff object diff values . what if (for loop) create hundreds of objects instead of 9 in single loop , each , every time request made? dump in memory right? how avoid this? thanks in advance. when this mywebservicerequest mywebservice = new mywebservicerequest(); myrequesttype typ

java - Use a radio button and make it hidden as well -

is there way use radio button , make hidden well? i trying store value inside 4 automatically (jsp) generated radio buttons. need place 1 more radio button hold default value should hidden user. there way this? see html forms: control types for: hidden controls authors may create controls not rendered values submitted form. authors use control type store information between client/server exchanges otherwise lost due stateless nature of http (see [rfc2616]). input element used create hidden control.

c++ - Is there a way to overload operator= to have specific behavior for a function on right hand side -

i have class named image non member function return image . image::image(const char * src); image::image& operator= (const image& p); image requestimg(std::string filename); //not member function and use so: image p = requestimg("grass.png"); this fine, however- able have requestimg spawn thread loads image image object(p), while modifying object have status of loading=true . in other words. image p = requestimg("grass.png"); //image loading std::cout << p.loading << std::endl; //true //some time passes std::cout << p.loading << std::endl; //false p cannot have loading set true initially, not loading , not lead sane naming. realize member function easier- or passing pointer function, there way i've laid out? you can leave image is, , use std::async , give std::future<image> . can decide when need result of that: #include <future> auto p = std::async(std::launch::async, &requestim

php - Select statement PDO error SQLSTATE[42000]: Syntax error or access violation: 1064 -

this question has answer here: reference - asked questions pdo 3 answers $orderby = 'title'; $order = 'asc'; $stmt = $conn->prepare('select f.id, title, description, release_year, first_name, last_name film f, film_actor fa join actor fa.actor_id = a.actor_id , fa.film_id = f.film_id order :orderby :order limit :limit'); $stmt->execute( array( 'order'=>$order, 'orderby'=>$orderby, 'limit'=>$limit ) ); i'm getting error described in title when trying run query. i've tried find way debug output failed. i'll appreciate help. ps: i'm learning sql using pdo in php. thanks in advance. you forgot : here array( 'order'=>$order, 'orderby'=>$orderby, 'limit'=>$limit ) should be arr

caching snippets (modX) -

i simple cruising through modx options , noticed option cache snippets. wondering kind of effect have (downsides) site. know caching improve loading time of site keeping them 'cached' after first time , reloading updates seems true. question simple: there downsides caching snippets? cheers, marco. great question! the first rule of modx (almost) cache. they've said in own blog. as said, loading time lower. let's basics on floor first. when chose cache page, page output stored file in cache-folder. if have small , simple site, might not see biggest difference in caching , not, if have complex 1 lots of chunks-in-chunks, snippets parsing chunks etc, difference enormous. of websites i've made goes down 15-30 levels parse content in come sections. loading fresh database can take coupe of seconds, while loading flat-file take few microseconds. there huge difference (remember that). now. can cache both snippets , chunks. important remember. can cache 1 c

visual studio 2010 - Printing WinForm with controls using PrintDocument component c# -

Image
i'm not interested in having else job me, appreciate point in right direction. i have couple of forms need printed. of them consisting of multiple datagridviews , other controls. jobcards, manufacturing sheets, stock cutting lists, quotes, etc etc.. i have tried many possible solutions on internet. printform component practically useless because of poor resolution. i've tried crystal report, success, use generate , print quotes , invoices. 'capturing' form (bitmap) ...(witch guess in case better alternative printform) doesnt cut ether. msdn printing form (visual c#) i'm rather demotivated, since last part of application before testing. want understand , learn can printdocument component can solve problem , gain vs-printing experience. i'm in depth itext-sharp last resort. please tell me if prove fruitless(in case atleast;) appreciated. thank kind sir or lady time , possibly knowledge kindest regards herman vercuiel quote form generates in

json - Interaction of a iOS app with server -

i working ios app needs remote interactive server.in app have request queries post data server.which right way or appropriate way so. 1 better rest or json or soap this? there tutorial or documentation site?thanks rest common way so. basically, rest relayes on simple http requests & json, both easy use ios sdk. if model simple, can go straight forward http & json. if it's more complicated, recommend using rest kit, here's link for straight-forward solution, if need simple call existing rest api, here few basic lines of code (these shouldn't run on main thread) // preform on background thread nserror *anerror; nsdata *apicallresponsedata = [nsdata datawithcontentsofurl:@"http://yourdomain.com/apicall?param=value"]; nsdictionary *response = [nsjsonserialization jsonobjectwithdata:apicallresponsedata options:kniloptions error:&anerror]; //lets result { "key" : "value" } nsstring *somefieldvalue = response[@"

github - Get git commits by branch name\id with git api -

i working on automated service work git hub repositories. , having problem on side - can't find way commit in particular branch hash\name. my code automated tool make code reviewes. i've added feature ignore particular branch in review process (ex. testing branch or that). in service marking branch ignored. once commits git hub api - there no information there branch current commit belongs to. i started thinking overall github idea wrong - since commit-branch link pretty obvious thing there should made api developers ignore in getcommits method so question - there way find out branch commit (using v3 api json result) belongs in github api (v3 - /repos/:owner/:repo/commits/:sha). thanks if want check if commit example on branch test123, do: https://api.github.com/repos/golang/go/compare/test123...001a75a74c4a27901b0b536efe1be581612c52a9 and check status. if it's 'identical' or 'behind', commit part of branch. if different, it's

c# - Pausing window wpf application -

i'd play video when no mouse action launch , cursor not moving 10 seconds. tried code: private void dispatchertimer_tick(object sender, eventargs e) { test t = new test(); t.show(); } public void declencher() { try { while (mouse.captured != null) { dispatchertimer = new dispatchertimer(); dispatchertimer.tick += new eventhandler(dispatchertimer_tick); dispatchertimer.interval = new timespan(0, 0, 0, 0, 12); dispatchertimer.start(); messagebox.show("hhh"); } } catch { } } i'd know how can test condition in wpf , best method it check code if (button1.content.equals("play")) { button1.content = "pause"; mediaelement1.play();

java - wicket unit testing : strange behaviour of startPage(Page page) and startPage(Class<Page> pageClass) -

i got strange behaviour of unit tests. my simple page looks like: public class registrationpage extends basepage { public registrationpage(imodel<service> model) { isuserloggedin(); add(new registrationpanel("registration", model)); } public registrationpage() { isuserloggedin(); } /** * checks if user logged in. * if not, user redirected loginpage. * */ public void isuserloggedin() { if (!getsession().issignedin()) { // redirecttointerceptpage(new loginpage()); setresponsepage(new loginpage()); } } } now want test page in 2 simple tests: first want check if page renders if no user logged: @test public void testregistrationpage() { wickettester.startpage(registrationpage.class); // redirect loginpage wickettester.assertrenderedpage(loginpage.class); } i expect test pass. correct! because of isuserloggedin() method, it's recognized no user logged in , redirected loginpage. now poi

bash - C - What is a proper way to loop inside a system() function? -

im converting of old .pcd images jpeg using pcdtojpeg solution. since have lot of pictures im penning c program automate process. have moderate c# experience still new c. here im @ placeholder magicnumbers: #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i=0; (i=0; i<90; i++) { if(i<10) { system("sudo ./pcdtojpeg img000%d.pcd", i); } else { system("sudo ./pcdtojpeg img00%d.pcd", i); } } return 0; } the compiler outputs error defining many arguments system function may not take any. i've googled plenty of documentation around web cplusplus.com , linux.die.net haven't found answers how iterate inside system() function in c. i running gcc 4.8.0 linux 3.9.2-1-arch #1 smp preempt x86_64 gnu/linux you don't want "iterate inside system() ". want do, iterate around system() , call multiple times. code this. missing part how

java.lang.UnsatisfiedLinkError - JNI -

i keep getting java.lang.unsatisfiedlinkerror error every time run program. have native, wrapper, , program call native through wrapper. main.h #ifndef __main_h__ #define __main_h__ #include <windows.h> #ifdef build_dll #define dll_export __declspec(dllexport) #else #define dll_export __declspec(dllimport) #endif #include<jni.h> #include<iostream> using namespace std; extern "c" { jniexport void jnicall native_messagebox(string text, string title); } #endif main.cpp #include "main.h" #include<windows.h> #include<iostream> using namespace std; jniexport void jnicall msgbox(string text, string title) { messagebox(null, text.c_str(), title.c_str(), mb_ok); } extern "c" dll_export bool apientry dllmain(hinstance hinstdll, dword fdwreason, lpvoid lpvreserved) { switch (fdwreason) { case dll_process_attach: break; case dll_process_detach: break;

iphone - Convert NSString into NSMutableArray (specific String) -

i have string test string =====>{"name":"0","age":"0","sex":"0","weight":"0"} want string array of type: myarray[0]="name"; myarray[1]="age"; myarray[2]="sex"; myarray[3]="weight"; please idea crack thing.. in advance. try nsarray *arrcomponents = [str componentsseparatedbystring:@","]; nsmutablearray *arrmfilter = [[nsmutablearray alloc] init]; for(int = 0; < [arrcomponents count] ;i++) { nsstring *str = [arrcomponents objectatindex:i]; str = [str stringbyreplacingoccurrencesofstring:@":" withstring:@""]; str = [str stringbyreplacingoccurrencesofstring:@"\"" withstring:@""]; str = [str stringbyreplacingoccurrencesofstring:@"{" withstring:@""]; str = [str stringbyreplacingoccurrencesofstring:@"}"

c - number of concurrent connections in multithreading tcp server -

we know in process, number of threads has limit, around 1000. if want create tcp server based on multithreading, each thread responsible 1 connection. since there 1 process, number of threads limited. then means number of concurrent connections limted. am understanding correct or not? if not, why? thanks yes, there resource limits on threads determined operating system , hardware. maximum number of threads per process in linux? you never build massively parallel server using thread per connection. use select() or poll() , non-blocking sockets. if need have more 1 thread working on input (it takes lot before can't in 1 process , shouldn't making blocking calls regardless), create worker pool sized around number of processor cores have available, , use process work becomes available. more details on worker pool concept. 1 thread can handle reading incoming network data off network , tossing somewhere. there still additional work process data,

asp.net - EF5 Code-First - Create new table -

i'm working asp.net mvc3 & entity framework5. my database has been designed code-first. entity code public class user { public int id { get; set; } public string name { get; set; } } public class efdbcontext : dbcontext { public dbset<user> users { get; set; } } create db option database.setinitializer(new dropcreatedatabaseifmodelchanges<efdbcontext>()); i use option, database has been created. after database has been created, need role table was. so had modify code follows. entity code public class user { public int id { get; set; } public string name { get; set; } } public class role { public int id { get; set; } public string name { get; set; } } public class efdbcontext : dbcontext { public dbset<user> users { get; set; } public dbset<role> roles { get; set; } } i use create db option again. in case, existing users table deleted after regeneration. i added role tabl

c - Why the first client sees to have source ip of 0.0.0.0? -

i have client.c server.c on linux. on both init socket: sockfd = socket(af_inet, sock_dgram, ipproto_udp) in server add: listen_addr.sin_family = af_inet; listen_addr.sin_port = htons(port); listen_adrr.sin_addr.s_addr = htonl(inaddr_any); the server.c calls (blocking way) recvform : if (recvfrom(sockfd, buf_get, buflen, 0, (struct sockaddr*)&talker_addr, &slen) == -1) err("recvfrom()"); and client.c sends packets with: if (sendto(sockfd, buf_sent, buflen, 0, (struct sockaddr*)&serv_addr, slen) == -1) err("sendto()"); the problem on first calling sendto client.c , servers sees client's ip 0.0.0.0 , after on second, third,... calls client.c ip , have legal ip such 127.0.0.3:3212 . another weird thing if start second new client gets ip first time. make sure setting slen size of talker_addr struct before call recvfrom. set value (which may explain why works in subsequent calls) in recvfrom if th

ios - Jquery mobile - How to handle click event on body tag? -

as title, want handle click event on body tag release focusing of text input. using phonegap , jquerymobile. please helps! thanks alot. what problem? developed lot ofapplications phonegap , jqm , never noticed problem describe. blur event fires automatically. anyway can use to: jquery('body').on('click',function(){ jquery('input').trigger('blur'); })

Very Confusing PDO php exec() connection issue -

i have run confusing issue connecting database via php pdo using exec(). i have thrown following snippet illustrate point. $host = "localhost"; $db_name = "some_db"; $user_name = "some_user"; $pass_word = "some_password"; try { // assign pdo object db variable $dbh = new pdo("mysql:host=$host;dbname=$db_name;charset=utf8", $user_name, $pass_word, array(pdo::mysql_attr_init_command => "set names 'utf8'")); $dbh->setattribute( pdo::attr_errmode, pdo::errmode_exception ); echo "yahoo connected"; } catch (pdoexception $e) { //output error - log error file rather output user. echo "connection error: " . $e->getmessage(); } when run code via browser connects fine when run @ command line gives following error: connection error: sqlstate[28000] [1045] access denied user 'some_user'@'localhost' (using password: no) needless confusing password indeed set can see in cod

mysql - what is wrong with this query?(sql convert date) -

the following query working : select * msuser absensi_tanggal = date_format( str_to_date( "' .$query_array['datepicker'] . '", \'%m/%d/%y\' ) , \'%y-%m-%d\' ) however, query not working. should miss there : select * msuser absensi_tanggal between date_format( str_to_date( "' .$query_array['datepicker1'] . '", \'%m/%d/%y\' ) , \'%y-%m-%d\' ) , date_format( str_to_date( "' .$query_array['datepicker2'] . '", \'%m/%d/%y\' ) , \'%y-%m-%d\' ) the query above return 0 result. any appreciated, :d since str_to_date returns proper date type value can used between, have tried simply: select * msuser absensi_tanggal between str_to_date( "' .$query_array['datepicker1'] . '", \'%m/%d/%y\' ) , str_to_date( "' .$query_array['datepicker2'] . '", \'%m/%d/%y\' ) my guess mysql

xml - How to count entries in XSLT? -

i quite new xslt , generate count of participants list of events . xml: <events> <event name="christmas"/> <event name="halloween"/> <event name="easter"/> <event name="easter"/> </events> what need this: christmas: 1 participant halloween: 1 participant easter: 2 participants can done xslt in way? thanks help! try stylesheet, uses muenchian method group event elements @name : <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output omit-xml-declaration="yes" indent="yes"/> <xsl:strip-space elements="*"/> <!-- based on http://stackoverflow.com/a/16509871/2115381 dimitre novatchev --> <xsl:key name="keventval" match="event" use="@name"/> <xsl:template match="*"> <xsl:appl

c# - Convert List<double[]> to List<T> -

i have list of doubles list<double[]> want convert list<t> t class. the array of double contains 17 values e.g. [1.0, 2.0, 3.0, 4.0, 5.0,.. 17.0 ]. have class defines 17 string properties e.g p1, p2, .... , p17 so every element of list<double[]> array of doubles and, every element in array represents value property in class of type t . is possible map each index of given array of doubles property of class of type t. convert list<double[]> list<t> t class . i know can done manually iterate on list read each array , read value each index of array , pass corresponding property of class. lot when have many class 10+ properties. edit: example of 1 of classes given below /// <summary> /// defines properties of centroid. /// </summary> public class centroid { // resharper disable inconsistentnaming /// <summary> /// calls made contacts /// </summary> public string contact_calls { get; set; }

Python "'module' object is not callable" -

i'm trying make plot: from matplotlib import * import sys pylab import * f = figure ( figsize =(7,7) ) but error when try execute it: file "mratio.py", line 24, in <module> f = figure( figsize=(7,7) ) typeerror: 'module' object not callable i have run similar script before, , think i've imported relevant modules. the figure module provided matplotlib . you can read more in matplotlib documentation i think want matplotlib.figure.figure (the class, rather module) it's documented here from matplotlib import * import sys pylab import * f = figure.figure( figsize =(7,7) ) or from matplotlib import figure f = figure.figure( figsize =(7,7) ) or from matplotlib.figure import figure f = figure( figsize =(7,7) ) or pylab work without conflicting matplotlib : from matplotlib import * import sys import pylab pl f = pl.figure( figsize =(7,7) )

ios - core data subclass with collectionViewCell -

in collectionview based app want cache last 100 cells loaded, , think best way me work core data. have custom class uicollectionviewcell, , cells objects of class. it's kind of this: @interface cell : uicollectionviewcell @property (strong, nonatomic) nsstring *cellfacebookid; @property (strong, nonatomic) nsstring *cellmail; @property (strong, nonatomic) nsstring *celladdid; @property (strong, nonatomic) nsstring *cellcategory; @property (strong, nonatomic) iboutlet uiimageview *cellbackimg; @property (strong, nonatomic) iboutlet uiimageview *titlebarimage; @end now i've created entity named cell, same attributes. can create nsmanagedobject subclass replace original "cell" class , still use uicollectionviewcell custom class? you can't use subclass of nsmanagedobject uicollectionview cell. has subclass of uicollectionviewcell. besides uicollectionview reuses cells caching them.

django - cannot create extension without superuser role -

i'm trying run unit tests in django, , creates new database. database has postgis extensions , when regularly create database, use "create extension postgis". however, when run tests, gives me following error: $ ./manage.py test creating test database alias 'default'... got error creating test database: database "test_project" exists type 'yes' if try deleting test database 'test_project', or 'no' cancel: yes destroying old test database 'default'... databaseerror: permission denied create extension "postgis" hint: must superuser create extension. the user has create db privilege already, i'm using postgresql 9.1 on ubuntu 12.04 postgis 2.0. the django documentation on postgis has information on setting user privileges . in worst case can create new superuser: $ createuser --superuser <user_name> or alter existing user's role: postgres# alter role <user_name> super

Windows Azure: Unexpected & unclean virtual-machine shutdown -

using large instance of virtual machine on windows azure. instance runs microsoft sql 2012 light usage, on windows server 2012 + date. no user logged in @ time of failures. however, several (between none , three) times day (appears random), vm halts , shuts down. not come online until logs management portal , starts vm again. there no memory dump created. guessing host halts running vm, rather configuration instance within guest os causes halt. subscription has billable funds. other vms in subscription affected. only event logs generated: kernel-power logged: the system has rebooted without cleanly shutting down first. error caused if system stopped responding, crashed, or lost power unexpectedly. kernel-boot logged: the last shutdown's success status false. last boot's success status true. how can resolved? there no way initiate support request within azure. the first point install monitoring software newrelic or foglight , se

c++ - Problems converting .flv to mp3 using FFmpeg SDK -

i'm using ffmpeg sdk programmatically convert videos mp3. i read audio frames of video way: while(av_read_frame(pfromctx, &pkt) >= 0) { if(pkt.stream_index == audiostreamindex) { avcodec_get_frame_defaults(frame); got_frame = 0; ret = avcodec_decode_audio4(pcodecctx, frame, &got_frame, &pkt); if (ret < 0) { av_log(null, av_log_error, "error decoding audio frame.\n"); continue; } if(got_frame) { // write decoded audio frame write_audio_frame(ptoctx, ptoctx->streams[ptoctx->nb_streams-1], frame); } } av_free_packet(&pkt); } decoding audio input video file works fine. problem occurs when try encode mp3 frame: static void write_audio_frame(avformatcontext *oc, avstream *st, avframe *

object - Java: Should I use float or Float? -

this question has answer here: when use wrapper class , primitive type 9 answers my colleague told me should use float whenever possible reduce object creation , increase performance. java silently converts float float (this needs computational power) whenever necessary. seems me need float when 1 needs use object float instead of primitive. when looking @ java.awt.color, using float, perhaps unnecessarily. when 1 need prefer float on float in java? the object float can set null represent value unknown. primitive float guaranteed have value. there overhead on autoboxing, negligible. still must allocate space primitive there nothing gain there.

java - Cannot refer to a variable inside an inner class -

i'm still learning java bear me. trying write program click button named "yes" , increases variable y 1, , same button "no" on variable x. i'm using eclipse , windowbuilder pro , gives me error "cannot refer variable inside inner class" here's code: import javax.swing.japplet; import javax.swing.jbutton; import java.awt.event.mouseadapter; import java.awt.event.mouseevent; import javax.swing.jformattedtextfield; public class qa extends japplet { /** * create applet. */ public qa() { getcontentpane().setlayout(null); int y=0; int x=0; string s1 = string.valueof(y); jbutton btnyes = new jbutton("yes"); btnyes.addmouselistener(new mouseadapter() { @override public void mouseclicked(mouseevent arg0) { ++y; } });

multithreading - Java Resource-Game Simulation -

i'm project of resource-game simulation. have is... "if there enough resources available, request satisfied, , requested quantities subtracted available quantities. if there not enough resources, animat consumes available quantities , wait more resources available." the question how make possible... reduce resource , hold somewhere still needed , reduce when there available resources(like loan)... example: ... 100 gold needed.... ... 50 gold available... ... reduce gold 50... , wait untill gold>=50 , ... reduce gold 50... etc... sample code... public void feedarmy(){ if(food>=100){ food=food-100; system.out.println("*feed soldiers (-100 food)"); system.out.println(tostring()); } else{ system.out.println("*feed soldiers (-100 food)"); system.out.println("-not enough food!"); //get loan instead } } (after edit) best solution now: actually ... thought

c++ unable to get proper string input -

i new programming wrote simple function calculate length of string unable take input string user properly(have tried alternatives). /////////function calculate length of string//////////////////// void str_length(){ char str[30]; int counter=0; cout << "enter string: "; gets(str); //cin.getline(str,256); //cin >> str; for(int i=0;str[i] != '\0';i++){ counter++; } cout << "string length is: " << counter << endl; } /////////////////////////////////////////////////////////////// of possible ways program either exits abruptly or 'cin' can partial string till first space. if tried cin.getline(str,256) , you'd have needed buffer declared char str[256] . you shouldn't involving these things however. stick std::string : std::string str; // declare string std::getline(std::cin, str); // line std::cin stream , put in str unsigned int stringlength = str.length

html - Disable a field after selection -

in piece of code need disable department field when approved selected in status(above field) , should active when clarifications selected must enabled. please try helping ! <form name="index" action="director"> <table border="0" style="width:300px"> <tbody bgcolor> <p> date: <%= df.format(new java.util.date()) %> </p> <tr> <td height="40"><font color="blue">branch:</td> <td> <select name="dbranch" id="dbranch" > <option value="select">select</option> <option value="kakinada">kakinada</option> <option value="vishakapatnam">vishakapatnam</option> <option value="tirupathi"&