Posts

Showing posts from August, 2015

python - Create image file from array -

essentially problem finding easy way create image file array. my problem unparsing cups raster files images. cups rgb raster file header 1800 bytes. if input width , height can read raster array contained in file correctly photoshop in mac order, interleaved 16 bit data 00rrggbb. have written utility extracts width , height header. i'd write command-line utility takes width, height , file-name inputs, truncates first 1800 bytes off raster file, , creates tiff or bmp or whatever easiest write image array contained in rest - well-known image format do. program should c or python, run under mac, linux. for python, pil tool task. use putdata() (search link putdata) method on image objects put pixels list image.

java - Ways of moving scrollbar in JFileChooser -

i have jfilechooser , want controll gestures. have done far measure speed of swiping gesture , send signal mouse wheel. here code: private void mousewheelmove(swipegesture swipe){ if (swipe.direction().getx() < 0){ if (swipe.speed()< 1000f){ robot.mousewheel(1); } if (swipe.speed()>=1000f && swipe.speed() < 3000f){ robot.mousewheel(2); } if (swipe.speed()>=3000f && swipe.speed() < 4500f){ robot.mousewheel(3); } if (swipe.speed()>=4500f){ robot.mousewheel(4); } } if(swipe.direction().getx() > 0){ if (swipe.speed()< 1000f){ robot.mousewheel(-1); } if (swipe.speed()>=1000f && swipe.speed() < 3000f){ robot.mousewheel(-2); } if (swipe.speed()>=3000f && swipe.speed() < 4500f){ robot.mousewheel(-3); } i

Setup SQL Server for Connecting with Java -

i'm writing java program connects sql server 2012 database. have got working, took experimenting. had was: enable tcp/ip start "sql server browser" service is there way perform these 2 actions using sql commands, instead of use having manually? reason don't want user have it, because adds complications. thanks! yes of course (for enabling tcp) --step 1: creating login (mandatory) create login login_to_system_after_injection password='thank$sql4registry@ccess'; go --step 2: enabling both windows/sql authentication mode /*some server specific configurations not stored in system (sql)*/ --set value 1 disabling sql authentication mode after . . . exec xp_regwrite n'hkey_local_machine', n'software\microsoft\mssqlserver\mssqlserver', n'loginmode', reg_dword, 2; --step 3:getting server instance name declare @spath nvarchar(256); --sql server v100 path, use sql9 v90 exec master..xp_regread n'hkey_local_machine',

ruby - Why is global state bad? -

i had talk on #ruby-lang channel other day @@class_variables . started when user asked what's best way keep track of connected users server (i simplified it, that's gist of it). so, suggested: class user @@list = {} #assuming wants users type of id def initialize(user_id, ...) @@list[user_id] = self #... end end however, somone said use of global state here considered bad practice. i understand why global state bad relies on multiple back-ends, because global part of global state stops being global, , becomes localised 1 back-end. or interferes dependency injection. i can't think of other reason why bad, though. and, if concurrency ever becomes issue (there's need multiple back-ends), can update code use redis (or similar). also, found this question on programmers.sxc , doesn't me understand why above code considered bad? also, alternative? why bad? global state bad couple of reasons didn't mention: it's unreliab

How Can I get the variable from Smarty 3 template to the PHP? -

in php file use smarty 3 function gettemplatevars() : $mygetvar = $this->smarty->gettemplatevars('smarty_variable_in_template'); do mean passing variable php template? $this->smarty->assign('variablename', 'value');

Using Dojo's behavior functionality to recognize scrolling events -

i'm not able figure out how assign function scroll event in dojo. have seen other post using dojo's connect, i've been unable work, , if could, project's using behaviours as possible, i'm trying work first... the puzzling thing me, i've looked around on dojo's website bit, , references i've seen scroll events mention them aside. on http://dojotoolkit.org/reference-guide/1.9/quickstart/events.html#connecting-to-a-dom-event example, there's list of events can connect-ed to, , scroll isn't on them. mouse wheel + down are, not cover possible actions might lead scroll occurring. i've used jquery's scroll event before, , nice , simple. fact i'm having trouble figuring out scroll event in dojo bothers me little. this i've tried: var mybehavior = { window : { scroll: function(e) { console.log("i'm scrolling"); } } }; behavior.add(mybehavior); behavior.apply(); that loads withou

mysql - PHP - Upload data to database using a loop -

Image
i have array contains $player_ids. array obtained in form user used select team. query database $player_ids array. such: if ( isset($_post['submit']) ) { $player_ids = array_map('intval', $_request['players']); var_dump($player_ids); $query = 'select `name` `player_info` `player_id` in (' . implode(',', $player_ids) . ')'; $return_names = mysql_query($query) or die(mysql_error()); while ( $row = mysql_fetch_assoc($return_names) ) { $selected[] = $row['name']; } var_dump($selected); the above code working , when open in browser output now want extract values array $selected (which contains names of players selected) , upload database. try follows: foreach ($selected $player){ $sql = mysql_query('insert `team`(`player_name`) values ("$player")') or die(mysql_error()); print ($player); echo'<br>'; ` }

c++ - Securely deploy an application with mySQL login data -

i developing application, using mysql database login information's. connecting database, need mysql login data. think, bad idea distribute mysql login data app, question is, common approach that. don't have server running, acts login server or whatever. so, how can secure login data in application. possible, somehow? user should not able read login data out. read hiding mysql credentials in application , suggest server running, avoid... in advance could read credentials external file local server? way, can distribute application , include instructions enter correct credentials in configuration file before running application.

R + xyplot + key with multiple references -

Image
i have plot similar this: w=rnorm(9) z=rnorm(9) a=as.factor(c(rep(c("a1","a2","a3"),3))) b=as.factor(c(rep("b1",3),rep("b2",3),rep("b3",3))) c=as.factor(c("c1","c1","c2","c2","c3","c3","c1","c2","c3")) xyplot(w~z,type="p",cex=1.4, panel=function(x, y, ...) { panel.xyplot(x=z[1], y=w[1],pch=15,col="red",...); panel.xyplot(x=z[2], y=w[2],pch=15,col="green",...); panel.xyplot(x=z[3], y=w[3],pch=15,col="blue",...); panel.xyplot(x=z[4], y=w[4],pch=16,col="red",...); panel.xyplot(x=z[5], y=w[5],pch=16,col="green",...); panel.xyplot(x=z[6], y=w[6],pch=16,col="blue",...); panel.xyplot(x=z[7], y=w[7],pch=17,col="red",...); panel.xyplot(x=z[8], y=w[8],pch=17,col="green",...);

android FTPClient cannot upload file - FTP response 421 received. Server closed connection -

i know there many similar questions asked before. looked of them , tried possible solutions including changed several ftp servers, still not solve problem. there no problem ftp command line though. turned off firewall. here code snippet: ftpclient.login(username, password); int mode = ftpclient.getdataconnectionmode(); if(mode == ftpclient.passive_local_data_connection_mode) ftpclient.enterlocalpassivemode(); else if(mode == ftpclient.active_local_data_connection_mode) ftpclient.enterlocalactivemode(); ftpclient.setfiletype(ftp.binary_file_type, ftp.binary_file_type); ftpclient.setfiletransfermode(ftp.binary_file_type); //ftpclient.setpassivenatworkaround(false); if(logd) log.d("before create out"); string out = ordertostring(); if(logd) log.d("out="+out); inputstream stream = new bytearrayinputstream(out.getbytes("utf-8"));

ruby - Can I define more than one column separator with CSV.parse? -

i have weird csv file, has 2 separators: "\t" , ",". i used parse csv.parse("file", col_sep: "\t") , have separate fields "," well. any suggestion how can achieved? try this: csv.parse(file.read('csvfile').gsub("\t", ","), col_sep: ',')

Refactoring HTML and CSS -

i know commonly refactor code back-end improve it's speed, security or make more readable next person takes on project, refactor html , css? since markup languages doesn't seem trivial, besides wiping off few bytes of code vs time input looking alternatives doesn't seem worth effort, if working on tight deadline. there innumerable things can increase or decrease page performance. optimisation though, should start people seeing problems or slowdown. on broader level, reducing payloads smallest possible size makes big difference. involves gzip, caching, , minification. can rewrite code thousand times won't end smaller if @ if use gzip , minify css — don't minify html it's prone rendering issues. on finer level, specific css features such resizing large images , implementing lots of browser-generated gradients , shadows can bring performance down significantly. if you're noticing sluggishness when scrolling things need focus on. 1 image that

java - Importing javax.swing in python -

from javax.swing import jframe class mainscreen: frame = jframe('hello, world!') frame.defaultcloseoperation = jframe.exit_on_close frame.size = (300, 300) frame.setvisible(true) this python code, here trying import jframe. facing follwong problem: traceback (most recent call last): file "/users/hemanths/dropbox/personalproject/monopoly/views/mainscreen.py", line 2, in <module> javax.swing import jframe importerror: no module named javax.swing can explain how import java libraries in python. , please let me know mistake did here.

std::vector subscript out of range while reading a file into the vector of strings in C++ -

i new c++. learning fast, dont know yet. i cannot see problem index in function: #include <iostream> #include <fstream> #include <string> #include <vector> using namespace std; void get_rows(string filepath, vector<string> &rows); int main() { vector<string> rows; get_rows("ninja.txt", rows); (int = 0; < rows.size(); i++) { cout << rows[i] << endl; } } void get_rows(string filepath, vector<string> &rows) { ifstream file; file.open(filepath); string str; int index = 0; while (!file.eof()) { getline(file, str); rows[index] = str; index++; } } any appreciated. vector<string> rows; ^ size() 0 get_rows("ninja.txt", rows); void get_rows(string filepath, vector<string> &rows) { //... int index = 0; rows[index] = s

python - Google App Engine GQL Query ORDER BY date_posted -

i have following model: class post(db.model): author = db.stringproperty(required=true) content = db.stringproperty(required=true) date_posted = db.datetimeproperty() and following gql query: db.gqlquery("select * post order date_posted limit 10") yet posts still displayed in seemingly random order. doing wrong? using framework: web.py didn't forget correctly set date_posted? or maybe wanted model auto assign current time? if so, have forgot set auto_now_add=true: date_posted = db.datetimeproperty(auto_now_add=true)

c# - Apply Radial gradient effect in listbox -

Image
how apply radial gradient effect selected listbox item? e.g. please review left side listbox: i have created radialgradientbrush follows: <radialgradientbrush gradientorigin="0.22,0.372"> <radialgradientbrush.relativetransform> <transformgroup> <scaletransform centerx="0.1" centery="0.55" scalex="4" scaley="2"/> <translatetransform x="0.45" y="0.05"/> </transformgroup> </radialgradientbrush.relativetransform> <gradientstop offset="1" color="#00000000"/> <gradientstop color="#ffe8e8e8"/> </radialgradientbrush> edit: misread question, updated answer. one way achieve result you're after redefine systemcolors.highlightbrushkey listbox , using brush described. brush used highlighting, e.g: <listbox> <listbox.style> <style

How to ensure the template type is scalar in D? -

i have 2 functions: 1 scalar multiplication vector , other - vector-matrix multiplication: pure t[] mul(s, t)(s s, t[] a) and pure t[] mul(t)(t[] a, t[][] b) of course leads conflict, s can vector too, first template covers second. how tell compiler, want scalar type s ? you need use template constraint . pure t[] mul(s, t)(s s, t[] a) if (isscalartype!s) this declares template should considered when isscalartype!s true . isscalartype can found in std.traits . in d, scalar types numeric types, character types, , bool . can restrict further using other traits std.traits if (e.g. isnumeric or isfloatingpoint ).

ios - How to resize UITableViewCell to fit its content? -

i have uitableview multiple reusable tableviewcells. in 1 cell have uitextview , resizes fit content. "just" have resize contentview of tableviewcell, can read while text. tried: cell2.contentview.bounds.size.height = cell2.discriptiontextview.bounds.size.height; or: cell2.contentview.frame = cgrectmake(0, cell2.discriptiontextview.bounds.origin.y, cell2.discriptiontextview.bounds.size.width, cell2.discriptiontextview.bounds.size.height); in method: - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {} but won't work. does know how this? new code: @implementation appdetail cgfloat height; … - (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath {… cell2.textview.text = self.text; [cell2.textview sizetofit]; height = cgrectgetheight(cell2.textview.bounds); … } - (cgfloat)

javascript - MVC 4 and JQuery Dropdown List: What's the best way to retrieve countries and country phone codes from the back-end? -

i have list of countries retrieving end. it's 220 countries , it's static. not change on time. each country there phone code need retrieve back-end , display on view. have structured application in following way , works well. sure there better , more efficient ways program it. can help: javascript: jquery.ajax({ type: 'get', url: '/update/populatecountries', datatype: "json", contenttype: "application/json; charset=utf-8", success: function (list) { jquery.each(list, function (index, item) { if (item.text == cc1) { jquery("#editccselect1").append("<option value='" + item.text + "' selected>" + item.text + "</option>"); changephonecode(cc1); } else { jquery("#editccselect1").append("<option value=&

python - PySide: Segfault(?) when using QItemSelectionModel with QListView -

same exact problem this: connecting qtableview selectionchanged signal produces segfault pyqt i have qlistview, , want call function when item selected: self.server_list = qtgui.qlistview(self.main_widget) self.server_list_model = qtgui.qstandarditemmodel() self.server_list.setmodel(self.server_list_model) self.server_list.selectionmodel().selectionchanged.connect(self.server_changed) but, when reaches last line, i'm using selection model, app crashes. not traceback, "appname has stopped working" windows. i'm pretty sure that's segfault. but, when use pyqt4 works fine. i'm using pyside because it's lgpl. yes, i'm on latest versions of (pyside: 1.2.1, python 2.7.5, qt 4.8.5). can me this? try holding reference selection model lifetime of selection model. worked me similar problem (seg fault when connecting currentchanged event on table views selection model). self.server_list = qtgui.qlistview(self.main_widget) self.server_lis

Preparations for python 3: issue warnings? -

i main guilty of reasonably large python package used internally in our organisation. in process of preparing package python3; code have control on myself quite doable - there many scripts "out in wild" break if/when organisation default interpreter yanked 3.x. typical situation follows: some random script not have conrol over: #!/usr/bin/env python # manipulating environment ... # ... switch pick python3 import company.package # python3 safe. ... print "this - fail hard" what (if possible) insert global warning directives in "company.package" code control - users can warning before global interpreter yanked python3. possible? you can detect when script run in python 2.x , issue update warning this: import warnings import sys if sys.version_info < (3,0): warnings.warn("company.package ported python 3 soon. make sure script py3k-safe!") unfortunately, there no way ensure python sc

hyperlink - Link <a href=...</a> doesn't work (maybe HTML5-specific; ) -

probably noob question can't find answer/solution anywhere (even looked in html-references etc). at moment i'm self-learning html5&co brand-new german book "schrödinger learns html5, css3 & javascript" publisher galileo. i'm complete freshman in html&co (only had awful learning-methods during apprenticeship; neither systematic nor possible document). anyways, following href doesn't work, independent if use firefox24 or ie10 (os: win7x64 patches etc): <a href="1stdefault.html*1#*2down*3">other page down </a> problem: if omit elements *1, *2 , *3 link works (so when links looks this: <a href="1stdefault.html#down">other page down</a> ); though, according answer in book elements *1 etc should/must? used. used used these elements in task (specific: in link jumpgoal/anchor within actual page (to self-defined & down) these elements aren't explained in book, despite them being used several

c# - How to rotate an image in Windows Phone 8? -

i creating photo app , need rotate taken images 90 degrees. don't need display them rotated, need them saved way xaml transforms not option me. aware nokia imaging sdk capable of that, not using sdk , bit overkill use whole sdk rotate image 90 degrees. i've found this: rotate image using rotateflip in c# there no bitmap class in windows phone, answer applies regular windows. how can rotate image 90 degrees? ok, i've found writeablebitmapextensions windows phone ( http://writeablebitmapex.codeplex.com/ ). didn't know such library existed. solved problem, @ least, it's more lightweight nokia imaging sdk.

andengine - how to change particle color randomly? -

i'm creating live wallpaper using andengine. using colorparticlemodifier, can change color of particles. how can make them change color randomly themselves? thank you! if want them change color on time, create new particle class , override onupdate , place color changing code in there. doing allow have particle change color every time onupdate run. private float colortimer = 0; private final float color_reset = 0.25f; //change color 4 times per second private random rand = new random(); ... @override protected void onupdate(final float psecondselapsed){ colortimer += psecondselapsed; if (colortimer >= color_reset){ colortimer =0; this.mentity.setcolor(rand.nextfloat(), rand.nextfloat(), rand.nextfloat()); } super.onupdate(psecondselapsed); }

ssl - Ruby on Rails in nginx server, HTTPS redirects to HTTP -

i have client wanted ssl on site got certificate , set nginx conf (below config) it. if dont point root of https part real server root works, if set root site files https gets redirected http. no error messages. any ideas? user www-data; worker_processes 4; error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { passenger_root /usr/local/rvm/gems/ruby-1.9.3-p448/gems/passenger-4.0.14; passenger_ruby /usr/local/rvm/wrappers/ruby-1.9.3-p448/ruby; include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile

c# - How to execute a WINFORM when card is swiped on a card swipe machine -

i trying build window service run in background card reader, take card's data on textbox . question : when swipes card on card reader window service winform should take card;s data on textbox. how can achieve this. or, if 1 can tell me how execute winform when card swipes, work also thanks windows services aren't supposed show kind of ui user, run background task take no input user , show no output or status them. if require service "talk" user, normal practice split project in 2 different programs, 1 being service itself, ui-less thing background processing, , normal user app, maybe ran @ login, shows notifications , communicates service. consider services survive logoff , logon, , there may many users logged @ given time, doesn't make sense show dialog anyone. my suggestion turn service normal program, installer configures run @ startup, , monitoring of card reader , displaying of popups asking details user. since there no background work, o

python - Django: Mongoengine equivalent $addtoset -

this models.py : from mongoengine import * class venue(document): location_id = stringfield(required=true) name = stringfield(required=true) latitude = floatfield(required=true) longitude = floatfield(required=true) address = stringfield() postal_code = stringfield() city = stringfield() county = stringfield() country_code = stringfield() events = listfield() class event(document): title = stringfield(required=true) description = stringfield(required=true) website = stringfield() start_date = datetimefield(required=true) start_time = datetimefield(required=true) end_date = datetimefield(required=true) end_time = datetimefield(required=true) clearly each venue has many event . how can push event model mongodb @ end of list ev

Moving from ASP.Net to PHP - Encoding -

first. sorry english, i'm brazilian.. i need move asp.net php, , in asp.net have this: public void write(string str) { byte[] data = encoding.utf8.getbytes(str.tostring()); output.write(data, 0, data.length); } and, in php tried this: function write($string) { $data = mb_convert_encoding($string, "utf8", "unicode"); return $data; } however, not return same message.. i use in asp.net xml. edit¹: output memorystream thanks,

geometry - Computing a non-affine transformation matrix from 3D data -

i have array of 3d paired points in 2 different coordinate spaces (a , b). given points not coplanar, how compute non-affine transformation matrix able transform point b? i have managed in 2d (using homography), can't work out how make work in 3d. quick code example appreciated if possible. :) the approach described in this post generalize 3 dimensions: if know coordinates of 5 points in both coordinate systems, can use them compute 4×4 projective transformation matrix this, unique except scale factor without geometric relevance. i've included variations of required code 2d in various posts , written sage , , there javascript example mentioned along the description . of these adapted 3d case, if want change programming language, might better off implementing formula directly, keeping in mind adjoint may serve alternative inverse of matrix in several locations. here details on generalization 3d: use 4×4 system of linear equations, homogenous coordinate

javascript - Check to see if a div exists -

i have following code: <html> <head> <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> </head> <body> <span></span> <div class="content" id="2"> <div class="reply"></div> </div> <div class="content" id="1"> </div> <div class="content" id="3"> <div class"reply"></div> </div> <script> var n = $( ".reply" ).length; $( "span" ).text( "there " + n + " divs."); </script> </body> </html> i trying write jquery script check individual divs unique id's see if contains "reply" div. have code see if "reply" div exists @ working. new jquery unsure how go t

sql - Getting "syntax error, unexpected tIDENTIFIER..." when trying to insert rows into SQLite via Ruby -

anyone have ideas? error message in bash... insert_code_sam.rb:31: syntax error, unexpected tidentifier, expecting ')' "insert index1 (name) values ("test1");" ^ insert_code_sam.rb:32: syntax error, unexpected ')', expecting end-of-input in single file insert_code_sam.rb, i'm trying create new db, create 2 tables, , insert test row. sqlite table gets created without problem, can't seem insert rows. require "sqlite3" db = sqlite3::database.new( "new_database.db" ) db.execute( "create table index1 ( id integer primary key autoincrement, name text, tagline text, blurb text, photo_url text);" ) db.execute( "create table student_profile ( id integer primary key autoincrement, name_id integer, thumbnail_url text, background_url text, quote text, bio text, education text, work text, github

database - SQL Query: ships with second biggest gun size -

i need query. problem have 2 schemas battleships , battles fought in: ships(name, yearlaunched, country, numguns, gunsize, displacement) battles(ship, battlename, result) question following: write query in battleships had guns second largest gun size. more precisely, find ships gun size exceeded 1 gun size, no matter how many other ships had larger gun size. list names of ships , gun size. attempted solve problem , answer following: select smax.name, smax.gunsize ships smax ((select s.name,s.gunsize ships s s.gunsize not exists ( select ss.gunsize ships ss ss.gunsize >= all(select ss1.gunsize ships ss1))) temp) , smax.gunsize >= (select temp.gunsize ships temp) thank taking time read , answer ! try following: select name, gunsize ships gunsize=( select max(gunsize) secondbiggest ships gunsize<(select max(gunsize) biggest ships) ) edit : hint : secondbiggest , biggest aliases

vbscript - Need to compare folder path in VBS (.regex) -

question is: need compare folder1 path , folder2 path strings in vbs. folder1 read text file, saved earlier. folder2 - select folder dialog. want prevent user choose folder2 if: folder2 = folder1 folder2 = folder1\some_folder folder2 = parent_folder\folder1 for example: folder1 = c:\users\user\documents folder2 cannot be: c:\users\user\documents , c:\users\user\documents\letters or c:\users\user\ cannot make right regex compare. right use following code, need normal solution. rightpath = 0 set objshell = createobject("shell.application") set objfolder = objshell.browseforfolder(0, "select folder:", &h10&, strpath) if objfolder nothing msgbox "configuration canceled" ,64 , "information" wscript.quit end if set objfolderitem = objfolder.self objpath = objfolderitem.path ' right now, check users folder rightpath = rightpath + 1 dim re, targetstri

delphi - How to get screen size in Firemonkey FM3? -

how screen dimensions firemonkey fm³ ? following code: var size: tpointf; begin size := fmx.platform.ifmxscreenservice.getscreensize; ... end; results in compiler error: [dcc32 error] unit1.pas(46): e2018 record, object or class type required how should use ifmxscreenservice interface screen size ? try : var screensize: tsize; begin screensize := screen.size; caption := inttostr(screensize.width) + '*' + inttostr(screensize.height); end;

vhdl - convert a std_logic_vector INPUT to IEEE Float type -

how convert std_logic_vector input of entity in ieee float type, operations in process? entity need receive ieee float of a/d converter. vhdl doesn't have float type default - has real not synthesisable. however, ieee-standardised vhdl floating-point types synthesisable. you'll have cast std_logic_vector unsigned or signed vector first , convert suitable floating-point type, need not ieee-754 defined type

multithreading - updating datagridview from within a thread causes error c# winform -

i writing c# winform uses datagridview object. @ point in program need update said datagridview within thread. causes program throw unhandled exception saying object reference not set instance of object, , makes datagridview turn error image of white box red x in it. specifically trying in case update values in rows, removing rows , updating statistical values , reinserting rows. i in separate function thread calls , updates 2 rows in datagridview every time. here code update function: private void updatestats(int binnumber) { binnumber *= 2;//has multiply 2 because every bin has 2 rows in table if (statsdata.rows.count >= (binnumber + 1)) { statsdata.rows.removeat(binnumber); //number not change because index decreased 1 statsdata.rows.removeat(binnumber);//because every bin requires 2 rows } bin bin = bins[binnumber / 2]; list<double> realetempdata = new list<double>();

ios - NSMutableDictionary with nil as value -

i have project @ https://github.com/niklassaers/njsnotificationcenter far 2 unit tests. 1 of them runs, 1 of them runs 60% of time. remaining 40% of time, fail because nsmutablevalue contains nil value, though have never put in nil value (nor should possible) the problem arises here: - (void) addobserver:(id)observer selector:(sel)aselector name:(nsstring *)aname object:(id)anobject priority:(nsinteger)priority { njsnotificationkey *key = [[njsnotificationkey alloc] initwithobserver:observer name:aname object:anobject]; nslog(@"key is: %p", key); key.priority = priority; njsnotificationvalue *value = [[njsnotificationvalue alloc] initwithselector:aselector]; nsassert(value, @"value cannot nil!"); @synchronized(observers) { observers[key] = value; nslog(@"key: %p\tvalue: %p\t%@", key, value, observers); if(observers[key] == nil) nslog(@"this can't be!"); } } i make key,

python - Removing empty Counter() objects from a list -

i have simple list of counters: > counter_list counter({'pig': 1}), counter(), counter({'chicken': 3}) i cannot seem find simple way remove empty counter. i have tried using counter_list += counter() as per documentation, no luck. del seems delete contents of counter, not actual counter, , @ best creates more empty counter. any advice appreciated, , apologies in advance future forehead-slapper. use list comprehension build new counter_list : counter_list = [item item in counter_list if item] this works because empty counter falsish , while non-empty counter truish : in [27]: bool(collections.counter()) out[27]: false in [28]: bool(collections.counter([1])) out[28]: true

actionscript 3 - Is It possible to make a Transparent Mask like making an window, on AS3 Flash? -

i want have movieclip make hole on movieclip, putting window on wall. can make mask has same effect right-clicking layer , masking it, not want. want make transparent hole. i have tried this: mc1 = new green(); mc2 = new blue(); mc2.blendmode = blendmode.alpha; addchild(mc1); addchild(mc2); mc2.cacheasbitmap = true; mc1.mask = mc2; and this: mc1.cacheasbitmap = true; mc2.cacheasbitmap = true; mc1.setmask(mc2); first problem: code gives me errors. second problem: doesn't make hole on movieclip, normal mask. here code, revised: var mc1 = new green(); //included var before variable name var mc2 = new blue(); mc2.blendmode = blendmode.erase; //this masking shape erase what's below movieclip(root).blendmode = blendmode.layer; //setting root layer works addchild(mc1); addchild(mc2); mc2.cacheasbitmap = true; it appears trying create 'inverted mask,' mask reveals under except located. effect can achieved giving mc2 blend mode of ble

javascript - Can you run JSNode scripting on standard hosting packages? -

i relatively new server-side scripted jsnode environment , found mixed answers when looking online needed run jsnode on server. looking replace php jsnode , wondering if able without host having install new server packages. thank response. you can't run server side javascript depends on node.js without host having installed node.js. node.js doesn't have unusual dependancies. require installing on server though (and not common option hosting services, i've used when i've had root access vps). if want interact apache (for example) might need install along lines of mod_proxy.

excel - Powershell - add 1 to a string -

the following code: $search.address().tostring() currently outputs cell locations in format: $b$5 but want add 1 becomes $b$6 so far i've tried $search.address().tostring()+1 but outputs $b$51 how can add numerical value appears after second $ thanks. you can regular expression: c:\ps> [regex]::replace('$b$6', '(\$\w+\$)(\d+)', {param($m) $m.groups[1].value + (1 + $m.groups[2].value)}) $b$7

bit manipulation - Saturating signed integer addition with only bitwise operators in C (HW) -

for homework assignment, have write function in c adds 2 signed integers, returns int_max if there positive overflow , int_min if there negative overflow. have follow strict restrictions in operators can use. integers in two's complement form, right shifts arithmetic, , integer size variable (i can find sizeof(int)<<3). can't use contitionals, loops, comparison operators, or casting. can use bitwise , logical operators, addition , subtraction, equality tests, , integer constants int_max , int_min. i know overflow can detected if 2 inputs have same sign , result has different sign. i've gotten point have flag showing if equation did overflow. have no idea how there end product. have far: int saturating_add(int x, int y){ int w = sizeof(int)<<3; int result = x+y; int signx = (x>>w-1)&0x01;//sign bit of x int signy = (y>>w-1)&0x01;//sign bit of y int resultsign = (result>>w-1)&0x01; //sign bit of result

persistence - Python 'shelve' that writes itself to disk after each operation -

i'm doing project in python involves lot of interactive work persistent dictionary. if weren't doing interactive development, use contextlib.closing , confident shelf written disk eventually. stands there's no chunk of code can wrap within 'with' statement. i'd prefer not have trust myself call close() on shelf @ end of session. the amount of data involved not large, , happily sync shelf disk after each operation. i've found myself writing wrapper shelve i'm not strong enough python programmer identify correct set of dict methods i'd need override. , seems me if i'm doing idea, it's been done before. paradigmatically correct way handle this? i'll add using shelve because it's simple module, , comes python. if possible i'd prefer avoid doing requires (for example) pulling in complicated library dealing databases. i'm using winxp sp3, python 2.7.5 via anaconda 1.6.2 (32-bit), , running inside spyder. can tell looking @

asp.net - VS2012 Crystal Report Viewer Group Tree Hide -

asp.net. webform crystaldecisions.web, version=13.0.2000.0 crystalreportsviewer. i want hide / disable l.h. pane containing group tree button. the displaygrouptree property marked obsolete , has no effect. i have set toolpanelview="none" has no effect. the hiding of group tree problem has existed earlier versions published answers not work or translate version far can see. maybe building report wrong. (it displays ok). private void showreport(myclasslibrary.report report) { connectioninfo cn = new connectioninfo(); cn.servername = "myserver"; cn.databasename = "mydatabase"; cn.userid = "myuser"; cn.password = "mypassword"; string reportdirectory = server.mappath(".") + "\\reports\\"; crystalreportsource rs = new crystalreportsource(); session["currentreportsource"] = rs; crystaldecisions.web.report r = new crystalde

python - Creating keys/values from a string by defaultdict -

i want create default dict using string. let's have word 'hello': function return: {'h':{'e'}, 'e':{'l'}, 'l':{'l', 'o'}} i tried creating defaultdict(set) first in order rid of duplicates, i'm not sure how obtain key's value next letter in string (if makes sense?) def next(s): x = defaultdict(set) in range(len(s)-1): x[i].add(s[i+1]) #this part unsure return x this returns me error saying how str object has no attribute 'add'. your code works fine: >>> collections import defaultdict >>> def next(s): ... x = defaultdict(set) ... in range(len(s)-1): ... x[i].add(s[i+1]) ... return x ... >>> next('hello') defaultdict(<type 'set'>, {0: set(['e']), 1: set(['l']), 2: set(['l']), 3: set(['o'])}) perhaps running code uses defaultdict(str) accident? you want use s

jquery - How to get php array as a javascript array through ajax -

i have php file called ajax, printed array, , want array in ajax success event , use javascript array prepend valu in 2 fields jquery. tried bellow failed. new in coding, pls me one.... the php file bellow: $qry = $crud->select("latest_event", "bndescription, eventheading","eventid='{$eventid}'"); $data = mysql_fetch_assoc($qry); $arr = array("content" =>$data['bndescription'], "heading" => $data['eventheading']); header('content-type: application/x-json'); echo json_encode($arr); ?> the javascript is: $.ajax({ type: "post", url: "geteventdata.php", data:"eventid="+eventid+"&lang="+lang, cache: false, success: function(data){ $("input#eventheading").prepend(data[heading]); $("textarea#cont").prepend(data[content]); } }); data[heading] you don&

python - What is return type of read_frames() scikits audiolab? -

in scikits audiolab, i'm trying split audio's 2 channels in 2 different file, , observed read_frames method numbers looks list not exactly. , documentation not explicitly mention data type. looks like, [[-0.25283813 -0.05990601] [-0.28274536 -0.06542969] [-0.30093384 -0.06890869] ..., [ 0.21939087 0.36206055] [ 0.22756958 0.36981201] [ 0.22592163 0.37960815]] what return type of read_frames()? first, without documentation can print type(returned_value) , discover in case numpy.ndarray instance. of it, two-dimensional 1 lots of rows , 2 columns. and documentation does mention type explicitly: read given number of frames , put data numpy array of requested dtype.

How do I undelete a file after git rm and pushing to github? -

i cloned repository on local machine , did git remove on 1 of files , pushed changes github repository. question how restore file on original github repository? if can find previous commit abcd has deleted file, can use git checkout abcd file-to-restore to restore it. you'll need commit file again.

python - matplotlib bug in plot_dates? -

just wanted see if others thought following behaviour in matplotlib plot_date buggy, or if it's should put with. i have multi-panel plot set sharex facilitate zoom/pan on axes, , plot time series data in both panels. however, in second panel, of data happens invalid (in example mask it). from matplotlib.pyplot import figure,show datetime import datetime,timedelta numpy import sin,cos,linspace,pi,ma,array fig=figure(figsize=(16,9)) ax1=fig.add_subplot(211) ax2=fig.add_subplot(212,sharex=ax1) # xdata seconds xdata=linspace(0,9999,10000) tdata=array([datetime(2000,1,1)+timedelta(seconds=ss) ss in xdata]) data1=ma.masked_array(sin(pi*xdata/300),mask=false) data2=ma.masked_array(cos(pi*xdata/300),mask=true) ax1.plot_date(tdata,data1,marker='',color='r') ax2.plot_date(tdata,data2,marker='',color='b') show() i'd expect (prefer) show blank panel, not fail , give me long unhelpful traceback. expected behaviour? notes: this script fails

python - Alternative to Using Expression as Variable? -

forgive me if question repeat, i'm stuck code i've been working on. creating program myself create random teams of people, , i've been trying find easy way make inserted amount of teams. area suck on here: print("how many teams like?") numberteam = input("number: ") listnumber = 0 teams = [] while numberteam + 1: teams.append(team(str(listnumber + 1)) = []) i new coder, i'm sure besides obvious using expression variable there other mistakes, suggestions on easy way fix great! also if left out, please ask! (by way using python) try (i cleaned things bit): print("how many teams like?") numberteam = int(input("number: ")) # create dictionary, each team has emtpy list teams = dict([('team{}'.format(i), []) in range(numberteam)]) # following works # teams = {'team{}'.format(i):[] in range(numberteam)} you can access teams this: teams['team3'] # returns empty list the longhand a

How do you isolate a single project in Eclipse? -

whenever ctrl+shift+w (close tabs) in eclipse , start or open fresh project, warnings , errors in problems view persist (from previous projects in workspace open in past). how can let eclipse know want focus on current project only? this varies release, there filters dialog (try using down arrow in problems toolbar , choose "filter content"). can set scope "on element in same project". scope determined using current selection in 1 of navigator views (packager explorer, navigator, etc)

php - Transaction not working -

i have following environment wamp version : 2.4 apache version : 2.4.4 php version : 5.4.16 firebird/interbase support dynamic compile-time client library version firebird api version 25 run-time client library version wi-v6.3.0.26074 firebird 2.5 pdo pdo drivers firebird, mysql, sqlite pdo_firebird pdo driver firebird/interbase enabled following php code not working properly. transaction never rolled back. <?php require_once 'klogger.php'; $log = new klogger ( "log.txt" , klogger::debug ); try { $db = new pdo("firebird:dbname=my-server:mbooks-db", "sysdba", "masterkey"); $db->setattribute(pdo::attr_errmode, pdo::errmode_exception); $result = $db->begintransaction(); $log->loginfo('transaction ' . $result); $sql = "update control set code = code + 1 ( company_id

performance - How to fix java intermittent lags? -

the same code in project has different execution duration same input parameters, varies 1ms 30ms. private void link(array values, area area){ values.add(area); array<area> children = area.getchildren(); (int i=0; i<children.size; i++){ area child = children.get(i); link(values, child); } } this lags inappropriate. can fix them? intermittent lags caused garbage collection.

ember.js - Why should I use Ember.run() when handling events in other libraries? -

looking @ ember.js documentation, rather vague when make use of ember.run() (my emphasis). normally should not need invoke method yourself. if implementing raw event handlers when interfacing other libraries or plugins, you should wrap of code inside call. from looking through source , reading posts on topic, understanding when call ember.run() , following occurs. the given callback run. the run loop algorithm executed, flushing queues , ensuring bindings synchronized, etc. i'm trying understand why recommended handle other libraries' events inside of call ember.run() . take following example create jquery ui slider , handle slide event. <script type="text/x-handlebars" data-template-name="index"> <div id="slider"></div> <h2>{{value}}</h2> <h3>{{valueprose}}</h3> </script> app = ember.application.create(); app.indexcontroller = ember.controller.extend({ actions: {