Posts

Showing posts from July, 2010

netlogo - Initialization and termination of Turtles timer -

in procedure want start timer every turtles (agent) when change shape "shape2" "shape1", , timer expire after 10 ticks , shape changes "shape1" . procedure works when hit "go" works first 10 ticks counted. after not called. have called procedure name "change" in go block. to change let test one-of breed-here [ shape = "shape2" ] if test != nobody , [ ticks ] of test = 10 [ask breed [ shape = "shape2" ] [ set shape "shape1" ] ] end the go block statement : to go ask breed [ shape = "shape2" ] [ change ] end here illustration using patches. (colors stand in shapes.) patches-own [shape-timer] globals [s1 s2] setup ca set s1 blue ;"shape" 1 set s2 red ;"shape" 2 ask patches [set pcolor one-of (list s1 s2)] end temp-change-shape set pcolor s2 set plabel "temp" set shape-timer 10 end update set shape...

python - psycopg2 set PRIMARY KEY from tuple with placeholder -

how can set primary key in psycopg2 tuple of values being looped in tuple? for example have tuple meetattrs = ('id', 'venue', 'date', 'rail', 'weather', 'trackcondition') and want create table , extract , insert values. meetattrs wish set id primary key. conn = psycopg2.connect("") conn, conn.cursor() cur: # first, create tables. cur.execute("drop table if exists meetings, races, horses") cur.execute("create table meetings (id integer primary key, " + ", ".join("%s varchar" % fld fld in meetattrs) + ")") this creates error, unsure how resolve. traceback (most recent call last): file "racemeeting.py", line 56, in <module> + ")") psycopg2.programmingerror: column "id" specified more once your current sql query after join performed , placeholders take values is: ...

node.js - Node http-server not working on Windows 10 Ubuntu Bash -

i tried install nodejs http-server on windows 10 ubuntu bash, installation worked fine running serve static site $http-server src throws error: $ http-server src /usr/lib/node_modules/http-server/bin/http-server:14 var ifaces = os.networkinterfaces(); ^ error: einval, invalid argument @ object.<anonymous> (/usr/lib/node_modules/http-server/bin/http-server:14:17) @ module._compile (module.js:456:26) @ object.module._extensions..js (module.js:474:10) @ module.load (module.js:356:32) @ function.module._load (module.js:312:12) @ function.module.runmain (module.js:497:10) @ startup (node.js:119:16) @ node.js:945:3 what can missing here? not supported yet ubuntu bash on windows 10? update: issue has been fixed since windows 10 creators update (april 2017). this known issue[ 1 ][ 2 ][ 3 ][ 4 ] regards low-level networking code has not yet been implemented bash on windows or windows-linux subsystem (wsl). until fixe...

python 2.7 - How to copy a url of a file in Dropbox folder on mac? -

i tried many other options using user id , all, seem changed dropbox now, ddnt user id. also, pythonscript can run command line didn't work. can me out on this? you can manually url file right-clicking on file , selecting "copy dropbox link". if you'd url programmatically, try using dropbox api. you can use /create_shared_link_with_settings endpoint generating sharable url: https://www.dropbox.com/developers/documentation/http/documentation#sharing-create_shared_link_with_settings the python sdk may helpful you.

Parsing multiple JSON Objects from a single file in PHP -

i need extract object id total_time file containing multiple json objects {"alternative_names":[["",""]],"route_name":["",""],"status_message":"found route between points","route_geometry":"qo{`o@wpslhbmfzwepbgdzdeblfwdgv@`g`czeybfiyeteonteumpauhkascgc[mb{agcua{@uca@}cl@ybtb}@ldvhecatdmcdbcdx@iddedk@ubebeb_ccgcxyfi^{dg\\wbkp_fs^wbis_ce[_d}uwackibqigi_telaucmmp_ishqf@_wyjee}f`mkdjiitth@y|@lobq^vy@mu@fw@cuxoco@r^gb@zroojpsbfmq@rmjbdpnepklenh`j~dvn@la@nd@pt|f@llv_@przlbhnb@fuxc@lmnac~zancbxna`kb|bb`|cbmcl]ry`xczkcjwbzobjxgl_g|fnhcmf~e~me~pft}ejbblzahvinyhfqdb~cbla`w@poazt@z}@bb@did~dbxtejgcfjdljbpuafw@bpgngdhqf~yc~g@la@v~@ni@rbajg@jp`jlc`fnddgddu@j@eahba@lcldcacji_btcy@va_dvf}qaf}bof@l{@{cnfokdr}ma`xbgm|tkjxpmllssf@|}@gf@`x@kozxmefgmsx^kf@tw@mdtl}k@r~@ykcjjeau@niaee@bu@uul\\}dpfzcrcr|@dt@|nblrobx_bdzlv|dbd`pbr~anq@xm@r|@ls@|y@dq@}o`xum`qcdheobgbeccu[xxmbh","route_summary":{...

c# - How can I cancel ajaxToolkit:AjaxFileUpload inside OnClientUploadStart? -

i'm trying validation of other fields on page after user clicks upload button of ajaxfileupload control. onclientuploadstart defined fire before upload starts. , works. want cancel upload if validation fails. tried doing "return false;" didn't work. how can cancel upload? if validation fails want cancel function uploadstart(sender, args) { var filedescription = document.getelementbyid("filedescription").value; alert( filedescription); return false; } <ajaxtoolkit:ajaxfileupload id="ajaxfileupload1" throbberid="mythrobber" onuploadcomplete="ajaxfileupload1_uploadcomplete" contextkeys="" onclientuploaderror="uploaderror" onclientuploadcomplete="uploadcomplete" onclientuploadstart="uploadstart" allowedfiletypes="jpg,jpeg,doc,xls" maximumnumberoffiles="1" runat="server"/> ...

google analytics - Associating Different URLS -

let's used have page /about.html period of time , ga tracked pageviews page. now url changed /about-us.html. there way, through ga's platform, or through js snippet, associate /about-us.html pageviews old data collected /about.html? the idea not lose collected data pages urls changed. know there no reprocessing ga, perhaps data correlation possible after fact? if viewing total number of pw page 2 urls create custom dimension , use regular expression include both versions. or simpler use filter in ga , use regexmatch in "all pages" report page dimension. /about.html, /about-us.html the regex filter can like: ^\/about(|-us)\.html$ how work?

Get mongodb collection using Eve -

i have mongod instances running on server database on it. i'm trying set eve rest http api database, simple respond requests. if request http://92.51.132.110:28017/clockrefdb/test/rows using mongod rest interface, get: { "offset" : 0, "rows": [ { "_id" : { "$oid" : "5745ef6494aef075d127f1d0" }, "timestamp" : { "$date" : "2016-05-25t22:31:00.035+0200" }, "frequencies" : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] } , { "_id" : { "$oid" : "5747034194aef04e87df598d" }, "timestamp" : { "$date" : "2016-05-26t18:08:01.209+0200" }, "frequencies" : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] } , { "_id" : { "$oid" : "5747050094aef04fe7aa7c14" }, "timestamp" : { "$date" : "2016-05-26t18:15:28.576+0200" }, "frequencies" : [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] } , { "_id" :...

javascript - $stateprovider throws 404 if i visit link directly from url bar -

Image
i'm using ui.router angularjs , came across strange behavior. if click trough page works expected, links changing, templates loading, if visit specific page directly (other www.myapp.com) 404 page not found this app.js var app = angular.module('app', ['ui.router', 'ui.bootstrap']); app.config(function($stateprovider, $urlrouterprovider,$locationprovider){ $urlrouterprovider.otherwise("/dashboard"); $stateprovider .state('dashboard', { url: "/dashboard", templateurl: "app/templates/dashboard/dashboard.html", controller: 'dashboardctrl' }) .state('locations', { url: "/locations", templateurl: "app/templates/locations/locations.html", controller: 'locationsctrl' }) .state('locations.add_location', { url: "/locations/add_location...

Python nested loop speed issues -

i working on program test ideal angle-values construct something. i'm stuck @ nested-for-loop i'm going attach below. while idealy count each 'a' 9000, takes forever if values set below. there way speed nested loop? or can somehow assign more ressources python? for a1 in xrange(15, 91): a2 in xrange(15, 91): a3 in xrange(15, 91): a4 in xrange(15, 91): a5 in xrange(15, 91): ite in xrange(1, 1000): ok = mathmatvec(a1, a2, a3, a4, a5, ite) if ok == 1: v[0] = a1 v[1] = a2 . . the itertools.product() function speed nested for-loops. that said, running time dominated total number of calls mathmatvec() .

android - Starting an IntentService at Background with a BroadcastReciever -

i coding app intentservice sends custom intent when job done. starts other intentservice. in order that, used broadcastreciever in mainactivity. my question if mainactivity goes background, onstop, broadcastreciever still work? if wouldn't, start new intentservice broadcastreciever? mean, since intentservice stops after job done, intentservice broadcastreciever work until mainactivity onstart? after registe broadcast receiver android framework, broadcast sent app no matter app running in background or foreground. if registe broadcast receiver in androidminifest.xml, if app has been stopped or destroyed, when broadcast coming, app's receiver load start again.

C# read byte array from SerialPort -

i ask why program returns first byte instead of byte. usb port sending byte value of 23, however, when c# program reads it, receives value of 2. why happening? c# code below private void button1_click(object sender, eventargs e) { serialport port = new serialport("com4", 9600); port.open(); byte[] buffer = new byte[2]; port.read(buffer, 0, 2); handleserialdata(buffer); port.close(); } private void handleserialdata(byte[] respbuffer) { string one, two; char a, b; = convert.tochar(respbuffer[0]); b = convert.tochar(respbuffer[1]); 1 = convert.tostring(a); 2 = convert.tostring(b); messagebox.show(one + two); }

firebase - GCM to FCM for Xamarin -

xamarin has predefined support gcm (google cloud messaging) explained in https://developer.xamarin.com/guides/cross-platform/application_fundamentals/notifications/android/remote_notifications_in_android/ as google migrated gcm fcm (firebase cloud messaging) work xamarin same instruction or there other docs integrating fcm xamarin? does features provided in firebase can used in xamarin app? does work xamarin same instruction? no, doesn't. can still work gcm since google hasn't announced gcm support stop now. posted fcm newest version of gcm . there other docs integrating fcm xamarin? not yet, xamarin doesn't have guide how integrate fcm xamarin.android app. does features provided in firebase can used in xamarin app? yes, can used xamarin. @ moment have wait until xamarin provides official bindings(dlls) fcm java libraries(jars) , post in their blog how integrate our apps. at point, best thing can while developing xamarin use gcm. ot...

javascript - Custom JS Confirm Modals using jQuery.Deferred and issues with return values based on buttons -

i'm java developer has entered javascript world, forgive me if make silly mistakes or assumptions. attempting translate our native browser/js "confirm" dialog boxes custom modals have been developed using backbone framework. currently, these modals not support "confirm" type functionality. think primary issue modals not working asynchronously. i have method calling opens modal, , hoping receive "true" or "false" value call depends on button user clicked. however, method returns modal displayed, , not wait button click. modal system supports seperate callbacks each button, can defined when calling "openportletmodal" method, demonstrate below. however, "confirmdiscard" method returns undefined value, without ever waiting of button calls. question is, possible pause execution of method until callback made? while researching, did find out bit jquery.deferred,but haven't found clear way of utilizing functionality wa...

Change column in rails from integer to float -

i have contact_number in customers table using field integer. tried creating record in rails c apparently can't store larger field of numbers. looked around online think should use float instead of integer given precision of 10 numbers in states my thought create new migration class changecontactnumberincustomertabletofloatfrominteger < activerecord::migration def change_table remove_column :customers, :contact_number, :integer add_column :customers, :contact_number, :float end end how specify precision , correct way in doing this? first off, if correct contact_number phone number, want use string rather numeric field. phone numbers not numeric values collection of digits. or stated more generally, collection of characters, happen limited numbers. additionally, easier parse area code , country code too, if relevant (however hypothetically if need parse country , area code, you'd want store in separate columns anyways, that's different...

sql server 2008 - Display Previous YTD Value member on MDX for SSAS? -

ytd working fine need value previous year. following previous ytd displays total previous years amount. example of august 2013, ytd display total ytd amount january august in 2013 , previous ytd should display total ytd amount january august 2012. ytd create member currentcube.[measures].[ytd amount] aggregate(ytd(), [measures].[amount]), format_string = "$#,##0.00;-$#,##0.00", non_empty_behavior = { [amount] }, visible = 1 , associated_measure_group = 'tf - bu transaction'; previous ytd create member currentcube.[measures].[prev ytd amount] (parallelperiod( [mf - time].[year - month].[year] ,1 ,[mf - time].[year - month].currentmember) , [measures].[ytd amount]), format_string = "$#,##0.00;-$#,##0.00", non_empty_behavior = { [amount] }, visible = 1 , associated_measure_group = 'tf - bu transaction'; i'm not sure can use year date calculation in pytd calculation because need ytd outside of parallell per...

Rails, running becomes after a find -

i need change class of each result returned in active record query. to happen whenever query run , results returned. unfortunately cannot use sti accomplish this. example: class foo < activerecord::base after_find :becomes_a_subclass def becomes_a_subclass becomes [bar, baz, raz].sample end end class bar < foo ; end class baz < foo ; end class raz < foo ; end i expect following return given result: => foo.all [#<bar id: 1>, #<baz id: 2>, #<bar id: 3>, #<raz id: 4>] you'll want implement discriminate_class_for_record(record) class method on foo . should return subclass record. example implementation: class foo < activerecord::base def self.discriminate_class_for_record(record) if record['foobar'] [bar, baz, raz].sample else super end end end class bar < foo ; end class baz < foo ; end class raz < foo ; end

c# - SQL database connection failure in another computer through |DataDirectory| -

i have database , server application , works fine while i'm running on computer. string connectionstring = @"data source=(localdb)\v11.0;attachdbfilename='|datadirectory|\fabrica.mdf';integrated security=true;connect timeout=30"; the problem is: have run application in computer , database must there well, when server application tries access database returns nothing. problem authentication? file path? @edit: here's how i'm accessing tables: sqlconnection con = new sqlconnection(connectionstring); sqlcommand cmd = new sqlcommand(); cmd.connection = con; cmd.commandtype = commandtype.text; cmd.commandtext = string.format("select * {0}", table); string name; sqldatareader reader; try { con.open(); reader = cmd.executereader(); while (reader.read()) { name = reader["name"].tostring(); } con.close(); } catch (exception e) { messagebox.show(e.tostring()); } @edit: don't know if helps have ...

python - Execute a file in temp (tempfile) -

i'm trying write python script creates temporary file (another python script) in temp folder. should proceed execute temp file. i wrote this: tempfile.temporaryfile(mode='w+b', suffix='.py') temp: stuff stuff stuff temp.write(mycode.encode('utf-8')) temp.seek(0) os.system(temp.name) when run it, the the process cannot access file because being used process. error. tried use tempfile.mkstemp instead (hoping "close" function handle this), nothing changes. so question is: how can create file, python script, in temp folder, execute it, , delete it? thanks answers :d the line os.system(temp.name) should outside of with closure. doing doesn't work here since file removed then, therefore need have parameter delete=false passed temporaryfile() . preferably consider using namedtemporaryfile .

postgresql - SQL Trigger to Insert a row -

i'm using postgresql. these table involved in trigger: pricing (title,publisher,period,offer,price) the db has 4 tables describing magazine business. the table above shows title, publisher of magazine, period (an option subscribe magazine, in months (integer), offer (a string, 'regular' or 'renew'), , price (integer). the question: write trigger adds new row in pricing table. if new row inserted offer='regular', insert new row, same but: offer='renew' , price discount of 10%. here trigger, doesn't work: create or replace function offer_f() returns trigger $$ begin if(tg_op='insert') if new.offer='regular' insert pricing (title,pusblisher,offer,period, price) values (new.title,new.publisher,"renew",new.period,new.price*0.9); end if; end if; return new; end; $$ language plpgsql; this trigger itself: create trigger reduced_offer after insert or upda...

javascript - How to change the color in a final object3d with properties THREE.SceneUtils.createMultiMaterialObject? -

i have object combined color , wireframe. want change color base , color mesh material in final object. use meshbasicmaterial multimaterialobject. if @ source three.sceneutils.createmultimaterialobject see creates multi-material effect creating child meshes of parent object. use following pattern change material colors: var object = three.sceneutils.createmultimaterialobject( geometry, materials ); ... object.children[ 0 ].material.color.set( 0xff0000 ); object.children[ 1 ].material.color.set( 0x00ff00 ); see three.color source code or docs acceptable formats setting colors. three.js r.77

ruby - Ensure orphaned processes are killed when the parent process dies -

in ruby, how ensure child processes spawned program don't keep running when main process exits or killed? initially thought use at_exit in main process, won't work if main process gets kill -9 ed or calls kernel.exec . need solution (basically) foolproof, , cross-platform. if have handle kill -9 termination parent app, have couple of choices can see: create work queue manager , spawn/kill child processes work queue manager. if can't guarantee work queue manager won't killed without warning, option 2 choice think, since thing know sure child processes still running. http://www.celeryproject.org/ http://aws.amazon.com/elasticbeanstalk/ more aggressive approach - spawn off whole os instances they'll killed off within parameters operation have child processes check "heartbeat" parent process through rpc or monitoring parent pid in memory or watching date/time on keep-alive file in /tmp make sure it's current. if child processes ...

sql - Combining groups in GROUP BY -

i have query groups field description. (there 9 total descriptions.) need somehow combine 3 of these descriptions 1 group, giving me total of 7 descriptions. i'm brand new sql querying, i'm lost on beyond joins , clauses far. appreciate help. select serviceclass.description, datepart(year, meterread.readdate) year, datepart(month, meterread.readdate) month, sum(meterread.consumption) consumption, count(distinct accountservice.account_id) locations accountservice inner join serviceclass on accountservice.serviceclass_id = serviceclass.serviceclass_id inner join meterread on accountservice.accountservice_id = meterread.accountservice_id (@year = datepart(year, meterread.readdate)) group serviceclass.description, datepart(year, meterread.readdate), datepart(month,meterread.readdate) order year, month you can achieve using case statement. replace serviceclass.desription in se...

python - Why simple import of module in same directory is not allowed -

i've created 2 modules in same directory: . ├── mod1.py ├── mod2.py there no __init__.py , don't want create package, i'm creating simple script have modularized breaking different modules. my intention run mod1.py using python mod1.py ~/junk/imports$ cat mod1.py . import mod2 print(mod2.some_expr) $ cat mod2.py some_expr = 'hello world!' although know directly using import mod1 work, i'm deliberately not using module name doesn't clash built in modules (which felt practice) i'm getting following errors python2 , python3 ~/junk/imports$ python3 --version python 3.4.3 kartik@kartik-lappy:~/junk/imports$ python3 mod1.py traceback (most recent call last): file "mod1.py", line 1, in <module> . import mod2 systemerror: parent module '' not loaded, cannot perform relative import ~/junk/imports$ python2 --version python 2.7.11 ~/junk/imports$ python2 mod1.py traceback (most recent call last): file ...

ruby on rails - UTF8 urls doesn't work in nginx+passenger -

i'm trying working utf8 routes in rails 4 get '/документы', to: 'static_pages#docs', as: :docs its working great on webrick, doesn't work in battlefield (nginx+passenger) i guess because nginx makes url lowercase no route matches [get] "/%d0%b4%d0%be%d0%ba%d1%83%d0%bc%d0%b5%d0%bd%d1%82%d1%8b" but rails expects uppercase started "/%d0%b4%d0%be%d0%ba%d1%83%d0%bc%d0%b5%d0%bd%d1%82%d1%8b" 127.0.0.1 completed 200 ok in 52ms (views: 49.0ms | activerecord: 1.0ms) is there way make nginx understand unicode routes? heres nginx server config server { listen 80; server_name website.com; charset utf8; root /web/website/public; location ~ ^/assets/ { root /web/website/public; expires 1y; add_header cache-control public;# add_header etag ""; break; } error_page 502 404 /502.html; passenger_enabled on; rails_spawn_method smart; rails_env production; }

wxpython - TypeError: GridSizer(): arguments did not match any overloaded call -

i display table of 6 buttons(cancel,delete,save,quit,stop,new), 3 rows , 2 colunms. tried run program below, did not work. import wx class identifiers(wx.frame): def __init__(self, parent, id, title): wx.frame.__init__(self, parent, id, title, size=(200, 150)) panel = wx.panel(self, -1) grid = wx.gridsizer(3, 2) grid.addmany([(wx.button(panel, wx.id_cancel), 0, wx.top | wx.left, 9), (wx.button(panel, wx.id_delete), 0, wx.top, 9), (wx.button(panel, wx.id_save), 0, wx.left, 9), (wx.button(panel, wx.id_exit)), (wx.button(panel, wx.id_stop), 0, wx.left, 9), (wx.button(panel, wx.id_new))]) self.bind(wx.evt_button, self.onquit, id=wx.id_exit) panel.setsizer(grid) self.centre() self.show(true) def onquit(self, event): self.close() app = wx.app() identifiers(none, -1, '') app.mainloop() this whole message error. file "c:/python34/test_wxpython/ev...

appcelerator - ArrowDB custom object "Count "API - does it use query parameters? -

created model in arrowdb project , in arrow builder web, can see api docs default apis created model (query, create, count, etc). api doc count seem indicate has query parameters where, sort, etc. in testing directly api doc test , in code, api returns total count of objects in model, not count based on filtered "where" criteria. has seem behavior? api in fact take these params and, if not, there way count number of objects in model based on filtered criteria? i think creates customobject in arrowdb? http://docs.appcelerator.com/arrowdb/latest/#!/api/customobjects-method-count count not seem take parameters guess 'where' not work @ moment...

r - Using a variable in a manual colour palette -

i've got variable called team team <- "denver" i want use in manual colour scheme. colours.manual <- c(team = "green", "draw" = "grey", "other team" = "red") the problem here colours.manual assigns green team instead of denver. what need use variable? thanks we can use setnames colours.manual <- setnames(c("green", "grey", "red"), c(team, "draw", "other team")) colours.manual # denver draw other team # "green" "grey" "red"

Eclipse Juno won't run all Junit tests in the package -

this issue in eclipse juno. working on project has large bunch of junit tests (800 +) exist in various packages beneath root package. when right-click on root package , choose "run . . . junit test" eclipse run 100 of tests. my run configuration has radio button checked says "run tests in selected project, package, or source folder:" , points correct package. i've tried deleting run configurations , re-creating them, various project cleans, restarts , etc. , eclipse runs 100 tests. anyone have ideas?

Throwing error when RecyclerView is added to xml layout file in Android -

i developing android application. trying use recyclerview in application. added recyclerxml layout file. when run app, throwing error. please see scenario below. this main_activity xml <?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.coordinatorlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:fitssystemwindows="true" tools:context=".mainactivity"> <android.support.design.widget.appbarlayout android:id="@+id/htab_appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:fitssystemwindows="true" android:theme="@style/the...

python - How to embed animation into ParaView scene from script? -

so try add animation scene in paraview using python. started wiki script . animation plays when scene.play() called. while playing paraview (5.0.1 in case) stuck window paying animation - scene can not rotated while playing, buttons cannot pushed. how keep editor alive in paraview animation script? also when click on editor animation play scene button nothing played @ all. i wonder how embed animation scene playable , savable paraview editor? that wiki example appears little dated. try in script instead: # active source. sphere1 = getactivesource() # animation track sphere1startthetatrack = getanimationtrack('starttheta', index=0, proxy=sphere1) # create keyframes animation track # create key frame keyframe1 = compositekeyframe() # create key frame keyframe2 = compositekeyframe() keyframe2.keytime = 1.0 keyframe2.keyvalues = [360.0] # initialize animation track sphere1startthetatrack.keyframes = [keyframe1, keyframe2] # animation scene animationsce...

excel formula - Concatenate TEXT, format only parses positive numbers -

i want concatenate 3 different cells 1 make nice table presenting average , maximum value , number of observations follows: 1.234 - 3.456 ( 7 ) i found way this, not efficient still. downside there negative numbers, reason ignored. the formula use following: =if(r[-24]c>1;concatenate(text(r[-8]c;"#,##0;;@")&" - "&text(r[-16]c;"#,##0;;@")&" ( "&r[-24]c&" )");concatenate(text(r[-16]c;"#,##0;;@")&" ( 1 )")) so question be, there i'm doint wrong "#,##0;;@" or there error in concatenate? further chris neilsen, create or delete custom number format has: a number format can have 4 sections of code, separated semicolons. these code sections define format positive numbers, negative numbers, 0 values, , text, in order. <positive>;<negative>;<zero>;<text> for example, can use these code sections create following custom...

python - SQLAlchemy - Try Except for different Integrity Errors -

sqlalchemy raises integrityerror both unique constraint , foreign key contraint violations. how can wrap in try/except block , discriminate between various causes of exception? want know column violation occurred , whether or not unique or foriegn key violation. take class example. class user(db.model): id = db.column(db.integer, primary_key=true) name = db.column(db.string, unique=true) org_id = db.column(db.integer, db.foreignkey('company_id') the following result in 1 of 2 different message: if name not unique, message (x.integrityerror) column name not unique if org_id not unique, message (x.integrityerror) foreign key constraint failed i suppose parse out "unique" , column name in 1st case. in second case parse out "foreign key", couldn't column name. if table has multiple foreign keys on it, how can tell violation happened without making call each parent table? user = user(name='matthew moisen', org_id=999...

.net - The proper way to await databound property getters c# -

what correct way use async method in databound property getter? talking solid, scientific arguments, not personal preferences. i've read many threads problem, not specific case. of solutions don't work in cases, , of suggestion, well... subjective or wrong. what don't accept , why: you can't - actually, possible. there many posts "there no such things async properties", "it against design of language" etc. there many sensible explanations why such expressions false this should me method, not property - can't be. want databind it. provide property "proxies" people using code because in future there may different method calculate pseudo-property. , want view-side of binding simple possible use property store cached result of method - defeat purpose, changes dynamically , class orm entity store redundant data db. use sometask.result; or sometask.getawaiter().getresult() - in cases use it. i've used in many cases i.e...

php - WooCommerce add data- attribute to view cart button on success message -

i've managed change html markup of view cart button on success message add id="open_cart" it, want add data- attribute such data-cart="open" html output, id returned. any ideas on how add data- attribute it? function my_add_to_cart_message() { if ( get_option( 'woocommerce_cart_redirect_after_add' ) == 'yes' ) : $message = sprintf( '%s<a id="open_cart" data-target="open-cart" href="%s" class="button">%s</a>', __( 'successfully added cart.' , 'woocommerce' ), esc_url( get_permalink( woocommerce_get_page_id( 'cart' ) ) ), __( 'view cart', 'woocommerce' ) ); return $message; } add_filter( 'wc_add_to_cart_message', 'my_add_to_cart_message' ); this function above returns: <a id="open_cart" href="http://example.com/cart/" class="button wc-forward">ver carrinho</a> ...

python 2.7 - Plot multiple lines on subplots with pandas df.plot -

Image
is there way plot multiple dataframe columns on 1 plot, several subplots dataframe? e.g. if df has 12 data columns, on subplot 1, plot columns 1-3, subplot 2, columns 4-6, etc. i understand how use df.plot have 1 subplot each column, not sure how group specified above. thanks! this example of how it: import pandas pd import numpy np import matplotlib.pyplot plt fig, axes = plt.subplots(1, 2) np.random.seed([3,1415]) df = pd.dataframe(np.random.randn(100, 6), columns=list('abcdef')) df = df.div(100).add(1.01).cumprod() df.iloc[:, :3].plot(ax=axes[0]) df.iloc[:, 3:].plot(ax=axes[1])

android - how to use context.getContentResolver() to execute a update with CASE WHEN statement -

having sql statement case update field based on row id, without need passing values. "update accounts set field= case when id=(select id accounts id=0) 1 else 0 end"; how use context.getcontentresolver() execute it? or other way? if go contentprovider , path approach i'll suggest use helper class: public static class uribuilder{ public static final string fragment_raw_update = "rawupdate"; // here nonotify, conflict resolver pathes, etc. private uri.builder uri; public uribuilder(uri uri){ this.uri = uri.buildupon(); } public uribuilder(string uri){ this.uri = uri.parse(uri).buildupon(); } public uribuilder append(string path){ uri.appendpath(path); return this; } public uribuilder append(long id){//points directly item uri.appendpath(string.valueof(id)); return this; } public uri...

arrays - I need assistance with my intro to Java assignment -

i have compiled java program (which generates 100 random numbers between 0 , 25, puts them in array, , sorts them 2 different arrays based on whether each or odd), although not run. suspect have made mistake 1 of while loops, although don't know sure. also, struggled code in formatted in question, tabs off, still legible. here .java text: public class assignment8 { public static void main( string [] args ) { int storage [] = new int[100]; int j = 0; while ( storage.length < 100 ) { int testvariable = 0 + (int) (math.random() * ((25 - 0) + 1)); storage[j] = testvariable; j++; } int oddarray[] = oddnumbers( storage ); int evenarray[] = evennumbers( storage ); int currentnumber = 0; system.out.println( "the odd numbers are: " + "\n" ); while ( currentnumber <= 99 ) { system.out.println( oddarray[currentnumber] + "\n...

c++ cli - C++/CLI and C# Garbage collection before context switch -

at 1 point in time searching msdn , found app config setting force garbage collection prior native managed boundary context switch. useful tracking down references improperly getting cleaned before meant them to. cannot life of me remember option was, ring bell anyone? thanks! of course minute after post question find answer. mda or managed debugging assistants: http://msdn.microsoft.com/en-us/library/d21c150d.aspx specifically part: gcmanagedtounmanaged mda.

asp.net - WebApi route not working -

here route: config.routes.maphttproute( name: "createuser", routetemplate: "api/user/createuser", defaults: new { controller = "user", action = "createuser" } ); here endpoint: [httppost] public async task<user> createuser([frombody] user user) { db.directusers.add(user); await db.savechangesasync(); return user; } i sending post data: { "userid" : 1 "name" : "nick" "twitterhandel" : "x" } to : http://localhost:56792/api/user/createuser but im getting 404 ideally, not need add routes each action method. 1 route configuration enough normal api. if need advanced routing, can @ web api 2's attribute routing. public static void register(httpconfiguration config) { config.maphttpattributeroutes(); // alone enough. config.routes.maphttproute( name: "defaultapi", routetemplate: "api/{cont...

c# - Variable available to multiple projects -

i have asp.net application designed ui layer connecting service layer, connecting business layer , down data access layer. the classes layers have constructors, accept userid (int). used logging, , things "lastupdateuser , createuser" storage. i working across time zones, , in user table, have timezoneid. in ui level, stored within session state , can manipulate dates based on timezone. i create method in service layer, "gettimezonebyuser" , pass userid, whcih goes down layers data access layer, , gets timezone info. problem having in data transfer object, have logic, uses time based info: public class persondto { public int id { get; set; } public string firstname { get; set; } public string surname { get; set; } public decimal grosssalary { get; set; } public string email { get; set; } public bool deleted { get; set; } public list<personnonavailibilitydto> nonavailibility { get; set; } public string fullname ...

excel - VBA If cell is under a certain length, highlight and display message -

i'm trying write macro examines column in excel spreadsheet looking entries shorter 9 characters greater 2, , if found, display message , highlight cell in value found. might happen multiple times. have written following code: sub highlight() dim c range dim lr integer dim intcell long lr = worksheets("basket").cells(rows.count, 6).end(xlup).row intcell = 1 8 each c in range("g20:g" & lr).cells if len(c.value) < 9 , len(c.value) > 2 msgbox "one or more of codes invalid. correct highlighted values." c.cells(intcell).interior.color = vbyellow end if next next end sub i can't figure out i'm doing wrong. appreciated. just guessing @ want highlight sub highlight() dim c range dim lr integer dim numprobs long dim sht worksheet set sht=worksheets("basket") numprobs=0 lr = sht.cells(rows.count, "g").end(xlup).row each c in sht.range("g20:g" & lr).cells if len(c.val...

release memory used in python function composition -

i dealing large arrays , huge number of loops, while script failed because of memory limit or bus error. now want optimize code little bit, release memory using del , gc.collect() as possible @ each loop. since i've used bunch of nested functions, such result = functiona(functionb(data, time)) , wondering how can release memory in implementation? basically, want have same effect of doing following: b = functionb(data, time) result = functiona(b) del b; gc.collect() any suggestions appreciated!

c++ - How can a variable be both constexpr and not constexpr? -

i have made constexpr string type, call staticstring . got idea this website. i having weird issues compiler treating variable constexpr on 1 line, , not constexpr on next line. here code: constexpr staticstring hello = "hello"; constexpr staticstring hello2 = hello + " "; constexpr staticstring world = "world"; constexpr staticstring both = hello + " world"; constexpr staticstring both2 = hello2 + world; //this works fine (world constexpr?) //constexpr staticstring both3 = "hello " + world; //error: "world" not constexpr int main(void) { static_assert(hello[4] == 'o' ,"error"); static_assert(hello == "hello", "error"); static_assert(both2 == "hello world", "error"); } and here definition of staticstring : class staticstring{ const char* const str; const size_t len; const staticstring* head; public: t...

Java file layout without IDE (OS: Ubuntu) -

i writing java code without ide, got little problem when try run code after compiling it. (i using ubuntu 64) $ javac classname.java $ java classname not find or load main class classname my directory structure following: projectname ----- packagename ---------- classname.java ---------- classname.class my code start writing down packagenmae. when remove package statement, works. while error occur when statement included. package packagename; public class myclass { // .... used in main class } public class classname { public static void main(string args[]) { // .... } } could tell me problem. the main issue trying run command from. not run inside package directory, root of package tree (in example, projectname directory). from there, should doing: javac packagename.classname which tells compile "classname"[sic] inside package "packagename"[sic]. way doing it, telling compile class not part of package (which...

oracle - Trying to Get the next department number from dept table using SQL Function -

lets assume have department table has deptno values (10,20,30,40...etc ) how can create function next department number ? studying , think if im not right function should contain sequence , still not sure , need guys . solving let me learn how functions work if thats ok explain how code can , thank . to numbers in table not easy. can select maximum , add 10. if 2 people working database want insert new department @ same time? both same maximum number, 20, add ten, , try insert same id 30. oracle has sequences that. when 2 people draw next sequence number, 1 has wait other, 1 gets next number 30 , other number following, i.e. 40. when 1 dismisses insert rollback, id not in table. records 10, 20, 40 instance. i think it's possible lock whole table, select maximum, insert value + 10 , commit , release table. most people use sequence. , don't care gaps. don't care numbers long unique. use them technical ids, exist able relate tables; have no meaning. depar...