Posts

Showing posts from February, 2014

Perl reads only the last line of my file? -

ok have file list of on 5000 names, 1 line each; file txt file generated microsoft excel. following code gave me output of 1. open filehandle, "< listname_fc2-3ss>0.txt"; chomp (my @genelist = <filehandle>); close filehandle; print "the number of item in list "; print scalar @genelist; i'm using '10 macbook air, perl 5.12.i tried output list , last line of file. tried code on tiny version of 10 names extracted hand myself , worked fine, reckon it's got delimiter? please help. ian try with local $/ = "\r"; before file reading. changes input record separator "\r" character.

r - Legend not displaying color -

i have drawn plot in r . plot(na,xlim=c(0,1),ylim=c(0,1), xlab=expression(delta),ylab="k", xaxs="i",yaxs="i",main = "zones of extreme equality , inequality in bo1") # empty plot cols <- c("red","black") legend("topright",legend=c("gini < 0.05","gini > 0.6"), density=c(na,na), angle=c(na,na), col=cols) the box in legend not getting coloured. wrong here ? try using pch : legend("topright", legend=c("gini < 0.05","gini > 0.6"), pch=15, col=cols)

sql - Analog of "select level from dual connect by level < 10" for Sybase? -

by select level dual connect level < 10 in oracle can generate sub-query of integer , transform sequence. is possible sybase? ps want find dates no data in table (missing days). in oracle as: select to_date('2012-01-01', 'yyyy-mm-dd')+level-1 dual connect level < to_date('2013-01-01', 'yyyy-mm-dd') - to_date('2012-01-01', 'yyyy-mm-dd') minus select distinct date tbl date between to_date('2012-01-01', 'yyyy-mm-dd') , to_date('2013-01-01', 'yyyy-mm-dd') in sybase analog minus is: select whatever table1 t1 not exists ( select 1 table2 id = t1.id ) but don't know analog connect level ... update there way create temporary table in sybase without storing data disk? the oracle syntax use hierarchical query used row generator. sybase has sa_rowgenerator system procedure can used generate set of integers between start , end value. the follo

c# - why not using Request.Cookies.Clear() in ASP.NET web forms? -

i searched here on stackoverflow removing cookies site, couldn't find single answer suggesting use of request.cookies.clear() method. what's difference between: if (request.cookies["usersettings"] != null) { httpcookie mycookie = new httpcookie("usersettings"); mycookie.expires = datetime.now.adddays(-1d); response.cookies.add(mycookie); } and: request.cookies.clear(); thanks in advance! , sorry bad language, english not native! calling remove or clear remove server side collection held request.cookies (which copy of cookies client sent you). not cause server instruct client browser remove cookie. need set timeout have indicated above (see msdn - how to: delete cookie official guidance).

internet explorer - Wordpress site not working in IE -

this site works in major browsers, when tested on explorer in explorer 9 or earlier versions, went insane: margin-auto didn't work, absolute positions went different locations, menu disappeared , on... i using "naked" html5-blank-master theme, works in ie on other sites i've created. i've tried placing " <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> " no results. please help. here link site my site you have white space, or else, before doctype. some/most versions of ie go quirks mode if there in front of doctype including spaces. remove , see stand.

php - Utilising minimal MySQL queries when building a database-driven user system -

i'm building user system site using php , mysql datastore, don't particularly want run mysql query every time user logs in i'm thinking using sort of caching solution (such memcache) store user data. my question is, safe , practical practice employ? , if not, how can reduce mysql queries as possible? what amount of concurrent user site needs handle? in opinion overhead kind of caching redundant... if u'r still go memcache, concerning security , remember memcache application session object application; considered secure long users not have access it. other ways of reducing mysql overhead setting commonly-needed information in session variable after login.

opencv - Image stitching: NullPointerException -

i have run code. seems result.png not generated result: public class imagestitching { public static void main(string[] args){ matvector images = new matvector(2); images.put(0,cvloadimage("sample1.png")); images.put(1,cvloadimage("sample2.png")); iplimage result = new iplimage(null); int status = stitcher.stitch(images,result); if( status == stitcher.ok ) { cvsaveimage("result.png", result); } result = cvloadimage("result.png"); final canvasframe canvas = new canvasframe("my image", 1); // request closing of application when image window closed. canvas.setdefaultcloseoperation(javax.swing.jframe.exit_on_close); // show image on window. canvas.showimage(result); } } and error exception in thread "main" java.lang.nullpointerexception @ com.googlecode.javacv.canvasframe.showimage(canva

Javascript validation doesn't work in my PHP -

i have simple javascript validation code works fine if send php address, while doesn't work if send php page have created. the code quite basic @ moment , validates fields regexes. basically, if try given ready-made php file (i can't access) works fine presenting me error dialog box until fields correct. meanwhile, in php page made, catches error, display dialog box on ok alert box click, submits fields php file. can give me clue of what's going on? thank you. this javascript: <script type="text/javascript"> /* <![cdata[ */ // function calls other functions validate each field of submitting form function validate() { var validated = false; validated = validaterid() && validateeid(); return validated; } // validates rid: checking field filled number between 1 //and 99999 function validaterid() { var ridelement = document.getelementbyid("rid"); patternrid = /^([1-9][0-9]{0,4})$/; if

javascript - How to transform a String "a,b,c,d..." into a.b(c,d,...); for execution -

i have small multiplayer app working in websockets. application composed of game , chat object, each specific methods. basically, client receives message string formatted : "object,method,arg1,arg2" , example "chat,newmsg,foo bar", or "game,addplayer,name,level,team". first example should translated chat.newmsg("foo bar"); while second example game.addplayer(name,level,team); having difficulties doing writing message reader. i trying figure out elegant solution, : var msgreader = function(message){ msg=message.split(","); msg[1].apply(msg[0],msg[2]); } but message can have many arguments, , can't quite figure out how handle that. me? not use eval() ^^ apply() expects array of arguments; if want pass arguments individually, use call() . however, apply() best in (in right use case), don't know number of arguments. var msgreader = function (message) { var props = message.split(",");

How do I use user input to invoke a function in Python? -

this question has answer here: calling function of module string function's name 10 answers create raw input commands inside python script 1 answer i have several functions such as: def func1(): print 'func1' def func2(): print 'func2' def func3(): print 'func3' then ask user input function want run using choice = raw_input() , try invoke function choose using choice() . if user input func1 rather invoking function gives me error says 'str' object not callable . anyway me turn 'choice' callable value? the error because function names not string can't call function 'func1'() should func1() , you can like: { 'func1': func1, 'func2': func2, 'func3': func3, }.get(cho

Passing a double pointer to a function as reference - c -

i'm having hard times trying pass reference of double pointer function. have this: #include <stdio.h> #include <stdlib.h> #include <string.h> #define max_rows 2 #define max_cols 2 int main(void){ int i=0,lenght=0,maxcolumns=0,j=0,k=0,maxrows=0,maxcolumns2=0; int **columnvect; /*lengthofptr gives me columns need. */ if((lenght=(lengthofptr(ptrmessage)))<=3){ maxcolumns=1; maxcolumns2=2; }else{ maxcolumns=lenght/2; maxcolumns2=maxcolumns; } /* allocating memory double pointer. */ columnvect=malloc(maxcolumns2 * sizeof(int*)); if(columnvect == null){ fprintf(stderr, "memory error.\n"); exit(0); } for(i = 0; < maxcolumns2; i++){ columnvect[i] = malloc(maxrows * sizeof(int)); if(columnvect[i] == null){ fprintf(stderr, "memory error.\n"); exit(0); } } // fills columnvect[i][j]

android - Volley - POST/GET parameters -

i saw google io 2013 session volley , i'm considering switching volley. volley support adding post/get parameters request? if yes, how can it? in request class (that extends request), override getparams() method. same headers, override getheaders(). if @ postwithbody class in testrequest.java in volley tests, you'll find example. goes this public class loginrequest extends request<string> { // ... other methods go here private map<string, string> mparams; public loginrequest(string param1, string param2, listener<string> listener, errorlistener errorlistener) { super(method.post, "http://test.url", errorlistener); mlistener = listener; mparams = new hashmap<string, string>(); mparams.put("paramone", param1); mparams.put("paramtwo", param2); } @override public map<string, string> getparams() { return mparams; } } evan cha

Commands in ruby terminal application -

i have written first terminal application in ruby. use optionparser parse options , arguments. want create commands. example: git add . in above line, add command cannot occur anywhere else after application. how create these. i appreciate if point me in right direction. however, please not reference gems such commander. know these. want understand how done. the optionparser's parse! takes array of arguments. default, take argv , can override behaviour so: basic approach def build_option_parser(command) # depending on `command`, build parser optionparser.new |opt| # ... end end args = argv command = args.shift # pick , remove first option, validation... @options = build_option_parser(command).parse!(args) # parse rest of advanced approach instead of build_option_parser method huge case-statement, consider oo approach: class addcommand attr_reader :options def initialize(args) @options = {} @parser = optionparser.new #...

ontouchevent - Android: Touch event for select item on a canvas -

i have many circles drawn on canvas , want know of them touched. 1 solution create bitmap size of screen , draw copy of circles on screen different color when call getpixel () bitmap poosso recognize circle clicked. problem not know how draw circle on bitmap ... is, how draw bitmap drawing on canvas. paint paint; bitmap screen; int w,h; int px=-1,py=-1; //coordinate @override protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { //registriamo le dimensioni della view w=measurespec.getsize(widthmeasurespec); h=measurespec.getsize(heightmeasurespec); setmeasureddimension(w,h); } public customview(context context, attributeset attrs) { super(context, attrs); bitmap.config conf = bitmap.config.argb_8888; //each pixel stored on 4 bytes screen=bitmap.createbitmap(w,h, conf); paint=new paint(); // pennello paint.setcolor(color.red); paint.setantialias(true); } @override protected void ondraw(canvas canvas) { //

Ruby get last * in a string -

i have string different data , stars well. how can index of last *? example hello * there * * now how can index of 3rd *? use string.rindex : returns index of last occurrence of given substring or pattern (regexp) in str. returns nil if not found. x = 'hello * there * *' puts x.rindex('*') # 16

ide - Javascript code -

i checked websites source code , javascript games. problem readable , understandable except javascript code isolated on file extension .js . looks this: {vargas=void0,h=!0,ge=null,l=!1,aa=component,ba=infinity,ca=set timeout,da=is nan,m=math,ea=deconstructionism;function he(a,b){return a.on-load=b}function ie(a,b){return a.on error=b}function ha(a,b) {return a.name=b} as can see, it's hard read code because of stupid indentation. tried use microsoft visual web developer , free javascript editors organize code, useless! how can make more readable? the best place start @ other open source java script libraries/modules/plugins. must have original code though, because see in browser "compiled" web small , fast. for client have plenty frameworks. example @ list jsfiddle uses (top-left). can use tool play javascript without having install anything. search on web projects (that jsfiddle uses libraries) , code. there server-side javascript library allows w

python - Notify parent instance about property change -

i have these 2 classes: class status(object): def __init__(self): self._message = '' @property def message(self): return self._message @message.setter def message(self, value): self._message = value class buddy(object): def __init__(self, name): self.name = name self.status = status() def status_updated(self): # should called when self.status.message changed and use them this: buddy = buddy('john') buddy.status.message = 'hello world!' # should call buddy.status_updated i want buddy.status_updated called when modify message property of status . how achieve this? you'll have store reference back parent; python values not track stored (there can multiple places refer status() instances): class status(object): def __init__(self, parent=none): self._message = '' self._parent = parent @property def message(self):

java - Can't remove distortion -

i'm making program calibrate camera , remove distortion chessboard using opencv in java. i've been reading "learning opencv" , code quite similar program run without errors results wrong. i'm looking intrinsic matrix , distortion coefficients. could me? i'm desperate!! briefly,i set size of cheesboard (4 points width , 5 height). i capture image, , create 4 matrix image_points, object_points, image size (as inputs) camera_matrix , distortion_coefficients (as outputs). apply smooth filter (gaussian one) noise effects and: cvfindchessboardcorners(image, board_sz, corners, corner_count, cv_calib_cb_fast_check); cvcvtcolor(image, gray_image, cv_bgr2gray); cvfindcornersubpix( // subpixel accuracy on corners gray_image, corners, corner_count[0], cvsize(11,11), cvsize(-1, -1), cvtermcriteria(cv_termcr

c++ - uBLAS matrix clear memory -

i have ublas matrix, so: boost::numeric::ublas::matrix<double> mat(50000,50000); once i'm done set of calculations on matrix, want memory freed. i have been using mat.clear() which, according docs , "clears matrix". program keeps running out of memory. digging headers, find this: void clear () { std::fill (data ().begin (), data ().end (), value_type/*zero*/()); } so there's clear semantics problem clear() . the question is, how ensure memory freed? an inelegant way return memory resizing matrix: mat.resize(0,0,false); though have not tried using 0 size value myself...

javascript - How to create nav list with different buttons so when I click on the button the content/text will change according to the button I clicked? -

i new programming here basic question. i know how make nav list don't know how make functional. example, let's navlist has 3 buttons: home, , contact me. how make webpage change home content between these 3 buttons??? mean how different text/content when click on or contact me button? hope understand mean. must simple begginer. thanks in advance help! most situations use css. if want them run in list, use following in html: <ul class="navmenu"> <li><a href="index.html">home</a></li> <li><a href="about.html">about</a></li> <li><a href="contact-me.html">contact me</a></li> </ul> and css style be: <style> ul.navmenu { /* enter css ul menu menu here*/ } ul.navmenu li { /* enter css list menu here*/ } ul.navmenu li { /* enter css link menu here*/ } </style> you can "css list style" , more information on how

How is the __LINE__ and __FILE__ constants implemented in Ruby? -

it seems __file__ , __line__ constants dynamically updated current file , line numbers under execution, wondering how behaviour implemented in ruby? i've greped source code there many noises __line__ , __file__ appearance, wonder me point source code , provide clue understand behaviour. explanation in either rubinis or mri fine. both __file__ , __line__ replaced literals directly in parser : case keyword__file__: return new_str(rb_external_str_new_with_enc(ruby_sourcefile, strlen(ruby_sourcefile), rb_filesystem_encoding())); case keyword__line__: return new_lit(int2fix(tokline)); in other words, behave if had typed in resulting string or number yourself. note __line__ , doesn't behave how you'd expect .

sql - Database structure for storing a statement and 4 options with inline images -

i have statement can have multiple inline block images (like mathematical formulaes) , has 4 associated choices (like in quiz) , each 1 of them can have number of inline images well. i know in naive manner can store html each of them q_id|ques|number of choices| choice | choice b | choice c | choice d or can have question table q_id|ques| q_contains_image| number of choices| choice | choice id| choice_contains_image| choice b | ....choice c... | choice d ... and image table img_id|q_id/choice_id|image_path i still don't know if best way , how second way affect performance if need render question choices in html. don't first way because require hardcoding path within html , html never nice read when see them result of sql query. i want know method store them along implied costs of using method. let's normalize data. normalizing data, eliminate redundancy in data , reduce storage needed minimum. you need join tables @ of information. joining

ios - Count number of rows that contain a string in table view always returns 1 -

my app dynamically adds table view rows receive pass/fail result displayed cell string (in addition description). im trying count amount of cells receive fail result in text. problem nslog(@"counted times: %i", times); returns 1 rather adding them up. cell.textlabel.text = [nsstring stringwithformat:@"appliance %@: %@", ((circuit *)[self.circuits objectatindex:indexpath.row]).circuitreference,((circuit *)[self.circuits objectatindex:indexpath.row]).rcdtestbutton]; if(cell.textlabel.text && [cell.textlabel.text rangeofstring:@"fail"].location != nsnotfound){ cell.textlabel.textcolor = [uicolor redcolor]; nsstring *string = @"str"; int times = [[string componentsseparatedbystring:@"-"] count]; nslog(@"counted times: %i", times); } updated code - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { nsstring *str

database - denormalization tables to 1NF -

how can denormalize 1nf. -------------------------------------------------- | | | | | | v v v v ----------------------------------------------------------- |post_id|post_title|post_text|post_submited_time|user_name| ----------------------------------------------------------- ------------------------------------------------ | | | | | v v v --------------------------------------------------------- |comment_id|comment_text|comment_submited_time|user_name| --------------------------------------------------------- ----------- | | | v -------------------- |post_id|comment_id| -------------------- i want 1 table in 1 normal form when normalize result tables. it depends on database using, because there databases postgresql can have arrays or c

Amazon S3 REST API; how is the API-key transferred firsttime between client and service? -

within research came across many different sources, somehow fail see, side generating private api-key , how other side getting hold of it. many people recommend amazon s3 restful api role model, hence if understand that, create similar own purposes. amazon's s3 rest api. e.g. example here explains process nicely, fails explain, side generating api-key? upon user signup, service side generating private api-key , assigns user id in database? if case though, client needs know api key in order create signature each request, service can verify it. how both sides hold of private api key? in case have iphone app , angularjs web app clients talking restful api service. many thanks, first, don't want give out keys clients. in general, that's security nightmare. (also, key creation can take hours propagate. , you'll have manage permissions each key, etc.) signing done server, , key doesn't leave server. you want server have s3 key, return signed

Getting information from PHP into HTML5 JavaScript Game -

i've been mucking around js/node/socket.io , made little multiplayer game dots , can move around. want take level further , add simple login system can display information user's login above head identify different players. now know php server-side language , javascript client-side need come way this. i'm asking is, know how information straight php javascript? later on might want add levelling , store player's levels in database , retrieve them when connect (as opposed using local storage). thanks much! joel you can use php write javascript. e.g. $jsvars = array( "one" => "hello" , "two" => "yo" ); echo '<script type="text/javascript">'; echo "var phpvars = ".json_encode($jsvars); echo "</script>"; or can utilise ajax make requests php , pass data via json.

Service with MediaPlayer doesn't stop when closing app - Android -

i'm developing simple game 3 activities (menu, settings , ranking list) needs 1 background music should play smoothly in background if example user leaves menu , goes settings , back. for created service works perfectly. there 1 major problem: when app closed (user press home button example), music doesn't stop playing. i have tried ondestroy, onstop, onpause problem not solved. service: package com.android.migame; import android.app.service; import android.content.intent; import android.media.mediaplayer; import android.media.mediaplayer.oncompletionlistener; import android.os.ibinder; public class meni_music extends service implements oncompletionlistener { private static final string tag = null; mediaplayer player; public ibinder onbind(intent arg0) { return null; } @override public void oncreate() { super.oncreate(); player = mediaplayer.create(this, r.raw.menu); player.setlooping(true); // set looping

algorithm - When c > 0 Log(n) = O(n)? Not sure why it isn't O(log n) -

in homework, question asks determine asymptotic complexity of n^.99999*log(n). figured closer o( n log n) answer key suggests when c > 0, log n = o(n). i'm not quite sure why is, provide explanation? it's true lg n = o( n k ) (in fact, o( n k ); did hint that, perhaps?) any constant k , not 1. consider k =0.00001. n 0.99999 lg n = o( n 0.99999 n 0.00001 ) = o( n ). note bound not tight, since choose smaller k , it's fine n 0.99999 lg n o( n 0.99999 lg n ), n lg n o( n lg n ).

c++ - Unexpected changes in std::vector -

here code: typedef struct triplet { double value; int row; int column; }; class matrix { public: //some methods double specialmethod(/*params*/); private: std::vector<triplet> elements; int nrows; int ncolumns; }; after specialmethod gets called values in matrix.element corrupted. there nothing done them except iterating this: std::vector<triplet>::iterator it; std::vector<pair> buff; (it = this->elements.begin(); != this->elements.end(); ++it) { if (it->column = n) { pair p; p.key = it->row; p.value = it->value; buff.push_back(p); } } don't have idea start looking mistake. if (it->column = n) should be: if (it->column == n) you doing comparison not assignment.

zeromq - How to fetch 0mq socket structure from fd? -

we have application in listening on socket. when clients connect, need know per client “fd” , peer address. info can fetched using socket monitors. subsequently, need send data separately each client. (not send same data clients). there standard api socket structure “fd” can use in send api? my understanding fd used field of zmq_pollitem_t struct used in zmq_poll or other pollers. there used when want interface zmq sockets other non-zmq pollers (so if you're using zmq_poll shouldn't set other 0 ). so, in case using non-zmq poller, you're setting fd value, not getting it. is use of fd you're referring to? if not, update question more specific?

javascript - Not getting change events when radio buttons are clicked -

mates, i'm tryin' set backbone events when radio buttons clicked. have following buttons: <p><label for="pays">pays now</label><input id="pays" name="pays" type="radio" value="1" class="_100"/></p> <p><label for="pays2">pays later</label><input id="pays2" name="pays" type="radio" value="2" class="_100"/> and define event this: 'click input[name=pays]:not(:checked)': 'radiochecked' so, understand it, should fire when clicking input named pays that's not checked. the thing is, not firing event when click on radio button. if try this... 'click input[name=pays]': radioclicked i can fix flags, i'll have event fired every time radio clicked. any idea? thanks! i've found solution. changed event declaration to: 'click input[name=pays]:checked&

google apps script - Import rows in Fusion Tables fails -

i can't seem import rows google fusion correctly. 503 backend error. google apps script code below. var getdataurl = ' https://www.googleapis.com/fusiontables/v1/tables/ {tableid} /import?key='+ {apikey} ; var ssdown = spreadsheetapp.openbyid({spreadsheet id}).getdatarange().getvalues(); var options = { "method" : "post", "contenttype" : "application/json", "headers" : { "authorization" : "bearer " + {token} , "accept" : "application/json", }, 'encoding' = 'auto-detect', 'payload' = ssdown.tostring(); } }; var output = urlfetchapp.fetch(getdataurl,options).getcontenttext(); the issue caused careless coding on part. correct code is: var getdataurl = 'https://www.googleapis.com/upload/fusiontables/v1/tables/{tableid}/import'; var options = { "method" : "post", &q

parallel processing - Shared memory C++ and Win API 32 with custom class -

are there samples getting custom class including large arrays properties in shared memory? need read/write access different threads in same process. size of class instance unknown @ compilation time. openmp solutions not allowed in case, win 32 api or native c++ features. you not need shared memory this. memory in 1 c++ process implicitly shared , accessible threads, far know address. what need synchronization threads access objects in proper order (without race condition). objects should implement so-called monitor pattern. in c++ manually this put (win32 api) mutex member of object lock mutex in beginning of every method unlock @ method exit. it's better use locker object on stack deal exceptions. (in languages declare methods or objects synchronized, in c++ manually) alternatively use higher level parallel pattern, 'readers/writers'. prefer message passing

PHP: How to get line from txt and dont repeat -

hello im using multithread class emails list using file_get_contents("http://server.com/getemails.php"); this getemails.php : index = file("index.dat"); $index = $index[0]; $f_contents = file("../susc/ar.txt"); $line = $f_contents[$index]; $data = $line; file_put_contents("index.dat",$index +1); echo $data; it gets data "../susc/ar.txt" file has 100.000 lines : sampleuser@hotmail.com suscribeduser@hotmail.com exampleemail@hotmail.com ... but, when run program multithreaded .. gives lot of repeated emails like this: [thread][t11] -> sampleuser@hotmail.com [thread][t12] -> sampleuser@hotmail.com [thread][t8] -> sampleuser@hotmail.com [thread][t1] -> sampleuser@hotmail.com [thread][t2] -> sampleuser@hotmail.com [thread][t5] -> suscribeduser@hotmail.com [thread][t3] -> suscribeduser@hotmail.com [thread][t6] -> suscribeduser@hotmail.com [thread][t7] -> suscribeduser@hotmail.com [thre

ios - UIImage resizes in custom UITableView on reloaddata -

i have tableview custom cells , adding data below: { uiimage *img = [uiimage imagenamed:@"black_lab_tideat2b.jpg"]; uiimageview *petpic = (uiimageview *)[cell viewwithtag:101]; uilabel *petname = (uilabel *)[cell viewwithtag:102]; petname.text = [current petname]; } this data shows correctly in uitableview. the issue occurs when attempt delete row using commiteditingstyle. after have deleted selected record sqlite , { [self.tbllistprofiles reloaddata]; } it resizes image in remaining cells. resized image changes normal size after add new record sql , refresh using { [self.navigationcontroller popviewcontrolleranimated:yes]; } can please help? regards make sure delegate uitableview implements tableview:heightforrowatindexpath: or has rowheight property set correct size. uitableviewdelegate reference uitableview reference

json - C / Youtube API Request > VLC -

im trying improve tiny c application wich streams youtube videos. reason im not beeing able send request , decode json. point me in right direction, original. #include <arpa/inet.h> #include <assert.h> #include <errno.h> #include <netinet/in.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <unistd.h> #define sa struct sockaddr #define maxline 4096 #define listenq 1024 void process_http(int sockfd, char argv[]){ char sendline[maxline], recvline[maxline]; char storeline[maxline]; char run_command[50]; char * linkpos; ssize_t n; int arraysize; int i; arraysize = strlen(&argv[0]); if(&argv[0] == "\32") { printf("har space\n"); } strcpy(sendline,"get /?youtubereq="); strcat(sendline,&argv[0]);

avd - parseSdkContent failed java.lang.NullPointerException. after bsod -

i got error android sdk content loader has encountered problem. parsesdkcontent failed java.lang.nullpointerexception after bsod.. have tried delete avd folders , .ini files. sdk working again. but, problems avd folders have backup cannot restored since when restored them, problems started occuring again. there way avd data again? follow these steps: c: -> users -> [abc] -> delete .android folder

python - How can I install Pygame on a 64-bit win7? -

i have searched forum , found related questions, seems no easy-to-understand answers me. i have come https://bitbucket.org/pygame/pygame/downloads provides 32-bit installer. on 64-bit win7, installed python 3.3.2. how can install pygame in case? thanks. this site contains non-official binaries of many python packages 32 , 64 bit versions of windows, , mentioned in downloads section of pygame.org . downloads pygame here .

Spring 3 -- NullPointerException from JDBCTemplate.getQueryForMap() -

i running custom tag in spring jsp. getting following error message. java.lang.nullpointerexception com.dao.poll1dao.getvotes(poll1dao.java:27) com.tags.poll1tag.dotag(poll1tag.java:23) org.apache.jsp.web_002dinf.pages.pollpage_jsp._jspx_meth_mytag1_005fpoll1_005f0(pollpage_jsp.java:602) org.apache.jsp.web_002dinf.pages.pollpage_jsp._jspservice(pollpage_jsp.java:195) org.apache.jasper.runtime.httpjspbase.service(httpjspbase.java:70) javax.servlet.http.httpservlet.service(httpservlet.java:722) org.apache.jasper.servlet.jspservletwrapper.service(jspservletwrapper.java:432) org.apache.jasper.servlet.jspservlet.servicejspfile(jspservlet.java:390) org.apache.jasper.servlet.jspservlet.service(jspservlet.java:334) javax.servlet.http.httpservlet.service(httpservlet.java:722) org.springframework.web.servlet.view.internalresourceview.rendermergedoutputmodel(internalresourceview.java:238) org.springframework.web.servlet.view.abstractview.rend

ajax - Rails: request.referrer == request.url -

perhaps misunderstand how request.referrer works, isn't suppose provide url of page user coming from? instance, if they're viewing article , click edit, request might this: request.referrer = http://localhost:3000/article/1 request.url = http://localhost:3000/article/1/edit if that's case, i'm getting odd behaviour, because user's request.referrer set current url. might causing this? it's worth noting i'm using ajax powered site, , these requests remote. request.referrer should url making request from, if ajax think should change url referrer change.

Android dividing a little part of screen vertically -

Image
i have 2 images next each other. sure using "dp" size, in screens images become little , in screens not. it's dp does. i don't know must set sizes. 50dp, 75dp or 100dp... , don't know how decide that. i want give images' size "screen size / 2" (because have 2 images) , want them scale sizes. mustn't give height. in resolution, must set width "screen width / 2" , height proportional width. here graphic of want: what should do? any suggestions appreciated. if want set images width screen size / 2 , make sure using px instead of dp , otherwise result different on various devices due resolution of devices. can width in pixels below code. displaymetrics dm = new displaymetrics(); getwindowmanager().getdefaultdisplay().getmetrics(dm); displaywidth = dm.widthpixels; after can set image width using one. image_view.getlayoutparams().width = displaywidth /2; hope solve problem.

asp.net mvc - Get selected DropDownList item from MVC Partial view -

i use @html.dropdownlist in partial view show list of banks , render in bank branch view. how can selected bank in @html.dropdownlist , fill bankid in bankbranchmodel . here code: bankbranchmodel : public class bankbranchmodel : basemodel { public int? **bankid** { get; set; } public string name { get; set; } public string code { get; set; } public string phone { get; set; } public string address { get; set; } } my partial view : @html.dropdownlist("banks", model , "- please select -"}) bankbranch view: @model mvcfirstsample.models.bankbranchmodel @{ viewbag.title = "create"; } <h2>create</h2> @using (html.beginform()) { @html.validationsummary(true) <div class="editor-field"> **@html.action("getallbank", "bankbranch")** </div> getallbanks return partial view: public actionresult getallbank() { var banks = contex

windows server 2008 r2 - Login as Administrator on Azure Virtual Machine -

i'm trying install software on azure virtual machine, fails indicating don't have administration privileges, though chooose "run administrator" option. how can login administrator on azure virtual machine? thanks https://serverfault.com/questions/111650/how-can-i-find-out-what-ad-groups-im-a-member-of the above link tell groups belong user in system. if running default user setup azure vm administrator on machine. if have been granted access user box, ask them upgrade rights. you should see if in event log there permissions error install of software or other error suggest why software cannot installed. maybe misleading error. i contact application provider , check support azure environment. hths, luck.

ajax - load a page inside page jquery div before posting form -

i have jquery code below posts form checkboxes , updates results according users choices. works fine automatically load page first default results returned when users visits page, if user clicked 1 of results , clicked return previous results. here code: $(document).ready(function () { $(".remember_cb").click(function () { var action = $("#criteria").attr('action'); var form_data = $('#criteria').serialize(); $.ajax({ type: "post", url: action, data: form_data, beforesend: function () { $("#loading").fadein('fast'); }, success: function (data) { $('#exercise_list').html(data).fadein('slow'); $("#loading").fadeout('slow'); } }); }); return false; }); any appreciated. i'm not sure if it's &q

javascript - Button that makes textarea text bold -

i have button has onclick="bold()" , supposed changing font weight normal bold , normal. isn't doing though. need change or add? here jsfiddle if helps: http://jsfiddle.net/dzvfh/ <script> var x = document.getelementbyid('description-box'); function bold() { if( $(x).css("font-weight") == "normal") { $(x).css("font-weight"), "bold"); } else { $(x).css("font-weight", "normal"); } } </script> there syntax error in code: change $(x).css("font-weight"), "bold"); to $(x).css("font-weight", "bold"); full function function bold() { var x = $('#description-box'); if (x.css("font-weight") !== "bold") { x.css("font-weight", "bold"); } else { x.css("font-weight", "normal"); } } wo

scala - Incorrect MIME type for GET requests -

i've been using lift web framework rest service quite while, need use stand alone tool now. <lift:surround with="default" at="content"> <head> <script data-lift="with-resource-id" src="/test.js" type="text/javascript"></script> </head> <h2>welcome project!</h2> <p><lift:helloworld.howdy /></p> </lift:surround> i have above basic lift template. problem when view in browser adding <?xml> doctype , browser defaults interpreting resource xml instead of plain html. how tell jetty/lift static file html? sounds may using xhtml doctype. in boot.scala file, may want try adding: liftrules.htmlproperties.default.set((r: req) => new html5properties(r.useragent)) that should set application use html5, , should turn off adding <?xml... encoding header. also, @vasyanovikov mentioned, lift: prefixed tags older construct (even

performance - Big(0) running time for selection sort -

you given list of 100 integers have been read file. if values zero, running time (in terms of o-notation) of selection sort algorithm. i thought o(n) because selection sort starts leftmost number sorted side. goes through rest of array find smallest number , swaps the first number in sorted side. since zeros won't swap numbers (or think). my teacher said o(n^2). can explain why? selection sort not adaptive. each element compared each other element (compare n elements n other elements → n^2 comparisons). thus, selection sort has o(n^2) comparisons. has, however, o(n) swaps. think of table n rows , n colums, , each cell needs comparison fill value (except diagonal). more info on amazing website

asp.net mvc - MVC WCF Validation -

i want validate view don't know best way it i want know if there option in service have [required(errormessage = "property required.")] [datamember] public string name { get; set; } and when pass view data want @html.label("name") @html.editorfor(model => model.name @html.validationmessagefor(model => model.name) but can't find solution in net think answer no can tell me best solution validate ?

java - Android : nonwritablechannelException and ClosedChannelException -

i'm using filelock , don't know why meet nonwritablechannelexception exception : public static list<string> readfromfile(context ctx, string filename) { try { fileinputstream fis = ctx.openfileinput(filename); // lock file filelock lock = fis.getchannel().trylock(); // exception here // unlock file lock.release(); return null; } catch (exception e) { log.i(tag, "cannot read file"); e.printstacktrace(); } return null; } and meet exception when writting file: exception closedchannelexception public static boolean savetofile(context ctx, list<string> lst, string filename) { try { fileoutputstream fos = ctx.openfileoutput(filename, context.mode_private); // lock file filelock lock = fos.getchannel().lock(); packageobject obj = new packageobject(lst); object

Python Function inputs -

i trying teach myself python on code academy , have written following basic code, not working whatever input outcome 'please enter valid number' , message saying "oops, try again! make sure area_of_circle takes 1 input (radius)." import math radius = raw_input("enter radius of circle") def area_of_circle(radius): if type(radius) == int: return math.pi() * radius**2 elif type(radius) == float: return math.pi() * radius**2 else: return "'please enter valid number'" print "your circle area " + area_of_circle(radius) + " units squared" the original assignment is: write function called area_of_circle takes radius input , returns area of circle. area of circle equal pi times radius squared. (use math.pi in order represent pi.) errors in program: raw_input() returns string, you've convert float or int first. type checking bad idea in python math.pi()

java - Using a collection reference as an if statement condition without a comparison? -

i'm little embarrassed asking because i'm sure basic question having searched , thought still can't work out. the code class tutor walked through developing during tutorial on collections course. class represents crime sheet of districts associated crime codes. sheet implemented sortedmap keys of type string (representing district) , values arraylist of integers (representing crime codes). there 1 method didn't manage finish during tutorial tutor sent on copy of , can't follow logic. code method below /** * displays districts affected given crime code * * @param integer crime code * @return none */ public void displayaffecteddistricts(integer crimecode) { arraylist<integer> searchcode; for(string eachdistrict: crimetable.keyset()) { searchcode = new arraylist<integer>(); searchcode.add(crimecode); if(!(searchcode.retainall(crimetable.get(eachdistrict)))) { system.out.prin

python - writing urlpattern in django for rendering an image -

in django app,i have index page lists summary info dynamic(based on user input data in db) . have coded below views.py def custom_render(request,context,template): req_context=requestcontext(request,context) return render_to_response(template,req_context) @login_required def index(request, template_name): summary_info = get_summary(...) return custom_render(request,{'summary':summary_info},template_name) urls.py urlpatterns=patterns('', ... url(r'^$', 'myapp.views.index',dict(template_name = 'myapp/index.html'), name = 'home'), ... now,i want include chart image generated matplotlib on home page..so,when user requests index page url, can see both summary info , chart i have written index.html below {% extends "myapp/base.html" %} .... <div id='summary'> {# here display summary #} ... </div> <div id='chart'> <img class="chartimage"src=&

ios - Can I trust objectForKey right after setObject in NSCache? -

considering sample code (cache instance of nscache): - (id)objfromcache { if ([cache objectforkey:@"myobject"] == nil) [cache setobject:[self generateobject] forkey:@"myobject"]; return [cache objectforkey:@"myobject"]; } should trust code? mean, objectforkey:@"myobject" ever return nil right after setobject:forkey:@"myobject" ? if so, whould change if while ? what's best way handle situation? thanks! at least in multi-threaded environment cannot assume nscache returns object inserted. also if first call [cache objectforkey:@"myobject"] not return nil , second 1 in return statement return nil . so play safe , write method as - (id)objfromcache { id value = [cache objectforkey:@"myobject"]; if (value == nil) { value = [self generateobject]; [cache setobject:value forkey:@"myobject"]; } return value; }

ios - Mocking expectations and Grand Central Dispatch -

i have simple manager object, , using mocks in kiwi, want check when call [apoimanager fetchnear:location] calls downloadpoisnear:completionblock: on downloader. everything worked fine until decided dispatch call downloader inside grand central dispatch. the call being asynchronous, test fails. kiwi has feature check asynchronously value, not check asynchronous calls . here part of test : it(@"should call proximity downloader", ^{ cllocation *location = [[cllocation alloc] initwithlatitude:1.0f longitude:1.0f]; id<rmproximitydownloader> mockdownloader = [kwmock mockforprotocol:@protocol(rmproximitydownloader)]; [[(nsobject*)mockdownloader should] receive:@selector(downloadpoisnear:completionblock:)]; rmpoimanager *apoimanager = [[rmpoimanager alloc] initwithdownloader:mockdownloader]; [apoimanager fetchnear:location]; }); try this: [[(nsobject*)mockdownloader shouldeventually] receive:@selector(downl

iOS google maps sdk custom call out view and marker centering -

hi guys working google maps sdk now, kinda have 2 doubts: callouts: how customize callouts, had hard time trying figure out way customize existing stuff not. found this though. gmsmarkers: i want center marker in map view i.e, marker should in particular position set , current zoom level should maintained. i did marker centering showing callout marker , want center callout centered. thanks in advance. for gmsmarker question: have create camera points marker position , set mapview camera it somemarker = [[gmsmarker alloc] init]; somemarker.position = cllocationcoordinate2dmake(lat, lng); somemarker.map = mapview; gmscameraposition *camera = [gmscameraposition camerawithlatitude:somemarker.position.latitude longitude:somemarker.position.longitude zoom:13]; [mapview setcamera:camera];

android - ListView id not valid -

i've got problem activity root element listview. i've followed this tutorial load items listview , work. i've tried change id of listview , now, when activity loading, receive problem: your content must have listview id attribute "android.r.id.list" i retried change id "list" i've got same problem. don't have problems in compiling in run-time. code of activity when load listview. public class startactivity extends listactivity { @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_start); //section inflating adapter.addsection(getstring(r.string.equationmenu), new arrayadapter<object>(this, android.r.layout.simple_list_item_1, new string[] {getstring(r.string.eq1title), getstring(r.string.eq2title), getstring(r.string.eqfractitle)})); setlistadapter(adapter); } sectionedadapter adapter = new sectionedadapter() {

how to make custom templates in Koken -

i'm using koken , customize template text entries putting date @ top of entry. i hacked call new date() core template file /admin/templates/text.tmpl.html <div id="entry-editor"> <div id="edit-area" data-bind="html: content() || '<p class=\'date\'>' + new date() + '</p> <p class=\'media-row\'><br /></p>'"> </div> </div> <!-- close #entry-editor --> this works fine, know perils of hacking core files. as of writing, don't see answer on page linked " define own custom template types " on help.koken.me . without hacking core files, how can have koken add date top of each text entry? from http://help.koken.me/customer/portal/questions/1080677-how-to-make-custom-templates-in-koken- simply place <koken:time> tag in customized theme template. for example, in /storage/themes/<custom-theme-name