Posts

Showing posts from September, 2011

arduino - NodeMCU MQTT RGB Led control -

i want control adafruit color picker rgb led. code this: string value = (char *)rgbled.lastread; //from adafruit color picker string red = value.substring(1, 3); string green = value.substring(3, 5); string blue = value.substring(5, 7); red.tochararray(charbuff, 1); green.tochararray(charbuff, 1); blue.tochararray(charbuff, 1); long r_val = strtol(red, null, 16); long g_val = strtol(green, null, 16); long b_val = strtol(blue, null, 16); please me this. unable convert hex color code respective rgb values.

AngularJs, Search one array against another -

so have 2 arrays, 1 looks little liek this $scope.users = {id: 1, email: xxx} {id: 2, email: xxx}.... and have one $scope.booking = {id: 20, regid: 2} .... so users being displayed in table @ moment. however if user has booking, want table row have red flag against (cant share table basic ng-repeat) if usersid exists regid in booking array, push user any wicked first of $scope.users , $scope.booking objects not arrays... i make example how know if users has book, heres code , plnkr the magic in foreach , loops. html <!doctype html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>angularjs plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.5.x" src="https...

sql - Oracle ORA-04030 even when using Bind Variables in a LOOP -

i have delete 500 million rows remote table using pl/sql. since undo tablespace cannot handle volume, deletes being done in batches size of 1,000,000 , committed. - reduce hard-parsing using bind variables using following syntax: str := 'delete table@link id >= :x , id < :y'; execute immediate str using start_id, start_id+1000000 and after every invocation, start_id incremented 1000000 till sql%rowcount returns 0 ( 0 ) , end_id ( known ) reached. but process getting ora-0430 follows: ora-04030: out of process memory when trying allocate 16408 bytes (qerhj hash-joi,qerhj bit vector) ora-04030: out of process memory when trying allocate 41888 bytes (kxs-heap-c,temporary memory) note using bind variables there no hard parsing after first execution. one thing range of id @ target. assuming first few rows in increasing order, ids 100,000,000,000 200,000,000,000 50,000,000,000,000,000 50,000,000,000,011,111 on second iteration, ids 200,000,000,000 200,000,1...

javascript - openlayers markers with popup -

i trying display map markers. want ability click these markers such information can displayed (similiar way works in google earth). have map , markers (or features) can not "popup" information work. the js: function init(){ var northsealonlat = [4.25, 52.05]; var centerwebmercator = ol.proj.fromlonlat(northsealonlat); var tilelayer = new ol.layer.tile({ source: new ol.source.osm() }); markerlayer = new ol.layer.vector({ source: new ol.source.vector({ features: [], projection: 'epsg:3857' }) }); var map = new ol.map({ controls: ol.control.defaults().extend([ new ol.control.mouseposition({ coordinateformat: ol.coordinate.createstringxy(3), projection: 'epsg:4326', undefinedhtml: '&nbsp;', classname: 'custom-mouse-position', target: document.getelementbyid('custom-mouse-position'), }) ])...

algorithm - Maximum Depth of Binary Tree in scala -

i'm doing exercise on leetcode using scala. problem i'm working on "maximum depth of binary tree", means find maximum depth of binary tree. i've passed code intellij, keep having compile error(type mismatch) when submitting solution in leetcode. here code, there problem or other solution please? object solution { abstract class bintree case object emptytree extends bintree case class treenode(mid: int, left: bintree, right: bintree) extends bintree def maxdepth(root: bintree): int = { root match { case emptytree => 0 case treenode(_, l, r) => math.max(maxdepth(l), maxdepth(r)) + 1 } } } the error here : line 17: error: type mismatch; line 24: error: type mismatch; know quite strange because have 13 lines of codes, didn't made mistakes, trust me ;) this looks error specific of leetcode problem. assume you're referring https://leetcode.com/problems/maximum-depth-of-binary-tree/description/ perhaps you'...

r - flexible patterns for a factor variable in order to subset a dataframe -

i have dataframe called mydf, simplified below: mydf var1 var2 abc_color1_location1_number1 1000 xyz_color1_location1_number1 100 asd_color2_location2_number1 900 qwe_color1_location1_number2 200 sdf_color2_location1_number2 1100 qwerrrr_ahjkkk_asdfgggg 234 sdf_color1_location2_number1 3577 abc_color1_location3_number1 86544 i want subset dataset flexibly based on var1 example: pattern <- c("abc", "color1", "number1") newmydf <- mydf[grep(paste("_",paste(pattern,collapse="_|_"),"_",sep=""),mydf$var1,ignore.case=t),] my expected result: newmydf var1 var2 abc_color1_location1_number1 1000 however, resulted dataframe being subset pattern "abc" , "color1" only, while want patterns should considered. can please me in case? many in advance! with kind regards, if want elements of pattern considered, mig...

google app engine - cron job throwing DeadlineExceededError -

i working on google cloud project in free trial mode. have cron job fetch data data vendor , store in data store. wrote code fetch data couple of weeks ago , working fine of sudden , started receiving error " deadlineexceedederror: overall deadline responding http request exceeded" last 2 days. believe cron job supposed timeout after 60 minutes idea why getting error?. cron task def run(): try: config = cron.config actual_data_source = config['xxx']['xxxx'] original_data_source = actual_data_source company_list = cron.rest_client.load(config, "companies", '') if not company_list: logging.info("company list empty") return "ok" row in company_list: company_repository.save(row,original_data_source, actual_data_source) return "ok" repository code def save( dto, org_ds , act_dp): try: key = 'fin/%s' % (dto['ticker']) com...

bash - trouble splitting a string by line and colon -

i know how split string such colon using ifs. however, script writing, running command returns me in format of birthday : mon, date, year first day : mon, date, year i want date of birthday. in order that, doing: ifs=: read -r -a datearr <<< "$dates" echo "${datearr[1]}" which ideally print date comes after "birthday :", unfortunately nothing printing. tips? should split string line well? the expected output i'd is: mon, date, year (corresponding birthday field) this tailor made job awk custom field separator: awk -f '[[:blank:]]*:[[:blank:]]*' '{print $2}' file mon, date, year mon, date, year note ifs=: , string left padded spaces: while ifs=: read -r -a datearr; echo "${datearr[1]}"; done < file mon, date, year mon, date, year you can use remove spaces: while ifs=: read -r -a datearr; echo "${datearr[1]//[[:blank:]]}"; done < file...

c - Sending parameter to a #define -

i wonder know possible send parameter #define macro selecting different output for example: #define row(1) lpc_gpio0 #define row(2) lpc_gpio3 #define row(3) lpc_gpio2 then in code create loop sending parameter row(x) this macro syntax doesn't exist. moreover, can't possibly exist , because macros expanded before compiler compiles code. if x isn't compile time constant, there never way determine replace in source code macro invocation. if need index values, use array, e.g. (assuming these constants integers): static int rows[] = { 0, lpc_gpio0, lpc_gpio3, lpc_gpio2 }; writing rows[x] would have effect seem have expected invalid macro syntax.

two way webservice SSL in apache tomcat 8.5.15 -

we have webservice client application deployed in apache-tomcat-8.5.15. 2 way ssl enabled on web service side. webservice trusts request sent client. webservice client deployed in tomcat not trusting cert sent webservice. it ignoring , allowing proceed. we need make sure trusted client. we have enabled certificateverification="required" doesn't work. please advise on configurations required trust client cert. thanks vinoth

Ember.js: use body-parser library in mocking backend with mirage -

i'm developing ember.js application authenticates against oauth2 endpoint. in order mock endpoint, use ember-cli-mirage needs parse http post having content-type of x-www-form-urlencoded . i decided use body-parser npm package in order parse body of request. currently have code in config.js : var urlencodedparser = bodyparser.urlencoded({ extended: false }); this.post('/login', (schema, request) => { }); i know request.requestbody contains data i'd parse, can't find correct way make use of 'urlencodedparser` in order parse data. help appreciated. const requestpayload = json.parse(request.requestbody); headers can found in request.requestheaders . don't need 3rd-party library this.

How to view HTML webpage in a new window? -

folks! have made html file example index.html , wanted in new window or own gui window not browser. new window no borders should display html webpage. should support html, javascript , css. not sure mean 'own gui window not browser'. webpage? android app? iphone app? windows/mac/linux desktop app? maybe check answer if you're trying launch new popup window browser without toolbars etc: open new popup window without address bars in firefox & ie if that's not you're trying need way more specific.

python - tensorflow input pipeline returns multiple values -

i'm trying make input pipeline in tensorflow image classification, therefore want make batches of images , corresponding labels. tensorflow document suggests can use tf.train.batch make batches of inputs: train_batch, train_label_batch = tf.train.batch( [train_image, train_image_label], batch_size=batch_size, num_threads=1, capacity=10*batch_size, enqueue_many=false, shapes=[[224,224,3], [len(labels),]], allow_smaller_final_batch=true ) however, i'm thinking problem if feed in graph this: cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label_batch, logits=model(train_batch))) the question operation in cost function dequeues images , corresponding labels, or returns them separately? therefore causing training wrong images , labels.

spring - Sorting the datatable works only at first time. but then it doesnt work -

there page: <p:datatable id="selectedlimitservicestbl" widgetvar="selectedlimitservicestblvar" var="service" value="#{massorderflowbean.limitservicesbean.limits}" scrollable="true" scrollheight="400" selection="#{massorderflowbean.limitservicesbean.selectedlimitservices}" emptymessage="#{msg['empty.result.message']}" rowkey="#{service.uniquekey}" filteredvalue="#{massorderflowbean.limitservicesbean.filtered}" sortby="#{service.name}" sortfunction="#{massorderflowbean.limitservicesbean.sortbyservicename}"> <p:ajax event="rowselectcheckbox" process="selectedlimitservicestbl" update=":massorderform:toconfirmlimitservices" /> <p:ajax e...

sql - How to filter out intraweek data in PostgreSQL? -

i have query i'm leveraging dashboard visualization. issue query includes data current week - problematic because week not baked. ideally, add filter pulls in data w/in last 52 weeks excludes data date greater recent reporting week (sun - sat). here have: select (date_trunc('week',cj.created_at:: timestamptz) + '5 days':: interval)::date ,case when o.vertical null or o.vertical not in ('auto','franchise') 'smb' else o.vertical end vertical ,count(distinct cj.native_candidate_job_id) applicant_traffic dim_candidate_jobs cj join dim_organizations o on cj.native_organization_id = o.native_organization_id o.demo = false , not(o.name ~~* (array['%test%','%api%'])) , cj.created_at:: date > current_date - interval '52 weeks' , cj.created_at:: date < (date_trunc('week',current_date:: timestamptz) + '1 day':: interval)::date , o....

test double - An example (or several) about method at() in phpunit -

would anybody, please, show me example at method in phpunit test doubles. don't understand purpose? the purpose of at() function specify order methods on mock should called. if use once() or exactly() , test pass no matter order methods called phpunit checking called during test not when. for example: class footest extends phpunittestcase { public function testproperorderofmethods() { $mockobject = $this->getmockbuilder('barobject') ->setmethods(['baz', 'boz']) ->getmock(); $mockobject->expects($this->at(0)) ->method('boz'); $mockobject->expects($this->at(1)) ->method('bar'); $sut = new foo(); $sut->methodbeingtested($mockobject); } this requires our function needs like: public function methodbeingtested($dependecy) { $dependency->boz(); $dependency->bar(); } and fail if...

typescript - What is behind the ‘@’ sign in @angular or @types? -

i trying understand behind ‘@’ sign when see import statements below: import { injectable } ‘@angular/core’; or npm cli commands below: npm -install –save @types/lodash the statements or commands working fine me, want learn happening behind scene of @ sign. is '@' typescript feature? or npm thing? a pointer in-depth online documentation great help. it's npm thing called scoped packages . here official doc : scopes namespaces npm modules. if package's name begins @, scoped package. scope in between @ , slash. all scoped packages stored inside folder begins @ . example, angular packages stored inside @angular folder in node_modules , whereas if there no @ scoped identifier , used angular/core , angular/compiler have separate folder each package. , same holds @types package. how typescript import statement recognizes or integrates '@'? the require function used node can traverse node_modules folder if use forwa...

javascript - JS PopUp windows from different sources -

i need make simple js popup view specific content of each link (team stats). i've got basic html set should popup mentioned content. <!-- start team-players --> <div class="team-players"> <div class="player-profile"> <img data-js="open" src="img/team-ico/team-srsne.jpg" alt="" class="thumbnail"> <span class="number">#1</span> <span class="name">hk sršňe košice</span> </div> <div class="player-profile"> <img data-js="open" src="img/team-ico/team-kvp.jpg" alt="" class="thumbnail"> <span class="number">#2</span> <span class="name">hk kvp represent</span> </div> <div class="player-profile"> ...

internet explorer - XMLHTTP support in IE from JavaScript -

i need know whether " enable native xmlhttp support " option enbaled in internet explorer. how can find out javascript? enable native xmlhttp support means browser not provide msxml.httprequest instead window.xmlhttprequest . there no way can control server side(in jsp). however, can still write javascript check logic around msxml.httprequest , window.xmlhttprequest objects. let write actual logic yourself.

Unable to import Python module written in C -

i have been trying work out how make .pyd (python extension module) file c script (without swig or else except mingw) , have built .pyd . the problem occurs when try , import module. if run module runs (as far can see) , error appears saying python has stopped working , closes without executing rest of program. here c script (test.c): #include <python.h> int main() { pyinit_test(); return 0; } int pyinit_test() { printf("hello world"); } and python script (file.py): import test print('run python extension') i compiled script with: gcc -c file.py gcc -shared -o test.pyd test.c i can't find errors when compiling in command prompt , using python 3.6 (running on windows 10). i can't find on subject , prefer keep away cython (i know c) , swig. any tell me wrong fantastic. creating python extension different writing regular c code. have done creating valid c program doesn't make sense python. that's ...

json - Postman Get Request Set Environment Variable -

i have get request in postman. trying set environment variable objectid response body. here response body fine. { "odata.metadata": "https://graph.windows.net/myorganization/$metadata#directoryobjects/microsoft.directoryservices.user", "value": [ { "odata.type": "microsoft.directoryservices.user", "objecttype": "user", "objectid": "0fjrkfkfc-50b1-4259-a778-sjvmfgr5bhjj", } ] } i have tried following save objectid environment variable not working. appreciated. var jsondata = json.parse(responsebody); postman.setenvironmentvariable("testtoken", jsondata.value[1]); // returns [object object] postman.setenvironmentvariable("testtoken", jsondata.odata.metadata); // returns [object object] postman.setenvironmentvariable("testtoken", jsondata.value); // returns [object object],[object object],[obje...

How to completely skip writing files to disk with libtorrent downloads? -

i have following code download torrent off of magnet uri. #python #lt.storage_mode_t(0) ## tried this, didnt work ses = lt.session() params = { 'save_path': "/save/here"} ses.listen_on(6881,6891) ses.add_dht_router("router.utorrent.com", 6881) #ses = lt.session() link = "magnet:?xt=urn:btih:395603fa..hash..." handle = lt.add_magnet_uri(ses, link, params) while (not handle.has_metadata()): time.sleep(1) handle.pause () # got meta data paused, , set priority handle.file_priority(0, 1) handle.file_priority(1,0) handle.file_priority(2,0) print handle.file_priorities() #output [1,0,0] #i checked no files written disk yet. handle.resume() while (not handle.is_finished()): time.sleep(1) #wait until download it works, in specific torrent, there 3 files, file 0 - 2 kb, file 1 - 300mb, file 3 - 2kb. as can seen code, file 0 has priority of 1, while rest has priority 0 (i.e. don't download). the problem when 0 file finishes download...

python - How to explain the reentrant RuntimeError caused by printing in signal handlers? -

code: # callee.py import signal import sys import time def int_handler(*args): in range(10): print('interrupt', args) sys.exit() if __name__ == '__main__': signal.signal(signal.sigint, int_handler) signal.signal(signal.sigterm, int_handler) while 1: time.sleep(1) # caller.py import subprocess import sys def wait_and_communicate(p): out, err = p.communicate(timeout=1) print('========out==========') print(out.decode() if out else '') print('========err==========') print(err.decode() if err else '') print('=====================') if __name__ == '__main__': p = subprocess.popen( ['/usr/local/bin/python3', 'callee.py'], stdout=sys.stdout, stderr=subprocess.pipe, ) while 1: try: wait_and_communicate(p) except keyboardinterrupt: p.terminate() wait_a...

asp.net - different result when encoding values from web.config -

i trying form basic authentication header getting username , password web.config when these values web.config, base64 string different ones hard coding values straight code. this web.config: <?xml version="1.0" encoding="utf-8"?> <appsettings> <add key="username" value="lowercaseusername"/> <add key="password" value="mixedcasepassword​"/> </appsettings> and code: var username = configurationmanager.appsettings["username"]; var password = configurationmanager.appsettings["password"]; string encodedvalues = `convert.tobase64string(system.text.encoding.utf8.getbytes(username + ":" + password));` i "4ocl" @ end of encoded string when them web.config opposed hardcoded directly values in code your web.config have utf-8 encoding. if copy-pasted password , set web.config encoding iso-8859-1 : <?xml version="1.0...

windows - Settings for CMD's console -

as asked in title i'd know correct console settings path command prompt (cmd). i've found computer\hkey_current_user\console , looks isn't correct one. tried changing values didn't appear in command prompt. i'm trying set console window transparency below 30%. you can not set opacity below 30% because valid range 0x4d-0xff. or 70-255 decimal. more info here

javascript - Chrome Extension androidpublisher packageName -

i have developed chrome extension using in-app-purchases. i've published google web store. now want use androidpublisher api validate purchases made: https://www.googleapis.com/androidpublisher/v2/applications/ {packagename} /inappproducts i unable find out packagename is. there numerous examples apps, not extensions. apps seem have packagename declared somewhere, looking 'com.mystuff.myproduct'. i cannot find such reference anywhere related extension, not in manifest file, google web store, google dashboard, google payments center or google play console. nowhere! have id looks 'abcdefabcdefabcdefabcdefabcdefabcdef'. does know? chrome extensions not android apps. chrome extensions don't have package names. check in-app payments payments merchant account , chrome web store api supported methods , api calls.

php - CodeIgniter- Failed to load resource: the server responded with a status of 500 (Internal Server Error) -

i new codeigniter , i'm trying integrate paypal payment system project have been working on. problem when i'm trying make ajax call make paypal check out getting internal server error 500. and when open controller see error though file still there in folder. a php error encountered severity: warning message: require_once(/home/*******/public_html/application/libraries/paypal-php-sdk/paypal/rest-api-sdk-php/sample/bootstrap.php): failed open stream: no such file or directory filename: controllers/paypal.php line number: 3 but script working fine in local host don't have htaccess. so, not sure going or or for. as understanding code working fine in local , not working in production/live if case, go check permission file/folder if in vendor folder

javascript - Sequelize cannot access alias. Alias is undefined -

Image
aliasname: -1 the value of aliasname -1. aliasname: undefined aliasname giving me undefined. did , worked. posts[0].get('aliasname')

Android MVP: handling changes to RecyclerView -

when using recyclerview in android app, many posts , tutorials have adapter handle managing updates list, using solutions diffutil. not seem follow mvp, however, adapter exists in view layer. so, how can presenter (or model) given responsibility of managing changes list of items displayed recyclerview, while keeping recyclerview date? for example, recyclerview displaying list of available bluetooth devices phone can connect to, each row containing device name , rssi value. presenter wants display devices greatest least rssi value, , wants insert new devices discovered , remove ones no longer available. source 1 , source 2 great starters i've used inplement recyclerviews using mvp, not cover data sets actively change. i think best way use private observablelist list; and later this.observablelist.addonlistchangedcallback(new observablelist.onlistchangedcallback<observablelist<***>>() { @override public void onchanged(o...

windows - How to get ATAPI SMART Data according to disks using C#/.NET -

i want write application monitors status of disk or more disks in system. i found can manage 1 disk via wmi "root/wmi" , msstoragedriver , query these actual values (data , threshold), followed below link - http://wutils.com/wmi/root/wmi/msstoragedriver_atapismartdata/ far, worked :-) however, have not managed multiple disks until now. don't know how smart data according disks could me resolve issue? many thanks, quyen i tried , succeed, share answers issue get pnpdeviceid get instancename of pnpdevice accordingly get s.m.a.r.t data instancename example code public string pnpdeviceid { set { this.m_pnpdeviceid = value; this.instancename = null; this.queryobjatapismartdata = null; searcherpnpdeviceid = new managementobjectsearcher("root\\wmi", "select * mswmi_pnpdeviceid"); foreach (managementobject queryobj in searcherpnpdeviceid.get())...

java - Apache Ignite - Why InteliJ is not recognizing Kafka dependency? -

Image
currently have pom mvn file in intelij , part - recognizes apache ignite dependencies not kafka one. this dependency part in pom: <!-- apache ignite dependencies --> <dependency> <groupid>org.apache.ignite</groupid> <artifactid>ignite-core</artifactid> <version>2.1.0</version> </dependency> <dependency> <groupid>org.apache.ignite</groupid> <artifactid>ignite-spring</artifactid> <version>2.1.0</version> </dependency> <dependency> <groupid>org.apache.ignite</groupid> <artifactid>ignite-indexing</artifactid> <version>2.1.0</version> </dependency> <dependency> <groupid>org.apache.ignite</groupid> <artifactid>ignite-log4j</artifactid> <version>2.1.0</version> </dependency> <depe...

Positioning in Xamarin Forms with Repeater, Relative view and scroll -

Image
i have problem setup proper layout xamarin forms i need have layout in buttons generated repeater. area must scrollable 3 buttons visible @ moment height of repeater/3, , filling whole area, rest scrolled. buttons need have same height (repeater/3). dont know number of buttons i have <scrollview horizontaloptions="fillandexpand" verticaloptions="fillandexpand" grid.row="3" grid.rowspan="2" grid.column="1" backgroundcolor="red"> <relativelayout x:name="xname"> <controls:repeaterview itemssource="{binding buttons}" x:name="test" relativelayout.widthconstraint="{constraintexpression type=relativetoparent,property=width,factor=1,constant=0}" relativelayout.heightconstraint="{constraintexpression type=relativetoparent,property=height,factor=1,constant=0}"> <controls:repeaterview.ite...

vba - How to copy multiple charts from Excel and embed it to PPT? -

i know question has been posted few times, still having issues. i relatively new vba, please bare me! i trying copy , paste multiple charts sheet in excel slide in powerpoint. have: public sub createmanagmentpres() dim ppapp powerpoint.application dim pppres powerpoint.presentation dim ppslide powerpoint.slide dim pptextbox powerpoint.shape set ppapp = new powerpoint.application ppapp.visible = true ppapp.activate set pppres = ppapp.presentations.add 'summary of assumptions (cont'd) set ppslide = pppres.slides.add(6, pplayouttitleonly) ppslide.select ppslide.shapes(1).textframe.textrange.text = "summary of assumptions (cont'd)" activeworkbook.sheets("case summary").chartobjects("chart rev").copy pppres.slides(6).shapes.pastespecial(datatype:=pppasteoleobject, _ link:=msotrue) end ppslide.shapes(2).top = 70 ppslide.shapes(2).left = 11 activeworkbook.sheets("case summary").chartobjects("chart lev").copy pp...

vba - Salesforce Search Automation -

i have list of names, companies, , emails. info in 1 companies' account, , i'm trying have account owner correlated , pasted column next company name. example: __name_ | email address | company | account owner | link account john smith | js@mail.com | excelx.inc | ____________ | __________ i'd macro search company name paste link of search in link account column. so far, i'm playing around code: sub dobrowse() mystr = cells(1, 1).value activeworkbook.followhyperlink _ address:="https://www.(salesforce link)/?q=" & mystr, _ newwindow:=true end sub this has been working fine 1 cell, how automate whole column , copy link?

How to stop Bitbucket and Git LFS file Duplication -

i using bitbucket , git lfs store binary files project working on. have found run out of storage , cause seems each time push change lfs add new file server instead of overwriting file. have particular file around 400 mb , if push can see in file storage more once. is there way stop behavior , instead overwrite file, or there easy process purge old files before pushing? very similar post (with no answer): git lfs tracking old data

Index out of range appears sometimes and disappears when i run again python -

import numpy import matplotlib.pyplot plt import serial v=[] i=[] p=[] count=0 arduinodata=serial.serial('/dev/ttyacm0',9600) # importing serial data a=input('enter no of observation required = ') # user choice required no of observations while count<a: count=count+1 while(arduinodata.inwaiting()==0): pass arduinostring=arduinodata.readline() data=arduinostring.split(",") voltage = float(data[0]) current = float(data[1]) power = float(data[2]) v.append(voltage) i.append(current) p.append(power) print v,",",i,",",p #plt.plot(v)`enter code here` #plt.show() #plt.ylim([150]) i error off , on code works fine , index out of range i'm confused why have started learning python programming have checked string make sure has 3 comma separated elements? if doesn't may need treat malformed , throw away.

Wordpress plugin + phpunit testing -

i new in wordpress developement, have own custom wordpress plugin allows admin click multiple author , save meta tag in database on post. works fine. want generate test case that. installed phpunit don't know how write test case. public function testone() { $this->factory->post->create(); } i tried not understand how works.

Python- pull csv from ftp url with credentials -

newb python , working apis. source create ftp url dumping files on daily basis , grab file perform engineering + analysis. problem is, how specify username , password pull csv? import pandas pd data = pd.read_csv('http://site-ftp.site.com/test/cat/filename.csv) how include credentials this? ps- url fake sake of example. you use requests.get() download csv data memory. use stringio make data "file like" pd.read_csv() can read in. approach avoids having first write data file. import requests import pandas pd io import stringio csv = requests.get("http://site-ftp.site.com/test/cat/filename.csv") data = pd.read_csv(stringio(csv.text)) print(data)

c# - How do I use reflection to call a generic method? -

what's best way call generic method when type parameter isn't known @ compile time, instead obtained dynamically @ runtime? consider following sample code - inside example() method, what's concise way invoke genericmethod<t>() using type stored in mytype variable? public class sample { public void example(string typename) { type mytype = findtype(typename); // goes here call genericmethod<t>()? genericmethod<mytype>(); // doesn't work // changes call staticmethod<t>()? sample.staticmethod<mytype>(); // doesn't work } public void genericmethod<t>() { // ... } public static void staticmethod<t>() { //... } } you need use reflection method start with, "construct" supplying type arguments makegenericmethod : methodinfo method = typeof(sample).getmethod("genericmethod"); methodinfo generic = m...

opencv - How to capture the contents of a specific window with python? -

i'm doing project requires me capture contents of particular window. till placing window on specific place on screen , taking screenshot of part of screen using mss library in python. using image further processing using opencv. i wondering if there better way contents of window image.

Twilio hangupOnStar problems -

when using hanguponstar within 'dial' user input not processed. instead found warning in twilio 'error , warning notifications' concerning corresponding http request: attribute 'hanguponstar' not allowed appear in element 'dial'. so... hanguponstar possible combine 'dial' or not? has solved problem? heared there maybe problems international conference calls in combination hanguponstar?

multithreading - Python pool.map for list of tuples -

i've got following issue. i'm trying refactor code in order process api calls using multithreading. core data simple list of tuples in following format: lst = [('/users/sth/photo1.jpg', '/users/sth/photo2'), ('/users/sth/photo1.jpg', '/users/sth/photo3'), (...)] function use takes lst list , process through api requires pair of photos. after single number returned each pair. far, i'm using loop put tuple function , produce mentioned number. paralellize whole computation in way 1 process takes part of list , calls function tuples inside batch. trying use pool function multiprocessing module: from multiprocessing.dummy import pool threadpool pool = threadpool(2) results = pool.map(score_function, lst) however, following error occurs: ioerror: [errno 2] no such file or directory: 'u' something strange happening here. tries treat single character tuple argument. ideas how properly? thank you @edit ...

How to enable Web Bluetooth on Samsung Internet browser? -

samsung has announced internet beta v6.2 web bluetooth . how enabled? navigate internet://flags/#enable-web-bluetooth enable it, restart. try simple sample, such device info .

xgboost importance plot (ggplot) in R -

Image
i have plotted importance matrix in xgboosot , want make text bigger, how do that? gg <- xgb.ggplot.importance(importance_matrix = a,top_n = 15) use theme() increased font size. below, have given minimum reproducible example; # load library library(ggplot2) require(xgboost) # load data data(agaricus.train, package='xgboost') data(agaricus.test, package='xgboost') train <- agaricus.train test <- agaricus.test # create model bst <- xgboost(data = train$data, label = train$label, max.depth = 2, eta = 1, nthread = 2, nround = 2, objective = "binary:logistic") # importance matrix imp_matrix <- xgb.importance(colnames(agaricus.train$data), model = bst) # plot xgb.ggplt<-xgb.ggplot.importance(importance_matrix = imp_matrix, top_n = 4) # increase font size x , y axis xgb.ggplt+theme( text = element_text(size = 20), axis.text.x = element_text(size = 15, angle = 45, hjust = 1)) use ?theme see list of parameters...

angular - Passing arbitrary data to a child directive -

i using wijmo's wjflexgriddetail directive, , want control rows display detail grid based on whether "detaildata" array in component contains matching data. rowhasdetail property takes function uses outer grid's row input , returns boolean. want this: <ng-template wjflexgriddetail let-item="item" [rowhasdetail]="hasdetail"> hasdetail (row): boolean { return this.detaildata.filter(item => item.id === row.dataitem.id).length > 0 } // detaildata undefined when try but doesn't work because this in scope of function refers wjflexgriddetail object, doesn't contain data i'm trying check against. tried binding data attribute: <ng-template wjflexgriddetail let-item="item" [rowhasdetail]="hasdetail" [attr.data-detail]="detaildata"> but got error: uncaught (in promise): error: template parse errors: property binding data-detail not used directive on embedded template. m...

python - Why A star is faster than Dijkstra's even the heuristic is set to be None in the networkx -

this update version of previous question. run 2 algorithm in networkx between 2 point (you can try on of network) in jupyter notebook. result shows astar faster, when heuristic none. suppose 'none' means dijkstra. wrong? import osmnx ox import networkx nx g = ox.graph_from_place('manhattan, new york, usa', network_type='drive') #change simple network in order run astar g_simple=nx.graph(g) dijkstra: %%time nx.dijkstra_path(g_simple, 42434910, 595314027, weight='length') #the node random selected nodes in graph the computation time is: cpu times: user 15.4 ms, sys: 1.86 ms, total: 17.2 ms wall time: 17.1 ms astar: %%time nx.astar_path(g_simple, 42434910, 595314027, heuristic=none, weight='length') the computation time is: cpu times: user 8.8 ms, sys: 313 µs, total: 9.12 ms wall time: 9.18 ms the dijkstra implementation networkx using doesn't stop when reaches target node. a* implementation does.

JavaScript (TypeScript/Angular): Shortest/Fastest method to set object keys/values based on previous logic? -

i'm attempting fill array objects objects same, , keys determined predefined item. know can multiple if...else, seems long method use , hoping more condensed and/or efficient without using external libraries. current method fill array hardcoded objects: fillarray(arr,n) { while(arr.length < n) { arr.push({ 'x': math.round(math.random(), 'name': 'item' + arr.length + 1 }); } } example of i'd achieve using if: fillarray(arr, n, type) { while(arr.length < n) { if ( type === 'type1' ) { arr.push({ 'x': math.round(math.random(), 'name': 'item' + arr.length + 1 }); } else if ( type === 'type2') { arr.push({ 'x': math.round(math.random(), 'y': math.round(math.random(), 'name': 'item' + arr.length + 1 }); } } } in application use type of method dozen if items, , the...

Elasticsearch get all parents and children -

i have elastic search mapping parent , child documents. can one-to-many have created one-to-one relationship between parent , child. reason relationship instead of nested documents children updated , can avoid touching parent documents everytime. avoid creating deleted documents of parent doc type taking 70% more space required before merge happens. now have query returns list of parent documents. want retrieve children parent list. is possible parents , associated children same query instead of running separate query children of each parent?

Writing Hive table from Spark specifying CSV as the format -

i'm having issue writing hive table spark. following code works fine; can write table (which defaults parquet format) , read in hive: df.write.mode('overwrite').saveastable("db.table") hive> describe table; ok val string time taken: 0.021 seconds, fetched: 1 row(s) however, if specify format should csv: df.write.mode('overwrite').format('csv').saveastable("db.table") then can save table, hive doesn't recognize schema: hive> describe table; ok col array<string> deserializer time taken: 0.02 seconds, fetched: 1 row(s) it's worth noting can create hive table manually , insertinto it: spark.sql("create table db.table(val string)") df.select('val').write.mode("overwrite").insertinto("db.table") doing so, hive seems recognize schema. that's clunky , can't figure way automate schema string anyway. that because ...

python - My buttons sit side by side in my Home window but they appear in the middle. How do I get them higher up? -

Image
i having similar issue shop class too. first button (teapops) want buttons on home window , shop window (except home) if use: button1.pack(side=top, anchor=nw, padx=10, pady=60, expand=no) button2.pack(side=top, anchor=nw, padx=30, pady=60, expand=no) button3.pack(side=top, anchor=nw, padx=60, pady=60, expand=no) but others appear lower , lower , don't have idea why except maybe have issue frames? if use this, button1.pack(side=left, anchor=nw, fill=both, expand=1) button2.pack(side=left, anchor=nw, fill=both, expand=1) button3.pack(side=left, anchor=nw, fill=both, expand=1) then buttons appear side side in middle of screen again on home screen: can please explain me whats going on? think there basics frames not understanding. please help!!!! import tkinter tk tkinter import * title_font = (“helvetica”, 18, “bold”) credits_font = (“helvetica”, 12, “bold”) class app(tk.tk): def __init__(self, *args, **kwargs): ...

sql server - Visual Studio 2017 15.3 Dockerize Database Project -

have visual studio 2017 (15.3) solution 2 projects: an api written in asp.net core 2 mvc database project i able "dockerize" mvc project (right click, add docker support) while trying dockerize database project keep getting error: value cannot null. parameter name: stream . google-fu failing me; closest resource found visual studio 15.2 . how i've setup database project far added dockerfile root: from microsoft/mssql-server-linux:latest expose 1433 env accept_eula=y env lang en_us.utf-8 env language en_us:en env lc_all en_us.utf-8 env mssql_tcp_port=1433 # add database project output vs build process run mkdir --parents /_scripts/generated copy ./_scripts /_scripts/ copy ./_scripts/generated/*.sql /_scripts/generated/ # add shell script starts mssql server, waits 60 seconds, executes script build out db (script generated vs build process) cmd /bin/bash /_scripts/entrypoint.sh modified docker-compose.yml file include new project version: '3' ...

java - What is the best way to read pixels of a JavaFX Canvas? -

Image
i want color specific coordinates inside canvas . tried getting snapshot using code: writableimage snap = gc.getcanvas().snapshot(null, null); snap.getpixelreader().getargb(x, y); //this gets color without assigning it. but takes time application. wondering if there other way access color of pixel know coordinates. a canvas buffers drawing instructions prescribed invoking methods of graphicscontext . there are no pixels read until canvas rendered in later pulse , , internal format of instruction buffer not exposed in api. as alternative, consider drawing bufferedimage , illustrated here , allows access image's pixels directly , via writableraster . adding following line complete example outputs expected value opaque red in argb order: ffff0000 . system.out.println(integer.tohexstring(bi.getrgb(50, 550)));

go - Golang exec.Command() error - ffmpeg command through golang -

currently working ffmpeg command edit video ffmpeg -i "video1.ts" -c:v libx264 -crf 20 -c:a aac -strict -2 "video1-fix.ts" when enter in terminal, works. when try use golang exec.command() func, err response of &{/usr/local/bin/ffmpeg [ffmpeg -i "video1.ts" -c:v libx264 -crf 20 -c:a aac -strict -2 "video1-fix.ts"] [] <nil> <nil> <nil> [] <nil> <nil> <nil> <nil> <nil> false [] [] [] [] <nil> <nil>} here below code cmdarguments := []string{"-i", "\"video-1.ts\"", "-c:v", "libx264", "-crf", "20", "-c:a", "aac", "-strict", "-2", "\"video1-fix.ts\""} err := exec.command("ffmpeg", cmdarguments...) fmt.println(err) am missing command syntax? not sure why not loading videos as @jimb says, exec.command not return error....

c++ - Has this vector occured before -

i have lot of vectors (in order of 10^4, more!) , getting more vectors in input stream. so, example, have v1 = 1 0 4 1 1 v2 = 1 1 2 5 3 6 2 v3 = 0 1 1 5 0 i have 10^4 such vectors now, in input vector v4 = 0 1 1 5 0 , , want check if has appeared before or not, how suggest me this? i list techniques have thought of, , errors accompany them: to use std::map , or std::set same. but, std::map std::set not support vector argument. to convert every integer in vector string type, append them in order , store string in map. error: case of v5 = 11 1 1 1 , v6 = 1 1 1 1 1 shown same. similiar above, add delimiter after every integer. error: tedious code? i wished know if can think of method achieve this? edit: 10^4, it's achievable. new task requires me store upto 10^9. don't think stl have space, have thrown sigabrt error. know other efficient hashing method can work in case? the simple method of doing store vectors in vector, , maintain o...