Posts

Showing posts from March, 2010

python - Referencing a csv within a zip file by its absolute path -

i have bunch of zip files within directory, , each zip file contains few csv's. i'm curious if it's possible files within each zip file, , add absolute paths list can referenced directly later? what have far below: # d directory folders containing zip files dirpath, _, filenames in os.walk(d): csv_list = [] # works since zip files files , not folders f in filenames: fp = os.path.abspath(os.path.join(dirpath, f)) if zipfile.is_zipfile(fp): # need unzip , add contents names_to_add = zipfile.zipfile(fp).namelist() paths_to_add = [os.path.join(fp, i) in names_to_add] # how absolute paths csv's? csv_list.extend(paths_to_add) else: # csv file csv_list.append(fp) # want contain absolute paths directly csv's print csv_list in other words, want treat zip files folders can ignore them , reference csv's within them directly. possible?

what do you mean by class and its instance ? (java) -

while checking questions found question. asks relationship between flower , rose. choices inheritance, class , instance , interface & implementation. now problem answer should know inheritance, answer class , instance. know class , instance mean? know instance means object of class. thank time. a class template objects created. in example mentioned, flower class rose , dandelion , lily , etc instances. eg, public class flower { private string type; .. public flower(string type) { this.type = type; } .. } and create instances of flower rose = new flower("rose"); flower lily = new flower("lily"); this viable explanation. i can see logical thought process well. have been public class flower { .. } and subclass like public class rose extends flower { .. } and public class lily extends flower { .. } but, subtleties depends on implementation. depends on how see problem (or rather how que

javascript - SQL Server 2008 on Node.js with Sequelize -

i'm new here ! i'm trying query on ms sql server2008 sequelize, error: unhandled rejection sequelizedatabaseerror: invalid column name 'id'. @ query.formaterror (c:\xampp\htdocs\lavori\bit_sense\api_bs\node_modules\s equelize\lib\dialects\mssql\query.js:217:10) @ request.usercallback (c:\xampp\htdocs\lavori\bit_sense\api_bs\node_module s\sequelize\lib\dialects\mssql\query.js:66:25) @ request.callback (c:\xampp\htdocs\lavori\bit_sense\api_bs\node_modules\te dious\lib\request.js:30:27) @ connection.state.sent_client_request.events.message (c:\xampp\htdocs\lavo ri\bit_sense\api_bs\node_modules\tedious\lib\connection.js:283:29) @ connection.dispatchevent (c:\xampp\htdocs\lavori\bit_sense\api_bs\node_mo dules\tedious\lib\connection.js:752:59) @ messageio. (c:\xampp\htdocs\lavori\bit_sense\api_bs\node_modul es\tedious\lib\connection.js:685:22) @ messageio.emit (events.js:104:17) @ messageio.eventdata (c:\x

Permutation vectors with unknowns in Sage -

i'm trying work sage, , can't understand how following. i've written little code: def elementdr1(r): g = symmetricgroup(r) e = g.list() o = g.order() coeff = zerocoeff(o) in range(0,o): if e[i] == g("(1,r)"): coeff [i]=1 if e[i] == g("(2,3)*(1,r)"): coeff [i]=1 if e[i] == g("(1,3)*(1,r)"): coeff [i]=-1 return coeff and sage says permutation vector (1,r) invalid. i'm sure there must way write permutation vectors unknowns, can't find method looking @ sage help. several issues here: the syntax creating element cycle decomposition g("(1,2)(3,4)") no * in between. the cycles must disjoint, i.e., no element can appear twice. have 1 appearing twice. using r inside string instead of substituting: samuel lelièvre commented on already. since (1,3)(1,r) not valid cycle decomposition, want multiply (1,3) (1,r). end, create th

bash - Using xargs to ssh to multiple hosts, receiving :Name or service not known -

i writing shell script ssh multiple hosts, , perform operations on them. my script, test.sh, looks follows: cat < $1 | xargs -e -d ' ' -i % ssh % grep "example" /opt/example/test.log i run via following command ./test.sh prod_hosts.txt and contents of prod_hosts.txt: hostname1 hostname2 hostname3 hostname4 i have verified there no carraige return @ end of file, yet getting following error: [ryan@hostname1 ~]$ ./test.sh prod_hosts.txt ssh: hostname4 : name or service not known xargs: ssh: exited status 255; aborting it looks ssh's 4 hosts has blank entry attempting ssh with, hence error. any idea i'm missing here? seems i'm missing obvious! echo '1 2' | xargs -d ' ' -i % echo % produces : 1 2 <blank line> whereas echo -n '1 2' | xargs -d ' ' -i % echo % returns: 1 2 i.e. xargs decides generate 1 more output entry if input string ended newline. workarounds: use newline

reactjs - How to give call to routing code again in react.js es6? -

import react 'react'; import { route, defaultroute, notfoundroute } 'react-router'; import app './app'; import tasklist './components/tasklist'; import {fetchdata } './utils/apiutils'; import config '../application.config'; var data={}; var roleid = $('#hdnroleid').val(); fetchdata(config.url+'/roles/'+roleid+'/tasks.json?tenantid='+config.tenantid).then(function(items) { console.log('tried fetch roles'); console.log(items); data =items; console.log('inside routes item fetched'); }).catch(function(response) { console.log(response); }); export default ( <route handler={app}> <route handler={tasklist} data={data} > </route> {data.map(task => <route name={task.pagename} handler={require(task.actualrout)}> </route> )}

javascript - breeze-sequelize - warning sequelize version is out of date 3.x has a critical security fix -

i added breeze-sequelize via npm. got warning effect of: "your sequelize version (breeze-sequelize has dependency on sequelize) out of date (has version 2.x). sequelize version 3.x has critical security fix." has run or information related this? breeze-sequelize still maintained. looking advice regarding issue. in advance. we planning update latest sequelize "soon". next month.

memory management - When ARC is triggered in the lifecycle of an iOS app? -

this question has answer here: autorelease pools , when release called under ios 3 answers the arc used in ios , object automatically deallocated when reference count 0. in example of swift book, code sets var nil in order make reference count 0. in real ios app, may not purposely set nil release memory unless object large. my question is, when deallocation in arc happen in lifecycle of app? considering 2 cases: if segue 1 viewcontroller next viewcontroller, first viewcontroller deallocated automatically? assume not retain copy in next viewcontroller. if ios somehow killed our app, needs memory or something, clear memory used our app? or set nil , trigger arc finish work? if there strong reference cycle in code, there memory leakage in case? its answered here, first view controller not deallocated if pushes/presents controller. if ios kills app, m

can not resolve method setText(java.lang.String[])- Android Studio -

i don't know why getting error in android studio, quite simple command executing. code provided below. appreciated. getting error in last line of code. string[] sadthought = {"a", "sad", "thought"}; string[] sadrandom ={(sadthought[new random().nextint(sadthought.length)])}; tvsad.settext(sadrandom); simply use tvsad.settext(sadthought[new random().nextint(sadthought.length)]);

php regex optional field -

i seem have confused myself preg_match regex i'm doing, fresh eyes , appreciated. my current regex follows: "#table.*?stream status:.*?<b>stream @ (.*?) kbps (.*?) of (.*?) listeners</b>.*?listener peak.*?<b>(.*?)</b>.*?stream name.*?<b>(.*?)</b>.*?content type.*?<b>(.*?)</b>.*?stream genre.*?<b>(.*?)</b>.*?stream url.*?<b>(.*?)</b>.*?current song.*?<b>(.*?)</b>.*?</table#si" but columns not given, best solution mark field optional? the table looks like: http://pastebin.com/wbrxhjdp any advice nice ;-) you shouldn't use regular expressions parse html. here's quick script create array filled keys , values: <?php $str = <<< endl <table cellpadding="2" cellspacing="0" border="0" align="center"> <tr> <td width="120" valign="top">server status: </td>

java - FileSystem.mkdirs() return code -

does know when filesystem.mkdirs() returns false ? return false when folder creation fails no error thrown, , if so, can give me example of occasion when occur? returns true when creation succeeds , throws exception under conditions (ie. ioexception due insufficient permissions). however, returns true if directory trying created exists. thanks.

javascript - Changing Coordinate string into a float -

i have geo coordinate json file {"location": "5.554565999999999,-0.2302829999999858"} i know how can convert float before using in google map. i glad if can me, thank you. one way (there many): var coords = json.location.split(','); var latlng = new google.maps.latlng(parsefloat(coords[0]), parsefloat(coords[1])); example fiddle code snippet: var geocoder; var map; var json = { "location": "5.554565999999999,-0.2302829999999858" }; function initialize() { var map = new google.maps.map( document.getelementbyid("map_canvas"), { center: new google.maps.latlng(37.4419, -122.1419), zoom: 13, maptypeid: google.maps.maptypeid.roadmap }); var coords = json.location.split(','); var latlng = new google.maps.latlng(parsefloat(coords[0]), parsefloat(coords[1])); map.setcenter(latlng); var marker = new google.maps.marker({ position: latlng,

php - ISPConfig Bulk Mail add with SOAP fails with domain does not exists although it does exist -

i tried adding mailadresses saved in txt file, 1 per line, following code <?php require 'soap_config.php'; $datei = "address.txt"; // name der datei $adresse = file($datei); // datei in ein array einlesen $client = new soapclient(null, array('location' => $soap_location, 'uri' => $soap_uri, 'trace' => 1, 'exceptions' => 1)); try { if($session_id = $client->login($username, $password)) { echo 'logged successfull. session id:'.$session_id.'<br />'; } foreach ($adresse $zeile) { //* set function parameters. $client_id = 1; $params = array( 'server_id' => 1, 'email' => $zeile, 'login' => $zeile, 'password' => 'password1!', 'name' => $zeile, 'uid' => 5000, 'gi

mysql - Joining two tables to count and list and sort -

table1: keywords itemid kwtype kwvalue 1 brand nike 2 brand nike 1 type soccer 4 brand adidas table2: items itemid siteid categoryid itemname 1 0 10 shoe1 2 0 10 shoe2 3 2 55 shoe3 4 1 11 shoe4 i have these 2 tables (who of course lot bigger) how proceed know 10 occurring brands in site = 0 , category = 10? want list top 10 (top 10 occurring brands) in 1 column , in other column want count how many times appear thanks first of all, should adjust data model. work lot more efficiently , easier understand table: brands id itemid brandname 1 1 nike 2 2 nike 3 4 adidas table: types id itemid typename 1 1 soccer table: items id siteid categoryid itemname 1 0 10 shoe1 2 0 10 shoe2 3 2 55 shoe3 4 1 11 shoe4

c# 6.0 - Can one install a vNext (C# 6) console app as a Windows service -

in previous versions of .net, there different methods of creating project run console app or installed service. things topshelf or other approaches like: .net console application windows service this nice convenience development , later deployment. put vnext console app using similar approach accepted answer here: .net console application windows service . issue vnext runs things in different way. if create output, no longer gives exe install. instead nuget package , .cmd file tell dnx host application. command file looks like: dnx --appbase "$(dirname $0)" microsoft.framework.applicationhost my.vnext.service $@ so question is: there way install thing windows service given new console application approach?

How to generate an key-values inversed object in JavaScript? -

update i have adjusted/corrected example objects, because contained error before. i have mapping object looks this: var atob = { "amore" : "love", "alimenti": "food", "bier" : "beer" }; which allows map 1 way i.e. atob["love"] yields "amore" . add inverse manualy i.e. var btoa = { "love": "amore", "food": "alimenti", "beer": "bier" }; anyway troublesome 2 objects in sync , create btoa programmatically in javascript. there sort of function xyz() yields var btoa = xyz(atob); ? the example above can extended include problem (e.g. if have "beer" ) var atob = { "amore" : "love", "alimenti": "food", "bier" : "beer" "cerveza" : "beer", "pivo" : "beer", "birra" : "beer&quo

php - How do the "And" and "Or" keywords behave in ASP when comparing numbers? -

i need convert old authentication code asp php. in code being used encrypt / decrypt passwords stumbled upon lines this char2 = mid(sbase_64_characters, (((byte2 , 240) \ 16) or (savebits1 * 16) , &hff) + 1, 1) i wonder how translate kind of code, how deal (number , number) part. unfortunately there isn't easy way convert without spending time. there neat tool can use here ... you'll have read comments in converted code tell there assumptions -- such user functions aren't defined.. there you'll need write own or try figure out. but, directly answer question, bitwise operations , can done such byte2 & 240

ajax - PHP upload files to server script doesnt upload everything -

i'm using php , ajax upload files server, can upload txt files, images, docs, zips,pdf... uploaded pdf of size 15m b when tried upload txt size 14mb script crashed here code <form id="form" action="db/upload.php" method="post" enctype="multipart/formdata"> <input type="file" name="filetoupload" id="file">\ <input type="submit" value="upload image" name="submit" id="">\ </form> javascript //click event upload new file button $('#edit_window .file_container').on('submit', '#form', function(e) { e.preventdefault(); //code uploading file //get file data var file_data = $("#file").prop("files")[0]; var form_data = new formdata(this); form_data.append('file', file_data); form_data.append('link', id); $.ajax({ type: 'post',

ios - Swift NSUserDefault for TableView with Multiple Sections? -

i'm doing xcode project (swift) , have few problems relate nsuserdefault , prepareforsegue. i have 2 tableviews. tableview1 has 2 sections: section1 , section2. here want: when click random row in section1 in tableview1, tableview2 shows number of sections want. (for example: click row 1 tableview2 shows 3 sections, click row 2 tableview2 shows 4 sections, number of sections show in tableview2 have different when click different rows) same above section2 in tableview1 i use array of 2 arrays show 2 sections in tableview1. sorry if question stupid, i'm new programming hope guys can show me how project. appreciate :) background in order make answer clearer, assuming have 2 view controllers, table1viewcontroller , table2viewcontroller , display table1 , table2 . assume know how wire 2 view controllers in interface builder can click on table1 , have table2viewcontroller presented. describe in question, when user clicks on row in table1 determines ho

javascript - binding radio buttons to ng-model with angularjs -

so relevant part of html-code. tried binding "formfriendsall" scope ng-model. <form ng-submit="submitform()" > <div class="col-sm-3"> <div class="form-group"> <label>which persons show?</label> <div class="radio"> <label> <input type="radio" name="friendsall" ng-model="formfriendsall" value="friends" > friends </label> </div> <div class="radio"> <label> <input type="radio" name="friendsall" ng-model="formfriendsall" value="alle"> </label> </div> <div>currently selected: {{formfriendsall}}</div> </div> </div><td><input type="submit" class="btn btn-p

web scraping - How to identify a request's crucial information that needs to be sent? -

i wanted scrape fares this website uses requests autocompletion. this code: import scrapy scrapy.http import request, formrequest import urllib class cabforcespider(scrapy.spider): name = 'cabforce' start_urls = ['https://www.cabforce.com'] complete_url = 'https://www.cabforce.com/v1/geo/autocomplete' def parse(self, response): payload = { 'chnl': 'cforce', 'complete': 'barcelona airport', 'destination': 'barcelona' } return request( self.complete_url, self.print_json, method='post', body=urllib.urlencode(payload), headers={'x-requested-with': 'xmlhttprequest'}) def print_json(self, response): print response.body unfortunately response looks this: {"status":"argumenterror","reason":"cannot valida

javascript - How to access a angular `value` outside the module? -

config.js angular.module("steam") .value("config", { baseurl: "http://dev-back1.techgrind.asia/" }); i have access value outside module replacing " http://dev .." config.baseurl test.js var frisby = require("frisby"); frisby.create("status test") .get("http://dev-back1.techgrind.asia/scripts/rest.pike?request=test") .expectstatus(200) .toss(); you might reach outside module these. in opinion use .constant instead of .value constant rest endpoints etc. var config = angular.injector(["ng", "module"]).get("config");

python - How to expose a function which returns a variant vector? -

i'm looking tiny working example of c++ module has method returns variant vector , exposes python (it seems ancient problem, dates 2004 , not find clear answers onwards). i've read this , this , more, still can not find solution. documentation seems throw reader tons of information right away. want tiny working example 1 tiny method returns 1 tiny vector. have now: #include <boost/variant.hpp> #include <boost/python.hpp> #include <vector> using namespace std; using namespace boost:python typedef boost::variant<int> variant; typedef vector<variant> vector; class some{ private: int idx; public: some(...){ ... } //not important vector mymethod(){ return vector{1}; } }; boost_python_module(some){ class_<vector>("vector").def(vector_indexing_suite<vector, true>()); class_<some>("some", init ... //not important .def("mymethod"

sap - How to add headers to odata get service -

i working on following odata service: https://10.49.78.69:8083/gateway/odata/sap/soa_login_get_data;v=1/inspectionset this service runs when following 4 headers defined. interfaceid adfca_crm_sbl_023 languagetype enu / ara username sheenar password sheenar#123 i have tried using filters follows no success. [ https://10.49.78.69:8083/gateway/odata/sap/soa_login_get_data;v=1/inspectionset ?$filter=username eq 'sheenar' , password eq 'sheenar#123' , interfaceid eq 'adfca_crm_sbl_023' , languagetype eq 'enu' guess headers have declared specifically. kindly suggest how these headers can written while setting data model in sap ui5. after creating instance odatamodel , var odatamodel = new sap.ui.model.odata.odatamodel(sserviceurl, mparameters); odatamodel.setheaders(mheaders) parameters: {object} mheaders :the header name/value map. read more here

c# - Autofac Resolve Open Generic Interface with Open Generic Class -

so have interface , class: public interface imyinterface<t> t : isomeentity {} public class myclass<t> : imyinterface<t> t : isomeentity {} i have class calls it: public class someclass : isomeclass { public someclass (imyinterface<auditentity> myinterface) {} } i've done sorts of things register open generic interface , class no luck. i want like: container.registertype(typeof(myclass<>)).as(typeof(imyinterface<>)); it annoying if have go through , explicitly like: container.registertype<myclass<auditentity>>().as<imyinterface<auditentity>>(); shouldn't trivial? you have use registergeneric method see registration concepts - open generic components something should works : builder.registergeneric(typeof(myclass<>)).as(typeof(imyinterface<>));

c# - After application has finished, why runtime values appear in design mode? -

i have custom descendant of datagridviewcomboboxcolumn following value of items property set in design mode: itema itemb itemc during runtime, i'm changing items property (example): for (int = 0; < items.count; i++) { items(i) = convert.tostring(items(i)) + " changed"; } after close form , return design mode, can see property value set itema changed itemb changed itemc changed i wouldn't believe possible i'm getting. after 5 launches, can see each item suffixed changed changed changed changed changed . i'm changing items once, in method called paint event handler of descendant of datagridviewcomboboxcell . (there no better place hook it, because in constructor, initialization not finished yet items.count = 0 ). most have created new component , used in designer. when design component itself, or forms, code in component or in form not execute. event handlers, method overrides, none of executes.

Java: polymorphism applied to Map generic types -

i want have function (for example) outputs values of map in both cases: map<string, string> map1 = new hashmap<string, string>(); map<string, integer> map2 = new hashmap<string, integer>(); output(map1, "1234"); output(map2, "4321"); and following doesn't seem work: public void output(map<string, object> map, string key) { system.out.println(map.get(key).tostring()); } are not both string , integer of type object ? map<string, string> not extends map<string, object> , list<string> not extend list<object> . can set value type ? wildcard: public void output(map<string, ?> map, string key) { // map value of type // can call tostring because value object system.out.println(map.get(key).tostring()); }

symfony - Doctrine2 / MySQL - Create an auto increment field on multiple columns -

i wanted know if possible have auto increment field based on multiple columns ? here problem : have table stores carts in lines. have unique id each carts want generate unique id each line. can have unique cart id inside line. actually, want same in example mysql doc : http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html +--------+----+---------+ | grp | id | name | +--------+----+---------+ | fish | 1 | lax | | mammal | 1 | dog | | mammal | 2 | cat | | mammal | 3 | whale | | bird | 1 | penguin | | bird | 2 | ostrich | +--------+----+---------+ the id increments within grp column. i'm bit lost primary key / index , don't know if have use these in order generate ids. i tried add symfony entity, didn't generate new column id want. * @orm\table(indexes={@orm\index(name="line_idx", columns={"line_id"})}) thanks help alright, managed want, i'm not sure if it's best way here

java - Check if indexing is exsits (Hibernate Search) -

can check if index files objects exist? start indexing @ stratup, takes long. another idea check whether folder exist. is there better solution? i not quite sure after , actual problem is, let me try answer of questions. can check if index files objects exist? there no api provided search, provided file based index, check whether index exists @ expected location. however, not able tell whether in sync database. i start indexing @ stratup, takes long. if have existing data need build initial index. once have index build can example rely on automatic index updates (when entities created/updated/deleted) or manually rebuild @ given time intervals. whether need rebuild full index using manual approach depends on whether have way of telling entities need re-indexed (eg via last update column in database). bottom line, in control on how date index in relation database. depend on requirements. another idea check whether folder exist. as explained above

string - How do I properly comment a variable definition in GNU Make (damn whitespaces)? -

Image
so want comment variable definitions in makefile in-line. problem make doesn't strip white spaces between definition , comment. here example of mean: opts += -dbla # bla opts += -dblubb # blubb opts += -dend .phony test test: @echo $(opts) the output of is -dbla -dblubb -dend with annoying white spaces between options. want this: -dbla -dblubb -dend how around problem? make string function @echo $(strip $(opts)) strip whitespaces after -dend or before -dbla , not inbetween. dirty hack far @echo $(shell $(opts)) , strips unwanted spaces uses shell call so, introduce other problems, i.e. unwanted shell injection via $(opts) variable. there better way it? simple @echo ($subst ...) doesn't work on mixed whitespaces unless 1 replaces of them reinserts @ - . of course, 'zzz' replaced "impossible" match...

c# - Duplicate parent forms as a result of calling a function from a child form -

in application have parent form , popup form. in popup form when click on button1, application supposed call function , result of function, label has change text. although popup button works, have 2 parent forms; 1 label in default state , 1 label changed result of clicking on button in popup. there way me hide initial parent form? here code i'm using in popup form: public form1 f1 = new form1(); private void button1_click(object sender, eventargs e) { f1.referansyaz = true; f1.show(); } so when change variable "referansyaz" true, call function in form 1 , result of function label in form 1 (or parent form) changes. , f1.show(), opens updated form 1. you can change code , pass method changes label on parent form delegate second form. i'd recommend not pass instance of parent form child form because breaks open-closed principle ... so in main form type: public partial class form1 : form { public action<bool> a

How to solve "Exception in thread "main" java.lang.NullPointerException" -

this question has answer here: what nullpointerexception, , how fix it? 12 answers i'm supposed instantiate object passing double array containing values , invoke methods , results should come out on console. code: public class client { public static void main(string[] args) { rainlog log = new rainlog(1.0,2.0,3.0,4.0,5.0,6.0,7.0,8.0,9.0,10.0); double[] inrangevalues = log.getinrange(0,0); for(int i=0; i<inrangevalues.length; i++) system.out.println(inrangevalues[i]); } } after running appears on console: exception in thread "main" java.lang.nullpointerexception @ comp125.rainlog.getinrange(rainlog.java:73) @ comp125.client.main(client.java:7) i click on: at comp125.rainlog.getinrange(rainlog.java:73) it directs me loop: for(int i=0; i<data.length; i++) which passed junit test not sure why. ne

php - Why custom directive not reflecting changes in its code immediately -

i writing simple custom directive in laravel. whenever make changes in code of custom directive, not reflected in view until i comment directive in view. reload page uncomment directive reload page changes custom directive code in global.php blade::extend(function($value, $compiler) { $pattern = $compiler->creatematcher('molvi'); return preg_replace($pattern, '$1<?php echo ucwords($2); ?>', $value); }); directive call in view @molvi('haji') //this output 'haji' due ucwords($2) //the ucwords() replaced strtolower() @molvi('haji') //this still output 'haji' i converting words uppercase. when lets want use strtolower() instead of ucwords() , have repeat above steps changes reflected. update i have tried clear cache various methods described in this thread still no success. update since no 1 answering question on stackoverflow, have posted on laravel github . note: pasting answer give

algorithm - Reservoir Sampling on large Streams -

i trying implement reservoir sampling algorithm using java. have n streams of data ( readings sensors arriving @ sink node ) of unknown size. sake of simplicity lets assume have 1 stream of unknown size. so 1 of reservoir sampling algorithms suggests create reservoir of size reservoirsize. lets 5. first 5 readings get, store them in reservoir. ok. more , more readings, each reading generate random number 0 reading number , if random number smaller reservoirsize store reading in reservoir[randomnumber]. so lets have reservoirsize = 5 , got 10th reading. generate random number 0 10 , if number smaller 5 wll store reading there random number points. lets random number 3 store reading number 10 in reservoir[3]. public void sample (vector pool, double measurement, int streamindex) { if (streamindex < reservoirsize){ pool.addelement(double.tostring(measurement)); } else if ((randomindex=(int)rannum.nextint((streamindex+1)))<reservoirsize) { poo

Downloading files with multiple extensions on a webpage using mechanize library in Python -

my first question on stack overflow! i'm trying download resumes of job posting website. i've found link leads download, downloads have '.php' ending, , hence don't know extension of file going downloaded (.doc, .docx, .pdf)the relevant last section of link looks this: ("~/resumedownload.php?f=wfeilbbzwg==") i'm logging website mechanize. i've used mechanize login website, , download file: filename = br.retrieve(link.get('href'), os.path.expanduser("~/desktop/job postings/hirist/" + str(i) + ".pdf"))[0] , brings .pdf files , corrupts rest. filename variable .php file. any suggestions? browser.retrieve() returns tuple consisting of filename file written , headers remote server. can use content-type header determine mime type of file , mimetypes module appropriate extension file. finally, rename file. import mechanize import shutil import os.path import mimetypes #url = 'http://stackoverflo

python - Save Scrapy output in individual json objects with while-loop -

i using while-loop scrape several fields on webpage. want save output every iteration of loop in individual json object. this works on machine (scrapy 0.24.6, python 2.7.5), not on ssh server (scrapy 1.0.1, python 2.7.6). want write item pipeline or item exporter ensure every iteration of loop saved single json object when running script on ssh server. this python code: from scrapy.spiders import spider blogtexts.items import blogitem class blogtext1spider(spider): name = "texts1" allowed_domains = ["blogger.ba"] start_urls = ["http://www.blogger.ba/profil/soko/blogovi/str1"] def parse(self, response): position = 1 while response.xpath(''.join(["//a[@class='blog'][", str(position), "]/@href"])).extract(): item = blogitem() item["blog"] = response.xpath(''.join(["//a[@class='blog'][", str(position), "]/@href"])).extract() item[&quo

java - on android, getting xml rsa public key and encrypt a string with it -

i'm developing android app , getting public key server of company work with: pfjtqutlevzhbhvlpjxnb2r1bhvzpnzocfhkrwvotu5pzdhuotluekrgmvo4mdnvtedrszlqwnnfodldd2tis29gv0tgzmt2qtzkodbnwhhpznhqbfziyu8vywm4yupmc1axwvr1rfnhvis3vexql0puvvpynljqqtdpbflmmitvwexis0u2zw1ryzbkdxloavarl0ftmgzmkzywsnzqekhyeedqqnvibwttcmrqdetfv0jczxjzwwnuqvjyt2zsyz08l01vzhvsdxm+pev4cg9uzw50pkfrqui8l0v4cg9uzw50pjwvulnbs2v5vmfsdwu+ the server windows iis 7.5. base64decode give me xml <rsakeyvalue><modulus>vnpxdeenmnid8n99tzdf1z803olgqk9jzse89cwkbkofwkffkva6j80mxxofxjlvhao/ac8ajlsp1ytudsgv+7tlp/jnuzr6rpa7ilyf2+uxlbke6emqc0juynip+/as0ff+60jvpzhxxgpbuhmksrdjtkewbbersycnarrofrc=</modulus><exponent>aqab</exponent></rsakeyvalue> extracting modulu , exponent xml, base64decode them , making spec public key object: publickey pbkey = null; xmlparser parser = new xmlparser(); document doc = parser.getdomelement(publickeystring); element rsakeyvalue = doc.getd

sql - Oracle Update table to set specific attribute value in semicolon separated values -

i have column have values like: email_password+oi8hu907b;new_email+y;email_username+iugbhijhb8 now want update new_email attribute rows has y n without affecting else. please advise. i hate but... update table set column = replace(column,'new_email+y','new_email+n') column '%new_email+y%' you don't need clause if put functional index on table may quicker it

php - symfony2 query builder with multiple databases (doctrine) -

i want join abteilung table in database other access data. here right database abteilung: $manager = $this->getdoctrine()->getmanager('olddb')->getrepository('chrisolduserbundle:bpdepartment'); and old query want change: $result = $this->getdoctrine()->getrepository('kfzbuchungbundle:rent') ->createquerybuilder('r') ->addselect('abteilung') ->addselect('auto') ->join('r.auto','auto') ->join('r.abteilung','abteilung') ->where('r.mietestart >= :date_from') ->andwhere('r.mieteende <= :date_to') ->setparameter('date_from', $date_from) ->setparameter('date_to', $date_to) ->orderby('r.mietestart', 'asc') ->distinct()

javascript - Why plus operator in brackets works differently? -

could please explain why results different? ({} + {}) // = "[object object][object object]" {} + {} // = nan i understand in both cases objects converted strings, why in second case result converted number? from: http://www.2ality.com/2012/01/object-plus-object.html the problem javascript interprets first {} empty code block , ignores it. nan therefore computed evaluating +{} (plus followed second {}). plus see here not binary addition operator, unary prefix operator converts operand number, in same manner number() ... why first {} interpreted code block? because complete input parsed statement , curly braces @ beginning of statement interpreted starting code block. hence, can fix things forcing input parsed expression: ({} + {}) '[object object][object object]'

javascript - Multiple files upload using AJAX -

i'm working on webapp , i'm using multiple files upload, doesn't work ajax. multiple files upload use apache fileupload working after using ajax servletfileupload.ismultipartcontent() returns false. thanks here jsp code : <!doctype html> <html> <head> <meta charset="utf-8" /> <title>envoi des fichiers rnp</title> <script src="js/jquery-1.11.3.min.js"></script> <script src="js/fileupload.js"></script> <link type="text/css" rel="stylesheet" href="css/form.css"> </head> <body> <form id="myform" > <fieldset> <legend>envoi de fichier</legend> <label for="fichier">emplacement du premier fichier <span class="requis">*</span></label> <input type

css - dynamic responsive grid using Suzy -

i'm using susy , want create grid show elements (charts actually) order determined @ runtime (user can change order). problem is, there charts preferably shown wider others. suppose @ width have 6 columns, , have 2 types of charts, small 1 preferably taking 2 columns , wide 1 preferably taking 4 columns. when have small , wide one, want them fill row 2 + 4 columns (meaning wide 1 need have "at 3" specified). when have 2 small ones want them fill row 3 + 3 columns (meaning second 1 need have "at 4" specified). when have 2 wide ones, want them on 2 rows, each taking 6 columns ("at 0"). so let's order 3 small ones, 2 wide ones, 1 small 1 , 2 wide ones, rows this: 3+3 2+4 4+2 6 6 at other widths rules may different. know how use breakpoints / element queries know how apply different scss depending on width. me seems order of wide/small elements must known when writing scss. how can done when order isn

watchkit - 'isReachable' is false when sending message from watch app to iOS app -

i want send instant message ios app watch app. implemented following code in xcode7 beta 4 version , keeping application in foreground in both simulators. here code implemented in watchkit interfacecontroller -(void)willactivate { [super willactivate]; if ([wcsession issupported]) { wcsession *session = [wcsession defaultsession]; session.delegate = self; [session activatesession]; } } -(ibaction)buttonclicked { nsdictionary *applicationdict = [[nsdictionary alloc] initwithobjects:@[@"hi"] forkeys:@[@"key"]]; if([[wcsession defaultsession] isreachable]) { [[wcsession defaultsession] sendmessage:applicationdict replyhandler:^(nsdictionary *reply) { nslog(@"%@",reply); } errorhandler:^(nserror *error) {

java - Calling the sub class method from super class isn't best practice? -

i working on project have abstract class( baseconverter ) 1 abstract method( convert() ) , few concrete methods. 1 important concrete method invokeconverter() call convert() method implemented in subclass. while our code being reviewed other guy, told that, subclass methods shouldn't called superclass , told not best practice. below our class structure. can please tell whether isn't right way do? @named public abstract class baseconverter{ @inject private conversiondriver conversiondriver;//this class responsible return correct subclass object based on type protected abstract string convert(object toconvert); public string invokeconverter(convertertype type, object toconvert){ conversiondriver.getconverter(type).convert(toconvert);//getconverter() return subclass object based on type } .... .... } it design pattern called template method gof. however, should not on apply favors inheritance on composition. de

python - Is there an option to recieve the data from a UI window to a variable? -

i saw possible print data has been written in user interface window, however, when searched in internet, none of options that, retrieve data variable. this simple window code - ' def printtxtfield ( fieldid ): print cmds.textfield( fieldid, query=true, text=true) winid = 'kevsui' if cmds.window(winid, exists=true): cmds.deleteui(winid) cmds.window(winid) cmds.columnlayout() whatusay = cmds.textfield() cmds.button(label='confirm', command='printtxtfield(whatusay)') cmds.showwindow() ' i want retrieve data text field variable, once confirm button pressed. up in cmds.button line, can see in command - 'print txtfield'. know if there option print written in text field, there must option put in variable instead. however, didn't find it.does knows how it? sorry prev. question. you have use partial module pass variable through button command (or lambda function) from functools import partial here same

php - Submenu adding wordpress -

i have wordpress page has following menu layout. primary menu sub menu primary list item i add submenu submenu (submenuception) primary sub menu sub sub menu my current theme doesn't support , how can add via code. can me pointing @ right direction. thanks! added code of themes nav-menu-template: <?php /** * navigation menu template functions * * @package wordpress * @subpackage nav_menus * @since 3.0.0 */ /** * create html list of nav menu items. * * @since 3.0.0 * @uses walker */ class walker_nav_menu extends walker { /** * class handles. * * @see walker::$tree_type * @since 3.0.0 * @var string */ public $tree_type = array( 'post_type', 'taxonomy', 'custom' ); /** * database fields use. * * @see walker::$db_fields * @since 3.0.0 * @todo decouple this. * @var array */ public $db_fields = array( 'parent' => 'menu_