Posts

Showing posts from January, 2012

R: print line when column value matches value from other file -

in r, have list of 11 dataframes named list1. every dataframe has same structure: names col2 col3 name1 1 10 name2 2 22 name4 3 40 i have dataframe called table1 looking this names col4 col5 name1 ... ... name2 ... ... name3 ... ... now want take subset of original 11 dataframes. each dataframe want print lines there match between values in 'names' column of dataframe , names column in table1. in case, new dataframe should this names col2 col3 name1 1 10 name2 2 22 all new dataframe should appended again in list2. work lapply , match function? mylist2 <- lapply(mylist1, function(...){ match(...) } you can this required.list = lapply(list1, function(x) subset(x, names %in% table1$names))

pygame - Python: None type object is not callable -

i'm doing game in pygame , i'm trying do, make entity target another. when call target function, "typeerror: nonetype object not callable" understood after doing research on error, occurs, when try use return value of function hasn't any. but, function isn't supposed return , don't use return value, i'm bit out of ideas. hope can me, here code: target function def target(self,x,y): target = self.world.getpointentity(x,y) if target != none , target.get_itarget(): self.set_target(target) call target function self.player.target(x,y) if have questions, feel free ask. edit: code of getpointentity function: def getpointentity(self, x, y, searchrange=24): entity in self.entities.itervalues(): if entity != none: distance = entity.get_distance(x, y) if distance < searchrange: return entity return none as get_itarget function, returns tr...

java - Change the look and Feel to Frame by an other one in Netbeans -

hey guys i've 2 frames 1 login frame means it's main frame , other 1 it's application create method change look&feel radio button in main of frame when run application it's doesn't work if run without login frame works goood used change : public static void changelaf(jframe frame) { try { uimanager.setlookandfeel(uimanager.getsystemlookandfeelclassname()); }catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandfeelexception e) { } swingutilities.updatecomponenttreeui(frame); } and public static void changelaf(jframe frame, string laf) { if (laf.equals("nimbus")) { try { uimanager .setlookandfeel("javax.swing.plaf.nimbus.nimbuslookandfeel"); } catch (classnotfoundexception | instantiationexception | illegalaccessexception | unsupportedlookandf...

C++ Field holding objects with different template arguments -

i have following setup: // n number of rooms template <size_t n> class house { void printnumberofrooms(); } house<1> house1; house<2> house2; now want have field can hold both house1 , house2 , on can call house.printnumberofrooms(). house house; house.printnumberofrooms(); gave me "requires template argument" error (obviously). what best way achieve goal? house<1> , house<2> different , incompatible types, therefore can't store them in single field. however can give them same parent class , store them pointer parent class , make printnumberofrooms virtual. this: class basehouse{ virtual void printnumberofrooms(); }; template<size_t n> class house: public basehouse{ virtual void printnumberofrooms(); }; class c{ basehouse * house; };

android - Add photo to new ParseUser -

i'm using parse android. want add photo newly created parseuser . here sample code: if(company.getbackgroundimage()!=null) { bitmap bitmap = bitmapfactory.decoderesource(c.getresources(),r.drawable.launcher); // convert byte bytearrayoutputstream stream = new bytearrayoutputstream(); // compress image lower quality scale 1 - 100 bitmap.compress(bitmap.compressformat.png, 100, stream); byte[] image = stream.tobytearray(); // create parsefile final parsefile file = new parsefile("androidbegin.png", image); user.put("alfa1",file); } user.signupinbackground(new signupcallback(){ @override public void done(parseexception arg0) { if (arg0 == null) { log.i("log_output", "data saved in sever"); ...

c - How to make sure the user enter a positive number -

i did this, sadly not working, , crashing when input char/string, etc. how fix it? while((scanf("%d",&numofdef) != 1 ) && (numofdef>0 )) { printf("not pos num try again"); } actually, 2 changes need made: while((scanf("%d",&numofdef) >= 0 ) && !( numofdef>0 )) firstly, compare return value of scanf 0, secondly condition should either !( numofdef>0 ) or ( numofdef<=0 ) return value of scanf (source: http://www.geeksforgeeks.org/g-fact-10/ ) : in c, printf() returns number of characters written on output , scanf() returns number of items read. ideone link code: http://ideone.com/tjtudy

How to add pandas data to an existing csv file? -

i want know if possible use pandas to_csv() function add dataframe existing csv file. csv file has same structure loaded data. you can append csv opening file in append mode: with open('my_csv.csv', 'a') f: df.to_csv(f, header=false) if csv, foo.csv : ,a,b,c 0,1,2,3 1,4,5,6 if read , append, example, df + 6 : in [1]: df = pd.read_csv('foo.csv', index_col=0) in [2]: df out[2]: b c 0 1 2 3 1 4 5 6 in [3]: df + 6 out[3]: b c 0 7 8 9 1 10 11 12 in [4]: open('foo.csv', 'a') f: (df + 6).to_csv(f, header=false) foo.csv becomes: ,a,b,c 0,1,2,3 1,4,5,6 0,7,8,9 1,10,11,12

c# - Iteration over dynamically added nested controls -

i have groupbox on winform. groupbox added in run time within first groupbox. few picturebox controls added within second groupbox. now iterate pictureboxes. currently code is: foreach (control gbfirst in this.controls) { groupbox firstgroupbox = gbfirst groupbox; //first groupbox if (firstgroupbox != null) { foreach (control gbsecond in firstgroupbox.controls) { groupbox secondgroupbox = gbsecond groupbox; //second groupbox if (secondgroupbox != null) { foreach (control item in secondgroupbox.controls) { var pb = item picturebox; // picturebox if (pb != null) { string pbtag = pb.tag.tostring(); string customtag = ipaddress + "onoff"; if (pb.tag.tostring() == ipaddress + "onoff") { ...

c - 'Node' undeclared (first use in this function) in DevC++ -

i have following code insert element in linkedlist. havebeen following tutorials , unable spot error in code. i using devc++ , gives me compile time error says: [error] 'node' undeclared (first use in function) #include<stdio.h> #include<conio.h> #include<stdlib.h> struct node{ int data; struct node* next; }; struct node* head; //global variable int main(){ head = null; //empty list int n, i, x; printf("how many numbers enter"); scanf("%d", &n); for(i=0; i<n; i++){ printf("enter number want add list:"); scanf("%d", &x); insert(x); print(); } } void insert(int x){ node* temp= (node*)malloc(sizeof(struct node)); //i error here temp->data = x; //temp->next = null; //redundant //if(head!= null){ temp->next = head; //temp.next point null when head null nd otherwise head pointing //} head = temp; } void print(){ struct node* t...

Node.js / Export configuration file -

i have following configuration file in /etc/sysconfig/myconf : export user=root export node_dir=/opt/mydir i want use these setting in .js file, located in /opt/myapplication : var userapp = //user in /etc/sysconfig/myconf file var dir = //node_dir in /etc/sysconfig/myconf file is there way without open file , parse contents? as understand export should give me option read in node.js, don't find how (in addition, when run export -p , don't see these variables) edit : search equal node.js's command source command in linux (the variables not environment variables) if environment variables available when launch program, can use process.env . https://nodejs.org/api/process.html#process_process_env

javascript - How do I send message to specific client in node.js -

how can send message specific client ?,is possible can send message specific client in node.js ? var net = require('net'); var clients = []; var server = net.createserver(function (socket) { clients.push(socket); var message = "message client"; //here how send specific client ? }); thank in advance. it's not entirely clear you're trying do, keeping list of sockets in clients array need apply whatever logic fits need select 1 of sockets , use .write() write data on socket: var net = require('net'); var clients = []; var server = net.createserver(function (socket) { clients.push(socket); var message = "message client"; // pick socket array using whatever logic want , send clients[0].write(msg); });

objective c - Best way to read Beacon Manufacture Data in iOS -

Image
i trying read beacon(ble device) manufacture data in below image and getting response as, and code is, id manufacturedata = [advertisementdata objectornilforkey:@"kcbadvdatamanufacturerdata"]; if ([manufacturedata iskindofclass:[nsdata class]]) { int8_t measuredpower = 0; nsuinteger datalength = [manufacturedata length]; (int = 0; < datalength; i++) { nsrange powerrange = nsmakerange(i, 1); [manufacturedata getbytes:&measuredpower range:powerrange]; nslog(@"index :%@ info :%hhd", [nsstring stringwithformat:@"%d", i+1],measuredpower); } } is correct way read manufacture data, here trying read battery address value. have show. this correct way of reading through returned nsdata . given this, information returning 32 battery value, seem correct? if not, can find out if manufacturer device little endian or big endian?...

python - backref lazy='dynamic' - does not support object population - eager loading cannot be applied -

how can planes bookings between 2 dates specified. need bookings filtered down included if they're between 2 dates. tried error: 'plane.bookings' not support object population - eager loading cannot applied. why error occur , how can fixed? planes = (db.session.query(plane) .join(booking) .filter(booking.start_date >= date) .options(contains_eager(plane.bookings))) the models: class booking(db.model): id = db.column(db.integer, primary_key=true) start_date = db.column(db.datetime) end_date = db.column(db.datetime) person_id = db.column(db.integer, db.foreignkey('person.id')) person = db.relationship('person', foreign_keys=[person_id], backref=db.backref('bookings', lazy='dynamic')) instructor_id = db.column(db.integer, db.foreignkey('person.id')) instructor = db.relationship('person', foreign_keys=[instructor_id],...

css - Unable to scroll the web page -

i developing website using ruby on rails. facing issue unable scroll webpage vertically. scroll bar appear doesn't scroll down. if resize webpage, contents fit in page displayed. using devise authentication signup/login/logout. if comment out following devise code, scroll work (for home page). can please me. in application.html, <html> <body> <div class="navbar navbar-fixed-top"> <ul class="navbar-text pull-right"> <% if user_signed_in? %> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <%= current_user.email %><b class="caret"></b></a> <ul class="dropdown-menu"> <li class="divider"></li> <li><%= link_to 'edit profile', edit_user_registration_path %></li> <li class="divide...

computation theory - Kolmogorov complexity is uncomputable using reductions -

can please give me proof of k-complexity unsolvable using reductions. eg: pcp(2) <= pcp(3) i can prove pcp(3) unsolvable reducing pcp(2) (by mapping every instance). i not sure how reduce k-complexity known undecidable problem (like halting problem). i.e., x <= k-complexity can please provide me proof that? @ least provide me idea ( x ). thanks in advance

Android Fabric Twitter Timeline -

i trying show user timeline in android fragment. homefragment.java oncreate() looks this: public class homefragment extends listfragment { @injectview(android.r.id.list) listview mtimeline; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); if (getarguments() != null) { msectionnumber = getarguments().getint(arg_section_number); } final usertimeline usertimeline = new usertimeline.builder().screenname("fabric").build(); final tweettimelinelistadapter adapter = new tweettimelinelistadapter(getactivity(), usertimeline); setlistadapter(adapter); } and fragment_home.xml has listview: <listview android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@android:id/list" android:layout_alignparenttop="true" android:layout_centerhorizontal="true"/> homefragment fragment of homeactivity. code ...

How to assign function output to an array type? In C? -

i try assign assign output of function array, upon compiling, doesn't seem work. the function takeinputs should return array. and, have it, thought holdinputs array. however, doesn't seem compile. error here? // holds expression user enters struct inputs { char word[10]; }; // declare these: struct inputs* takeinputs(struct inputs *userinputs, int numinputs); // must return pointer pointer because returning array struct inputs* printinputs(struct inputs *userinputs); struct inputs* takeinputs(struct inputs *userinputs,int numinputs){ /*inputs: userinputs: array of struct inputs, each of contain string called "word" numinputs: integer user */ int i; (i=0;i<numinputs;i++){ printf("please input word"); fgets(userinputs[i].word,10,stdin); } } int main(int argc, char const *argv[]){ //user input should this: ./takes_input.exe 7 if (argc!=2){ error(...

c++ - Get An Row From Dynamically Allocated 2D Array Pointer -

i'm pretty novice c++ , have been trouble working way through pointers. //define colormaps (for brevity null) //256 rgb combinations in each colormap uint8_t colormap0[256][3]; uint8_t colormap1[256][3]; //insert color maps in storage array via pointer uint8_t *colormaps[] = {*colormap0, *colormap1}; //well define current map index read colormaps uint8_t colormapindex = 0; //we define pointer active array we'll update in loop() uint8_t *currentcolormap; occasionally we'll reassign current color map currentcolormap = colormaps[colormapindex]; and other times values it uint32_t c = getcolorfrommap(125); we'll need these functions well // create 24 bit color value b,g,r uint32_t color(uint8_t r, uint8_t g, uint8_t b) { uint32_t c; c = r; c <<= 8; c |= g; c <<= 8; c |= b; return c; } uint32_t getcolorfrommap(byte indexvalue) { uint8_t rgb = currentcolormap[indexvalue]; return color(rgb[0], rgb[1], rgb[2]); } the trouble li...

c# - How to customize CreateUserWizard to get UserId and UserName values? -

i using membership provider deal user registration , logging website. membership provider part of package comes through: install-package microsoft.aspnet.providers i have 2 aspx pages 1 has createuserwizard control , other has login control. registration , logging working correctly. i have defined profile properties in web.config file: <profile defaultprovider="defaultprofileprovider"> <properties> <add name="id" type="system.guid" /> <add name="username"/> </properties> what trying able take userid , username values on registration of user, , store them profile.id , profile.username respectively. how customize createuserwizard achieve this?. my try: when show createuserwizard on browser. can see button named "create user", thought place extend on , add code take required values. clicked small arrow on createuserwizard , choose customize create user setup , e...

sql server - "java.util.Scanner[delimiters=\p{javaWhitespace}+]" Error in JDBC program -

i have written jdbc application has function called "updatestudent," takes studentid parameter , receives user input student's variables changed to. stored procedure works fine within sql server, running things java results in string varaibles being changed value "java.util.scanner[delimiters=\p{javawhitespace}+]". however, integer values not affected, , updated correctly. believe issue has implementation of scanner in java, since works fine within sql server itself. below function updatestudent main: public static void updatestudent() { system.out.print("\n please enter id of current student wish update"); system.out.print("\n==>"); student student = new student(); @suppresswarnings("resource") scanner insertstudentid = new scanner(system.in); int passedstudentid = insertstudentid.nextint(); //program starts counting @ zero, starts displaying @ 1 system.out.print("\n enter new value fir...

queries in mongodb command line -

i want query list cities in specific state populations between 6000 , 8000. in big data. : { "_id" : "01564", "city" : "sterling", "loc" : [ -71.775192, 42.435351 ], "pop" : 6481, "state" : "ma" } { "_id" : "01566", "city" : "sturbridge", "loc" : [ -72.084233, 42.112619 ], "pop" : 7001, "state" : "ma" } { "_id" : "01568", "city" : "west upton", "loc" : [ -71.608014, 42.173275 ], "pop" : 4682, "state" : "ma" } { "_id" : "01569", "city" : "uxbridge", "loc" : [ -71.632869, 42.074426 ], "pop" : 10364, "state" : "ma" } i want return cities in massachusetts let above example. how can ? t tried : >db.zipcodes.aggregate( [ { $group: { _id: "$city",stat...

How to update nothing in an update fuction in PHP? -

i have form user details updated. once page uploads user few fields loaded current database values. i can allow them upload images, it's optional. once form submitted fields updated problem images. how can not update image field @ still use in update function have. is possible way of doing ? if (empty($_files['logo']['name'])) { // no file selected upload, (re)action goes here } this function: public function update_header($pagetitle,$title, $slogan, $logo, $titlechoice, $sloganchoice, $logochoice){ global $pdo; $sql= "update `header` set `pagetitle`=?,`title`=?,`slogan`=?,`logo`=?,`titlechoice`=?,`sloganchoice`=?,`logochoice`=? `header_id` =1"; $query = $pdo->prepare($sql); $query -> execute(array($pagetitle,$title, $slogan, $logo, $titlechoice, $sloganchoice, $logochoice)); return "has been updated!!"; } any ideas? how can not update image field @ still use in update function have. ...

android - Return to a fragment stateless -

i have 3 fragments a, b(with search) , c. want fragment b on key pressed c, not retained state/with nothing in search bar precisely. here did: public class fragcount extends fragment{ //expandablelistadapter listadapter; // searchableadapter listadapter; expandablelistview explistview; list<string> listdataheader; hashmap<string, list<string>> listdatachild; private int groupid = -1; public static edittext searchtext; @override public view oncreateview(layoutinflater inflater,viewgroup container, bundle args) { view view = inflater.inflate(r.layout.country_main, container, false); setretaininstance(true); // listview explistview = (expandablelistview) view.findviewbyid(r.id.lvexp); // preparing list data preparelistdata(); listadapter = new searchableadapter(getactivity(), listdataheader, listdatachild); // setting list adapter explistview.setadapter(listadapter); explistview.setonchildclicklistener(new expandab...

java - Adding objects to an ArrayList from another class -

this question has answer here: what nullpointerexception, , how fix it? 12 answers i trying add objects arraylist file getting java.lang.nullpointerexception though have initialized arraylist. here example of code structure talking about. //objectone.java import java.util.arraylist; public class objectone { public innerclass inner; class innerclass { arraylist<string> list = new arraylist<string>(); public void addstring(string str) { list.add(str); } } public void addstr(string str) { inner.list.add(str); } } here second file: //objecttwo.java public class objecttwo { public static void main(string args[]) { objectone obj = new objectone(); obj.addstr("test string added"); } } i have initialized arraylist in innerclass but when try add item in...

php - Is it possible to use the MVC path in XDebugs profiler outout filename? -

i using xdebug profile large mvc application , easier profile individual requests uri rather filename (.php) several requests made via internal functions, resulting in multiple grind files single page refresh. i have seen %p = process id, %t = timestamp , %s = script name ( var_path_to_example.php ) it easier if file named more grind.{domain}{path}.%p is possible? havent been able find other string formatting replacers may im after. single page refresh creates 4 grind files ( 3 index, 1 main request, other 2 media compressors ) , 1 img.php media path rewriter , resizer. all of combined single www.example.com/path/to/controller.grind preferable situation. the answer use %r - found list of string replacements here xdebug settings under trace_output_name section. seems same replacers can used profiler output names well. name files in php.ini - "cachegrind.out.%r" uri name slashes replaced underscores. now grind files cachegrind.out._page_minify_css ...

html - Yesod CSS lucius -

Image
i have made table in hamlet file: <table> $forall ivlist <- y <tr> $forall iv <- ivlist <td>^{fvinput iv} and respective css in lucius file: td { width:1em; height:1em; } the css generated expected,but output different. when change height , width higher value change visible, when change sum lower value no longer decreases. here image of generated table i couldn't change column width .i wanted make square. don't know should done. using static bootstrap.css file , each cell input . think problem should due default values in bootstrap. couldn't find should changed. have tried few changes changing width , modifying bootstrap.css file, didn't required results. input[type="range"] { display: block; width: 100%; } in short how modify cell width ? should modifying see changes in width of table ? i got it. simple. change made input tag. added following lucius file input { ...

java - Gradle - import GitHub repository and make it a subproject dependency? -

i trying avoid multi-project builds deploying jar file dependencies, undermined nimble workflow , need faster way make git repositories dynamically add each other dependencies. i'm sure write creative deployment procedures using jar files, changes 1 project ripple other dependent projects without intermediary deployment. i looking through grgit documentation, , see allows branch cloning operations. how extract working tree after clone , include dependency, assuming repo has own gradle.build script? repositories { mavencentral() } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'idea' dependencies { compile group: 'com.google.guava', name: 'guava', version: '18.0' compile 'org.xerial:sqlite-jdbc:3.8.7' compile 'net.jcip:jcip-annotations:1.0' compile 'joda-time:joda-time:2.7' compile files('path/to/my/repo') //not quite sure here??? } task downloadgitdepende...

c++ - malloc(): memory corruption (fast), std::vector and std::stringstream -

so... got weird one. in following code, receive *** error in `./a.out': malloc(): memory corruption (fast): 0x00000000011165f0 *** on while loop line of below function. std::vector<std::string> stringsplitter(const std::string & tosplit, char split) { std::stringstream stream(tosplit); std::vector<std::string> toreturn; std::string current; while (std::getline(stream, current, split)) toreturn.push_back(current); return toreturn; } i have been able reproduce error sending send allenh1 passwd sup? but function works intended when send it command allenh1 passwd room1 any ideas? the call function comes following lines in function: file * fssock = fdopen(fd, "r+"); // read character character until \n found or command string full. while (commandlinelength < maxcommandline && read( fd, &newchar, 1) > 0 ) { if (newchar == '\n' && prevchar == '\r') { ...

knockout.js - Knockout radio button check binding -

i have viewmodel in have array of "answers". "answer" object has property 'selected'. in demo array have 2 answers. first selected=1 , second selected=0. have no idea why both radio buttons selected. here demo link - https://jsfiddle.net/jwoscjot/3/ , binding is <input type="radio" data-bind=" value: selected, checked: selected"> from http://knockoutjs.com/documentation/checked-binding.html for radio buttons, ko set element checked if , if parameter value equals radio button node’s value attribute or value specified checkedvalue parameter. you should consider adding selectedanswerid property view model. <!-- ko foreach: answers --> <input type="radio" data-bind="value: answerid, checked: $parent.selectedanswerid"> <!-- /ko --> if want keep answer's selected state part of answer, can used checkedvalue part of binding. note won't have way "desele...

html - Need to be able to target individual button using code that applies to all buttons -

when 1 of buttons clicked, need button change red background white text. needs work new buttons added later on. how can without individually adjusting each button? here's code: <!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>page 2</title> <style type="text/css"> /* styles go here */ img { width:200px; height:100px; animation: widthchange 3s 2s; -webkit-animation: widthchange 3s 2s; -moz-animation: widthchange 3s 2s; -0-animation: widthchange 3s 2s; } p {text-align:center} button {margin:20px} .stylized { font-style: italic; border-width: 5px; border-color: yellow; border-style: outset; } @-webkit-keyframes widthchange { 0%, 100% {width: 200px;} 50% {width: 400px;} } @-o-keyframes widthc...

unity3d - How to restrict which colliders are triggered? -

sorry if similar questions have been asked. i have character can hold shield block incoming damage. character has circle collider body space. shield has box collider blocks off portion of whatever direction he's facing, , it's enabled when player holding down button. enemies have weapons surrounded triggered box colliders enabled when decide attack. so, problem when character attacked while shielding, body collider detected , shield collider detected. can't find consistency no matter try. [screenshots] ( http://i.imgur.com/vhujbcg.png ) [code] https://gist.github.com/siketh/2401454977d10ed7699b i've been struggling day , need set of eyes. isn't serious project if need see else i'm happy post more code or explain more of design. it's because weapon intersects both character , shield @ same time. there great tools in unity if want see if that's case. notice unity has "play", "pause" , "play 1 step" b...

java - Boolean and conditionals in order -

so below have , method returns true if second condition met. however, want return false if first condition met. however, problem returns false times. public static boolean matching(request a, request b) { if (a.info[2].equals("*") & b.info[2].equals("*")) { return false; } return ((a.info[1].equals(b.info[1]) && a.info[2].equals(b.info[2])) || (a.info[1] .equals(b.info[1]) && a.info[2].equals("*") || b.info[2] .equals("*"))); } without trying understand whole conditional sentences, i'm guessing have typo here.- if (a.info[2].equals("*") & b.info[2].equals("*")) { and meant if (a.info[2].equals("*") && b.info[2].equals("*")) { instead. you can take this old thread further information. edit if problem persists, chances there're issues on second conditional sentence...

javascript - Hide an option in a dropdown menu, when a specific option has been selected in another menu -

i'm stuck right on following problem: have 2 dropdown menus next each other, both offer same options choose (users can choose travel route choosing point of departure , destination). the items on these dropdown menus taken table in database. want achieve following: locations "a", "b" , "c" choosable start or destination. when user chooses "b" point of departure (in 1st dropdown menu), option should not shown anymore in 2nd dropdown menu (destination). (edit: should reappear, when option selected in 1st dropdown) same "a" , "c" of course. the code use right fill dropdown menus is: <select name="anfang"> <?php $sql = "select * orte"; $result = mysqli_query($dblogin,$sql); while($zeilestart=mysqli_fetch_array($result)) { include("includes/database.php"); $ortname=$zeilestart['name']; $ortkurz=$zeilestart['kurz']; echo "<option value=\"$ortku...

Memory leak when I add last a node to a doubly linked list C++ -

i facing memory leak when add last node doubly linked list. function is: void addlast(const char* word){ // homework , parameter must const char* std::string c2 = word; // nodes std::string node *aux = new node(c2); if (tail == null) { head = tail = aux; } else { tail->next = aux; aux->prev = tail; tail = aux; } } my strct node following: struct node { std::string value; node *next, *prev; node (std::string value) { this->value = value; next = prev = null; } node () { next = prev = null; } } i mention fact if try delete aux in function addlast face seg fault. problem>

javascript - Grunt: Task "grunt-bower" not found -

i want install package grunt-bower grunt using npm install grunt-bower --save . after install, see package grunt-bower inside node_modules . here gruntfile.js : module.exports = function(grunt) { grunt.initconfig({ bower: { dev: { dest: 'public', js_dest: 'public/javascripts', css_dest: 'public/stylesheets' } }, watch: { source: { files: ['sass/**/*.scss', 'views/**/*.jade'], tasks: ['sass'], options: { livereload: true, // needed run livereload } } } }); grunt.loadnpmtasks('grunt-bower'); grunt.loadnpmtasks('grunt-contrib-watch'); grunt.registertask('default', ['grunt-bower']); }; i have register on official page : grunt.loadnpmtasks('grunt-bower'); when ...

HTML - Press enter in text field set focus on other text field -

i want create form in html 3 textfield , 1 button. in load page or refreshed txt1 textfield automatically focused, when pressing enter key txt2 focused , if pressed enter again txt3 focused , when pressed enter again submit. is there knows how it? please help... code example below... thanks... <form name="form1" action="filename.php" method="post"> text1: <input type="text" name="txt1" autofocus><br> text2: <input type="text" name="txt2"><br> text3: <input type="text" name="txt3><br> <input type="submit"> </form> you can combination of html , jquery: html: <form name="form1" action="filename.php" method="post"> text1: <input type="text" id="txt1" name="txt1" autofocus><br> text2: <input type="text" id=...

visual studio 2013 - Tools for Cordova CTP3 Unknown encoding MDAVSCLI -

i'm writing new cordova hybrid app using visual studio community 2013. after creating first blankcordovaapp , error when try run (after clicking on running- f5 icon). error 1 unknown encoding c:\users\name\documents\visual studio 2013\projects\blankcordovaapp1\blankcordovaapp1\mdavscli 1 1 blankcordovaapp1 here full console output ------ build started: project: blankcordovaapp1, configuration: debug android ------ build started 4/25/2015 8:52:16 pm. compiletypescript: skipping target "compiletypescript" because output files up-to -date respect input files. trackjschanges: generatedjavascript=scripts\file.js;scripts\file.js.map installmdatargets: c:\users\kamdjou\documents\visual studio 2013\projects\blankcordovaapp1\blank cordovaapp call "c:\program files (x86)\nodejs\"\nodevars.bat environment has been set using node.js 0.10.33 (ia32) , npm. ------ ensuringcorrect global installation of package source package directory: ...

swift - 'anyObject' is not convertible to 'Dictionary<key, value>]' -

hi want object type dictionary using nsuserdefaut : var favoriteplace = nsuserdefaults.standarduserdefaults().objectforkey("saveplace")! [dictionary] but error 'anyobject' not convertible 'dictionary]' i try : var favoriteplace = nsuserdefaults.standarduserdefaults().objectforkey("saveplace")! [dictionary<string, string>()] but it's not work, too. know how can ? ! both tries syntax errors. to cast dictionary: dictionary<type, type> or [type : type] so doing var favoriteplace = nsuserdefaults.standarduserdefaults().objectforkey("saveplace")! [[string: string]] or var favoriteplace = nsuserdefaults.standarduserdefaults().objectforkey("saveplace")! [dictionary<string, string>]

mysql - Website slow loading on VPS -

i have vps, centos 6 64bit directadmin + custombuild. web server: apache reverse proxy nginx. i hosting lot of websites on vps. when there lot of hits on website "example.com", website becoming extremely slow (can 50 seconds , more), others work perfect , fast. i checked cpu , memory, there nothing weird. i installed "mytop" monitoring database, , happened when there 20+- running queries. my.cnf content: [mysqld] max_allowed_packet=16m innodb_buffer_pool_size = 5096m innodb_buffer_pool_instances = 12 innodb_file_per_table = 1 innodb_log_file_size = 64m innodb_log_files_in_group = 2 innodb_log_buffer_size = 10m innodb_flush_log_at_trx_commit = 0 innodb_buffer_pool_load_at_startup = 1 innodb_log_buffer_size = 8 innodb_thread_concurrency = 12 innodb_flush_method = o_direct innodb_read_io_threads = 4 innodb_write_io_threads = 8 #max_connections = 800 #max_user_connections = 400 local-infile=0 max_connections=120 # interactive_timeout=300 join_buffer...

How to change shade of color dynamically android? -

i'm using palette class programmatically dominant color image want use status bar , toolbar. according material design guidelines, status bar color should 2 shades darker toolbar color. bitmap bitmap = ((bitmapdrawable) ((imageview)mimageview).getdrawable()).getbitmap(); if (bitmap != null) { palette = palette.generate(bitmap); vibrantswatch = palette.getvibrantswatch(); darkvibrantswatch = palette.getdarkvibrantswatch(); } for darker color i'm using darkvibrantswatch , lighter color, i'm using vibrantswatch. in of cases, these turn out different each other , hence becoming unusable. there workaround this? maybe if possible 1 color, darkvibrantswatch, , programmatically generate color 2 shades lighter? i'm not sure getting 2 shades lighter can play around shade_factor , see if can achieve want. private int getdarkershade(int color) { return color.rgb((int)(shade_factor * color.red(color)), (i...

c# - How can I convert a 'System.Linq.IQueryable<System.Collections.Generic.ICollection<ApplicationUser>> to IList<ApplicationUser>? -

in project want display list of users in project. projects , users have many many relationship in database. query users via var users = dbcontext.projects.select( u => u.users); this gives me object of type iqueryable> display model requires type of ilist can display on view page. please how can convert between 2 or helpful suggestions. you need use selectmany() flatten list , tolist() convert list: var users = dbcontext.projects.selectmany( u => u.users).tolist();

html - PHP's preg_replace returns null when replacing underscores with white spaces -

i have webpage includes hyperlink follows: $name = "hello world"; echo "<a href='page.php?name='". preg_replace(" ", "_", $name) "'> bla bla </a>" this generates following link successfully: ...page.php?name=hello_world in page.php try reverse operation: if($_server[request_method] == "get"){ $name = $_get['name']; //testing if problem echo $name; //now here's problem: $string = preg_replace("_", " ", $name); echo $string; } the $name echoes correctly $string null i've tried possible combinations ~ ~ , / / , [_] , \s , using $_get directly like: preg_replace("_", " ", $_get['name']); none of them worked. problem has burned of day. appreciated. preg_replace accepts regular expression it's first arguments. neither " " nor "_" valid regular expressions. in case can use str_replace . ...

android - How to get the MvxGridView to be efficient and performant? -

using xamarin , mvvmcross, i'm writing android application loading images album mvxgridview custom binding: <mvxgridview android:id="@+id/grid_photos" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" android:numcolumns="3" android:verticalspacing="4dp" android:horizontalspacing="4dp" android:stretchmode="columnwidth" android:fastscrollenabled="true" local:mvxbind="itemssource allphotos" local:mvxitemtemplate="@layout/item_photo_thumbnail" /> which uses item_photo_thumbnail.axml : <imageview local:mvxbind="picturepath photopath" style="@style/imageview_thumbnail" /> here binding class: public class picturepathbinding : mvxtargetbinding { private readonly imageview _imageview; public picturepathbinding(imageview imageview) ...

plot - Highlighting intersection points of 2 functions (Mathematica) -

Image
given 2 functions, need find intersection points , show them on graph. particular problem, functions are: f(x) = - (x - 2) ^ 2, g(x) = x/(x+1). so far, have following: plot[{-(x - 2)^2 + 4, x/(x + 1)}, {x, 0, 4}, filling -> {1 -> {{2}, {white, lightblue}}}] nsolve[-(x - 2)^2 + 4 == x/(x + 1), {x, y}] but have no idea how show points on graph. how do that? you can use epilog option add graphics primitives plot: intersections = {x, y} /. nsolve[y == -(x - 2)^2 + 4 && y == x/(x + 1), {x, y}]; plot[{-(x - 2)^2 + 4, x/(x + 1)}, {x, 0, 4}, filling -> {1 -> {{2}, {white, lightblue}}}, epilog -> {red, point[intersections]}]

javascript - Navigation ul li a detect which is clicked and do something -

i've decided build own navigation scratch. i using jquery if/else handle interaction. the issue having detecting ul li clicked, , doing based upon result (using $this). can first depth level function correctly, ie first ul li on-click opens first sub-child ul class .c (c = child), not next depth level below that, ie second ul li doesn't open second sub-child ul class .sc (sc = sub child). here fiddle. here live example: !function(n){ $('ul li + ul').prev('a').append('<span class=ai></span>'); $('ul li a').on('click', function(n) { if($('.c').css('display') == 'none') { $this = $(this); $(".c").slidetoggle(); $this.find('span.ai').toggleclass('st'); n.preventdefault(); } else if($(this).is('ul li.p a')) { $this = $(this); $(".c").slidetoggle(); $this.find('span.ai').toggleclass(...

sockets - python asyncio run event loop once? -

i trying understand asyncio library, using sockets. have written code in attempt gain understanding, i wanted run sender , receiver sockets asynchrounously. got point data sent till last one, have run 1 more loop. looking @ how this, found this link stackoverflow , implemented below -- going on here? there better/more sane way call stop followed run_forever ? the documentation stop() in event loop is: stop running event loop. every callback scheduled before stop() called run. callbacks scheduled after stop() called not run. however, callbacks run if run_forever() called again later. and run_forever() 's documentation is: run until stop() called. questions: why in world run_forever way run_once ? doesn't make sense is there better way this? does code reasonable way program asyncio library? is there better way add tasks event loop besides asyncio.async() ? loop.create_task gives error on linux system. https://gist.github.com/cloudformdes...

ssl - Cannot get Chrome version 42 to accept localhost cerfificate -

attempting develop oauth 2 web app in visual studio 2013. development website needs ssl accomplish this. so... how chrome accept localhost's ssl certificate? there various solutions out there, none of work chrome's current version (42). cheers. in short: use chrome://flags/#allow-insecure-localhost . more detailed answer see https://superuser.com/a/903159/291741 .

html - Navigation bar made of images -

i have 5 different images being used buttons website's navigation. want them inline horizontally , centred in browser window. looked fine until added code have text appear under each button when hovering on each image. buttons aligned vertically in middle of window. in html file: <div class="nav"> <div class="container"> <ul> <div class="about"> <li><input type="image" src="image.png" id="aboutpage" onclick = 'aboutpage()'/></li> <p class = "text1"> </p> </div> <div class="resume"> <li><input type="image" src="image.png" id="resumepage" onclick = 'resumepage()'/></li> <p class = "text2"> resume </p> </div> ...