Posts

Showing posts from January, 2015

ruby - How to organize Rails app where each customer has it's own specific gem list? -

i'm creating architecture of app , trying find best one. few words it: box solution (each app installed on customer's machine) there main app , gems extend (private) main app has default list of gem other functionality extending adding additional gems request (our gems) but customers no need full functionality, don't need include gems it's gemfile. what best way organize it? think way? maybe can offer more effective way? you may want consider making "main app" or core functionality a mountable engine , not rails application. that means packing controllers, models, , routes gem added stock rails application customized specific customer. how cms:es refinery , radiant structured. this allows full freedom each "box" have whatever settings , gems wants. important if intend let clients self host (which nightmare). it makes developing , updating core easier bundler resolve gem dependencies. add "default" gems depend

mysql - Summing-up For an Arbitrary List of Rows -

i wish write this: select sum(weight) items itemid in (4217,4575,6549,4217) where itemid primary key, , sqlite , mysql process expected, i.e. add 4217-th row sum twice, don't. is there @ least in mysql i'm not aware of that's intended cases this? if not, workaround like? row can have number of duplicates in list. list can big although in cases small. i don't know out of box functionality can this. here workaroud. can insert values temp table , use join: create temporary table list(id int); insert list(id) values(4217),(4575),(6549),(4217); select sum(i.weight) items join list l on i.itemid = l.id;

javascript - Angular 2 / Typescript - TypeError: ClassName is not a constructor -

i learning angular 2 , ran error while trying create service. tried searching solution, cannot see mistake. error: angular2-polyfills.js:1243 typeerror: tweet not constructor code: export class tweetservice{ gettweets(){ return tweets; } } let tweets = new tweet("url", "author 1", "handle 1", true, 50); class tweet { image: string; author: string; handle: string; status: "lorem ipsum dolor sit amet."; isliked: boolean; favorites: number; constructor(img, aut, hndl, ilkd, fav){ img = this.image; aut = this.author; hndl = this.handle; ilkd = this.isliked; fav = this.favorites; } } your let statement floating outside class declarations. work (but in real app setting tweets based on http call or something): import {injectable} '@angular/core'; @injectable() export class tweetservice{ gettweets(){ let tweets =

c# - Should the Repository pattern manipulate an object before passing it to the consumer/service layer? -

the current solution working structured single core layer connecting database whenever needs retrieve data. i suggested few colleagues create dal layer , move of database logic it's own project , call application.dataaccess this layer use entity framework , repository pattern abstraction between application.core , application.dataaccess (the repository implementation sit within application.dataaccess). i plan to consume repository in service layer. public class jobservice { private ijobrepository _jobrepository; public jobservice(ijobrepository repository) { _jobrepository = repository; } public ienumerable<job> getjobs() { list<jobs_alljobs> alljobs = _jobrepository.getalljobs(); list<job> result = new list<job>(); foreach(job in alljobs) { result.add(new jobs() { title = job.title, otherentity = "internal service"; }); } return result; } } job r

what is the wrong with this Jquery form validation -

i trying validate form element 3 condition using jquery. this code - var valid = true, errormessage = ""; if ($('#name').val()) { if ($('#name').val().length > 60 || $('#name').val().length < 3) { errormessage = "length of name must between 3 , 60.\n"; valid = false; } else { var rege = /^[a-z]([a-z_])+$/i; if(!rege.test(!$('#name').val())){ errormessage += "please enter valid name.\n"; valid = false; } } } else { errormessage += "please enter name \n"; valid = false; } if name field empty should display 'please enter name'. if field not empty , length < 3 or > 60 should display 'length of name must between 3 , 60'. finally should check user name valid or not. if not valid 'please enter valid name' should display. my problem when entering valid user name going messa

facebook - ANR caused by com.google.android.gms.DynamiteModules -

Image
i using firebase inside app facebook authentication. after 3th restart of app, freezes , shows anr (please see last question ). after doing research found out blocking main thread. have no clue why happening. error below show couple of times when app running (my app not freeze when error appears). have idea? i have included info below, maybe helps note: google play services on test device (samsung sm-g920f) running version: 9.0.83 (440-121911109) getting error: 05-28 02:35:56.798 29479-29506/? e/dynamitemodule: failed load module descriptor class: didn't find class "com.google.android.gms.dynamite.descriptors.com.google.firebase.auth.moduledescriptor" on path: dexpathlist[[zip file "/data/app/com.package.myapp-1/base.apk"],nativelibrarydirectories=[/data/app/com.package.myapp-1/lib/arm64, /vendor/lib64, /system/lib64]] theads: dependencies: compile 'com.facebook.android:facebook-android-sdk:4.12.1' compile 'com.google.code.gson:gs

python - Assign two variables with ternary operator -

is there way variable assignments(as shown below) using ternary operators in python: if(x>1): y="yes" else: z="yes" something (x='yes') if(x>1) else (z='yes') , gives error. there other way this? i know single variable assignments can done this: x="yes" if(l==0) else "no" edit: assume x, y & z assigned value before run. you can use exec function this: exec("y='yes'" if x > 1 else "z='yes'")

http - Wireshark showing post parameters in diffrent locations in follow TCP stream window -

Image
im running tests on app , ive stumbled upon odd thing happends when sniff traffic between me , app server using wireshark: in scenario when im making post request through app's html, looks that: but when im requesting same thing using chrome extension "postman" , looks that: why parameters shown @ top of request? mean, changed here? im trying find clue why working in first option , refuses work on second. thats why need investigate every little thing.. edit: i wrote short html page illustrate , second option happens here well: ... <form action="http://x.x.x.x/page.cgi?id=1726931735&host_name=blah" method="post"> .... postman send empty body default, need enable rows of key-value fields them added request . postman not read form on page, parameters must inserted plugin fields. otherwise postman send empty request see. you need enter fields in body tab in postman :

android asynctask - How to edit SharedPreferences without blocking UI Thread? -

i want put many values in sharedpreferences doing blocking ui thread. tried in asynctask's doinbackground() , using handler, both attempts turned out of no use. here's method: .... context c = ramadanwidgetconfig.this; saveddatasehri = c.getsharedpreferences("sehri", 0); saveddataiftar = c.getsharedpreferences("iftar", 0); boolean sfilled = saveddatasehri.getboolean("filled", false); boolean ifilled = saveddataiftar.getboolean("filled", false); if (!sfilled || !ifilled) { fillsharedpreferences(); } .... private void fillsharedpreferences() { string date[] = {"6/18/2015", "6/19/2015", "6/20/2015", "6/21/2015", "6/22/2015", "6/23/2015", "6/24/2015", "6/25/2015", "6/26/2015", "6/27/2015", "6/28/2015", "6/29/2015", "6/30/2015"

java - Setting Clipboard from non-ui thread -

issue: can't set clipboard non-ui background thread how go around setting clipboard while app in background? public class messages { public void setmessage(string text) { if (build.version.sdk_int < build.version_codes.honeycomb) { clipboardmanager clipboard = (clipboardmanager) getsystemservice(context.clipboard_service); clipboard.settext(text); } else { android.content.clipboardmanager clipboard = (android.content.clipboardmanager) getsystemservice(context.clipboard_service); clipdata clip = clipdata.newplaintext("newclip", text); clipboard.setprimaryclip(clip); } } } error: cannot resolve getsystemservice(java.lang.string) i tried multiple things solve issue, 1 of them is: configuration class /* made config class file so: */ public final class config { public static com.dysanix.official.mainactivity maincontext = null; } /* , pu

perl - Analyse text records based on the value of two fields -

i using perl test couple of conditions in each line of input file. one-liner below works records not all. in current output , lines 2,3, , 5 correct, lines 1 , 4 not, presumably because stb value has 2 comma-separated values in instead of one. instance stb=0.5,0.645036; instead of stb=0.590597; . i can not seem figure out how apply same logic both conditions, if stb >= 0.8 , "strand bias" , reads value of fdp field. the input file have lines in 1 stb value , two. perl perl -ple '/^[^#].*fdp=(\d+);.*stb=(\d+\.\d+);/ , $_.=($2 >= 0.8?" strand bias ":" ").$1." reads"' input > out input chr1 93159358 . ct ac,c 51.3482 pass af=0,0.538462;ao=4,12;dp=39;fao=0,21;fdp=39;fr=.;fro=18;fsaf=0,11;fsar=0,10;fsrf=15;fsrr=3;fwdb=0.0379899,0.0954749;fxx=0;hrun=1,5;len=2,1;mlld=22.441,10.1519;oalt=ac,-;oid=.,.;omapalt=ac,c;opos=93159358,93159359;oref=ct,t;pb=0.5,0.5;pbp=1,1;qd=5.26648;rbi=0.0698716,0.219287;

c - Summation of the absolute difference between every two adjacent number is maximum in a array -

e.g (1,2,7) , m =[1-7]+[2-7} gives m=11 instead of calculating directly gives 6 [1-2]+[2-7] please me how solve this?? have used array find max , min afterwards don't know how proceed. #include <stdio.h> int main() { long int a[100000]; int n,i; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%lu",&a[i]); } int max=a[0]; int min=a[0]; for(int i=0;i<n;i++){ if(a[i]>max){ max=a[i]; }else if(a[i]<min){ min=a[i]; } } printf("%d\n",max); printf("%d\n",min); return 0; } #include <stdio.h> #include <stdlib.h> #include <limits.h> int main(void){ long int a[100000], max = long_min; int n; scanf("%d", &n); for(int = 0; < n; i++){ scanf("%lu", &a[i]); if(a[i] > max) max = a[i]; } long long int sum = 0; f

How to check if running as root in a bash script -

i'm writing script requires root level permissions, , want make if script not run root, echoes "please run root." , exits. here's pseudocode i'm looking for: if (whoami != root) echo "please run root" else (do stuff) fi exit how best (cleanly , securely) accomplish this? thanks! ah, clarify: (do stuff) part involve running commands in-and-of require root. running normal user come error. meant cleanly run script requires root commands, without using sudo inside script, i'm looking syntactic sugar. the $euid environment variable holds current user's uid. root's uid 0. use in script: if [ "$euid" -ne 0 ] echo "please run root" exit fi

d - Compile-time foreach outside function body -

is there way have foreach outside function body ex. generating code. my scenario have associative array @ compile-time need use generate specific fields. unfortunately can't use foreach outside of function body generate members. right using work-around have few mixins give 1 aa first mixin , mixin converts aa array , passes second mixin, second mixin recursive ng until there no more member, while calling first member in array, calls third mixin can use generate code. it's not smooth , dynamic want , wondering if has better solution. here solution // first mixin takes associative array , string mixin handle items mixin template staticforeachaa(tkey,tvalue, tkey[tvalue] enumerator, string itemmixin) { enum array = arrayaa!(tkey,tvalue)(enumerator); // converts aa array of key-value pair structs alias arraytype = keyvaluepair!(tkey,tvalue); mixin staticforeacharray!(arraytype, array, itemmixin); // calls second mixin array } // second mixin "fa

android - Firebase Storage request params -

i using firebase storage in android app , using getbytes method file. i want set param request unable find method add params. these params set automatically on download (we build download urls you), we're totally abstracted away networking. additional query params add? a better way of doing might attaching custom metadata file , checking custom metadata in rules .

save results of loop in a vector R -

i run loop: n = 10 alpha = 0.05 sigma = 0.01 (i in 0:n){ vt10[i] = ((sigma^2)/(alpha^2))*((n-i)+(2/alpha))*exp(-alpha*(n-i))-(1/(2*alpha))*exp(-2*alpha*(n-i))-(3/(2*alpha)) } however, vt10 outputs 10 outcomes (doesn't include first iteration, when i = 0 ). how can create vector include 11 iterations? answer: n = 10 alpha = 0.05 sigma = 0.01 vt10 = numeric(11) ## this! (i in 0:n){ vt10[i+1] = ((sigma^2)/(alpha^2))*((n-i)+(2/alpha))*exp(-alpha*(n-i))-(1/(2*alpha))*exp(-2*alpha*(n-i))-(3/(2*alpha)) } also, need vt10[i+1] , because loop 0 10, while array index should 1 11. comment: your code looks c code. not start index 0, write loop task. try: n = 10 alpha = 0.05 sigma = 0.01 = 0:10 vt10 = ((sigma^2)/(alpha^2))*((n-i)+(2/alpha))*exp(-alpha*(n-i))-(1/(2*alpha))*exp(-2*alpha*(n-i))-(3/(2*alpha)) in situation, there no need predefine vector. r knows performing element-wise computation, , automatically assign length-11 vector vt10 .

R Shiny Download Handler Cant Read in other Output in the Server -

i trying use downloadhandler function in r shiny app , encounter erorr. relevant bit of server.r: shinyserver(function(input, output, process) { output$week1day1<-dt::renderdatatable({ bench <- input$bench.input squat <- input$squat.input dl <- input$dl.input ex1 <- input$day1main ex2 <- input$day1acc1 ex3 <- input$day1acc2 ex4 <- input$day1ass1 ex5 <- input$day1ass2 pr1 <- input$week1day1ex1pr/100 pr2 <- input$week1day1ex2pr/100 pr3 <- input$week1day1ex3pr/100 w4 <- input$week1day1ex4pr w5 <- input$week1day1ex5pr if(grepl("squat",ex1)){ w1 <- pr1*squat } if(grepl("bench",ex1)){ w1 <- pr1*bench } if(grepl("deadlift",ex1)){ w1 <- pr1*dl } ### if(grepl("squat",ex2)){ w2 <- pr2*squat

javascript - span tag text not change using JQuery ajax -

Image
i cant give json value span tag using jquery ajax function var productid = $("#product_id").text(); var city = $("#spn-deliveryloccookies").text(); $.ajax({ url: '/product/est_time', type: 'get', data: { 'city': city, productid: productid }, contenttype: 'application/json; charset=utf-8', success: function (res) { //your success code alert(res); //$("#p_price").html(""); $("#p_price").text(res.ourprice); }, error: function () { alert("some error"); } }); }); after produce result , web page having i cant give text value in span tag in ajax function success block there have **alert(res); , work fine produce result** $("#p_price").text(res.ourprice); not work you need parse json string javascript object. access p

php - How Do I JOIN a third Table called all_recipes using recipe_id KEY -

select cou.recipe_id, ifnull(fou.found, 0) found, cou.count ( select recipe_id, count(recipe_id) count recipe_ingredients group recipe_id) cou left outer join ( select r.recipe_id, count(r.key_ingredient) found users_ingredients u join recipe_ingredients r on r.key_ingredient = u.key_ingredient group r.recipe_id) fou on fou.recipe_id = cou.recipe_id i need join 3 tables - well, 4 in end. can please show me how can , explain how keep joining when required later. have 4 or more tables. many credit @arulkumar above i don't understand sql but, join table need this. select recipe.id, all_recipes.id recipe left join all_recipes on recipe.id = all_recipes.id

java - Concatenate list of paths in bash-script, with colon as separator -

i have following difficult read script consisting of single command: #!/bin/sh /library/java/javavirtualmachines/jdk1.8.0_45.jdk/contents/home/bin/java \ -classpath /users/afarber/src/jetty-newbie/embeddedwebsocket/target/classes:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-server/9.3.9.v20160517/jetty-server-9.3.9.v20160517.jar:/users/afarber/.m2/repository/javax/servlet/javax.servlet-api/3.1.0/javax.servlet-api-3.1.0.jar:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-http/9.3.9.v20160517/jetty-http-9.3.9.v20160517.jar:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-util/9.3.9.v20160517/jetty-util-9.3.9.v20160517.jar:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-io/9.3.9.v20160517/jetty-io-9.3.9.v20160517.jar:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-servlet/9.3.9.v20160517/jetty-servlet-9.3.9.v20160517.jar:/users/afarber/.m2/repository/org/eclipse/jetty/jetty-security/9.3.9.v20160517/jetty-security-9.3.9.v20160517.jar:/users/afarber/.m

html - How to remove the spacing between the columns or grids in bootstrap? -

i trying build tile view using bootstrap grids dont want spacing between adjacent columns or rows. tried many ways remove not able to. can 1 please same ? following code <div class="container"> <div class="row"> <div class="col-lg-8 col-sm-12 col-md-8 col-xs-12"> <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12"> <div class="col-lg-6 col-sm-12 col-md-6 col-xs-12"> //a vertical long image </div> <div class="col-lg-6 col-sm-12 col-md-6 col-xs-12"> <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12"> //square image </div> <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12"> //square image </div> &l

2D image processing algorithm to process a set of images and build a big image -

i wondering if there algorithm provide set of images build 1 big image out of them? set of images can have overlapping pixels. thus, algorithm detects corners of set image , glues big image ignoring pixels drawn in big image. i hope explanation not bad.

javascript - How to assign function to selector switch? -

i used selector switch in html: <div class="onoffswitch"> <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked> <label class="onoffswitch-label" for="myonoffswitch"> <span class="onoffswitch-inner"></span> <span class="onoffswitch-switch"></span> </label> i need assign 2 functions on & off position. on position : send message arduino yun server : auto_on off position : send message arduino run server : auto_off something similar used onclick action on button: function autoon() { $('#content').load('/arduino/auto_on'); } function autooff() { $('#content').load('/arduino/auto_off'); } i don't think can use onclick event on slider switch, i'm wondering how this? try : <div class

sqlite - Strange order when retrieves data from android database -

i trying data database using sqldatabase.query method: public cursor getlist() { dataprovider.dbhelper mdbhelper = dataprovider.getdbhelper(); sqlitedatabase db = mdbhelper.getwritabledatabase(); return db.query(shotstable.table_name, new string[]{shotstable.json}, null, null, null, null, shotstable.views + " desc"); } private list<shots> getallfromdb() { gson gson = new gson(); cursor cursor = new shotsdatahelper().getlist(); list<shots> data = new arraylist<>(); if (cursor.movetofirst()) { { data.add(gson.fromjson(cursor.getstring(cursor.getcolumnindex(shotsdatahelper.shotstable.json)), shots.class); } while (cursor.movetonext()); } cursor.close(); return data; } public void insert(shots shots) { contentvalues contentvalues = new contentval

c# - RadDropDownButton.DropDownContent as a RadButton - cannot change highlight color -

here xaml code... the hover color still yellow goldish out of box color... doing wrong. want change can specify mouse on color. <telerik:raddropdownbutton height="16" horizontalalignment="left" isopen="false" margin="999,16,0,0" name="rddlocations" verticalalignment="top" width="15" content=" " background="#ff25b7db" foreground="white" borderthickness="0"> <telerik:raddropdownbutton.dropdowncontent> <telerik:radlistbox x:name="uioptionslist" itemssource="{binding locationitems}" background="#ff25b7db"> <telerik:radlistbox.itemtemplate> <datatemplate> <telerik:radbutton> <telerik:radbutton.style> <style targettype="telerik:radbutton">

python - Access element using xpath? -

i links of elements in first column in page ( http://en.wikipedia.org/wiki/list_of_school_districts_in_alabama ). i comfortable using beautifulsoup, seems less well-suited task (i've been trying access first child of contents of each tr hasn't been working well). the xpaths follow regular pattern, row number updating each new row in following expression: xpath = '//*[@id="mw-content-text"]/table[1]/tbody/tr[' + str(counter) + ']/td[1]/a' would me posting means of iterating through rows links? i thinking along these lines: urls = [] while counter < 100: urls.append(get xpath('//*[@id="mw-content-text"]/table[1]/tbody/tr[' + str(counter) + ']/td[1]/a')) counter += 1 thanks! here's example on how can of links first column: from lxml import etree import requests url = "http://en.wikipedia.org/wiki/list_of_school_districts_in_alabama" response = requests.get(url) parser = e

python - PyBluez pairing bluetooth device -

how initiate pairing of bluetooth device pybluez in python? see ways discover, not pair. pybluez not support cross-platform pairing management. because operating systems, windows, require super-user level permissions programatically pair devices. on operating systems, when pybluez attempts connect socket using connect method, operating system try pair (often asking user permission). however, can make own super user tools or improve pybluez same. for example, can make own command line tools using .net windows pair , unpair devices, run these python. implementation of command line pairing tools can found here windows: http://bluetoothinstaller.com/bluetooth-command-line-tools/

ios - Accesing function in current center view controller in MMDrawerController -

i want update content on current visible center view controller when selection change in right side bar, left side bar : changes center view right side bar : lists items available, on selection change center view should update content current selection, created extension class uiviewcontroller function,and overrided function in view controllers, call goes parent viewcontroller function not actual centerview controller , following way trying execute function on right sidebar table view item tap let appdel = uiapplication.sharedapplication().delegate as! appdelegate let currentview = appdel.drawercontainer?.centerviewcontroller currentview.processselection(selectedstring) this executes function in base class extension uiviewcontroller { func processselection(item:string){} } and processselection overrideded @ viewcontroller.swift not getting called

php - odd even colored rows into a repeat region -

i try make work repeat region doesn't work. <body> <?php { ?> <table class="test"> <tr> <td><?php echo $row_recordset1['fld1']; ?></td> <td>...</td> <td><?php echo $row_recordset1['fld2']; ?></td> <td>...</td> <td><?php echo $row_recordset1['fld3']; ?></td> </tr> </table> <?php } while ($row_recordset1 = mysql_fetch_assoc($recordset1)); ?> </body> and style is <head> <style type = "text/css"> .test tr:nth-child(even) {background: #a4d1ff;} .test tr:nth-child(odd) {background: #f2f2f2;} </style> </head> the answer simple: take <table> tags outside of php loop. should generating 1 set of <table> tags @ start , end of table, not every row. once this, css stands chance of working.

how to make Javascript alert box display a variable from Rails controller -

i have piece of javascript codes in view file: <script> function hint() { var str = @user.name; var name = str.tolowercase(); alert(name); } </script> i want alert box display name of user use variable @user defined in controller. however, when click button active alert box, nothing shows up. tried current_user.name, didn't work either. how can display value of variable in alert box? just keep this, in html file. var str = '<%= @user.name %>';

amazon web services - Docker - Cant access docker port from outside -

so created new ec2 instance , installed docker on it. i deployed code ( https://github.com/commonsearch/cosr-front/blob/master/install.md ) , followed install instructions. install successfull , started server: [ec2-user@ip-172-30-0-127 cosr-front]$ make docker_devserver docker run -e docker_host --rm -v "/home/ec2-user/cosr-front:/go/src/github.com/commonsearch/cosr-front:rw" -w /go/src/github.com/commonsearch/cosr-front -p 9700:9700 -i -t commonsearch/local-front make devserver mkdir -p build go build -o build/cosr-front.bin ./server godebug=gctrace=1 cosr_debug=1 ./build/cosr-front.bin 2016/05/28 16:32:38 using docker host ip: 172.17.0.1 2016/05/28 16:32:38 server listening on 127.0.0.1:9700 - should open http://127.0.0.1:9700 in browser! well, when want access outside, cant! not curl local server. when run docker ps gives me correct port forwarding: [ec2-user@ip-172-30-0-127 ~]$ docker ps container id image co

AngularJs multiple select shows unresolved list instead of contents in IE -

i using angularjs bind list of employees mult-select tag. below code: <select class="form-control" ng-model="event.attendees" ng-options="c.email c.fullname c in employees" id="eemployees" multiple style="height:315px !important; -webkit-appearance:listbox !important;"> </select> the result displayed correctly in chrome , firefox, in ie shows list of {{c.fullname}}, instead of real names. tried right-click view source in ie (and ie inspector, f12), in source, employee names display correctly. have here ever ran issue before? have no sense why happened. placed multiple select tag in modal-dialog, matter? i figured out added $scope.$apply() after angular service pulled list data. needs little delay before binding it. still don't know why situation happened in ie though.

c# - MySQL View on one machine and a MySQL table in another machine. Query -

i have view located in mysql database in let machine1 i have machine mysql database in machine2 the view located in machine1 , table located in machine2 have same exact columns. is there way query both @ same time so: select * view join table1 on view.id = table1.id string select = "select * view join table1 on view.id = table1.id"; oledbcommand run_select = new oledbcomamnd(select, con); oledbdatareader read_run_select = run_select.executereader(); etc. etc. yes, can use connect storage engine. can connect other server , use on same machine

python - Edit a piece of data inside a csv -

i have csv file looking this 34512340,1 12395675,30 56756777,30 90673412,45 12568673,25 22593672,25 i want able edit data after comma python , save csv. does know how able this? bit of code below write new line, not edit: f = open("stockcontrol","a") f.write(code) here sample, adds 1 second column: import csv open('data.csv') infile, open('output.csv', 'wb') outfile: reader = csv.reader(infile) writer = csv.writer(outfile) row in reader: # transform second column, row[1] row[1] = int(row[1]) + 1 writer.writerow(row) notes the csv module correctly parses csv file--highly recommended by default, each row parsed text, why converted integer: int(row[1]) update if want edit file "in place", use fileinput module: import fileinput line in fileinput.input('data.csv', inplace=true): fields = line.strip().split(',') fields[1] = str(int(fields[1

javascript - How to render partial views with Angular? -

i have following route config : var company; (function (company) { var homeconfig = (function () { function homeconfig($stateprovider, $urlrouterprovider) { this.$stateprovider = $stateprovider; this.$urlrouterprovider = $urlrouterprovider; this.$urlrouterprovider.otherwise('/welcome'); this.$stateprovider .state('welcome', { url: '/welcome', template: function () { return $("#welcome").html(); } }) .state('employee', { url: '/employee', views: { '': { template: function () { return $("#employee").html(); }, controller: 'employeecontroller',

Apache kafka sending java object failed -

i have object hashmap message = new hashmap(); message.put("x", "xxxxx"); message.put("y", "yyyyy"); message.put("z", 100); producerrecord producerrecord = new producerrecord(topic, message); producer.send(producerrecord); i getting exception in thread "main" org.apache.kafka.common.errors.serializationexception: can't convert value of class java.util.hashmap class org.apache.kafka.common.serialization.stringserializer specified in value.serializer you have provide kafka way how convert messages, in case hashmap , binary form. kafka documentation : the key.serializer , value.serializer instruct how turn key , value objects user provides producerrecord bytes. can use included bytearrayserializer or stringserializer simple string or byte types. the example of usage: properties props = new properties(); props.put("key.serializer", "y

mysql - How to know count data and show in multiple table -

i have problem query. this first table, "order": id_order id_event ------------------ 1 12 2 12 this second table, "event_table": id_event event_name id_eo -------------------------------- 12 festival 1 13 music 1 all want result this: festival : 2 order music : 0 order this have been done far: select (select count(*) order) jumorder, event_name order p inner join event on (p.id_event = event.id_event) event.id_eo = '1' using left join , concat can expected result mentioned in post. select concat(e.event_name, ": ", count(o.id_event), " order") result `event_table` e left join `order` o on o.id_event = e.id_event id_eo = '1' group e.event_name; result festival: 2 order music: 0 order sql fiddle: http://sqlfiddle.com/#!9/006c09/4

java - Libgdx | How to render game when not in focus? -

how render , update game on desktop when i'm not clicked on game window? want render, in background. thanks! wyatt, in game's main class, override pause(). if main class implements applicationlistener, done automatically. remove super.pause() within override , game render in background.

python - How to use a handler from settings for a non-Django log -

in django project, i'm using suds , logs predetermined log (suds.client) , doesn't let me configure different log messages. i'm trying around adding 1 of handlers have defined in settings.py. in code uses suds: logging.basicconfig(level=logging.info) suds_logger = logging.getlogger('suds.client') suds_logger.setlevel(logging.info) suds_logger.addhandler('my_handler') suds_logger.propagate = false this incorrect (because i'm passing string naming handler , not handler itself) , results in error: error:my_handler:'str' object has no attribute 'level' so, seems have correctly use 'my_handler' handler settings , should go. so, correct syntax?

opengl - How can OpenAI Gym's visualizations work within Docker? -

i'd openai gym working rendered opengl visualizations within docker container. it's straightforward openai gym running within docker. however, it's not clear how rendered environment display in window on os x laptop when call env.render() on openai environment within docker container. how go this? you can try sharing x11 socket file container... way container can write , show on machine: something this: docker run --privileged=true --rm \ -e display=$display -v /tmp/.x11-unix:/tmp/.x11-unix \ ...

python - How to get the Nth occurrence of a day of the week for a given month? -

the week of month not define value. shift between starting week , starting month causes problem in cases. is there python lib or algorithm calculate value? you can calculate looping on days of month , counting whether you've come across n th weekday: import datetime def get_n_weekday(year, month, day_of_week, n): count = 0 in xrange(1, 32): try: d = datetime.date(year, month, i) except valueerror: break if d.isoweekday() == day_of_week: count += 1 if count == n: return d return none for example: get_n_weekday(2016, 1, 1, 1) = first monday of january 2016 datetime.date(2016, 1, 4) . this uses date.isoweekday() means monday 1 , sunday 7.

git reset --soft HEAD~ modifies staged snapshot? -

from whatever have read git reset --soft , learned doesn't modified staging area or index. in below example can see staging area/index modified result of git reset --soft . why? mkdir test;cd test;git init; touch a; echo 1 >>a;git add a;git commit -m"1" a; echo 2 >>a;git commit -m"2" a; git diff --cached; <no output> git reset --soft head~; git diff --cached;<see below output> --- a/a +++ b/a @@ -1 +1,2 @@ 1 +2 a commit of particular content. index indexes particular content. git diff --cached compares indexed content against named commit. when reset head , changed commit git diff --cached compares against.

wordpress - Backbone Local Storage “undefined is not a function” -

i'm stumped here. i'm loading scripts in correct order, confirmed viewing source , i'm still getting error in console: app.todolist = backbone.collection.extend({ model: app.todo, localstorage: new backbone.localstorage("backbone-todo") // uncaught typeerror: undefined not function }); app.todolist = new app.todolist(); here's how i'm queueing scripts: function av_one_load_scripts() { wp_register_script( 'backbone_localstorage', 'https://raw.github.com/jeromegn/backbone.localstorage/master/backbone.localstorage-min.js', array( 'backbone' ) ); wp_register_script( 'bb_one', get_stylesheet_directory_uri() . '/js/bb_one.js', array( 'jquery', 'backbone', 'backbone_localstorage' ) ); wp_enqueue_script( 'backbone' ); wp_enqueue_script( 'backbone_localstorage' ); wp_enqueue_script( 'bb_one' ); } add_action( 'wp_enqueue_scripts&#

jdbc - Java framework to manage BLOB data outside of database -

i want store blobs outside of database in files, random blobs of data , aren't directly linked file. so example have table called data following columns: id name comments ... i can't include column called filelink or because blob raw data. want store outside of database. love create file called 3.dat 3 id number row entry. thing setup main folder start have large number of files id flat folder structure , there os file issues. , no data not grouped or structured, it's 1 massive list. is there java framework or library allow me store , manage blobs can myblobapi.saveblob(id, data); , myblobapi.getblob(id) , on? in other words file io handled me? simply use appropriate database implements blobs described, , use jdbc. not looking api specific implementation. it's db take care of effective storing of blobs.

c++ - Copy constructors with move-only, but cloneable types in member containers -

assume have 2 types, t1 , t2 . t1 isn't important except following facts: it isn't copy constructible it has move constructor we have excellent function signature t1 copy(t1 const& orig) , creates copy. t2 can simplified following class: // t2.h class t2 { public: t2() { /* initializes vector */ } t2(t2 const& other); private: std::vector<t1> v; } // t2.cpp t2::t2(t2 const& other) : ... {} how implement method, if write ellipsis part, or global scope? a simple real world use case - assuming "you can't write between curly braces" part real world restriction: t1 std::unique_ptr<anything> copy std::make_unique anything has copy constructor i have 2 additional requirements implementation: performance. shouldn't (considerably) slower naive implementation for loop in copy constructor's body. readability. entire point behind question more clear/clean trivial loop (e.g. imagine t2 2 or mo

xcode - iOS Swift Tab Bar Icon Insets Being Erased At Runtime -

i have 2 viewcontrollers inside tab bar controller. in interface builder, i've applied image insets (5, 5, 5, 5) tab bar icons sizes how want them. looks great when run simulator, when tab second viewcontroller, both tab bar icons automatically resize default (0, 0, 0, 0). when tab return first viewcontroller, both icons remain trapped @ default size no insets. note: icon images .pdf files in xcassets folder (set single vector scale factor). i've seen other threads suggest "balancing" insets (5 top, -5 bottom). compress image 5 away top , stretch 5 toward bottom. don't see how that's meant balance image size. if knows code set insets @ runtime, maybe use instead of setting insets in interface builder? in advance. reading documentation, uibaritem (superclass of uitabbaritem ) has property imageinset , , can access tab bar items via self.tabbarcontroller.tabbar.items . without testing myself, think may have issue insets getting reset

bash - sed or awk remove multiple lines starting with `if` and ending with that `if`'s closing `fi` -

an extension question delete multiple lines - "patterna" match, through second occurrence of "patternb" ... thinking should make more robust. so, rather counting how many fi 's, in likelihood there may unknown amount, i'd able execute where... if have following file /somepath/somefile containing: ... # test something? if something if somethingelse somethingelse fi fi ... ...with unknown amount of possible if / fi statements, how can remove line starting string containing " something? " through line containing closing " fi " first if ? any/all appreciated. generally speaking, need parser this. however, if of commands in script follow pattern sample in question ( if / fi @ beginning of line), crude if-counting solution should work. awk 'begin { del=0; level=0 } /test something?/ { del=1 } del==0 { print } /^if / { level++ } /^fi( |$)/ { level--; if (level == 0) del=0 }' somefile

javascript - Characters in other forms -

im pretty sure has been asked before not know how phrase it. mods, maybe can collapse questions once compatible answer has been found? i have node.js server , send url read or write json data. node.js url parser seems characters "?" "#" , "&" reserved while in json.parse/stringify side """ , "'" reserved well. how can work around this? kind of song data , these characters can , come in title names. tia niko update: i forgot mention turned out crucial: in node side using url , querystring modules have own logic manipulating url. due url , querystring modules using in node parse url according own logic have opted treat query part of url stringified json. have end-to-end control on application , make sure url send has stringified json query part of url.

python - Pandas Mapping Multiple Column Function on a DataFrame -

so have pandas dataframe containing column fields 'latitude' , 'longitude' , map function take 2 fields precision applied entire dataframe, , add column 'geohash' frame output of function being mapped. right i've been able implement hackish string concatenation having mapped function parse out args appropriately. @ least shows output i'm looking for. what have currently: def my_encode(argstring): argstring = str.split(argstring,'_') lat,long,precision = float(argstring[0]),float(argstring[1]),int(argstring[2]) try: hash = geohash.encode(lat,long,precision) except: hash = '' return hash precision = 7 data['args'] = data['latitude'].astype(str) + '_' + data['longitude'].astype(str) + '_' + str(precision) data['hash'] = data['args'].map(my_encode) its not terrible think more appropriate solution exists. in advance! iiuc can way

fortran: how to call intrinsic function time() when I already have an array time -

i need time routine , want wallclock time, using time() routine. however, code has 2d array called time, when do: startt=time() thinks referring array. how around without changing array name? i tried make function outside main program bypass doesn't work: program timetest real time(0:10,0:10) ! dummy array demonstrate problem integer*8 startt,endt,tdif time=0 ! initialize dummy array 0 startt=gettime() call sleep(2) !stuff timed endt=gettime() tdif=endt-startt print*,"tdif= ",tdif end integer*8 function gettime() gettime=time() print*,"gettime= ",gettime end function output: gettime= 0 gettime= -9223372036854775808 tdif= 0 you can't have 2 different things visible in program unit same name. first recommendation use fortran standard intrinsic subroutine system_clock rather time(). the approach took sep

mysql - Joing multiple with one master table -

i have 6 tables- project,equipment,fish,staff , junction tables - project_equipment,project_fish , project_staff.i want retrieve project total cost. so, wrote statement follows, select p.projectid, (sum(e.equipprice*pe.equantity)+sum(f.fishprice*pf.fquantity)+sum(ps.salary)) projectcost equipment e inner join project_equipment pe on e.equipid=pe.equipid inner join project p on pe.projectid=p.projectid inner join project_fish pf on p.projectid=pf.projectid inner join fish f on pf.fishid=f.fishid inner join project_staff ps on p.projectid=ps.projectid inner join staff s ps.staffid=s.staffid group projectid but, got price twice of correct amount. your query end lot of duplicate results. consider following simpler case: table: project projectid equantity 1 1 2 1 table: equipment equipid eprice 1 1 2 1 table: fish fishid 1 2 table: project_equipment projectid equipid 1 1 1