Posts

Showing posts from April, 2013

asp.net - Concurrency check when updating using GridView -

with sqldatasource, how can sure data i'm going update not modified in meantime when fetched data , when i'm make update. <asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:chartdatabaseconnectionstring %>" selectcommand="select * [student]" updatecommand="update [student] set [studentname] = @studentname, [dob] = @dob, [age] = @age, [course] = @course, [city] = @city, [mobileno] = @mobileno [studentid] = @studentid"> is there gridview method or parameter can use ? there propery on sqldatasource named conflictdetection . setting property compareallvalues may trick you.

What is bash/zsh "|&" syntax mean? -

what |& syntax means? example: tree |& less i see no difference tree |& less . from bash manual : command1 [ [| or |&] command2 …] if |& used, standard error of command1 connected command2 ’s standard input through pipe; shorthand 2>&1 | . implicit redirection of standard error performed after redirections specified command. in zsh too, |& shorthand 2>&1 |

python - Drop NaNs from a pandas dataFrame -

i dont understand how nan's being treated in pandas, happy explanation, because logic seems "broken" me. i have csv file, im loading using read csv. have "comments" column in file, empty of times. i've isolated column, , tried varies ways drop empty values. first, when im writing: marked_results.comments i get: 0 vp 1 vp 2 vp 3 test 4 nan 5 nan .... the rest of column nan. pandas loading empty entries nans. great far. im trying drop entries. iv tried: marked_results.comments.dropna() and recieved same column. nothing dropped. confused, i'd tried understand why nothing dropped, tried: marked_results.comments==nan and recieved series of falses. nothing nans... confusing. tried: marked_results.comments==nan and again, nothing falses. got little pissed there, , thought smarter. did: in [71]: comments_values = marked_results.comments.unique() comments_values out[71]: array(['vp', 'te

How to build a ViennaCl project using Visual C++ 2010? -

i have built viennacl using mingw32-make , run of generated tests on windows 7 x64. when try build new viennacl project using visual c++ 2010 ultimate, linker gives me below answer: error lnk2019: riferimento al simbolo esterno _clgetplatformids@12 non risolto nella funzione "class std::vector > __cdecl viennacl::ocl::get_platforms(void)" code: #include "stdafx.h" #include <process.h> #include <viennacl\ocl\device.hpp> #include <viennacl\ocl\platform.hpp> int _tmain(int argc, _tchar* argv[]) { typedef std::vector< viennacl::ocl::platform > platforms_type; platforms_type platforms = viennacl::ocl::get_platforms(); system("pause"); return 0; } p.s. sorry linker's italian answer. basically, linker cannot find function _clgetplatformids. in advance. pietro.

Meteor Streams : client doesn't receive streams -

i'm working on simple app based on meteor , meteorstreams. aim simple : 1 user click on button create room other users join room users can emit streams simple message creator listen message , display them in fact : message other users sent (log in server script), creator doesn't receive them. if reload page of creator, messages sent other user. i don't understand why doesn't work first time. i use meteor-router routing system. code can seen here https://github.com/rebolon/meetingtimecost/tree/feature/pokervoteprotection for client side code availabel in client/views/poker/* , client/helpers server stream's code in server/pokerstreams.js application can tested here : http://meetingtimecost.meteor.com creator must logged. if have idea, welcome. thanks ok, ok, after doing debugging, understand wrong in code : it's easy in fact. problem comes fact forgot bind stream.on event deps.autorun. result part of code not manag

r - How to quantify overlap between three periods? -

i writing function calculate duration of overlap between 3 periods, having trouble in finding out how efficiently program this, can me out. i have dataset of people have been followed on time. starting date, , time spent in study differs between participants. each participant, calculate how many days in study in specific year , in 5-year age category was. example, if in study 01-01-2000 01-06-2001, , born on 15-06-1965, contribute 166 days 30-34 year age category in 2000, 200 days in 35-39 year age category in 2000 , 151 days in 35-39 year age category in 2001, while spent 0 days in other categories. in other words: quantify overlap between these periods: a = entering study ending study (varies among participants, fixed value within participant) b = begin specific year end specific year (same among participants, varies within participant) c = entering specific 5-yr age category exiting specific 5-yr age category (varies among participants, varies within part

html - form background style not expanding with form in IE8.0 -

Image
my css code form, form { margin:0 auto; text-align:left; width:740px; border:1px solid #ccc; padding:15px; background:#fff; border-radius: 10px; -moz-border-radius: 10px; -webkit-border-radius: 10px; box-shadow: 0 0 4px #ccc; -webkit-box-shadow: 0 0 4px #ccc; -moz-box-shadow: 0 0 4px #ccc; behavior: url(./border-radius.htc); font-family:calibri; height: auto; } js fiddle i want form background expand form, happening in chrome not in ie8. i have hidden div set visible depending on selections. also how can css formatting of chrome , ie alike. ex: if want make 2 div visible form expand accordingly thing form border not extend in ie. please check out entire working code in jsfiddle create container div goes around form (in case called formcontainer) , move following css

Java Generics wildcard extends final class -

why java doesn't throw warning when compiling testgenerics class , considering string class final , cannot extended? import java.util.*; public class testgenerics { public void addstrings(list<? extends string> list) { // code here } } } let's had method this: public list<? extends t> filteroutnulls(list<t> input) { ... granted, not best signature in world, still legal. happen if passed list<string> method? according signature, returns list<? extends string> . if java disallowed type, it'd impossible use method list<string> (or @ least, it'd impossible use return value). secondarily, extends syntax still useful in case, since list<string> , list<? extends string> have different restrictions -- specifically, can't add null literal list<? extends string> . i'll use ? extends signify collection read-only (since t s can pass in null ), , ? super

user interface - Slick2D GUI Button listener -

i'm trying make button in slick extending abstractcomponent: public class standardbutton extends abstractcomponent { protected int x; protected int y; protected int width; protected int height; protected string text; public standardbutton(guicontext container,int x, int y, string text, int width, int height,componentlistener listener) { super(container); this.text=text; setlocation(x, y); this.width=width; this.height=height; addlistener(listener); } @override public void render(guicontext container, graphics g) throws slickexception { g.setcolor(color.white); g.setlinewidth(2f); g.drawrect(x, y, width, height); g.drawstring(text, x+5, y+(height/2-4)); } [...] and in state: public class updaterstate extends basicgamestate implements componentlistener { private standardbutton buttonplay; @override public void init(gamecontainer container, final statebasedgame game) throws slickexception { buttonplay=n

javascript - ng-bind but store internal value -

some server side code (gsp) generating html me so: <span> <g:generateamount /> </span> i'm wrapping in angular controller , want able bind scope variable span : <span ng-bind="subtotal"> <g:generateamount /> </span> problem is, after binding, inner text removed because subtotal isn't set in controller on initialization (although writing controller works fine). ng-model doesn't seem read either. question is there way bind node persist data inside node? instance, in above example, $scope.subtotal equal whatever <g:generateamount /> outputs. able update subtotal controller , have changes reflected. see example: http://jsfiddle.net/robcampo/zg6ge/2/ just create custom directive , value dom before $compile . alternatively can change generated html , put <g:generateamount /> ng-init attribute, like <div ng-controller="myctrl" ng-init="subtotal=<g:generateamo

caching - How to prevent form fields from repopulating after clicking the back button? -

i have simple form has 4 fields named firstname, lastname, address , phone number. after user fills form , clicks submit button, if goes fine, redirecting user success page. but on clicking browser button success page form field values repopulating on form. how can prevent happening? i have tried code: <cfheader name="cache-control" value="no-cache, no-store, must-revalidate"> <cfheader name="pragma" value="no-cache"> <cfheader name="expires" value="#gethttptimestring(now()-1)#"> but not working. repopulating form fields good thing, stop trying break it. if want prevent duplicate submissions, send unique id (e.g. uuid) along form , keep track of ones you've received (how many keep track of depends on application). if receive duplicate can either ignore (and display appropriate message), or go step further: check whether received data has been submitted or whether it's atte

mongodb - $Where gives error -

i have collection containing data: { "_id" : objectid("51dfb7abe4b02f15ee93a7c7"), "date_created" : "2013-7-12 13:25:5", "referrer_id" : 13, "role_name" : "physician", "status_id" : "1", } i sending query: cmd { "mapreduce" : "doctor" , "map" : "function map(){emit(this._id,this);}" , "reduce" : "function reduce(key,values){return values;}" , "verbose" : true , "out" : { "merge" : "map_reduce"} , "query" : { "$where" : "this.demographics.first_name=='makdoctest'"} } i getting error as: "errmsg" : "exception: count failed in dbdirectclient: 10071 error on invocation of $where function:\njs error: typeerror: this.demographics has no properties nofile_a:0" as sammaye says in comment:

How to subset a list of dataframes in R? -

i have multiple datasets of physical variables, , want work on r. however, use list. here code 1 of dataframe : # table definition df.jannuary <- read.table("c:\\...file1.csv", sep=";") # subset of table containing variables of interest df.jannuary_sub <- subset(df.jannuary, select=c(2:8, 11:12)) # column names colnames(df.jannuary_sub)<-c("year","day","hour","minute","temp_air","temp_eau","humidity_rel","wind_intensity","wind_direction") # aggregation of 4 year-day-hour-minute columns single column , conversion posixct objet through temporary column "timestamp" df.jannuary_sub$timestamp <- as.posixct(paste(df.jannuary_sub$year, df.jannuary_sub$day, df.jannuary_sub$hour, df.jannuary_sub$minute), format="%y %j %h %m", tz="gmt") # getting date new format julian day normal day column called "date" df.jannuary_sub$date &

ios6 - MPMoviePlayerController load video from Photo library,play so fast -

// cameraviewcontroller.h @interface cameraviewcontroller : uiviewcontroller{ uiimagepickercontroller *_picker; } @property (strong, nonatomic) iboutlet uiimageview *imageview; @property (nonatomic, retain) mpmovieplayercontroller *player; (ibaction)loadimage:(uibutton *)sender; // cameraviewcontroller.m @interface cameraviewcontroller () @property (strong, nonatomic) mpmovieplayercontroller *playview; @end @implementation cameraviewcontroller @synthesize imageview = _imageview; @synthesize player = _player; @synthesize playview = _playview; (void)viewdidload { [super viewdidload]; _picker = [[uiimagepickercontroller alloc] init]; } (void)didreceivememorywarning { [super didreceivememorywarning]; } (ibaction)loadimage:(uibutton *)sender { _picker.delegate = self; _picker.sourcetype = uiimagepickercontrollersourcetypephotolibrary; nsarray *mediatypes = [nsarray arraywithobjects:(nsstring *)kuttypeimage, (nsstring *)ku

Javascript regex replace inserts extra slashes -

i'm trying clean file using javascript. file contains lines of text this: a <- b + c / d; i want replace <- = when there string of non-whitespace on either side of <- , separated single space. pretty easy in theory: line = "a <- b + c / d" result = line.replace( /(\s+) <- (\s+)/, /$1 = $2/ ) the above code produces /a = b/ + c / d when run. however, conceptually, should produce a = b + c / d . how can use $1 -style backreferences without allowing javascript opportunity insert slashes willy-nilly? use string second parameter: result = line.replace( /(\s+) <- (\s+)/, "$1 = $2" ); . what happening second parameter being coerced regexp string adds slashes in replacement.

'Add to Cart' button fails using 'Display: inline' in in Agile Web Development with Rails (4th edition) -

i cannot make 'add cart' button inline next product price, reason not understand, button appears below product price. here development settings: ruby 1.9.3p392 rails 4.0.0.rc2 i following depot project , stuck in iteration d3 author insert button next product price through following css code: #store .entry form, #store .entry form div { display: inline; } and views/store/index.html.erb follow: <% if notice %> <p id="notice"><%= notice %></p> <% end %> <h1>your pragmatic catalog</h1> <% @products.each |product| %> <div class="entry"> <%= image_tag(product.image_url) %> <h3><%= product.title %></h3> <%= sanitize(product.description) %> <div class="price_line"> <span class="price"><%= number_to_currency(product.price) %></span> <%= button_to 'add cart' , line_items_path(:produc

ExtJs 4 Data associations -

i'm having hard time getting want out of ext. i'm trying divide restful response nested parameters. 1 of parameters array of objects, each object has few more parameters. how can build model/store/view recognize type of response? response = { stuffineed: { animals, fruits, veggies = { cucumbers, apples, pears, squash = { winter, pumpkin, summer = { yellow, green } } } }, stuffidontneed: { ... }, morestuffidontneed: { ... } } how use associations build model/store? lets assume 'base' model looks this: ext.define('myapp.model.stuffineed', { extend: 'ext.data.model', fields: [ {name: 'animals', type: 'boolean'}, {name: 'fruits', type: 'boolean'}, {name: 'veggies', type: 'array'} ], hasmany: [{name: 'veggies', model: 'veggiemodel'}],

javascript - Why can't set the value type property of prototype via the this pointer -

i have following javascipt code. var person = function(){}; person.prototype.age = 0; person.prototype.setage = function(age) { this.age = age; }; var jack = new person(); console.log(jack.age); // #1 jack.setage(25); // why not function assign value person.prototype.age. console.log(jack.age); // #2 console.log(jack); after running code, got output below. 0 25 person {age: 25, age: 0, setage: function} age: 25 __proto__: object age: 0 constructor: function (){} setage: function (age) { __proto__: object at statement labeled #1, age property found in prototype of jack instance. reasonable print 0 . at statement jack.setage(25); , when execute code this.age = age; , seems new property added jack instance. i'm confused why not function jack.setage(25); assign value person.prototype.age ? thanks, jeffrey what happens is: intepreter looks setage function in jack object. it's not there, looks 1 level in prototype chain. it&#

Changing Email Passwords With cPanel XML API in PHP -

i've been jogging mind on how enable users change passwords using cpanels xml api. i've googled, played example code, , not find remotely works. can please tell me i'm doing wrong? thanks! require_once('../includes/xmlapi.php'); $ip = '127.0.0.1'; $root_pass = 'secret'; $account = 'accountna'; $email_account = $_post['email']; $email_domain = "mydomain.com"; $xmlapi = new xmlapi($ip); $xmlapi->password_auth("root",$root_pass); $xmlapi->set_debug(1); $args = array( 'domain'=>$email_domain, 'email'=>$email_account ); if ($xmlapi->api2_query($account, "email", "passwdpop", array( 'domain' => "domain name", 'email' => "user name", 'password' => "new password") )) { echo "success!"; }; you neet set port! before password_auth $xmlapi->set_port ( 2083 ); $xmlapi->

how to trigger a quickbuild flow after github push -

i want quickbuild automatically run on each push detected on github repository. how can that? i have flow clones , executes mvn deploy missing automatic trigger. quickbuild 5.1 adds ability of detecting pull requests , trigger relevant builds off them. refer github integration guide details: http://wiki.pmease.com/display/qb51/working+with+github

forms - javascript, how to implement an index page function to execute a seperate page of .js functions -

i've created 2 functions perform these tasks: function displaybanner(currentdate) { /* month current date */ /* set imgsource variable defaultlogo image */ /* if month 12, 1, or 2, set variable imgsource winterlogo or defaultlogo if not 1 of 3 months */ /* if month 3, 4, or 5, set imgsource springlogo or defaultlogo if not 1 of 3 months */ /* if month 6, 7, or 8, set imgsource summerlogo or defaultlogo if not 1 of 3 months */ /* if month 10, 11, or 12, set imgsource falllogo or defaultlogo if not 1 of 3 months */ /* return imagesource variable set mybanner imgsrc attribute image*/ } function calcdaystosale(currentdate) { /* create date object 15th of current month */ /* compute difference in days between currentdate , 15th */ /* if difference positive return va

arrays - My code Catalan number in C is not working ( using recurrence formula ) -

i trying insert catalan number in array, code not working. description: insert elements in catalan sequence in array given initialized c[0]. inputs: address of array n: next position filled; top: maximum number of entries computed. output: int: number of elements in array. side effects: update elements of array. code: #include <stdio.h> #define max 6 int catseq (int catarray[], int n, int top){ int c; if (top == 1) catarray[n]= 1; else{ ( c = 0; c <= max; c++){ catarray[n] = 2 * (2*top - 1) * catseq(catarray, n, top-1) / (top+1); n++; } } return n; } void printseq(int seq[], int top){ int i; ( = 1; < max; i++) printf("%d \n", seq[i]); } int main(){ int c = 0, n = 0 ; int catarray[max]; c = catseq(catarray, n, max); printseq(catarray, c); return 0; } array out of index error: for ( c = 0 ; c <= max;c++){ ^

multithreading - Is there a way to pause a thread indefinitely in VB.Net -

i came know thread.suspend not way pause thread indefinitely. please let me know if other way achieve same. thanks in advance. a short vb example private sub form1_shown(sender object, e eventargs) handles me.shown thrd.isbackground = true thrd.start() end sub dim thrd new threading.thread(addressof somethread) private sub button1_click(sender object, e eventargs) handles button1.click 'pause , resume 'first click pauses, second click resumes reqpause.set() 'set event end sub dim reqpause new threading.autoresetevent(false) private sub somethread() 'simulate work - code here threading.thread.sleep(500) debug.writeline(datetime.now.tolongtimestring) 'end simulate work if reqpause.waitone(0) 'pause requested? debug.writeline("t-thrd paused") reqpause.waitone() 'wait here continuation debug.writeline("t-continue thrd")

vbscript - Script that displays a message based on ping success/failure -

right have following script working: set wshshell = createobject("wscript.shell") wshshell.run ("%comspec% /c ipconfig /release"), 0, true wshshell.run ("%comspec% /c ipconfig /renew"), 0, true pingflag = not cbool(wshshell.run("ping -n 1 www.google.com",0,true)) if pingflag = true msgbox("ip release/renew successful") else msgbox("ip release/renew not successful") end if i'm not familiar vbscript seemed best option displaying popup message. pieced script others found online know more how works: my question don't understand how following line working: pingflag = not cbool(wshshell.run("ping -n 1 www.google.com",0,true)) what doing determine boolean value of pingflag? thanks! .run(...) returns exit code/ errorlevel of process executed. cbool() returns false 0 or true other numbers. applying not, 'good' case becomes true, 'bad' errorlevels false. then can

javascript - regular expression for no more than 2 repeated letters/digits -

i have requirement need handle regex expression no more 2 same letter/digit in xsl file -no space -does not support special chars. -support (a-z,a-z,0-9), -require 1 of a-z, -require 1 of 0-9, -no more 2 same letter/digits (i.e bbb fail, bb accepted) what have far (?:[^a-za-z0-9]{1,2}) this regex it: ^(?!.*([a-za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[a-za-z0-9]+$ here's breakdown: (?!.*([a-za-z0-9])\1{2}) makes sure none of chars repeat more twice in row. (?=.*[a-z]) requires @ least 1 lowercase letter (?=.*\d) requires @ least 1 digit [a-za-z0-9]+ allows letters , digits edit : removed extraneous .* negative lookahead

java - Jsoup can't open html page Status=-1 -

while connecting url i'm getting below logcat error i'm getting and below code connect url. when try connect base url http://www.apkmania.co/ connects but when try connect url throws me error. 07-31 20:47:20.150: i/system.out(14295): ioexception: org.jsoup.httpstatusexception: http error fetching url. status=404, url=http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html/ break; thread thread=new thread(new runnable(){ public void run(){ prepareitem(webrss); runonuithread(new runnable(){ public void run() { if(dialog.isshowing()){ try { setdatatohandels(); } catch (nullpointerexception e) { // todo auto-generated catch block e.printstacktrace(); system.out.println("set data handels:

html5 - How to cache a whole layer right before dragstart and revert it back on dragend? -

i'm trying speed web app mobile devices little bit up, i'm stuck @ important part - caching. how possible cache entire layer right before user starts drag , revert usable kinetic.nodes when drag-action has stopped? at moment start caching on stage.on('mousedown touchstart', function(){ // caching}) but problem here is, user has perform second mousedown touchstart event "grab" cached image, which, of course, starts new caching. in case questions be: how can pass mousedown touchstart event cached image, user can drag 1 fluent movement? how can speed caching? (it takes 1-2 seconds cached image appear. useful cache in setinterval after every, lets 4 secs, , use precached image or causes high performance drain?) i highly appreciate kind of suggestions regarding problem or further tips&tricks speed things. based on statement: stage.on('mousedown touchstart', function(){ // caching}) i'm assuming on mousedown touchst

redis get key which is another key's value -

i want use redis value key ,but key key's value.like: set name "david" set david femal i david key->name,and value second object's key,like get (get name) i hope result "femal", how should do?besides java client can support .

iphone - Notification not getting shown in one of IOS device -

i facing problem notification. notification not getting shown in device last 12 hours. working earlier. sending other devices works fine. checked notification center , other thing. notification enabled app. after following http://developer.apple.com/library/ios/#technotes/tn2265/_index.html have enabled enabling push status messages on ios. on console , device printing information like: <error>: kdataattachstatusnotification sent, wasattached: 1 isattached: 1 what mean ? getting notification server side , failing show , receive due reason ? edit: after syncing logs itunes. logs says like: 2013-08-01 10:51:06 +0530 apsd[76]: _getclientidentity: had identity: <secidentityref: (some value here)> wasup no isup no linkqualitybelowandwowavail: yes wantsinterfaceassertion yes avoidwwanoncall no 2013-08-01 10:51:06 +0530 apsd[76]: _getclientidentity: had identity: <secidentityref: (some value here)> 2013-08-01 10:51:06 +0530 apsd[76]: peer(68) received xpc

Service which provides interface-impelementation instead of data -

since while i'm implementing services whenever possible servicestack (or webapi) instead of wcf. what want sending interface (-name) server , class-implementation back. maybe that's confusing, i'll give example: my service-client has multiple operations - "check form": logic checking form not implemented. has interface called iformchecker methods nameisvalid(string firstname, string middlename, string lastname) . instead of sending whole form-data server validation, client request implementation of iformchecker server. i know that's possible wcf, have no idea how servicestack. if that's possible, what's way go? checked documentation, i'm not wiser. it seams there's no "magic trick" or anything. have serialize/deserialize class "old-fashion way". if you're interested, here's solution: i created "root"-interface, in example imodule. imodule contains 1 property, called name. string ,

assembly - Cairo library arguments format -

what format of cairo functions arguments. mean coordinates , color rgba arguments. i want use assembly language, c/c++ types not suitable. is 32bit floating point format? also, if "double" 64bit - next question calling convention - how in 32bit stack, 64bit arguments passed? calling conventions vary across different operating systems , different platforms. example, x86 uses stack-based arguments, whereas x86-64 uses register-based arguments. as pushing 64-bit value onto 32-bit stack, you'll need push 2 halves separately - since x86 little-endian push-down stack, you'll need push upper-32 bits first, followed lower-32 bits. to sure, though, can write small c function calls library function in question, compile assembly, , see how handles arguments.

wordpress - wp_enqueue_scripts jquery to footer.php -

i have script in footer.php , add footer.php using wp_enqueue_scripts. <script type="text/javascript"> jquery(window).load(function(){ <?php if ( is_home() ) { if ( option::get('featured_posts_show') == 'on' ) { ?>if ( jquery('#slider li').length > 0 ) { jquery('#slider').flexslider({ controlnav: false, directionnav: false, animationloop: true, animation: '<?php echo option::get('slideshow_effect') == 'slide' ? 'slide' : 'fade'; ?>', usecss: true, smoothheight: false, touch: false, slideshow: <?php echo option::get('slideshow_auto') == 'on' ? 'true' : 'false'; ?>, <?php if ( option::get('slideshow_auto') == 'on' ) echo 'slideshowspeed: ' . option:

javascript - Difference between offsetParent and parentElement or parentNode -

i have following dom structure <body> <div> <table> <outerelement> <innerelement /> </outerelement> <table> </div> </body> div has it's overflow set auto if table grows bigger - scrolls within div. in scenario why table.offsetparent returns body while both table.parentnode , parentelement return div? i need calculate current position of innerelement within window, traverse thru parent elements, collecting offsettop , offsetleft values. until div offsetparent works fine , skips directly body. problem if there's scrolling involved @ point, need account scrolltop , scrollleft - in div in above example. problem if use offsetparent never encounter div 1 of parents. update this part of code traversing: while (oelem && getstyle(oelem, 'position') != 'absolute' && getstyle(oelem, 'position') != 'relative

class - Should I be passing S_ variables into functions - PHP -

i building little website project on side , having go @ mvc. i have built request class, , router class. simple enough question, have read on place globals bad such whatever reason, should passing in, $_get, $_post, $_server etc request class, or referencing them inside request class. new request($_get, $_post, $_server); or new request(); thanks. one of main aspects of oop abstraction. class should not know global variables. if change key of get. first method common way.

java - How do you clear objects between JUnit/Maven tests? -

i'm testing different parts of miniature search engine, , of junit tests leaving entries in index interfere other tests. there convention in junit/maven clearing objects between tests? there 2 particular annotations can this, , intended used in cases such yours: @after defines method must executed after every @test , while @afterclass method execute once entire test class has been executed. think of latter last cleanup method purge structures or records you've been using , sharing between tests far. here example: @after public void cleanindex() { index.clear(); //assuming have collection } @afterclass public void finalcleanup() { //clean both index and, example, database record. } note : have counterparts ( @before , @beforeclass ) opposite invoking related methods before @test method , before starting execute @test s defined on class. ones setup used in previous versions of junit. if can't use annotations, alternative use old teardown

c - Type definitions in POSIX/SUS headers -

this question concerns various types need defined in required headers of posix/sus standard. some types needs defined in many header files, , i'm wondering what's correct , compliant way of achieving this. for instance, @ <time.h> header specification: inclusion of header may make visible symbols <signal.h> header. this straightforward, <signal.h> included <time.h> . now this: the clock_t , size_t , time_t , clockid_t , , timer_t types shall defined described in <sys/types.h>. as understand it, means can't include <sys/types.h> <time.h> , expose more symbols required. so can confirm this? break standard compliance include <sys/types.h> ? if so, think best solution create specific header each type, particular type can made visible anywhere, without worrying other symbols. is there other solution? and last thing, types c standard? lots of types in posix/sus specification integral typ

python - Using savetxt in numpy with custom data types -

i trying export data complex numpy calculation text file can analyze in excel or something. data type of array i'm trying export complicated , defined like: rowtype = np.dtype([("sn", "s8"), ("freqs", np.uint16, (3,)), ("peaks", np.float32, (3,))]) so each "row" of array 8-character string, 3-element subarray of 16-bit integers, , 3-element subarray of floats. want have 1 row per row in text file, tabs between each element of subarrays. when call savetxt export populated array, supply fmt parameter keep throwing exception? the format code applies each element in row. because have arrays elements, can control format of array , not individual elements. you'd better off printing array line line, answered this question . if must use savetxt , closest request: np.savetxt(my_file, my_array, ['%s\t', '%s\t', '%s']) however, if change data type flatte

java - How to get and change System password using servlet? -

i have system(windows) username , system(windows) current password , change current password new password using servlet code. getting current windows password not possible. if jvm running under user account admin rights, can reset users password using processbuilder class , windows net user command. processbuilder pb = new processbuilder("net", "user", "someusername", "somepassword"); process pro = pb.start(); to check result of command, read it's error stream , input stream of process object returned exec method. bufferedreader bre = null; bufferedreader bri = null; try{ bre = new bufferedreader(new inputstreamreader(pro.geterrorstream())); bri = new bufferedreader(new inputstreamreader(pro.getinputstream())); pro.waitfor(); //wait command finish string line; while((line = bre.readline()) != null) system.out.println(line); while((line = bri.readline()) != null) system.out.println

javascript - How to deactivate a nested anonymous function in Jquery -

i have following code: $('#button-a').click(function(){ $('#button-b').click(function(){ alert('something'); }); }); $('#button-b').click(function(){ // }); how can deactivate nested #button-b function after have clicked #button-a, last #button-b function (not nested) activates when click #button-b , not them both? try using .on() , .off() event handlers. $('#button-a').click(function(){ $('#button-b').off('click'); //unbind click event of #button-b $('#button-b').click(function(){ alert('something'); }); }); $('#button-b').on('click',function(){ // });

html - Text in <a> tag is not vertically centered -

i have used following code , seeking why "upload" text rendered over-line? <form id="form1" runat="server"> <table style="width: 100%; direction: rtl;"> <tr> <td style="width: 100px; margin: 0px 5px 0px 5px;"> <div style="text-align:center;display:block;position: relative; height: 30px;" onclick="inform();"> <a runat="server" id="uploadbtn" class="btn">upload</a> </div> </td> </tr> </table> with following css : .btn{ -webkit-border-radius: 3px; -moz-border-radius: 3px; border-radius: 3px; background-color: #a19e86; background-image: -moz-radial-gradient(center -100%, ellipse cover, #a19e86, #5e5c49 100%); background-image: -webkit-radial-gradient(center -100%, ellipse cover, #a19e86, #5e5c49 100%); background

python - Can we use pip downloaded files after an install error? -

this newbee question. forgot add sudo before pip install, , got permission denied message after whole while. there method can make use of downloaded files when invoke pip command sudo subsequently, can save bandwidth. ditto gem install. thanks. no, can't you're asking, @ least not , securely. to want involve changing user ownership of parts of system, bad lot of reasons. or, you'd have change group or add group, bad same reasons first. in both cases, odds of damaging system beyond repair goes way up. we have sudo reason; it's keep running system administrator time , shooting ourselves in foot. invoking command using sudo gives chance pause , think whether want that. adds thin layer of sanity-checking code looks see if safe command issue, can tweak allow/disallow particular actions. if choose go last route, how off-topic stack overflow , should asked on http://superuser.com instead.

android - app using camera on phone keeps crashing -

i've been trying write basic apps use native android camera take picture , display picture. apps write keep crashing when try display picture. downloaded project found on internet here http://www.techrepublic.com/blog/android-app-builder/androids-camera-intent-makes-taking-pics-a-snap/ crashed on phone. i'll post code here; there wrong phone , how fix it? i'm running android 4.1.1 on galaxy s3 package com.authorwjf.camera; import java.io.file; import android.app.activity; import android.content.contentresolver; import android.content.intent; import android.graphics.bitmap; import android.graphics.matrix; import android.net.uri; import android.os.bundle; import android.os.environment; import android.provider.mediastore; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.imageview; import android.widget.toast; import com.authorwjf.came

tsql - SQL query, select row based on another row -

i have photo review application, sql server 2008 r2 back-end. 1 requirement me able mark photos anomalies such "bad lighting," "blurry," etc. option "unidentified." whenever user chooses "unidentified," required add additional anomaly, called "other," , give description. can have "other" anomaly without "unidentified," not vice versa. i need create report lists "other" anomalies, if picture has "unidentified" anomaly. no idea how write query accomplishes this. table has photoid, , anomalyid, , description text field "other," if required (plus other irrelevant stuff). so, psuedocode be: select photoid, description photo_anomalies photo anomaly "other" description not null, if there matching "unidentified" anomaly photoid. clear mud? i figured out solution - not sure if it's best seems work. using select = "unidentified" inner join

R summary function in ddply (plyr) in a simple way -

how replicate plyr ? with(mtcars, tapply(mpg, cyl, summary)) with same elegance, i.e. without spelling out individual statistics? library(plyr) dlply(mtcars, .(cyl), function(x) summary(x$mpg)) you data.frame, prefer on complex lists... ddply(mtcars, .(cyl), function(x) summary(x$mpg)) # cyl min. 1st qu. median mean 3rd qu. max. # 1 4 21.4 22.80 26.0 26.66 30.40 33.9 # 2 6 17.8 18.65 19.7 19.74 21.00 21.4 # 3 8 10.4 14.40 15.2 15.10 16.25 19.2

pie chart - How to align two pie graphs (highcharts) next to each other -

i have 2 pie charts show on page, next each other. both same style different data. possible , how? thank you you can have multiple series of pie chart data on same chart var chart = new highcharts.chart({ chart: { renderto: 'container', type: 'pie' }, title: { text: 'group name' }, series: [{ data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], center: ['20%'], name: 'foo' }, { data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4], center: ['80%'], name: 'bar' }], plotoptions: { pie: { datalabels: { enabled: false } } } }); jsfiddle: http://jsfiddle.net/4ntbw/

jquery - Parameters and AJAX, PHP -

i'm trying retrieve information php page queries database based on ?id= parameter given. doing via ajax should give user information on specific item etc. if id parameter not exist within database, user redirected lookup page. when looking @ ajax examples , following same steps seem parameter isn't being used mysql query - it's using header information redirect me , retrieve lookup page if incorrect value given id exists. any ideas on what's going wrong? var id = $('#code').val; input users supply id wish lookup. $(document).ready(function() { $('#check').click(function() { var id = $('#code').val; if (id=="") { document.getelementbyid("result").innerhtml=""; return; } if (window.xmlhttprequest) { xmlhttp=new xmlhttprequest(); } else { xmlhttp=new activexobject("microsoft.xmlhttp"); } xmlhttp.onreadystatechange=func

html - Php query string url issue -

i've php page following string. http://mydomain.com/businesspage.php?profile=khafihan so i'm trying convert url following style http://mydomain.com/khafihan is possible php , how ? thanks help. regards. you need put following lines .htaccess file: rewriteengine on rewriterule /(.*)$ /businesspage.php?profile=$1

ruby on rails 3 - Security riddle: confirming email and resetting passwords -

i'm using devise on rails 3.0 app, , have confirmable , recoverable turned on. these modules require users confirm email account (confirmable) , allow users reset password having email sent email account (recoverable). unfortunately we've had difficulty "devising" (pun intended) reasonable security policy permits users use site without confirming account. enforce following requirements security: confirming account requires being signed in or signing in. not case , user accidentally entered wrong email address of malicious user b, b receive confirm email link, automatically signed in, , there reset password via "email reset password link." requiring b sign in a's credentials eliminates possibility. resetting password via email requires having confirmed email. because if user accidentally enters wrong email address, 1 belonging malicious user b, b receive confirm email link , know has signed account. b can visit site , use reset password function

caching - Function which computes once, caches the result, and returns from cache infinitely (Python) -

i have function performs expensive operation , called often; but, operation needs performed once - result cached. i tried making infinite generator didn't results expected: >>> def g(): ... result = "foo" ... while true: ... yield result ... >>> g() <generator object g @ 0x1093db230> # why didn't give me "foo"? why isn't g generator? >>> g <function g @ 0x1093de488> edit : it's fine if approach doesn't work, need performs regular function, so: >>> [g() x in range(3)] ["foo", "foo", "foo"] here's dead-simple caching decorator. doesn't take account variations in parameters, returns same result after first call. there fancier ones out there cache result each combination of inputs ("memoization"). import functools def callonce(func): result = [] @functools.wraps(func) def wrapper(*args, **kwar

c# - Accessing properties of object stored in session -

i must misunderstanding session. i'm trying store information, let me give details. here's "container" class holds list of business objects. container stored in session. public class mysessioncontainer { private ilist<somebusinessobjecttype> _businessobjectlist = new list<somebusinessobjecttype>(); public ilist<somebusinessobjecttype> businessobjectlist { { return _businessobjectlist; } set { _businessobjectlist = value; } } } i have set of pages form wizard/multi-step process, , need access list of business objects in container, in session. the first page adds business objects list in session, sort of code used achieve that: string key = getkeyforcurrentuser(); mysessioncontainer container = (mysessioncontainer) session[key]; somebusinessobjecttype businessobject = /* object view. */; container.businessobjectlist.add(businessobject); the generated key same across pages. however, when user gets second