Posts

Showing posts from February, 2010

ruby on rails - Skip registrations in devise_token_auth -

i'm using devise_token_auth want have put , delete actions available registration. right i'm doing this: rails.application.routes.draw concern :api_endpoints mount_devise_token_auth_for 'user', at: 'users', skip: [:registrations] :users put 'users', to: 'devise_token_aut/registrations#update' delete 'users', to: 'devise_token_auth/registrations#destroy' end resources :orders, only: [:index] post 'sign_up', to: 'inactive_users#create' end namespace :api, defaults: { format: :json } namespace :v1 concerns :api_endpoints end end end and gives me routes: prefix verb uri pattern controller#action new_api_v1_user_session /api/v1/users/sign_in(.:format) devise_token_auth/sessions#new {:format=>:json} #some other routes... api_v1_users put /api/v1...

asp.net - vuejs with select 2 control missing -

Image
i have simple vue js setup trying used bind select2 using directive. rather use template reasons beyond control actual forced use asp:dropdownlist means forced have select boxes inline on client side. so attempting set vue.directive after executing directive, select2 not anywhere found. because select2 executed, original select box hidden , end nothing showing on page. debugging stops being hit , there not errors being displayed in console. <div id="tabuserinfo"> <input id="myid" type="text" required="required" ref="myid" v-model="firstname" /> <span>{{firstname}}</span> <select id="sel" v-select2="''" v-model="optid"> <option value="1">1</option> <option value="2">2</option> </select> </div><sc...

node.js - Executing Python through NodeJS -

purpose: execute python machine learning models existing nodejs api so far: i've written small class handle spawning , keeping child processes alive. can spin up, execute, , return results python process, seems oddly slow. after profiling i've discovered < 18ms spent in python code, time calling execute() callback(result) takes > 500ms. does end event take long time fire? suggestions helpful! class: const spawn = require('child_process').spawn; class pythonrunner { constructor(opts) { this.py = {}; this.script = opts[0].script; this.py.process = spawn('python', [opts[0].script]); } /* time leak in execute between write , .on(data); */ execute(args, callback) { console.time('execute'); args = json.stringify(args); let result = ''; this.py.process.stdout.on('data', (data) => { // console.log(data.tostring()); ...

Python not recognizing multiprocessing semaphore in other file -

i have 3 different files in project, main.py, generator.py , multiplicator.py. it's program multiply 2 matrix using phyton multiprocessing module. i've created semaphores in main file: from multiprocessing import process, semaphore, queue, cpu_count, value, manager random import randrange generator import * multiplicator import * mutex_mult = semaphore(1) sem_generator = semaphore(1) and i'm trying use mutex_mult lock queue in init of multiplicator process (i python has own mutex, it's programming exercise). from main import * class multiplicator(process): def __init__(self, rows_matrix_1, matrix_2, queue, row_start): process.__init__(self) self.queue = queue mutex_mult.acquire() self.matrix_final = queue.get() queue.put(self.matrix_final) mutex_mult.release() self.rows_matrix_1 = rows_matrix_1 self.matrix_2 = matrix_2 self.row_start = row_start but when call in main initializer m...

pdflatex - change alignment of \lfoot and \cfoot in latex with \fancyhdr -

i using \pagestyle{fancy} , trying align \lfoot , \cfoot sections of page. here's code: \documentclass{article} \usepackage{fancyhdr} \usepackage{graphicx} \usepackage{lipsum} \renewcommand\familydefault{\sfdefault} \makeatletter \usepackage[letterpaper,top=1.in,left=0.4in,right=0.4in]{geometry} \usepackage{calc} \usepackage{varwidth} %for varwidth minipage environment \pagestyle{fancy} \setlength{\footskip}{60pt} \lhead{} \chead{} \rhead{} \lfoot{\includegraphics[scale=0.22]{fakelogo}} \cfoot{footer \\ more footer} \rfoot{} \renewcommand\headrulewidth{0pt} \renewcommand\footrulewidth{0pt} \fancyhfoffset[lh]{\oddsidemargin + \hoffset + 0.5in} \begin{document} \lipsum[1-5] \end{document} this results in the resulting footer (i lack reputation embed it. sorry!) based on reading of fancyhdr documentation , geometry, i've tried messing \footskip , \fancyhfoffset seem move both \cfoot , \lfoot, , keep them non-centered. ideas? i'm not sure want, once f...

c# - How to serialize entity if using lazy loading in entity framework? -

i started learn entity framework , facing problem related serialization of generated models. have tables 1 many relation country , state 1 country have many states. using db first approach , when create entities using entity framework, class country has 1 property of icollection. read , found navigation property. let me show generated class first below: //this generated class. public class country { public country() { states = new hashset<states>(); } public int id { get; set; } public string contrycode { get; set; } public string contryname { get; set; } public virtual icollection<states> states{ get; set; } } i generated models , step forwarded. got problem of serialization when request via ajax list country. googled , found terms lazy loading, eager loading , n+1 problem. read in detail. found solution turning off lazy loading. question how can serialize model lazy loadin...

Connect Firebird localhost DB with php -

i have firebird server , firebird database installed on windows server. port on db 8095. on server have installed php, , need connect on db php, here code tried not success: <?php $host = 'localhost:d:\path\to\database.fdb'; $username = 'user'; $password = 'pass'; $dbh = ibase_connect($host, $username, $password); $stmt = 'select * storecards'; $sth = ibase_query($dbh, $stmt); while ($row = ibase_fetch_object($sth)) { echo $row->code, "\n"; } ibase_free_result($sth); ibase_close($dbh); ?> can me please? thanks lot edit : working code : $dbh = ibase_pconnect("ipaddr:path-to-db.fdb", "user", "pass") or die('die message'); $q = ibase_query($dbh, "select * storecards"); while ($r = ibase_fetch_object($q)) { $some_value = $r->code; echo $some_value; } as long said firebird runs on non standard 8095 port (usually 3050), should specif...

java - Tell me someone how to print string is palindrome or not -

i trying print string palindrome or not import java.util.*; import java.lang.*; class testclass { public static void main(string args[] ) throws exception { scanner s=new scanner(system.in); int n=s.nextint(); string s1=""; string rev=""; for(int i=0;i<n;i++){ s1=s.next(); stringbuilder sb=new stringbuilder(s1); stringbuilder re=new stringbuilder(rev); re=sb.reverse(); when assign sb value re apply condition check if after reversal string equal or not if(re.tostring().equals(sb.tostring())){ system.out.println("yes"); } else{ system.out.println("no"); } } } } but it's not working it's printed yes whether palindrome or not the problem called reverse() on stringbuilder , not on string . reverse character sequence of stringbuilder . , i...

c++ - Using [] operator with unordered_map in gdb give unresolved operator -

i have c++ code instantiating unordered_map , printing it's values using cout. works fine. but, when try run in gdb , print values of unordered_map, gives me error. below, code snippet: std::unordered_map<std::string,int> mymap = { { "mars", 3000}, { "saturn", 60000}, { "jupiter", 70000 } }; std::cout<< mymap.at("mars"); std::cout<< mymap["mars"]; both cout statements above print unordered_map value key "mars". however, when use gdb , try using below statements print value of mymap @ key "mars", errors. (gdb) print mymap.at("mars") cannot resolve method std::unordered_map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, std::hash<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::equal_to<std::b...

java - Change Jfoenix TabbedPane Header Color -

how change jfoenix tabbedpane default header color? jfoenix tabbedpane header only tabs color changes. colored tabs

c - Is this use of unions strictly conforming? -

given code: struct s1 {unsigned short x;}; struct s2 {unsigned short x;}; union s1s2 { struct s1 v1; struct s2 v2; }; static int read_s1x(struct s1 *p) { return p->x; } static void write_s2x(struct s2 *p, int v) { p->x=v;} int test(union s1s2 *p1, union s1s2 *p2, union s1s2 *p3) { if (read_s1x(&p1->v1)) { unsigned short temp; temp = p3->v1.x; p3->v2.x = temp; write_s2x(&p2->v2,1234); temp = p3->v2.x; p3->v1.x = temp; } return read_s1x(&p1->v1); } int test2(int x) { union s1s2 q[2]; q->v1.x = 4321; return test(q,q+x,q+x); } #include <stdio.h> int main(void) { printf("%d\n",test2(0)); } there exists 1 union object in entire program-- q . active member set v1 , , v2 , , v1 again. code uses address-of operator on q.v1 , or resulting pointer, when member active, , likewise q.v2 . since p1 , p2 , , p3 same type, should legal use p3->v1 access p1->v1 , , p3->v2 access p2...

python - BeautifulSoup4 with lxml xml parser removes xmlns attributes from inline svg in xhtml file -

i have beautifulsoup4 v4.6.0 , lxml v3.8.0 installed. trying parse following xhtml . my code parse: from bs4 import beautifulsoup xhtml_string = """ <?xml version="1.0" encoding="utf-8" standalone="no"?> <!doctype html public "-//w3c//dtd xhtml 1.1//en" "http://www.w3.org/tr/xhtml11/dtd/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> </head> <body class="sgc-1"> <svg xmlns="http://www.w3.org/2000/svg" height="100%" preserveaspectratio="xmidymid meet" version="1.1" viewbox="0 0 600 800" width="100%" xmlns:xlink="http://www.w3.org/1999/xlink"> <image height="800" width="573" xlink:href="../images/cover.jpg"></image> </svg> </body> </html> """ soup = beauti...

c# - Loading a WinForms UserControl into a WPF UserControl? -

i have wpf application, , winforms usercontrol opentk 3d viewport. trying load opentk usercontrol wpf usercontrol, in turn loaded window. compiles, viewport not show. my code is: //winforms form namespace opentk_viewport { public partial class form3dviewport : usercontrol { public form3dviewport() { initializecomponent(); } } //wpf usercontrol <grid> <wrappanel name="load3d" horizontalalignment="left" verticalalignment="top"/> </grid> public partial class form3dhost : system.windows.controls.usercontrol { public form3dhost() { initializecomponent(); // create interop host control. system.windows.forms.integration.windowsformshost host = new system.windows.forms.integration.windowsformshost(); // create maskedtextbox control. opentk_viewport.form3dviewport view = new ...

gis - Point counting under polygon -

getting count of points within polygon. have thousands of postal codes buffers surrounding them , required count of intersections fall beneath them. finding difficult, know spatial join connect them count unsure. 1 know how conduct such endeavor?

java - Vaadin navigation error -

i ve got problem navigation in vaadin. have made everythink here: http://vaadin.github.io/spring-tutorial/#_views_and_navigation_with_vaadin_spring and tried search internet answer, example here: https://vaadin.com/wiki/-/wiki/10674/iii+-+views+and+navigation+with+vaadin+spring?_36_delta=20&_36_keywords=&_36_advancedsearch=false&_36_andoperator=true&p_r_p_564233524_resetcur=false&_36_cur=2 but still have error: java.lang.illegalargumentexception: trying navigate unknown state '' , error view provider not present @ com.vaadin.navigator.navigator.navigateto(navigator.java:557) ~[vaadin-server-8.1.0.jar:8.1.0] @ com.vaadin.ui.ui.doinit(ui.java:750) ~[vaadin-server-8.1.0.jar:8.1.0] @ com.vaadin.server.communication.uiinithandler.getbrowserdetailsui(uiinithandler.java:216) [vaadin-server-8.1.0.jar:8.1.0] @ com.vaadin.server.communication.uiinithandler.synchronizedhandlerequest(uiinithandler.java:74) [vaadin-server-8.1.0.jar:8.1.0] @ com.vaadin.server.s...

visual studio - Managed Debugging Assistant 'FatalExecutionEngineError' 0xc0000005 -

managed debugging assistant 'fatalexecutionengineerror' : 'the runtime has encountered fatal error. address of error @ 0x641ad419, on thread 0x5d0c. error code 0xc0000005. error may bug in clr or in unsafe or non-verifiable portions of user code. common sources of bug include user marshaling errors com-interop or pinvoke, may corrupt stack.' this seems happen using asp.net core 1.1 , entity framework .net (not ef core). not happen of time, when it's during ef call. i've tried enabling "use managed compatibility mode" described here , doesn't seem make difference.

Is there a simple way to identify all dependent records of a record using SuiteScript in NetSuite? -

in deleting existing records during automated tests, encounter "this record cannot deleted because has dependent records" error. right scrape dependent records page record types , id's of each dependent record , delete them nlapideleterecord before proceeding. there must better way identify , delete dependent records.

javascript - applying background style to single elements safari -

so, every item produce gets individual style= background: url(${[this guy's image url]}) [blahblahblah] it works in other browsers not safari! in safari, none of images show (and there's no element.style tool in developer tools) you try putting url in single quotes this: background: url('http://some-url.domain/picture.png')

class constructor and member variables(fields) -

i trying declare class constructor there seems conflict syntax , declaring class members. any suggestions how these go together? class person (aname:string) { var name : string get() = this.name set(myname) {this.name = myname} init { this.name = aname } } you're using setter inside setter doing set(myname) {this.name = myname} . recursive call , not should do. instead use field accessor this: name: string? = null set(myname) { field = myname } but actually, don't need this. can declare in primary constructor, name should property of class: class person(var name: string)

mysql - Join parent to child node in hierarchical table structure -

i have following sql grabbing tree node , it's parent: select c.id , c.tag , ( select s.id treetable s s.lft < c.lft , s.rgt > c.rgt order s.rgt - c.rgt asc limit 1 ) parent treetable c; the problem though want s.tag inside table, can't select 2 columns wtihin subquery. how can go refactoring sql able select 2 columns? i've looked @ lot of resources on possibly trying left join, can't work. cant think of simple grouping operation either due needing use order , limit within subquery edit: structure of table looks follows: field type collation null key default privileges comment -------- ---------------- ----------------- ------ ------ ------- -------------- ------------------------------- --------- id int(10) (null) no pri (null)...

if statement - PHP only runs if I reload page -

i have if statement that'll run when reload page. here's code: if ($date == date('00:00:00') && (isset($postchecktoday))){ // code goes here } the if statement within function runs constantly. when hits 00:00:00, have reload page dead-on time if statement runs. want if statement run without having reload page @ 00:00:00. the whole point of running precisely @ 00:00:00 runs if statement once every 24 hours. is there alternative way of doing using strictly php? use cron wouldn't execute whole php file once day? @ moment have function that's running code, , if statement within function runs @ 00:00:00. unless cron able directly call if statement php file, i'm unsure if use me. if need keep seperate, create php script , use cron execute once day, @ hour 0, minute 0, second 0. reference this

Exception and Error in powershell -

try block throws exception in catch block resolve-error method gets $error null (zero elements in array), although $_.exception gives me correct message. reason , how should resolve it? function resolve-error($errorrecord=$error[0]) { $errorrecord | format-list * -force $errorrecord.invocationinfo | format-list * $exception = $errorrecord.exception ($i = 0; $exception; $i++, ($exception = $exception.innerexception)) { "$i" * 80 $exception | format-list * -force } } try { dsfhjbahdjfb } catch { write-host $_.exception if ($_.exception.response -ne $null) { $result = $_.exception.response.getresponsestream() $reader = new-object system.io.streamreader($result) $reader.basestream.position = 0 $reader.discardbuffereddata() $responsebody = $reader.readtoend(); write-host $responsebody } resolve-error throw "exception....." }

c# - For some reason my async method doesn't work in specific cases -

so... month ago started developing universal windows platform on visual studio, , made small app keep prices of bitcoin, ethereum , litecoin (each 1 chart , everything). my problem comes in function called "gethisto", gets historic values last hour/day/week/month/year, , works expected changing between time-ranges clicking in 1 of 5 buttons, except if jump month/year last hour, when app stays loading forever. this code gethisto: async internal static task gethisto(string crypto, string time, int limit) { string url = "https://min-api.cryptocompare.com/data/histo" + time + "?e=cccagg&fsym=" + crypto + "&tsym=" + coin + "&limit=" + limit; if (limit == 0) url = "https://min-api.cryptocompare.com/data/histoday?e=cccagg&fsym=" + crypto + "&tsym=" + coin + "&alldata=true"; uri requesturi = new uri(url); httpclient http...

Elm: How to fetch data on page load with Navigation.newUrl? -

i have elm application multiple pages/routes. have "/dashboard" route needs data on page load. i had modify init function when user hard browser reload, , had modify update function's onlocationchange clause when navigation.newurl called. my question is: right way this? hate having modify 2 functions when feels there should 1 place handles this. i think let update function handle cmd creation. init : navigation.location -> ( model, cmd msg ) init location = update (locationchange location) initialmodel

python - Trying to understand scipy and numpy interpolation -

Image
if have measured data function don't know (let's it's either not important, or computationally difficult), such as x2 = [0, 1, 10, 25, 30] y2 = [5, 12, 50, 73, 23] and use numpy.interp find intermediate values, gives me linear interpolant between points , straight line: xinterp = np.arange(31) yinterp1 = np.interp(xinterp, x2, y2) plt.scatter(xinterp, yinterp1) plt.plot(x2, y2, color = 'red', marker = '.') the example scipy.interpolate docs gives x = np.linspace(0, 10, num=11, endpoint=true) y = np.cos(-x**2/9.0) f = interp1d(x, y) f2 = interp1d(x, y, kind='cubic') xnew = np.linspace(0, 10, num=41, endpoint=true) plt.plot(x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--') plt.legend(['data', 'linear', 'cubic'], loc='best') plt.show() with different kind s of interpolation smoother curve. if want points in smooth curve, rather curve? there function in numpy or scipy can g...

linux - create deb package - version equal not working in Depends section -

i creating deb package requires specific version of docker-ce, in "depends" section, wrote "depends: docker-ce(=17.03.0~ce-0~ubuntu-xenial)". deb generated fine, , after installation "dpkg -i my-package-name.deb", use "sudo apt install -f" force install missing package. trying remove package, output follows. <= , >= work pretty well. the following packages removed: my-package-name 0 upgraded, 0 newly installed, 1 remove , 177 not upgraded. 1 not installed or removed.

java - Dynamodb mapper unable to read when using @DBDocument annotation -

i have entity class has strings/ints member variable , member variable type photo. have defined photo type as: @dynamodbdocument public static class photo { @dynamodbattribute(attributename = "url") public string geturl() { return url; } @dynamodbattribute(attributename = "width") public integer getwidth() { return width; } @dynamodbattribute(attributename = "height") public integer getheight() { return height; } public void seturl(string url) { this.url = url; } public void setwidth(integer width) { this.width = width; } public void setheight(integer height) { this.height = height; } private string url; private integer width; private integer height; public photo(string url, integer width, integer height) { this.url = url; this.width = width; this.height = height; } } when try write entity ob...

c# - Multithread SQL select statements -

i multithreading novice , sql novice, please excuse rookie mistakes. i trying execute many sql queries asynchronously. queries select statements same table in same database. can run them synchronously , works fine, testing small subset leads me believe run queries synchronously take approximately 150 hours, far long. such, i'm trying figure out how run them in parallel. i have tried model code after answer @ run method multiple times simultaneously in c# , code not executing correctly (it's erroring, though not know how. code says error occurs). here have (a smaller , simpler version of doing): class program { static void main(string[] args) { list<string> employeeids = file.readalllines(/* filepath */); list<tuple<string, string>> namesbyid = new list<tuple<string, string>>(); //what not want (because takes long) ... using (sqlconnection conn = new sqlconnection(/* connection string */)) ...

azure - How to make a controller method private and accessible only to a specific service in Service Fabric? -

i have 2 services running in service fabric cluster. let's assume service , service b, both of them stateless services. using dns service method communicate between , b , entry point in b api has route. route publicly accessible since have exposed port 80 publicly service. , though trying access api have send appropriate auth tokens, still don't want able outside cluster access api. there other way can achieve trying do? know way use service proxy pattern reason did not work me.

Maven archetype:generate -

i trying generate project instructed third party. however, unknown reason not working. given limited knowledge, grateful can point me in right direction solve issue. i did a mvn archetype:crawl then trying create project in interactive mode follow: mvn archetype:generate -darchetypecatalog=local i presented available choice. here complete dialog: c:\projets\oo_actions\loadfile>mvn archetype:generate -darchetypecatalog=local [info] scanning projects... [info] [info] ------------------------------------------------------------------------ [info] building maven stub project (no pom) 1 [info] ------------------------------------------------------------------------ [info] [info] >>> maven-archetype-plugin:3.0.1:generate (default-cli) > generate-sources @ standalone-pom >>> [info] [info] <<< maven-archetype-plugin:3.0.1:generate (default-cli) < generate-sources @ standalone-pom <<< [info] [info] [info] --- maven-archetype-plugin...

python - Flask: OperationalError: unable to open database file -

i having immense difficulties attempting flask application's database working. following sample tutorial flask , deploying site on apache server through amazon ec2 instance. have no difficulties accessing site, whenever try post database 500 internal server error. checking error.log shows: [wed sep 13 19:37:47.713249 2017] [wsgi:error] [pid 27587] [client 209.54.86.83:50492] [2017-09-13 19:37:47,712] error in app: exception on /add [post], referer: http://www.zachflask.tk/ [wed sep 13 19:37:47.713291 2017] [wsgi:error] [pid 27587] [client 209.54.86.83:50492] traceback (most recent call last):, referer: http://www.zachflask.tk/ [wed sep 13 19:37:47.713294 2017] [wsgi:error] [pid 27587] [client 209.54.86.83:50492] file "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1982, in wsgi_app, referer: http://www.zachflask.tk/ [wed sep 13 19:37:47.713296 2017] [wsgi:error] [pid 27587] [client 209.54.86.83:50492] response = self.full_dispatch_request(), refere...

SublimeREPL: R - Want the cursor back after running R scripts -

i'm using sublime text 3 r scripts sublimerepl: r. spliting st3 2 panels(shift + alt + 2, left , right panels), edit r scripts , execute scripts(ctrl + enter, r-box), see results on sublimerepl r panel. i want 2 st3 windows (not spliting 1 window 2 panels), , easy - moving r source code tab main window. after executing r scripts, cursor goes repl: r window not return r script window. there configuration settings this? (returning cursor original editor after executing scripts)

python - Text File to Numpy Array -

good evening, have text file has letters, floats , ints such this: p 0 0 p 1 0 p .5 1 p .1 2 f 3 1 2 f 2 1 4 f 4 1 3 w -20.0 -20.0 20 20 so basically: p = points(x,y) f = faces f 4 1 3 means connect p4 p1 , p3 creating lines between these points create figure w = window size on canvas through tkinter i'm attempting read in text file array through numpy using: np.genfromtxt(filename, delimiter=' ', dtype=none) but keep getting valueerror: got 3 columns instead of 2 at point, there way store of data array ? or should store them separate lists p, f, , w , converting lists parray, farray, , warray ? , connecting points drawing lines using these different arrays ?

mysql - I can't insert stock's data into my database -

def connect(date1,volumn1,price1,rise1,time1): #print type(date1),volumn1,price1,rise1,time1 db=mysqldb.connect("localhost","root","998426","stock") cursor=db.cursor() sql=" insert tab1(date,volumn,price,rise,time) values(%s,%s,%f,%s,%s)"%(date1,volumn1,price1,rise1,time1) #sql = "insert tab1(date,volumn,price,rise,time) values('2017/9/13 星期二','200',17.5,'2.14%','15:30')" //this can work! try: cursor.execute(sql) db.commit() except: db.rollback() db.close() date1,volumn1,rise1,time1 string; price1 float; sql="insert stock_cb(dates,volumn,price,rise,times) values('%s','%s',%f,'%s','%s')" % (date1.encode("utf-8"),volumn1.encode("utf-8"),price1,rise1.encode("utf-8"),time1.encode("utf-8")) it can work when change it.

javascript - Errors initiating Angular Authentication using JWTs and jwtInterceptor -

currently, running angular 1.6.6. , angular-jwt 0.1.9. following examples read.me file of angular-jwt auth0 site here "how can send jwt on every request server?" . 2 examples vary slightly. angular-jwt docs uses jwtoptionsprovider , auth0 example uses jwtinterceptorprovider in .config section angular controller. when run code browser console states: "failed instantiate module controllername due to: error: [$injector:unpr] unknown provider: jwtinterceptorprovider" the error same jwtinterceptorprovider , jwtoptionsprovider. here code in angular controller, same docs. wanting make code run can understand how use it: angular .module('app', ['angular-jwt']) .config(function config($httpprovider, jwtoptionsprovider) { jwtoptionsprovider.config({ tokengetter: ['myservice', function(myservice) { myservice.dosomething(); return localstorage.getitem('id_token'); }] }); $httpprovider.intercepto...

Colormapping the Mandelbrot set by iterations in python -

i using np.ogrid create x , y grid drawing values. have tried number of different ways color scheme according iterations required |z| >= 2 nothing seems work. when iterating 10,000 times sure have clear picture when zooming, cannot figure out how color set according iteration ranges. here code using, of structure borrowed tutorial. suggestions? #i found function , searched in numpy best usage type of density plot x_val, y_val = np.ogrid[-2:2:2000j, -2:2:2000j] #creating values work during iterations c = x_val + 1j*y_val z = 0 iter_num = int(input("please enter number of iterations:")) n in range(iter_num): z = z**2 + c if n%10 == 0: print("iterations left: ",iter_num - n) #creates mask filter out values of |z| > 2 z_mask = abs(z) < 2 proper_z_mask = z_mask - 255 #switches current black/white pallette #creating figure , sizing optimal viewing on small laptop screen plt.figure(1, figsize=(8,8)) plt.imshow(z_mask.t, extent=[-2, 2, -2, ...

node.js - How to use "import" in nodejs v6.11.3 -

this question has answer here: nodejs plans support import/export es6 (es2015) modules 1 answer i want use "import" in nodejs + express app. i know nodejs v6 support es6. but can't use "import" in nodejs app. node give me message. => syntaxerror: unexpected token import what can es6. node.js 6 not support esmodules, commonjs modules. can still use esmodules need install babel , transpile code.

Vb.Net: Limit the total width of characters entered into a textbox? -

let me clear - not looking static character limit here (textbox.maxlength doesn't cut it.) i'm making simple messaging program , i'd implement character limit. messages displayed inside listbox , can't horizontally scrolled/wrapped. solution: impose limit on every message users don't accidentally cut off own messages. the problem 10 small characters lot smaller 10 full width characters. - e.g. , w: iiiiiiiiii wwwwwwwwww i'd find way limit characters entered text box actual amount of pixels string wide. that: nobody can use capitals , cut off, , nobody can type , stopped character limit far earlier neccesary. for reference, i'm using verdana 8.25pt listbox. any suggestions appreciated, thanks. this should trick you. i've deliberately chosen keyup event because user see letter typed , disappearing. private sub textbox1_textchanged(sender object, e keyeventargs) handles textbox1.keyup dim text1 string = textbox1.text ...

android - Alarm Manage Issue -

my app has repeating tasks running every 5-minutes. try install same app twice , alarm manager don't fire broadcast doing task. first time install working time, until reinstall same version stop repeating task. problem alarm manager. don't it. this code: intent intent = new intent(context, checkingpricereceiver.class); intent.setaction("com.abccompany.trading"); pendingintent pendingintent = pendingintent.getbroadcast(context, req_code, intent, pendingintent.flag_update_current); long minterval = 300000; long triggertime = system.currenttimemillis() + minterval; alarmmanager alarmmanager = (alarmmanager) context.getsystemservice(context.alarm_service); alarmmanager.setrepeating(alarmmanager.rtc_wakeup, triggertime, minterval, pendingintent); i don't know how fix it. please help!!~~ from answer, android alarm difference between 4 types of alarm alarmmanager provides , when use what? also tells ...

java - using a while loop for user to input multiple int and find the max and min -

so homework question prompt user series of integers , find max , min of integer. use loop , -99 break loop.below code question is there shorter way this? feel free comment , appreciate time reading this. scanner input=new scanner(system.in); int num1,num2,max,min; system.out.print("enter number: "); num1=input.nextint(); system.out.print("enter number: "); num2=input.nextint(); max=math.max(num1,num2); min=math.min(num1,num2); while (num2!=-99){ system.out.print("enter number or -99 stop: "); num2=input.nextint(); if(num2!=-99){ max=math.max(max,num2); min=math.min(min,num2); } } system.out.println("largest is: "+max); system.out.println("smallest is: "+min); ok after working on this. did it. have small bug, don't wanna fix if anyway wants edit guest. scanner input = new scanner(system.in); int studentnum = 0; arraylist<integer> calc = new...

java - How should I approach or shouldn't unit test? -

i have huge codebase written else not unit tested @ all. want add unit testing spring application.but code of decoupled , times code not testable. how should approach should start low level objects or high level once , can give me step step example of how write unit tests spring application. you can transform @autowired attributes @autowired constructors. check example: @component public class someclass { @autowired private somedependency somedependency; public ... dosomething(...) { ... } } can transformed to @component public class someclass { private somedependency somedependency; @autowired public someclass(somedependency somedependency) { this.somedependency = somedependency; } public ... dosomething(...) { ... } } in fact, injection method preferred since object has all dependencies needs when constructor finishes. in first approach need like: someclass someclass = new someclass(); somec...

How to dynamic add rank on Solr? -

i'm using solr 6.1 for request, need dynamic add ranking solr can this? and if want add ranking field value, there way it? you can use function queries dynamic ranking. see https://wiki.apache.org/solr/functionquery additionally, try out solr's learning rank module. you'll have upgrade @ least solr 6.4.0.

Toggle SideBar Menu from other component in Angular 4 -

Image
how can implement sidebar toggle menu in angular app. i'm confused on how call sidebar menu in other component. toggle button found on header component. it's purpose show sidebar menu when click toggle button on header component. header.component.html <div class="navbar-header"><a id="toggle-btn" href="#" class="menu-btn"><i class="icon-bars"> </i></a><a href="index.html" class="navbar-brand"> <div class="brand-text"><span>mcdonalds</span></div></a></div> sidebar.component.html <nav class="side"> <h1>click show me</h1> </nav> core.component.html <app-header></app-header> <app-sidebar></app-sidebar> you can use shared service open sidebar. create service vith eventemitter , emit event when want open sidebar. then,...

javascript - Highcharts manually added svg elements not following stock graph on pan -

i have click event in highstock / highchart graph, have added custom drawing tools such adding lines , text. here code that $('#stockchart-canvas-container').on('click','svg',function(e){ var svg = $('#stockchart-canvas-container svg')[0]; var point= svg.createsvgpoint(), svgp point.x = e.clientx point.y = e.clienty svgp = point.matrixtransform(svg.getscreenctm().inverse()); if(user.selected_tool=='line'){ if(user.previous_x == undefined && user.previous_y == undefined) { user.current_x = svgp.x user.current_y = svgp.y user.previous_x = 0 user.previous_y = 0 $('#stockchart-canvas-container').on('mousemove','svg',function(ev){ var svg2 = $('#stockchart-canvas-container svg')[0]; var point2= svg.createsvgpoint(), svgp2 ...

Reading csv files and importing data into SQL Server -

i'm reading numbers .csv file sql server below statement, assuming i've created linked server named csv_import. select * csv_import...sophos#csv however, problem if have comma numbers data, show null instead of correct one. how can read "54,375" correctly sql server? thank help. below data in csv file. 09/07/2017,52029,70813,10898,6691,6849,122,25,147427 09/08/2017,47165,61253,6840,5949,5517,75,2,126801 09/14/2017,"54,375","16944","15616","2592","3280",380,25,"96390" this result statement: 2017-09-07 00:00:00.000 52029 70813 10898 6691 6849 122 25 147427 2017-09-08 00:00:00.000 47165 61253 6840 5949 5517 75 2 126801 2017-09-14 00:00:00.000 null 16944 15616 2592 3280 380 25 96390 one way go using temporary table. read data text, replace every comma in whole table dot ( . ), if want decimal separator, or empty string( '' ) if it's...

MIPS Input floating point number -

how take in input of floating number in mips? have tried using: li.s $f0, 6 syscall but keep getting there error line. li $v0, 6 syscall //the float value read in $f0 register

sse - atan2 approximation with 11bits in mantissa on x86(with SSE2) and ARM(with vfpv4 NEON) -

i'm trying implement fast atan2(float) 11 bits accuracy in mantissa. atan2 implementation used image processing. might better implemented simd instruction(the impl targeting x86(with sse2) & arm(with vpfv4 neon)). for now, use chebyshev polynomial approximation( https://jp.mathworks.com/help/fixedpoint/examples/calculate-fixed-point-arctangent.html ). i'm willing implement vectorized code manually. use sse2(or later) & neon wrapper library. plan or tried these implementation option vectorized polynomial approximation chebyshev polynomial(now implemented) scalar table ( + linear interpolation) vectorized table (is possible? i'm not familiar neon, don' know instructions vgather in neon) vectorized cordic method (this may slow since require 12+ rotation iterations 11bits accuracy) else idea? the first thing want check whether compiler able vectorize atan2f (y,x) when applied array of float s. requires @ least high optimization level su...

Google Chart API Implementation -

Image
am using google api implement chart in project. using scatter chart. need implement chart below. how can achieve this.? there other way achieve using other open source chart.? sample google chart need additional requirement you can use combochart combine scatter , area series the area series should stacked set color of first layer 'transparent' use null values series not coincide see following working snippet... google.charts.load('current', { callback: drawchart, packages: ['corechart'] }); function drawchart() { var data = new google.visualization.datatable(); data.addcolumn('number', 'x'); data.addcolumn('number', 'area bottom'); data.addcolumn('number', 'area top'); data.addcolumn('number', 'scatter'); data.addrows([ [1.5, null, null, 1.5], [3, 3, 3, null], [6, 3, 3, null] ]); var options = { areaopaci...