Posts

Showing posts from February, 2015

c++ - "Project.exe has triggered a breakpoint" after implementing multithreading -

i have visual studio project worked fine until tried implement multithreading . project acquires images gige camera, , after acquiring 10 images, video made acquired images. the program flow such program didn't acquire images when making video. wanted change this, created thread makes videos images. wanted program acquire images continuously, after 10 images acquired, thread runs in parallel make video. continue until stop program, 10 images acquired, video these 10 images made in parallel while next 10 images acquired , on. i haven't created threads before followed tutorial on this website . similar website, created thread function saves video. function creates video takes 10 images vector argument. execute join on thread before line main function terminates. for clarity, here's pseudo-code i've implemented: #include ... #include <thread> using namespace std; thread threads[1]; vector<image> images; void thread_method(vector<image...

Advanced editing commands for Visual Studio -

in recent years used both visual studio , idea-family ides (webstorm , phpstorm), , there several text editing commands miss in vs. example, command expand selection next sub-expression containing cursor. are there visual studio extensions provide kind of commands?

scala - Reference to container for an item in the container -

in small library i'll try write, end user-facing part looks this: case class box(is: item*) case class item(data: int) box(item(0), item(1)) ideally, however, each item should know in box is: case class item(data: int, box: box) is there way establish bidirectional connection immutable case classes? tried avoid this... val box = box() val = item(0, box) box.add(i) // requires var in box :( or this: val = item(0, none) // requires option :( val box = box(i) i.box = some(box) // requires var in item :( ...by using lazy , implicits couldn't come solution. possible @ all? from following question, learned pass-by-name + lazy useful, still, box required passed explicitly: [ scala: circular references in immutable data types? . goal make end user-facing part simple/slim possible, behind scenes magic required used :) you this: case class box(is: (box => item)*) { lazy val items = is.map(_(this)) } class item(val data: int, val box: box) object ite...

Is there an idiom or API for synchronized shuffling of Python arrays? -

is there api in numpy (or perhaps tensorflow) performing synchronized shuffling of several arrays (with same first dimension)? for example, if 2 arrays dimensions (n, a) , (n, b), , want randomize ordering of n elements of each, while maintaining association between elements of first array , second. is there api or python idiom accomplishing this? note combining these single array of n tuples shuffled random.shuffle might option i'd accept answer, can't work: getting original arrays (as near i've managed) messy since combined_array[:,0] have dimension (n,) objects elements, rather dimension (n, a), unless manually rebuilt like [x x in combined_array[:,0] permutation = numpy.random.permutation(n) arr1_shuffled = arr1[permutation] arr2_shuffled = arr2[permutation] pick 1 permutation , use both arrays.

Making a bot for the game HaxBall in python using OpenCV, need help in emulating the key presses according to its physics -

i have been working on haxball bot. don't know haxball is: simplistic football game (or soccer) in control circle , try shoot ball in goal, can play here . making bot simulate human using opencv image processing detect player , ball. program quite nicely. the next step move player, have used pyautogui move player around. want player move 1 coordinate , here problem lies. i able move object in bumpy way alternating between keydown , keyups, want smooth motion decided use kinematics , found player velocity , hence found time key down. player still overshoots , needs move back. physics of haxball such objects (player , ball) slide on field , acceleration of objects not constant. would recommend better approach movement problem. code can found here . def emulate(): epsilon = 1e-5 starttime = time.time() # x,y = coords final position # buffer = acceptable error x,y,buffer = 276,132,40 # dict time how long press key presskeys = {"w": 0....

postman - Asp.net core seems to ignore the Accept:"application/xml" header for my custom formatter -

the api i'm building returns json everywhere, need return xml custom formatter. i created custom formatter (i didn't copy writeresponsebodyasync keep shorter) public class xmloutputformatter : textoutputformatter { public xmloutputformatter() { supportedmediatypes.add(mediatypeheadervalue.parse("application/xml")); supportedencodings.add(encoding.utf8); supportedencodings.add(encoding.unicode); } protected override bool canwritetype(type type) { return true; // tried doing force work on type, // don't think it's needed } public override bool canwriteresult(outputformattercanwritecontext context) { if (context == null) throw new argumentnullexception(nameof(context)); return context.contenttype.tostring() == "application/xml"; } } it works when have [produces("application/xml")] on controller method, when d...

java - Is there an advantage to use a Synchronized Method instead of a Synchronized Block? -

can 1 tell me advantage of synchronized method on synchronized block example? can 1 tell me advantage of synchronized method on synchronized block example?thanks. there not clear advantage of using synchronized method on block. perhaps 1 ( wouldn't call advantage ) don't need include object reference this . method: public synchronized void method() { // blocks "this" here.... ... ... ... } // here block: public void method() { synchronized( ) { // blocks "this" here .... .... .... .... } // here... } see? no advantage @ all. blocks do have advantages on methods though, in flexibility because can use object lock whereas syncing method lock entire object. compare: // locks whole object ... private synchronized void someinputrelatedwork() { ... } private synchronized void someoutputrelatedwork() { ... } vs. // using specific locks object inputlock = new object()...

Vim copy and paste between remote vim instances using tmux -

working on remote server cannot copy , paste between 1 vim instance , another. have installed gvim +clipboard, along xclip. use tmux split panes, , work concurrently. in vimrc set clipboard+=unnamedplus i tried copying y , "+y , "*y, , paste p, "*p, "+p, , ctrl+shift+v. i'm confused why not working now, maybe x11 problem. robust way can set copy , paste between 2 panes on remote tmux? i have been using " copy paste on system clipboard function func2x11() :call system('xclip -selection c', @r) endfunction vnoremap <f9> "ry:call func2x11()<cr>

python - own Nominatim server not working with geopy -

i have database of on 6k entries of addresses need geocoding, have installed nominatim server docker geocoding work. works should in web form on 'localhost:8080'. however, when try query geopy in jupyter. throws error time. my jupyter code: from geopy.geocoder import nominatim nom=nominatim(domain='http://localhost:8080') nom.geocode('some address') #the address works on public server the error stack: --------------------------------------------------------------------------- gaierror traceback (most recent call last) /usr/local/cellar/python3/3.5.2_3/frameworks/python.framework/versions/3.5/lib/python3.5/urllib/request.py in do_open(self, http_class, req, **http_conn_args) 1253 try: -> 1254 h.request(req.get_method(), req.selector, req.data, headers) 1255 except oserror err: # timeout error /usr/local/cellar/python3/3.5.2_3/frameworks/python.framework/versions/3.5/l...

css - navbar-collapse not covering body content -

here codepen: https://codepen.io/anon/pen/evvnjz here navigation part of html: <nav class="navbar"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a asp-area="" asp-controller="home" asp-action="index" class="navbar-brand"> <img class="img-responsive" src="~/images/2040_logo_nav_...

javascript - Include Page for every No. of Div -

Image
good morning. have code here displays data in every loop. <script> function loadalldata(){ google.script.run.withsuccesshandler(generatemaintable).getdata(); } function generatemaintable(data) { var createcard = document.getelementbyid("maincontainer"); createcard.innerhtml += '<div class="container" width = "100%" >' (var = 1; < data.length; i++) { var imagelink = data[i][0], brand = data[i][1], prodcat = data[i][2], prodcode = data[i][3], prodname = data[i][4], packaging = data[i][5], srp = data[i][6] , des1 = data[i][7], des2 = data[i][8], des3 = data[i][9], des4 = data[i][10], des5 = data[i][11], des6 = data[i][12]; if (data[i][0] === "") { break; } createcard.innerhtml += '<div class="card">' + '<div...

reactjs - Update loginc for component with setState -

i read several posts on setstate batching updates , not being in sync, however, don't understand how component should update (in fact text in same container won't update)... i have component (really glyph , text) should update when state changes - when user clicks on nav - (imitating checkbox since 1 doesn't work of "navitem") import react, { component } 'react'; import { glyphicon, nav, navbar, navitem, menuitem, navdropdown } 'react-bootstrap'; class app extends component { constructor(props) { super(props); this.state = { isdevon: false }; } toggledevtools = (k,event) => { event.preventdefault(); this.setstate({ isdevon : !this.state.isdevon, }); } render() { <div classname="app container"> <navbar.collapse> ...

dictionary - How to split values of a map in terraform to create lists? -

i have map variable many values (nacl rules). trying add rules accordingly variable "rules" { default = { = "200,false,tcp,allow,0.0.0.0/0,23,23" b = "100,true,tcp,allow,0.0.0.0/0,1024,65535" } } resource "aws_network_acl_rule" "bar" { network_acl_id = "<id>" rule_number = "${split(",",element(values(var.rules),count.index))[0]}" egress = "${split(",",element(values(var.rules),count.index))[1]}" protocol = "${split(",",element(values(var.rules),count.index))[2]}" rule_action = "${split(",",element(values(var.rules),count.index))[3]}" cidr_block = "${split(",",element(values(var.rules),count.index))[4]}" from_port = "${split(",",element(values(var.rules),count.index))[5]}" to_port = "${split(",",element(values(var.rule...

c++ - Using RegGetValue to grab WOW64_64 keys -

is there way use reggetvalue 64 bit registry keys on 32 bit application older windows operating systems (ie win 7 or win 8)? reggetvalue( key, nullptr, "product", rrf_rt_any | rrf_subkey_wow6464key, dwtype, (pvoid)&buff, &size); rrf_subkey_wow6464key introduced in windows 10 , fails work in win 7/8.1

python - Duplicate array dimension with numpy (without np.repeat) -

i'd duplicate numpy array dimension, in way sum of original , duplicated dimension array still same. instance consider n x m shape array ( a ) i'd convert n x n x m ( b ) array, a[i,j] == b[i,i,j] . unfortunately np.repeat , np.resize not suitable job. there numpy function use or possible creative indexing? >>> import numpy np >>> = np.asarray([1, 2, 3]) >>> array([1, 2, 3]) >>> a.shape (3,) # not want... >>> np.resize(a, (3, 3)) array([[1, 2, 3], [1, 2, 3], [1, 2, 3]]) in above example, result: array([[1, 0, 0], [0, 2, 0], [0, 0, 3]]) from 1d 2d array, can use np.diagflat method, create two-dimensional array flattened input diagonal : import numpy np = np.asarray([1, 2, 3]) np.diagflat(a) #array([[1, 0, 0], # [0, 2, 0], # [0, 0, 3]]) more generally, can create zeros array , assign values in place advanced indexing : a = np.asarray([[1, 2, 3], [4, 5, 6]]) result ...

excel - Deleting Rows From Filtered Range Via Macro -

i having issues below code, trying filter set of data, delete visible rows. "run time 1004 error: delete method or range class failed" occurs on last line of code. found similar question on site, , answer appears have in last line of code. dim lastrow long lastrow = worksheets("orders").range("a" & rows.count).end(xlup).row worksheets("orders").range("a1:cu" & lastrow).autofilter field:=10, criteria1:="new" if worksheets("orders").range("a1:cu" & lastrow).specialcells(xlcelltypevisible).count > 1 worksheets("orders").range("a1:cu" & lastrow).offset(1, 0).specialcells _ (xlcelltypevisible).entirerow.delete later in code, filter same set of data again, time deleting non-visible (filtered out) rows. getting same error on last line of code well: worksheets("orders").range("$a1:cc" & lastrow).autofilter field:=26, criteria1:= _ ...

r - Custom classification threshold for GBM -

i'm trying create custom gbm model tunes classification threshold binary classification problem. there nice example provided on caret website here , when try apply similar gbm receive following error: error in { : task 1 failed - "argument 1 not vector" unfortunately, have no idea error , error isn't helpful. here's example, code i've used defining custom gbm library(caret) library(gbm) library(proc) #### define custom gbm model probability threshold tuning #### ## model code original gbm method caret customgbm <- getmodelinfo("gbm", regex = false)[[1]] customgbm$type <- c("classification") ## add threshold (i.e. class cutoff) tuning parameter customgbm$parameters <- data.frame(parameter = c("n.trees", "interaction.depth", "shrinkage", "n.minobsinnode", "threshold"), class = rep("num...

laravel 5 - Envoy Task Runner: run command that requires sudo access -

i using https://laravel.com/docs/5.4/envoy deployment tool. in envoy.blade.php, have command requires sudo access example:- chmod 777 -r storage/ chmod 777 -r bootstrap/cache these commands fails error saying operation not permitted. how can resolve this? to run commands sudo try following: echo "{{ $password }}" | sudo -s chmod 777 -r storage/ echo "{{ $password }}" | sudo -s chmod 777 -r bootstrap/cache obviously you'll need pass sudo password envoy run command. envoy run mytask --password=mypass tested on ubuntu server 16.04 & 17.04

angular - 'NgModuleInjector' does not exist on type -

i have used " https://www.npmjs.com/package/angular2-social-login " application integrate social media authentication , working angular2. trying use same angular4 getting following error - error in .../angular2-social-login.module.ngfactory.ts (12,57): property 'ngmoduleinjector' not exist on type 'typeof "../node_modules/@angular/core/src/linker/ng_module_factory.' please image.. help me out resolve this. thanks!

javascript - How to store and access data on eventBus in VueJS -

basically want able access centralized data setting databus vue instance object, , access , tweak data different components. i cant seems access data componenets, basic string interpolation not getting rendered dom. export const databus = new vue({ data: { numquotes: 4, stringvar: 'hellow there' } }); i tried setting data return of function data(). being data bus actual vue instance don't think correct. (i wrong). following component in import databus , try output data. <template> <div> <h1>quotes added</h1> <div id="trackerbar"> <div id="trackerbaractual"> <h2>{{numquotes}}/10</h2> </div> </div> </div> </template> <script> import { databus } '../main.js'; export default{ } </script> i getting following error: property or method "numquotes...

java - My Recyclerview list stopped working after implementing SQLite database -

i'm building list app. i'm learning sqlite databases , i'm trying save user input sqlite database table , display in recyclerview list. when did without sqlite, worked problem implementation of database table. app supposed add data list per button click: addingitems.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { if(itemsinput.gettext() != null){ items.add(new todo(itemsinput.gettext().tostring())); itemsinput.settext(""); }else { toast.maketext(mainactivity.this, "please enter do", toast.length_short).show(); } itemadapter.notifydatasetchanged(); } }); but not that. app not crash. problem list shows absolutely no data. following relevant java files: mainactivity.java public class mainactivity extends appcompatactivity { pri...

vb.net - How to change characters in textbox? VB -

i have question how can make multiple characters work rather single character. appreciated thank you. private sub button1_click(sender object, e eventargs) handles button1.click if textbox1.text = "a" textbox2.text = ":regional_indicator_a:" end if if textbox1.text = "a" textbox2.text = ":regional_indicator_a:" end if end sub i think want program accept both 'a' , 'a' in case should asking or question. private sub button1_click(sender object, e eventargs) handles button1.click if textbox1.text = "a" or textbox1.text = "a" textbox2.text = ":regional_indicator_a:" end if end sub

java - Android Studio TextViews onClick all perform the same action, how do I fix it? -

i have function supposed create array of textviews unique ids. each textview supposed perform unique action, when 1 of them clicked, perform function of last textview . (ie, of them appends 9 last textview way set up) know why this, , how can fix it? any appreciated. //code: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_what_can_imake); int textviewcount = 10; textview[] textviewarray = new textview[textviewcount]; relativelayout mylayout = (relativelayout) findviewbyid(r.id.mylayout); for(int = 0; < textviewcount; i++) { textviewarray[i] = new textview(this); textviewarray[i].settext("title"+integer.tostring(i)); textviewarray[i].setpadding(8,8+50*i,8,0); textviewarray[i].setid(i); layoutparams mytitledimensions = new relativelayout.layoutparams( ...

c - Creating a Database and want to write out to disk and not keep in RAM -

hi writing database in c , write out data hard drive , not have stored in ram anymore. there way this? currently create big file , open such fd = open("database.dat",o_creat | o_rdwr); hd = mmap(0, ssd_size, prot_read | prot_write, map_shared, fd, 0); and write memory addresses have been mmapped , then msync(dest,db_page_size, ms_sync); where dest in in mmaped region. mmap() maps file in virtual address space, not load whole file ram. on 32 bit operating system database quite limited address space available, on 64 bit operating system mmap() should fine. so, assuming os 64 bit, solution if fine: operating system manage mapping used pages in ram and, in case of memory pressure, pages wrote disk automatically.

pandas - forward fill method fills extended rows -

forward fill method overwrites 'na' values original file. there way treat "na" literally instead of converting nan while reading file? !wget https://s3.amazonaws.com/datameetgeo/sample.txt import pandas pd df=pd.read_csv('sample.txt', sep='\t') df=df.fillna(method='ffill') as can seen in above example, value of "c-54465" carried forward next college code 954. wrong , should limited first 22 rows. there way control how ffill works or how "na" values treaded while reading? by default pd.read_csv interprets na null. can turn off parameter keep_default_na=false pd.read_csv('sample.txt', sep='\t', keep_default_na=false)

php - Why PhpStorm doesn't know PHPUnit_Framework_TestCase -

Image
i'm trying configure phpstorm 2017.2 use phpunit 5 php 5.6 project. i've downloaded phpunit-5.7.21.phar file the official source , placed in php 5.6 installation dir. in phpstorm settings >> languages & frameworks >> php >> test frameworks , i've linked .phar executable , set default config file phpunit.xml in project root directory here contents of phpunit.xml : . <?xml version="1.0" encoding="utf-8"?> <phpunit> <testsuites> <testsuite name="test suite"> <directory>tests</directory> </testsuite> </testsuites> </phpunit> i'm trying structure tests in tests/unit directory within source file project structure mirrored described in manual . instance: // project files: classone.php vendor/ classtwo.php utility.php // test files tests/unit/ classonetest.php vendor/ classtwotest.php utili...

Adding lines from a file into 2D array Java -

this question has answer here: read .txt file 2d array 4 answers i'm having trouble trying write syntax in java want file what i'm doing reading in file , want add specific lines of file elements of 2d array, have written pseudo code below understand im trying try { fileinputstream fstream = new fileinputstream(filename); datainputstream instream = new datainputstream(fstream); bufferedreader brread = new bufferedreader (new inputstreamreader(instream)); string line; while ((line = brread.readline()) !=null) { //lines 1-3 //{ // add line 1 element 0,0 of array // add line 2 element 0,1 of array // add line 3 element 0,2 of array //} //lines 4-10 //{ // add line 4 element 1,0 of array ...

algorithm - Maximum sum in array such that atmost 2 consecutive in 5 elements can be selected -

i can't work around how select elements. for example if have 1,2,3,4,5,6,7,8,9,10 and choose 4,5 then cant choose 6,7,8 can choose 9th so, guess in general if choose 2 consecutive elements arr[i] , arr[i+1] , then cannot choose next 3 values arr[i+2], arr[i+3], arr[i+4] , may choose arr[i+5] for ex: consider array 9 elements input: arr[] = {100, 200, 100, 500, 900, 500, 300, 400, 100} output: 1500 maximum sum should be: 1500 which obtained taking values @ places 4, 5 , 9 i.e 500+900+100 = 1500 another example: consider array 10 elements input: arr[] = {500, 700, 300, 500, 900, 700, 600, 400, 700, 500} output: 2800 select elements @ (2, 5, 9, 10) i.e 700+900+700+500 = 2800 to me can done using simple modification dynamic programming algorithm. in fact, can add variable indicate if last element picked or not. let's considering element @ position idx, need variable tell if idx - 1 picked or not: (1) if isn't, haven't pi...

angular - Http provider Error Ionic 3 -

i'm getting error have no idea how fix. search solutions, didn't me. it's make http request using ionic native http, both , post. the error: it's i'm not setting http provider, in app.module.ts i'm importing it error error: uncaught (in promise): error: no provider http! error: no provider http! @ injectionerror (vendor.js:1590) @ noprovidererror (vendor.js:1628) @ reflectiveinjector_._throwornull (vendor.js:3129) @ reflectiveinjector_._getbykeydefault (vendor.js:3168) @ reflectiveinjector_._getbykey (vendor.js:3100) @ reflectiveinjector_.get (vendor.js:2969) @ appmoduleinjector.get (ng:///appmodule/module.ngfactory.js:240) @ appmoduleinjector.getinternal (ng:///appmodule/module.ngfactory.js:365) @ appmoduleinjector.ngmoduleinjector.get (vendor.js:3936) @ resolvedep (vendor.js:11398) @ injectionerror (vendor.js:1590) @ noprovidererror (vendor.js:1...

multiprocessing django model database -

my database in implementation of script, database has lost data, may more or less, there lot of empty data. thank following list of configuration information: sqlite3 django1.9.8 python 2.7.6 def flush_price(): logging.error("sub-process(es) begin.") logging.error(int(time.time())) key = '2500_wine_info.xlsx' lists = import_excel(key) lwin11s = [] item in lists: lwin11s.append(str(item['lwin11'])[:11]) contracts = contract.objects.filter( is_del=false, wine__lwin11__in=lwin11s ) lwins = [] contract in contracts: lwins.append(str(contract.wine.lwin)) new_arrs = arr_split(lwins, 50) = conversion_reduce_8_time() index in range(1, 3641): date_now = (now - datetime.timedelta(days=index)).strftime('%y-%m-%d') pool = multiprocessing.pool(processes=len(new_arrs)) new_arr in new_arrs: pool.apply_async(request_price, (new_arr, date_now, )...

.net - Comparing datatable values between row for change detection -

my goal detect & write information value changed before update row database. for example, have 2 datatables same column structure: beforeedit , afteredit . in case, have 1 row each datatables. for integer = 0 beforeedit.columns.count - 1 if beforeedit(0).item(i) <> afteredit(0).item(i) 'storing log column have changed end if next is there better approach task? thanks in advance you don't need 2 datatables . each datarow maintains 2 copies of data. rowstate property of datarow can tell whether has changed or not. unchanged if no change has occurred , modified otherwise. can use code determine if , changes have occurred in datarow : private sub logrecordchanges(row datarow) if row.rowstate = datarowstate.unchanged console.writeline("no changes row.") else each column datacolumn in row.table.columns dim currentvalue = row(column, datarowversion.current) dim original...

geometry - How to change the radius of the arc of a line in Open Layers 3, using arc.js? -

i using open layers 3 , springmeyer's arc.js draw arc on map between 2 points. i have been following a flight animation example. this working well. however, able change radius of arc drawn. know how achieve this?

mysql - value of SELECT COUNT(DISTINCT allcolumns) bigger than SELECT COUNT(1) -

i run following sql in mysql, , why 2 count show different results? select count(1), count(distinct column1, column2, column3, column4, column5) distinctcount `parts_color`; the results are: count(1) : 647611 distinctcount : 647263 why? your table parts_color must have duplicate values. select count(1) similar select count(*) retains duplicate values , returns count. when use distinct in query duplicate values discarded , hence value less count(1).

Interpreting keypresses sent to raspberry-pi through uv4l-webrtc datachannel -

i apologize if doesn't make sense since i'm still newbie using raspberry pi , first time posting on stackoverflow. i making web app lets me stream video , raspberry pi while letting me send keycodes. sent keycodes let me control servos on drone. after scouring internet, figured simplest way stream 2-way video using uv4l have installed along uv4l-webrtc on raspberry pi. hooked gpio pins flight controller , using pigpio send pwm signals it, monitor using cleanflight. right now, can manipulate keypresses roll, pitch, etc. of flight controller using python script if access pi remotely using vnc , able through custom web page being served uv4l-server. trying use webrtc data channels, i'm having trouble understanding need recognize messages sent through data channels. know data channels opened when video call initiated , i've tried test in link see if can indeed send keycodes pi (and can). my problem right have no idea sent messages go or how can them can incorpora...