Posts

Showing posts from July, 2014

python - average of certain values of an array -

i have array contains numbers distances, , represents values @ distance. how calculate average of data @ fixed value of distance? e.g distances (d): [1 1 14 6 1 12 14 6 6 7 4 3 7 9 1 3 3 6 5 8] e.g data corresponding entry of distances: therefore value=3.3 @ d=1; value=2,1 @ d=1; value=3.5 @ d=14; etc.. [3.3 2.1 3.5 2.5 4.6 7.4 2.6 7.8 9.2 10.11 14.3 2.5 6.7 3.4 7.5 8.5 9.7 4.3 2.8 4.1] for exampe @ distance d=6 should mean of 2.5, 7.8, 9.2 , 4.3 i want values of d appear in vector 'd' , create vector (or matrix) of averages corresponding distance. thank in advance magnificent help! this handles every case in lists. adjust needed. key = [1, 1, 14, 6, 1, 12, 14, 6, 6, 7, 4, 3, 7, 9, 1, 3, 3, 6, 5, 8] dist = [3.3, 2.1, 3.5, 2.5, 4.6, 7.4, 2.6, 7.8, 9.2, 10.11, 14.3, 2.5, 6.7, 3.4, 7.5, 8.5, 9.7, 4.3, 2.8, 4.1] d in set(key): choose = [dist[i] in range(len(key)) if key[i] == d] print d, float(sum(choose)) / len(choose) you can shorten code

google maps - GMaps InfoWindow display issue -

Image
i cannot figure out why google maps infowindow not display properly. screengrab below: any idea may causing this? here code (js): /** * basic map */ $(document).ready(function(){ var map = new gmaps({ el: '#basic_map', lat: 51.5073346, lng: -0.1276831, zoom: 10, zoomcontrol : true, zoomcontrolopt: { style : 'small', position: 'top_left' }, pancontrol : false, }); map.addmarker({ lat: 51.5073346, lng: -0.1276831, title: 'big ben', infowindow: { content: 'big ben nickname great bell of clock @ north end of palace of westminster in london, , extended refer clock , clock tower, officially named elizabeth tower.' } }); }); css: .map { display: block; width: 95%; height: 350px; margin: 0 auto; -moz-box-shadow: 0px 5px 20px #ccc; -webkit-box-shadow: 0px 5px 20px #ccc; box-shadow: 0px 5px 20px #ccc; } html: &

winforms - Memory leak in windows forms -

we have form forma, , form adding form fromb forma. on dispose method disposing forma using forma.dispose(). step whether dispose child forms used in forma or need call dispose() method explicitly each forms , controls? similarly in fromb using list of windows.forms.control , not making these lists null in dispose method of formb. need dispose these list also?

internet explorer - How to apply IE Fixes for LESS CSS -

my page code is: <!doctype html> <!--[if lt ie 7 ]><html class="no-js ie6" lang="en"><![endif]--> <!--[if ie 7 ]><html class="no-js ie7" lang="en"><![endif]--> <!--[if ie 8 ]><html class="no-js ie8" lang="en"><![endif]--> <!--[if ie 9 ]><html class="no-js ie9" lang="en"><![endif]--> <!--[if (gte ie 9)|!(ie)]><!--><html class="no-js" lang="en"><!--<![endif]--><head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge,chrome=1"> <link rel="shortcut icon" href="favicon.ico"> <title>blue monday-homepage</title> <!--default style sheet--> <link rel="stylesheet/less" href="css/blue.less" media="screen" type="text/css" ti

python - Extract dictionary from QTreeWidget -

Image
i managed create treewidget dictionary, want reverse engineer it, , want create dictionary qtreewidget. quite lost on how that, seems straight forward fail. the idea parent items for index in range(self.treewidget.toplevelitemcount()): parent = self.treewidget.toplevelitem(index) from there on need recursively go through each sublevel parent.childcount(), if childcount valid, iterate on child. but dont know how create dictionary that. please me out.. ideally this "core.global_vars.arrunner_qmenu_object_name" "core.global_vars.metadata_label" "core.logger.console_verbosity" or in best case {"core:{"global_vars:{"arrunner_qmenu_object_name":none}}, ...} update replacejson main functions gets root parents, there on gather childrens , add them global children list. after that, generate string "root.child.child.child" can expand dict {"root":"{"child":...}} then in replace

cq5 - storing custom data in AEM 6.1 JCR repository -

we got aem 6.1, , went through developer training, well. coming cms background (sharepoint) , wanted learn / know, if need create list store data it, , refer programatically, somewhere on page or other common libraries in project , how do , store data , in /etc folder. not clear, guess, learnt training data stored in node types key / value pair, example if had list of movies attributes such date released, actors, awards etc. how store information in aem, don't want store part of list component of page. let me know if question vague, said, transitioning form cms. in advance. i appreciate pointers blogs, etc.. @rahul store data? data can stored in both /etc folder , /content folder. folders in /etc used supplement application's business logic code development, eg. clientlibs folder used store client side code(website styling, scripts etc. content folder authored content, user generated content gets persisted key value pairs , have build logic using jcr api's

sql - MySQL CONCAT returns NULL if any field contain NULL -

i have following data in table "devices" affiliate_name affiliate_location model ip os_type os_version cs1 inter dell 10.125.103.25 linux fedora cs2 inter dell 10.125.103.26 linux fedora cs3 inter dell 10.125.103.27 null null cs4 inter dell 10.125.103.28 null null i executed below query select concat(`affiliate_name`,'-',`model`,'-',`ip`,'-',`os_type`,'-',`os_version`) device_name devices it returns result given below cs1-dell-10.125.103.25-linux-fedora cs2-dell-10.125.103.26-linux-fedora (null) (null) how come out of should ignore null , result should be cs1-dell-10.125.103.25-linux-fedora cs2-dell-10.125.103.26-linux-fedora cs3-dell-10.125.103.27- cs4-dell-10.125.103.28- convert null values empty string wrapping in coalesce select

Qt/C++/Android - How to install an .APK file programmatically? -

i implementing own auto-updater within application. able download .apk file of newer version /download folder on sdcard, can't figure out how open/run file user presented new installation dialog. the thing come with: qstring downloadedapk = "/storage/emulated/0/download/latest.apk"; // not hardcoded, wrote here way simplicity qdesktopservices::openurl(qurl(downloadedapk)); debugger output: d/instrumentation(26418): checkstartactivityresult :intent { act=android.intent.action.view dat=file:///storage/emulated/0/download/latest.apk } d/instrumentation(26418): checkstartactivityresult inent instance of inent: w/system.err(26418): android.content.activitynotfoundexception: no activity found handle intent { act=android.intent.action.view dat=file:///storage/emulated/0/download/latest.apk } w/system.err(26418): @ android.app.instrumentation.checkstartactivityresult(instrumentation.java:1660) w/system.err(26418): @ android.app.instrumentation.execstartactivi

java - JMenu's pop-up will not close when the cursor leaves the JMenu -

jbutton jbutton1 = new jbutton("click me"); public void showpopupmenu1(jbutton invoker){ jpopupmenu popupmenu = new jpopupmenu(); popupmenu.setlayout(new gridlayout(5, 1)); jmenu menu = new jmenu("other"); menu.add(new jmenuitem("a")); menu.add(new jmenuitem("b")); menu.add(new jmenuitem("c")); popupmenu.add(menu); popupmenu.add(new jbutton("apple")); popupmenu.add(new jbutton("banana")); popupmenu.add(new jbutton("carrot")); popupmenu.add(new jbutton("orange")); popupmenu.show(invoker, 0, invoker.getheight()); } private void jbutton1actionperformed(java.awt.event.actionevent evt) { showpopupmenu1(jbutton1); } when cursor goes apple button, menu's popup not close , still marked selected.

PHP Simple HTML DOM Parser finding specific text -

trying data poorly created html format http://www.weather.gov.sg/lws/zoneinfo.do all need data 3 places, e.g. bedok, city , katong. how store data in array this? this did store first 5 lines, not want. $row_counter='0'; while($row_counter<5) { $ret['name'][] = $html->find('.form1', $row_counter)->innertext; $ret['area'][] = $html->find('.form1', $row_counter)->next_sibling()->innertext; $ret['alert'][] = $html->find('.form1', $row_counter)->next_sibling()->next_sibling()->innertext; $ret['from'][] = $html->find('.form1', $row_counter)->next_sibling()->next_sibling()->next_sibling()->innertext; $ret['till'][] = $html->find('.form1', $row_counter)->next_sibling()->next_sibling()->next_sibling()->next_sibling()->innertext; $row_counter++; } i able store data whole row , columns. efficient way search name, e.g. bedok , getting

python - Pip install Scrapy giving an error on Windows -

i trying install scrapy. giving me error code 1. can me this. command "c:\python27\python.exe -u -c "import setuptools, tokenize;__file__='c:\\users\\define~1\\appdata\\local\\temp\\pip-build-mycaf8\\lxml\\setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record c:\users\define~1\appdata\local\temp\pip-8n6sxr-record\install-record.txt --single-version-externally-managed --compile" failed error code 1 in c:\users\define~1\appdata\local\temp\pip-build-mycaf8\lxml unfortunately, installing scrapy on windows little bit complicated. see stack overflow answer you have follow guide: how install scrapy in 64-bit windows 7

c# - How to find key value pair in a dictionary with values > 0 with key matching a certain string pattern? -

this dictionary, dictionary<string, uint> osomedictionary = new dictionary<string, uint>(); osomedictionary.add("dart1",1); osomedictionary.add("card2",1); osomedictionary.add("dart3",2); osomedictionary.add("card4",0); osomedictionary.add("dart5",3); osomedictionary.add("card6",1); osomedictionary.add("card7",0); how key/value pairs osomedictionary keys starts string "card" , has value greater zero? var result = osomedictionary.where(r=> r.key.startswith("card") && r.value > 0); for output: foreach (var item in result) { console.writeline("key: {0}, value: {1}", item.key, item.value); } output: key: card2, value: 1 key: card6, value: 1 remember inlcude using system.linq

javascript - ASP.Net How to programmatically add a background image for my site? -

i want add background image site programmatically code have came upon not work. first use javascript print browsers dimensions: $(document).ready(function () { $("#clientscreenwidth").val($(window).width()); $("#clientscreenheight").val($(window).height()); }); after send these dimensions vb.net via hidden inputs , assign them values: dim height string = httpcontext.current.request.params("clientscreenheight") dim width string = httpcontext.current.request.params("clientscreenwidth") however when tried input these arguments string , pass body's css there error: dim backgroundimageurl string = "https://unsplash.it/" + height + "/" + width body.style.add("background-image: url(""" + backgroundimageurl + """);") overload resolution failed becuase no accessible 'add' accepts number of arguments. edit: posting fixed overload resolution err

php - CodeIgniter Hello World MVC with two models -

my ci controller looks this: // controller. class hello extends ci_controller { public function one($name) { $this->load->model("hello_model"); $profile = $this->hello_model->getprofile("me"); //$profile2 = $this->hello_model->otheraction(); $this->load->view('header'); $data = array("name" => $name); $data['profile'] = $profile; $this->load->view('one.html', $data); } } and here is/are model(s) class hello_model extends ci_model { public function getprofile($name) { return array("fullname" => "martin", "age" => 28); } } class hello_model_2 extends ci_model { public function otheraction() { echo "data"; } } when enable $profile2 statement , visit controller in browser, find error message in apache error l

security - What prevents the "state" parameter in OpenID Connect server flow? -

not sure kind of csrf attack prevents "state" parameter in openid connect server flow. give me example? it prevents attack attacker produces fake authentication response, e.g. part of basic client profile sending code client's redirect uri. example: after phishing user attacker inject stolen code associated current user in way. state correlates request , response unsolicited crafted response not possible without knowing state parameter used in request.

range - Get a specified rows amount from an array -

i have array 1000 rows , want convert string 50 rows of it. $thearray = array ( [0] => row1 [1] => row2 [2] => row3 [3] => row4 [4] => row5 [5] => row6 ... [999] => row1000 ) the output should use: $string1 = implode(',', $thearray); but said need $string1 have 50 rows array , if possible, them randomized. need advices. thx you try this, see comments in code explanations , http://3v4l.org/hjuv6 demonstration // lets create dummy array $array = array(); for($i = 0; $i < 1000; $i++) { $array[] = $i; } // lets make randomized temporary array $backuparray = $array; $temparray = array(); for($i = 0; $i < 50; $i++) { // select random index $randomindex = rand(0 , count($backuparray)); // copy temp array $temparray[] = $backuparray[$randomindex]; // delete row our backup unset($backuparray[$randomindex]); // reorganiz

java - How do I load a file from resource folder? -

my project has following structure. /src/main/java/ /src/main/resources/ /src/test/java/ /src/test/resources/ i have file in /src/test/resources/test.csv , want load file unit test in /src/test/java/mytest.java i have code didn't work. complains "no such file or directory". bufferedreader br = new bufferedreader (new filereader(test.csv)) i tried this inputstream = (inputstream) mytest.class.getresourcesasstream(test.csv)) this doesn't work. returns null . using maven build project. thanks in advance. try next: classloader classloader = thread.currentthread().getcontextclassloader(); inputstream = classloader.getresourceasstream("test.csv"); if above doesn't work, various projects have been added following class: classloaderutil (code here ).

polymorphism - C++ Polymorphic memory cost -

i have chunk of code: #include <stdio.h> class coolclass { public: virtual void set(int x){x_ = x;}; virtual int get(){return x_;}; private: int x_; }; class plainoldclass { public: void set(int x) {x_ = x;}; int get(){return x_;} private: int x_; }; int main(void) { printf("coolclass size: %ld\n", sizeof(coolclass)); printf("plainoldclass size: %ld\n", sizeof(plainoldclass)); return 0; } i'm getting little bit confused because says size of coolclass 16? how? why? pointer vtable, shouldn't size 8? size of oldclass 4 expected. edit: i'm running linux mint 64 bit g++ 4.6.3. you can't assume sizes of other char or unsigned char . if you're building on 64 bit platform, int still 4 bytes, size of virtual table pointer 8 , , 4 bytes padding (so pointer aligned 8 bytes). 64-bit +----+----+----+----+ | vp | vp | x_ | p | +--

How can you mutate (or avoid the need to mutate) nested, constructed fields in Rust, without making everything mutable, when Cell can't be used? -

i'm pretty new rust , i've been following an arcade game tutorial has been great concepts goes through. in part nine of tutorial, in main menu created, author suggests 'homework' reader of making labels on main menu ("new game", "quit") animate change in size when focused , unfocused, rather jump idle/focused size. have been having difficulty... the basic layout of relevant parts of code before started implement change following: // equivalent 'menu option' struct action { /// function executed if action chosen func: box<fn(&mut phi) -> viewaction>, label: &'static str, idle_sprite: sprite, // smaller (32) focus_sprite: sprite, // larger (38) // ... } impl action { fn new(phi: &mut phi, label: &'static str, func: box<fn(&mut phi) -> viewaction>) -> action { // ... } struct mainmenuview { actions: vec<action>, selected: i8, /

OpenVPN set alias for server -

i have made vpn server in local (home) network, run in bridging mode. now, want configure notebook able connect vpn, want use server's local lan ip when using notebook @ home , use server's public ip when using notebook @ school/... how can add alias server address in client configuration? <connection> remote 11.22.33.44 1194 udp </connection> <connection> remote 10.0.0.1 1194 udp </connection> according documentation: an openvpn client try each connection profile sequentially until achieves successful connection. --remote-random can used "scramble" connection list.

python - Using googleapiclient to send an email draft by Id -

i'm using google's api client interact gmail api. assuming have draft's immutable id, i'd send associated draft. i tried: service.users().drafts().send( userid='me', id=draft_id).execute(http=http) here draft_id id of draft i'd send, http instance of http works other requests (so authenticated). trying above, typeerror : traceback (most recent call last): file "/applications/googleappenginelauncher.app/contents/resources/googleappengine-default.bundle/contents/resources/google_appengine/lib/webapp2-2.5.2/webapp2.py", line 570, in dispatch return method(*args, **kwargs) file "/users/mgilson/git/spider-web/app/pattern/handlers/ajax/email.py", line 77, in post 'success': int(client.send_draft(draft_id)) file "/users/mgilson/git/spider-web/app/pattern/services/email/gmail.py", line 601, in send_draft userid='me', id=draft_id) \ file "/users/mgilson/git/spider-web/app/thi

php - How do I create a tree structure with an array using javascript? -

my problem create tree structure in json format flat data mysql query. the array have coming mysql query in format: {"level":"higher","course":"administration , it","grade":"a" }, ...etc is there way order tree format using javascript? or need include hierarchical structure within database? any pointers appreciated. cheers.

javascript - jQuery conflict when removing div after page load -

i'm trying remove div page (preferably prevent loading @ all) i'm settling on removing after page loads. when try following lines of code in jsfiddle , #content div gets removed, expected. <script type='text/javascript'>//<![cdata[ $(window).load(function(){ $('#content').remove(); });//]]> </script> however, have tried implementing on an actual website , in case, #content div isn't removed. any suggestions might wrong? if you're sharing jquery library uses dollar operation need guard against this, using anonymous wrapper: (function($) { $(window).on('load', function(){ $('#content').remove(); }); }(jquery)); note instead of .load() i'm using .on('load', fn). instead of on page load bind code on dom ready; jquery passes first argument inner function: jquery(function($) { $('#content').remove(); });

swift - make init() private for NSObject subclass -

the class fooclass should allow interaction via sharedinstance . trying prevent misuse not allowing access init() of fooclass . i have tried few different approaches, none work: using private keyword: class fooclass: nsobject { // singleton static let sharedinstance = fooclass() let value: string private override init() { self.value = "asdf" } } // should compile error, not let foo = fooclass() using @available: class fooclass: nsobject { // singleton // compile error - "init unavailable. use sharedinstance" static let sharedinstance = fooclass() let value: string @available(*, unavailable, message="use sharedinstance") override init() { self.value = "asdf" } } // compile error - should let foo = fooclass() i have tried using internal well, still no luck. update first version works if move own file, objc version of class still allows init called. ideas?

java - NativeSQLQueryPlan in Hibernate? -

i want know why hibernate generates nativesqlqueryplan (query plan native queries). also, how can skip query cache plan native queries? i doing bulk data operation, , there firing native queries, getting outofmemoryexception because hibernate caching resultset , query plans. have native queries in logic (no named query).

angularjs - Updating $scope in an Angular directive -

i m using following, after frustration , googling cannot data_banks item update in $scope after $resource marketplace.buy has been loaded successfully; myapp.directive('marketplacebuy', function() { return { restrict: 'a', controller: ['$scope', "$timeout", "marketplace", "notification", "databank", function ($scope, $timeout, marketplace, notification, databank) { $scope.dooo = function(attrs) { marketplace.buy({'item': attrs.itemid}, function(){ databank.query({word: "databanks"}, function(data){ $scope.data_bank = data.data; }); }, function(resp){ notification.error(resp.data.message); }); } }], link: function ($scope, element, attrs) { element.bind

java - Is it possible to create an object that has a generic attached to it that is an extension of an abstract class? -

i'm making abstract class (let's call screen) extension of jpanel. want in future users/myself able extend it. part isn't issue. i'm trying make class (let's call 1 "scratchdrawingproject") extension of jframe, , has generic attached it. class has instance of abstract class mentioned above screen added it. i want user, in project's main method (inside other random file create), able create instance of scratchdrawingproject generic being extension of screen. in scratchdrawingproject's constructor, want it's screen variable instantiated new object of extension of screen user passes in. so far screen have: public abstract class screen extends jpanel{ private jframe parent; private graphics2d graphics; //constructor public screen(jframe parent){ this.parent = parent; parent.add(this); setbounds([bounds]); repaint(); } //basically stuff put in extension's constructor, method

algorithm - Graph backtrack complexity -

i'm trying analyse complexity of backtracking graph in order find longest path. my algorithm consists of topological sort , backtrack each vertex in order find longest path. if helps, algorithm basically: topological sort(g), each vertex calculate distance each other vertex ,return maximum distance anyway, don't know worst case complexity of backtrack operation. any suggestions? thanks in advance!

asp.net - Save and retrieve image from cookies using AJAX -

i want download images 1 time whilst same. need save images on network traffic. how can using ajax updates. thanks in advance kuldeep dwivedi set expiration of image. cached in client browser. and saving image in cookies :- can't save object in cookies. can save string in cookie.

create Class diagram using JAVA code -

this question has answer here: generate uml class diagram java project [closed] 4 answers is there softtware create class diagram, activity diagram,sequence diagram , other related diagrams using java source code. most uml tools can import source code , generate class diagrams. tool using? sequence diagrams more problematic, because have run code. intellij enterprise edition, best ide in world jetbrains, can both you.

javascript - Paginated data cursor in RXJS and confusion about subject.onCompleted and errors -

i'm working rxjs , came implementation of paginated data cursor. having not spent time reactive functional programming, i'm wondering if implementation in spirit of how library intended used. i want class can load in pages endpoint. if subscribe it, receive last page queried. first subscription results in first page being automatically queried. call "getpage" should trigger onnext subscriptions. multiple subscriptions should not cause multiple requests. i wrote basic example satisfies this, heavily commented thought process: https://jsfiddle.net/gfmn708g/1/ my questions are: is in spirit of rxjs? using both replysubject , sharereplay feels wrong me, found no other way behavior want. read using subjects "bad" , against principles of paradigm. will line 63 unsubscribe/finish of items$ subscriptions (lines 82 , 89) after in-flight requests completed , processed? what proper way handle errors, errors propagated subscribers, don't murder stream

Is using Entity Framework code first purely for database migrations ok? -

i'm using roundhouse manage database migrations , works nicely. i have been looking various migration creation technologies fluentmigrator , others. possibility errors though seems high because of them aren't typed. instance migration fluentmigrator public class createmembertable : migration { public override void up() { create.table("members") .withnamedidcolumn("memberid") .withcolumn("name").asstring().notnullable(); } public override void down() { delete.table("members"); } } i've used entity framework code-first before , liked migration engine in generates code based migrations can make changes require afterwards. don't need rest of ef framework, it's bit heavyweight i'm looking for. would acceptable use ef migrations not bother of rest of it? there's nice roundhouse plugin most of data i'm using flat petapoco or dapper seems

meteor - Dynamic dispalying of data based on fields of a collection -

so, have collection of documents following fields (id, usera, userb, message). (document name room) want name room based on user logged in. ie if user want userb displayed , vice versa. have code below , seems outputting userb time. suggestions appreciated. <template name="rooms"> <h4>contacts:</h4> <ul> {{#each rooms}} {{> room}} {{/each}} </ul> <template name="room"> <li style="cursor: pointer; {{roomstyle}}"> {{#if userais}} {{userb}} {{/if}} </li> }); template.room.helpers({ userais: function(usera) { return this.usera==meteor.userid(); } });

javascript - Why won't re-usable service refresh view in AngularJS -

an html view in angularjs contains form sends data through view's ccontroller , reusable service. re-usable service receives form's value, , charged updating values of 2 cookies values should printed in view. in devbox, firefox debugger shows form's data enters serice's handler method. view not beiing updated values of cookies changed service's form handler. specifically, view elements should shown or hidden based on values of cookies changed form's handler. what specific changes need made code below cookie values changed form handler able change content shown in view? all of code required recreate probblem in the plnkr can examine clicking on link , , can recreate problem following gui /someroute (from drop down navigation menu) , entering value in form. the re-usable service someclass.js , , content here: angular .module('someclass', ['ngcookies']) .service('someclass', ['$rootscope', '$http', '$c

android - Filtering out unwanted native libraries in Fresco -

looking @ generated apk, can see fresco comes native libraries popular image formats. how keep 1 (e.g. webp) , exclude rest? note: i'm not talking cpu architecture, handle using split . fresco consists of multiple (optional) artifacts , can select need app, see http://frescolib.org/docs/index.html

java - Unable to receive proper UDP packets using SSDP -

i'm trying implement simple ssdp functionality android app taken from here . my application sends udp packets containing relevant m-search message broadcasting address without issue. problem is, should getting proper response other devices that's running upnp server. reason, i'm receiving exact same packets sent android device. mainactivity.java @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); wifimanager wm = (wifimanager)getsystemservice(context.wifi_service); wifimanager.multicastlock multicastlock = wm.createmulticastlock("multicastlock"); multicastlock.setreferencecounted(true); multicastlock.acquire(); setcontentview(r.layout.activity_main); ((button)this.findviewbyid(r.id.btnsendssdpsearch)).setonclicklistener(this); } @override public void onclick(view v) { switch (v.getid()) { case r.id.btnsendssdpsearch:

python - How to access same multiprocessing namespace from different modules -

i need able create shared object pyserial object in it. object created child process once after finding device list of locations. other processes use in later time. python multiprocessing manager can't know changes objects embedded other objects. if create manager: import multiprocessing mp manager=mp.manager() ns=manager.namespace() i can share object between processes. ns.obj = serialreader() where class serialreader(object): port = none def connect(self): #some code test connected device ... #end of code ser=serial.serial(device, etc) self.ser=ser #or self.saveport() #for future use def saveport(self): self.port = self.ser._port ns.port= self.ser._port now run in child process: p=process(target = ns.obj.connect) p.start() and print results: print ns.obj.port print ns.port output: none /dev/ttyacm0 i whant able use simple code like: ns.obj.ser.write(), ns.obj

javascript - How to decrement work in java script for loop? -

below java script loop increment working decrement not work, how solve think? for(var i=1; i<5; i++) { alert(i); } work fine for(var i=10; i<5; i--) { alert(i); } not working better check ease... decrement use for (var = 10; > 5; i--) { alert(i); } njoy...

Sorting key,value pairs in a perl array data structure according to key(id) -

i trying sort key,value pairs present in array data structure in perl .however,i not resolve how sort when there multiple entries. below code: @users = ( {id => 1, name => "frank"}, {id => 10, name => "joe"}, {id => 5, name => "paul"} ); i want output sorted respect id in ascending order: {id => 1, name => "frank"}, {id => 5, name => "paul"}, {id => 10, name => "joe"} below effort: use strict; use warnings; use 5.010; @users = ( {id => 1, name => "frank"}, {id => 10, name => "joe"}, {id => 5, name => "paul"} ); foreach $name (keys %users) { printf "%-8s %s\n",$users{id},$users{name}; } any suggestions highly helpful. you have conflicting specifications of data, need? use strict; use warnings; use 5.010; @users = ( {

pug - html to jade error when contains <pre> -

i have static html documents, , want convert them jade. tried html2jade in npm, ok except this: <pre> elements in html convert empty, can me? the html code looks this: <pre><code>&lt;p&gt;hello&lt;/p&gt;&lt;span&gt;hello again&lt;/span&gt;</code></pre> the result is: pre. you can write couple different ways in jade. here 2 different methods. first takes advantage of jade's automatic escaping while second uses html entities instead. automatic escaping: pre code= '<p>hello</p><span>hello again</span>' html entities: pre code &lt;p&gt;hello&lt;/p&gt;&lt;span&gt;hello again&lt;/span&gt;

jvm - Limits and scope of the Java Attach API -

as far understand attach api introduced in java 6 allows inter-process modification of classes running in target jvm means of agents. questions are: is strategy limited instrumentation of classes have not been loaded yet target jvm ? , which limits of these transformations ?. example, body of existing methods can modified ?, or in class definition changed ? you can instrument both classes loaded or loaded intercepting them classfiletransformer . if retransformed method has active stack frames, active frames continue run bytecodes of original method. retransformed method used on new invokes. the redefinition/retransformation may change method bodies, constant pool , attributes. redefinition/retransformation must not add, remove or rename fields or methods, change signatures of methods, or change inheritance. these restrictions maybe lifted in future versions. class file bytes not checked, verified , installed until after transformations have been applied, if result

how to implement spring cloud config server security with docker -

i want use spring cloud config server security : i find example in : https://github.com/spring-cloud-samples/config-repo/blob/master/application.yml profile: cloud: config: uri: ${vcap.services.${prefix:}configserver.credentials.uri:http://user:password@${prefix:}configserver.${application.domain:cfapps.io}} but: can not understand : whats words meaning ? e.g. vcap.services ${prefix:}configserver.credentials.uri ${prefix:} ${prefix:}configserver ${prefix:}sso.credentials.tokenur and , if use docker instead of cloud profile , : docker config: uri: http://${configserver_1_port_8888_tcp_addr:localhost}:8888 client: serviceurl: defaultzone: http://${eureka_1_port_8761_tcp_addr:localhost}:8761/eureka/ when try : in coifing-server application.yml : security: user: password: 1 in client-server application.yml spring: cloud: config: uri: http://user:1@localhost:8888 the client-se

ios - How to fix camera orientation when rotate device -

Image
i use avfoundation record video. set video orientation: [captureconnection setvideoorientation:avcapturevideoorientationportrait]; when record video, output video looks this: when rotate device looks this: i want video first image when rotate device. have do? in advance i think might help supportsvideoorientation = no for more refer link

php - Wordpress - Ultimate Product Catalog Plugin - What file lists the products? -

ultimate product catalog plugin . what file handles html products list? when short code file in plugin handles html suppose listed out when short code put page, want edit html , php. it in file functions/shortcodes.php when shortcode [product-catalog] used, big function insert_product_catalog() in php file put html display.

unit of timespan of command simin in matlab -

can guide me unit of parameter 'timespan' of simin command in matlab. [t,x,y1, y2, ..., yn] = sim(model,timespan,options,ut) i think can consider units choose, provided make other variables , parameters consistent choice. for example if modelling simple de like: d2x/dt^2 = ax + b dx/dt + c you may use "x" in meters , "t" in seconds, imply "a" given in sec^(-2), "b" in sec^(-1) , "c" in meters/second^2. but valid take "x" in km , "t" in years, provided gave constants a, b , c (and initial conditions) in appropriate units. in other words, it's not question of right or wrong units in dynamical system this, it's question of consistent or inconsistent units.

java - using keyword throws to declare throwing of Runtime Exceptions -

for me, these code static int faktorial (int n) throws arithmeticexception { if ((n < 0) || (n > 31)) { throw new arithmeticexception(); } if (n > 1) { return n * faktorial(n - 1); } else { return 1; } } and same code without throws arithmeticexception do same, when use following code: public static void main(string[] args) { try { int n; scanner sc = new scanner(system.in); system.out.print("insert integer number: "); n = sc.nextint(); system.out.println(n + "! = " + faktorial(n)); } catch (inputmismatchexception e) { system.out.println("not integer number!"); e. printstacktrace(); } catch (runtimeexception e) { system.out.println("number big!"); e. printstacktrace(); } } could describe me if use of throws arithmeticexception has advantages in code. i appreciate example of using keyword throws . thank much!

opencart2.x - Reward points is not updating in customer account in opencart website -

i using opencart 2.0 version. when customer buy product has rewards point not updating in "view rewards point" option under "my account". and show "you not have reward points!". one thing know rewards came oc_customer_reward table table not updating when customer place order. thanks..!

qt - I need help using FTP to upload files with C++ -

i've been looking way upload file using ftp c++. i'm using qt, looked built-in function, they're complicated me , don't understand explanations on pages or examples. this example: http://doc.qt.io/qt-5/qtnetwork-download-example.html i tried use curl, when tried compile example gave me bunch of errors don't understand following: this curl example: http://curl.haxx.se/libcurl/c/ftpupload.html this error when tried compile: ...ftpuploader\ftpupload.cpp:35: error: invalid conversion 'void*' 'file* {aka _iobuf*}' [-fpermissive] size_t retcode = fread(ptr, size, nmemb, stream); ^ i feel lost, welcome, either in fixing curl error or helping me understand how use qt functions handle ftp. go trusted ftp filezilla or other. files secure. rather making y

android - Cannot change the text of TextView on Button Press -

what want every time user goes 1 text in textview (q) textview (nm) shows number @ user is. in brief, every time value of variable changes, want set value text @ texview (nm) . but, here shows error. the button doesn't work. what's wrong? logcat 04-01 19:54:55.901: e/androidruntime(32078): fatal exception: main 04-01 19:54:55.901: e/androidruntime(32078): java.lang.nullpointerexception 04-01 19:54:55.901: e/androidruntime(32078): @ com.dreamgoogle.gihf.quotes$1.onclick(quotes.java:43) 04-01 19:54:55.901: e/androidruntime(32078): @ android.view.view.performclick(view.java:3524) 04-01 19:54:55.901: e/androidruntime(32078): @ android.view.view$performclick.run(view.java:14194) 04-01 19:54:55.901: e/androidruntime(32078): @ android.os.handler.handlecallback(handler.java:605) 04-01 19:54:55.901: e/androidruntime(32078): @ android.os.handler.dispatchmessage(handler.java:92) 04-01 19:54:55.901: e/androidruntime(32078): @ android.os.looper.loop(looper.java: