Posts

Showing posts from February, 2011

java - Mockito return false -

i write simple test on mokito. public class contactservicetest { @mock private serviceclient client; @mock private contactservice contactservice; @before public void init() { client = mock(serviceclient.class); contactservice = mock(contactservice.class); } @test public void test_sendemailcontact() { contactdto cdto = new contactdto(); cdto.settitle("mr"); cdto.setfirstname("pritam"); cdto.setlastname("mohapatra"); cdto.settelephone("9439586575"); cdto.setemail("pritam.pritam176@gmail.com"); cdto.setbetreff("test value"); cdto.setanfrage("test value"); when(client.posttoservice("customer/sendemailcontact", cdto, boolean.class)).thenreturn(true); assert.assertequals(true, contactservice.sendemailcontact(cdto)); } } but when fail msg expected true return false m

c++ - Print Preview in Qt -

i want preview page or want have print preview. preview window opening contents of qt window not comming in it. code print preview follows: void user::on_actionprintpreview_triggered() { qprinter printer(qprinter::highresolution); qprintpreviewdialog preview(&printer, this); connect(&preview, signal(paintrequested(qprinter *)), this, slot(print(qprinter *))); preview.exec(); } void user::print(qprinter *printer) { // print page qpainter painter(printer); int w = printer->pagerect().width(); int h = printer->pagerect().height(); qrect page(0, 0, w, h); qfont font = painter.font(); font.setpixelsize((w+h)/100); painter.setfont(font); painter.drawtext(page, qt::alignbottom | qt::alignright, qdatetime::currentdatetime(). tostring(qt::defaultlocaleshortdate)); page.adjust(w/20, h/20, -w/20, -h/20); } how can content of qt window in it. doing wrong. please m

what happens when the function returning value is a pointer and the returning type is a reference in c++? -

guys, got bonus question teacher! helping me !! the sub2 below not result in run-time error, there may other problem. problem? enter code here int& sub2 ( int& , int& b ){ int * pc = new int ; *pc = - b ; return (*pc ) ; } this function might lead memory leaks. if user of function relies on signature of function, he'll assume function returns reference object else owns. hence object allocated not released. of course, if user aware of trick, still delete object taking address of reference if function used in larger expression (which quite tempting, given signature), such sub(3, sub(2,1)) not opportunity catch temporary reference. note function might throw bad_alloc if there's issue memory allocation.

webserver - String after a Variable .htaccess -

i'm stucked in little problem: i want make short link let user view images of user "test.test". my code: rewriterule ^(.*)\.(.*)$/images images.php?user-id=$1.$2 [qsa,l] example: website.com/tester.tester/images           <== has end-result full code here: rewriteengine on # turn on rewriting engine rewriterule ^(login|settings|friends|gallery|logout|signup|administrator)/?$ $1.php [nc,l] rewriterule ^home/?$ profile.php?user-id=home [qsa,nc,l] rewritecond %{request_filename} !-f rewritecond $1 !^index [nc] rewriterule ^(.*)\.(.*)$ profile.php?user-id=$1.$2 [qsa,l] # rewriterule ^([a-za-z0-9-\s]+)\.([a-za-z0-9-\s]+)$ profile.php?user-id=$1.$2 [qsa,l] #umlaute müssen gehen!! well tried best , hope work. i'm not happy that: the updated code: rewriteengine on # turn on rewriting engine rewriterule ^(login|settings|friends|gallery|logout|signup|administrator)/?$ $1.php [nc,l] rewriterule ^home/?$ profile.php?user-id=home [qs

python 3.x - Stuck on Encryption with a keyword -

i using python3.4.1. appreciated text = (str(input('enter message here, in upper case'))) key = (str(input('enter key word here, in upper case'))) in range (0,len(text),1): code = ord((text[a])+(ord(key[a%len(key)]))-64) if (text[a]==' '): print(' ', end= '') elif code > 90: print(chr(code + 26), end = '') else: print(chr(code), end = '')

html - Preview not displaying any letters while typing in search box -

Image
in jsfiddle.net it's working not when previewing app worklight console: http://jsfiddle.net/sphakrrokr/k4l6ej9z/6/ before, when simple html written working position not side side search box , go buttton <input type="search" name="search" id="search" data-mini="true" placeholder="search restaurants" data-theme="a" data-inline="true"> <input type="submit" value="go" data-inline="true" id ="submit" onclick="getrestaurants()"> after changes positioning side side, afterwards text not displayed when typing... <head> <style type="text/css"> #the-page {float:center;width:100%} #submit_con {width:20%; float:left;} #search_con {width:80%; float:left;} #search {width:100%;} #submit {width:100%;} </style> </head> <body> <div data-role="header" id="the-page"

python - Forcing a thread to block all other threads from executing -

update: this answer states i'm trying impossible of april 2013. this, however, seems contradict alex martelli says in python cookbook (p. 624, 3rd ed.): upon return, pygilstate_ensure() guarantees calling thread has exclusive access python interpreter. true if calling c code running different thread unknown interpreter. the docs seem suggest gil can acquired, give me hope (except don't think can call pygilstate_ensure() pure python code, , if create c extension call it, i'm not sure how embed memory_daemon() in that). perhaps i'm misreading either answer or python cookbook , docs. original question: i want given thread (from threading module) prevent other thread running while segment of code executing. what's easiest way achieve it? obviously, great minimize code changes in other threads, avoid using c , direct os calls, , make cross-platform windows , linux. realistically, i'll happy have solution whatsoever actual environment

project - Need advice on what technologies to use for mobile app -

i need develop mobile application school work , need advice on best approach be. can html5 based, native android app or else long it's made mobile platforms. needs make use of database, have login function (can login through facebook) , interaction between users. i barely have experience server-side scripting, web development or mobile app development. i'm quite @ general java programming though, , know bit of html/css (no javascript). so i'm wondering is: technologies should invest time in learning in order develop app within 8 weeks or so? ease of learning top priority. it's plus if it's multi-platform solution. for ease of learning recommend html 5 , javascript make phonegap application. phonegap faster develop native android app, because can test web browser.

html - Dropdown menu in sidebar -

this has got me stumped. have done before when worked, , won't. the light background behind navagation bar should behind body of page. footer should not in it. there more content go on page heading welcome herb place should have light background same nav bar. when have written <div id="content-scroll"> in html div part comes red , doesn't recognise it. body { background-attachment: fixed; background-image: url("../photos/background.jpg"); background-position: center center; background-repeat: repeat; background-size: 100%; font-family: "open sans", sans-serif; font-size-size: medium; font-style: normal; line-height: 1.6em; margin: 1px auto auto; text-align: left; max-width: 1024px; } #navigation li { list-style: none; display: block; float: left; margin: 1em; } #navigation li { display: block; text-decoration: none; color: #006

calculate distance b/w Bluetooth Low Energy device and android phone -

i have ble device. want rssi values device. calculate distance between android phone & ble device. please send procedure/code that. there no known way compute distance between wireless transmitter , receiver based on rssi. due multipath effects in sending wireless signals in real environments. rssi not monotonic decreasing on distance; if take receiver , measure rssi while moving away transmitter, may see rssi go , down. the way location computed devices bluetooth low energy find closest device of known location , approximate using that.

Twitter unavailable on ios simulator -

twitter says unavailable in ios simulator next logo in settings. still logged in perfectly, why unavailable. the unavailable you're seeing button takes twitter app in app store. app store not available on simulator, unavailable button shown. it's not stating logging twitter through simulator's settings unavailable.

xcode - UISearchController not updating -

i developing using xcode 6.2 in ios8 , swift, trying implement uisearchcontroller inside uitableviewcontroller updated after search, wrote simple code check if works, when compile, search bar there, when enter text , hit search, nothing happens: here code: import uikit class searchresult: uitableviewcontroller,uisearchbardelegate, uisearchcontrollerdelegate, uisearchresultsupdating { var result:[string] = ["a","b","c"] override func viewdidload() { super.viewdidload() var searchcon = uisearchcontroller(searchresultscontroller: self) searchcon.delegate = self searchcon.searchbar.delegate = self searchcon.searchbar.sizetofit() self.tableview.tableheaderview = searchcon.searchbar searchcon.searchresultsupdater = self searchcon.searchbar.showssearchresultsbutton = true self.definespresentationcontext = true searchcon.dimsbackgroundduringpresentation = false

javascript - Return to scroll position after the page has been scrolled to top -

i trying make sidebar appear when relevant button clicked, on small devices, i'm facing difficulties. i found way toggle class make dis/appear on click , automatically scroll page top once done, top of sidemenu shown viewers regardless of part of page viewing @ moment. however, find quite hard combine these way make page return scroll point visitor at, after sidemenu has disappeared. me this? html: <div class="col-md-2" role="navigation"> <ul class="nav" id="sidemenu"> <li><a href="#">lorem ipsum dolo</a></li> <li><a href="#">lorem ipsum dolo</a></li> <li><a href="#">lorem ipsum dolo</a></li> </ul> </div> js: $('#sidebutton').click(function() { $('#sidemenu').toggleclass("current") && $('html,body').scrolltop(0); $('.nodispla

javascript - google sheets trouble with xml -

i trying pull data ups tracking spreadsheet. signedforbyname part of xml feed there , not. when isn't there, issue: typeerror: cannot read property "text" undefined. (line 60, file "code") if comment out line 60 looking signedforbyname fine after pull variable out of string supposed generated. i'm not familiar javascript doing daft syntax thing, great. easy answers. if point me in right direction snippit, appreciate it. i figured if check if value there way go, doesn't seem working either same error occurs in same place or without if/then (even if messed syntax). code missed mark on: catch(err) { if (jsontext.trackresponse.shipment.package.activity.activitylocation.signedforbyname.text !==null){ var signedby = jsontext.trackresponse.shipment.package.activity.activitylocation.signedforbyname.text;} else {var signedby = "no signature";} var droplocation = jsontext.trackresponse.shipment.package.activity.activitylocation.descriptio

bitmap - com.android.camera.action.CROP The auto resize? -

i using com.android.camera.action.crop . code similar jennifer's answer here app works fine on android 4.4 - 5.0, there problems on api levels 4.0 - 4.3. my question: latter, cropped , saved image smaller in size illustrated here . there known issue com.android.camera.action.crop in terms of auto resizing on api levels?

MYSQL on delete cascade example -

i can't figure out how use on delete cascade in example. create table `users` ( `login` varchar(16) not null, `password` varchar(16) not null, primary key (`login`), unique key `login` (`login`) ) engine=innodb default charset=utf8 create table `employees` ( `id` int(11) not null auto_increment, `name` varchar(20) not null, `surname` varchar(25) not null, `birthday` date not null, `adres` varchar(50) not null, `telephone` varchar(25) not null, `login` varchar(16) default null, primary key (`id`), unique key `login` (`login`), constraint `employees_ibfk_1` foreign key (`login`) references `users` (`login`) ) engine=innodb default charset=utf8 one table stores informations employee , if has account(login) there table logins , passwords. my goals: not every employee needs have user account(that means - unique record in users table) employees.login shouldn't restricted not null. i want possiblity add new user in users , assign employee

api - cannot get the favorite movies from tmdb with validated session ID? -

i can account details via session id cannot favorite movies same session id. know? once have valid session_id user, need call users /movie/favorite method. here's example: https://api.themoviedb.org/3/account/{id}/favorite/movies?api_key={api_key}&session_id={session_id} note {id} , {api_key} , {session_id} vars need changed. hope helps.

python - How can I use scipy.interpolate.interp1d to interpolate multi Y arrays using the same X array? -

as example, have array of 2-d data error bars on 1 of dimensions, such this: in [1]: numpy np in [2]: x = np.linspace(0,10,5) in [3]: y = np.sin(x) in [4]: y_er = (np.random.random(len(x))-0.5)*0.1 in [5]: data = np.vstack([x,y,y_er]).t in [6]: data array([[ 0.00000000e+00, 0.00000000e+00, -6.50361821e-03], [ 2.50000000e+00, 5.98472144e-01, -3.69252108e-03], [ 5.00000000e+00, -9.58924275e-01, -2.99042576e-02], [ 7.50000000e+00, 9.37999977e-01, -7.66584515e-03], [ 1.00000000e+01, -5.44021111e-01, -4.24650123e-02]]) if want use scipy.interpolate.interp1d, how format have call once? want avoid repeated method: in [7]: import scipy.interpolate interpolate in [8]: new_x = np.linspace(0,10,20) in [9]: interp_y = interpolate.interp1d(data[:,0], data[:,1], kind='cubic') in [10]: interp_y_er = interpolate.interp1d(data[:,0], data[:,2], kind='cubic') in [11]: data_int = np.vstack([new_x, interp_y(new_x), interp_y_er(new_x)]

c++ - Break for loop with function? -

void fbreak(int i){ if(5==i) break; } void main(){ for(int = 0;i<10;i++){ fbreak(i); } } i want function fbreak break loop. seems code not work. in fact trying implement stadard algorithm std::find (or std::find_if ) declared in header <algorithm> you write program following way bool fbreak( int ) { return == 6; } int main() { int = 0; while ( < 10 && !fbreak( ) ) i++; } take account function main shall have return type int .

node.js - Error installing bcrypt with npm -

i'm unable install bcrypt using npm on machine because encounter following errors. have been troubleshooting issue without luck. can recommend steps diagnose or fix problem can run npm install bcrypt successfully? someones-macbook:node_modules cody$ npm install bcrypt npm warn package.json grunt-contrib-htmlmin@0.1.3 no readme data | > bcrypt@0.7.7 install /applications/mamp/htdocs/richintime/ultimate-seed/node_modules/bcrypt > node-gyp rebuild child_process: customfds option deprecated, use stdio instead. cxx(target) release/obj.target/bcrypt_lib/src/blowfish.o cxx(target) release/obj.target/bcrypt_lib/src/bcrypt.o cxx(target) release/obj.target/bcrypt_lib/src/bcrypt_node.o ../src/bcrypt_node.cc:118:18: error: no member named 'dispose' in 'v8::persistent<v8::function, v8::noncopyablepersistenttraits<v8::function> >' callback.dispose(); ~~~~~~~~ ^ ../src/bcrypt_node.cc:202:19: error: unknown type name 'uv_w

python - Dedenting function in QPlainTextEdit causes segfault if last line is involved -

i'm working on source code editor should have smart indent/dedent behaviour. however, dedenting method seems causing segmentation fault. i'd pleased if work out why. here's minimal example: #!/usr/bin/env python import sip sip.setapi('qstring', 2) sip.setapi('qvariant', 2) pyqt4 import qtgui pyqt4.qtcore import qt class editor(qtgui.qplaintextedit): def keypressevent(self, event): key = event.key() if key == qt.key_backtab: cursor = self.textcursor() start, end = cursor.selectionstart(), cursor.selectionend() cursor.begineditblock() b = self.document().findblock(start) while b.isvalid() , b.position() <= end: t = b.text() p1 = b.position() p2 = p1 + min(4, len(t) - len(t.lstrip())) cursor.setposition(p1) cursor.setposition(p2, qtgui.qtextcursor.keepanchor) cursor.removeselec

Java Communication Server Client with Socket -

i'm having trouble client/server program in java . i'm able communicate client server when i'm broadcasting server client it's not working. there part of program not working : server : while (true) { socket socket = server.accept(); out = new bufferedwriter(new outputstreamwriter(socket.getoutputstream())); out.write("welcome server !"); out.flush(); } client ( running thread): while(true){ try { //s socket connection server in = new bufferedreader (new inputstreamreader (s.getinputstream())); string msg = in.readline(); system.out.println(msg); } catch (ioexception ex) { } } when use client programm don't receive message sent server . when use netcat on terminal establish connection on server, got message . don't it. thanks the client expects complete line sent: string msg = in.readline(); it ca

xcode - Why SKNode isn't reacting to touch in SpriteKit game? -

Image
in order make pause in spritekit game made pause button. worker charm when wanted make scene pause , respond touch transitioning scene. function looked like this (p.s. pause = pause button) there other problems , decided make pause within main scene: playscene added pausebackground , resumebutton attached pause background , hided (declared resumebutton.hidden = true ) function looks this: override func touchesbegan(touches: nsset, withevent event: uievent) { if self.onground { self.speedy = -20.0 self.onground = false } touch: anyobject in touches { let location = touch.locationinnode(self) if self.nodeatpoint(location) == self.pause { self.scene?.view?.paused = true self.pausebackground.hidden = false self.resumebutton.hidden = false if self.nodeatpoint(location) == self.resumebutton { self.pausebackground.hidden = true self.resumebutton.hidden = true self.scene?.view?.paused = f

c - Saving registers state in COM program -

i disassembled simple dos .com program , there code saves , restores registers values push ax ; first instruction push cx .... pop cx pop ax mov ax, 0x00 0x4c int 21 // call dos interrupt 21 => end this similar function prologue , epilogue in c programs. prologues added automatically compiler, , program above written manually in assembler, programmer took full responsibility saving , restoring values in code. my question happen if unintentionally forgot save registers in program? and if intentionally replace these instructions nop in hex editor? lead program crash? , why called function responsible saving outer context on stack? point of view should done somehow in calling function prevent problems if use 3rd party libraries , poorly written code may break program execution. one problem of making calling function save of working registers before calling function function interrupted (i.e. hardware interrupt) without knowledge. in dos, example, there pesky 54 mi

java - abstract class and arraylist -

i don't understand lines on code public abstract class subject{ the class abstract subject super class public subject() { and constructor? like inside constructor passed on sub classes? observers = new arraylist<ioserver> (); here have no idea. the constructor passed on subclass constrained. observers variable initialized within constructor, don't see declared. like: arraylist<ioserver> observers = new arraylist<ioserver> ();

c# - Xmlpullparser in Xamarin android -

i'm trying parse rss feed 1 website got stuck parsing images. want replace placeholders images website , when try nothing happens placeholders ar still there , here code feedservice class: try { webrequest webrequest = webrequest.create(url); webresponse webresponse = webrequest.getresponse(); stream stream = webresponse.getresponsestream(); xmldocument xmldocument = new xmldocument(); xmldocument.load(stream); xmlnamespacemanager nsmgr = new xmlnamespacemanager(xmldocument.nametable); nsmgr.addnamespace("dc", xmldocument.documentelement.getnamespaceofprefix("dc")); nsmgr.addnamespace("content", xmldocument.documentelement.getnamespaceofprefix("content")); xmlnodelist itemnodes = xmldocument.selectnodes("rss/channel/item"); (int = 0; < itemnodes.count; i++) {

python - "key values mismatch" when using context.use_certificate_chain_file -

when using context.use_certificate_chain_file key error (openssl.context python). error is: traceback (most recent call last): file "/home/user/public_html/application.py", line 363, in <module> context.use_privatekey_file('/etc/ssl/private/' + hostname + '.key') openssl.ssl.error: [('x509 certificate routines', 'x509_check_private_key', 'key values mismatch')] it saying key values mismatch, wouldn't think chain affect that. if comment context.use_certificate_chain_file line, works (but gives ssl verification error in browser). here snippet of code: context = openssl.context(openssl.sslv23_method) context.set_options(openssl.op_no_sslv2) context.set_options(openssl.op_no_sslv3) context.use_certificate_file('/etc/ssl/certs/' + hostname + '.crt') context.use_certificate_chain_file('/etc/ssl/certs/' + hostname + '.cabundle') context.use_privatekey_file('/etc/ssl/private/

java - libgdx - error while trying to use ShapeRenderer -

i'm trying make fade in effect using shaperenderer code: gdx.gl.glenable(gl20.gl_blend); gdx.gl20.glblendfunc(gl20.gl_alpha, gl20.gl_one_minus_src_alpha); //shaderprogram.pedantic = false; shaperenderer.setprojectionmatrix(stage.getcamera().combined); shaperenderer.begin(shaperenderer.shapetype.filled); shaperenderer.setcolor(new color(0,0,0,fadetimeelapsed/1.5f)); shaperenderer.rect(0,0,gdx.graphics.getwidth(),gdx.graphics.getheight()); shaperenderer.end(); gdx.gl20.gldisable(gl20.gl_blend); i following exception: fatal exception: glthread 2715 java.lang.illegalargumentexception: no uniform name 'u_projmodelview' in shader @ com.badlogic.gdx.graphics.glutils.shaderprogram.fetchuniformlocation(shaderprogram.java:287) @ com.badlogic.gdx.graphics.glutils.shaderprogram.fetchuniformlocation(shaderprogram.java:277)

authentication - Jawbone UP API oAuth and Access Tokens -

i have started digging jawbone's api today , seems go fine throughout authentication process. problem that, once access token back, it's same token, doesn't work in of requests, , can't change refresh_token endpoint. oauth setup: $url_params = array( 'response_type' => 'code', 'client_id' => client_id, 'scope' => array('basic_read', 'extended_read', 'move_read'), 'redirect_uri' => 'https://my-site.com/up_auth.php', ); these parameters attached https://jawbone.com/auth/oauth2/auth url , sent jawbone , prompted expected. when accept authorization kicked my-site.com expected code in url. use code so $params = array( 'client_id' => client_id, 'client_secret' => app_secret, 'grant_type' => 'authorization_code', 'code' => $code, ); and attach parameters https://jawbone.com/auth/oauth2/token , ki

c++ - Google linked_ptr implementation and usefulness of linked_ptr -

i've found interesting type of smart pointer called linked_ptr supports shared ownership without heap memory allocation, worse performance / memory overhead. i've found 2 implementations - on doubly linked list ( example implementation , has x3 memory overhead comparing raw pointer) , on cycled singly linked list ( example implementation google , x2 memory overhead, asymptotically slower). my first question is: why second implementation insert new element before copied 1 in copy constructor? taskes o(n) time, n size of list; while seems easier insert new element after , this: void join(linked_ptr_internal const* ptr) { next_ = ptr->next_; ptr->next_ = this; } or, probably, missing something? secondly, how useful linked_ptr ? seems in case of small number of references same object. why there no implementation of it, example, in boost? if missing something, must missing well. found googling same question because can't think of use-cas

for loop - Why do I need a temporary value for the columns in the 2D Fourier Transform (Matlab) -

here matlab code 2d discrete fourier transform. code transcribed from: scilab textbook companion digital image processing s. jayaraman, s. esakkirajan , t. veerakumar . i not going on during second loop, , why have use temporary value f_2. what happening during stage of script? thank you. function [ftransformed2d]= dft2d(f) [rows,cols]=size(f); k=1:cols f_1(:,k)=exp(-2*1j*pi*(0:nrows-1)'*(0:rows-1)/rows)*f(:,k); end j=1:rows f_2_a=exp(-2*1j*pi*(0:ncols-1)'*(0:ncols-1)/cols)*(f_1(j,:)).'; f_2(j,:)=f_2_a.'; end ftransformed2d = circshift(f_2,floor(size(f_2)/2)); end the first loop performs fft on each column, , second loop performs fft on each row. concerns second loop, f_2_a=exp(-2*1j*pi*(0:cols-1)'*(0:cols-1)/cols)*(f_1(j,:)).'; f_2(j,:)=f_2_a.'; the use of f_2_a not necessary may have been included ease of reading. have been written instead f_2(j,:) = ( exp(-2*1j*pi*(0:cols-1)'*(0:cols-1)/c

python - Architecture of a Django project -

i have started learning django , having confusion regarding architecture of django project. basically want know recommended way design django application ie: type of code put in models file, views file , write validators etc. as example, suppose while creating registration form add new user want make sure user not register username present in database. per observation there 3 ways it. i define method in models.py file , call after getting data form. i define method in views.py file , call method. i write custom validator or clean method in forms.py file. as beginner confused per approach best. basic set of rules follow can me decide type of code written me. thanks unsurprisingly, general recommendation put view code in views.py , model code in models.py , form code in forms.py . you have ability put code more or less wherever want it, better off sticking these recommendations beginner. since want sure added user isn't in database best handled in view c

Keep chat history with socket.io-redis -

i have chat socket.io , redis store. question is, how can retrieve emits socket room? chat working, on refresh messages lost. below how manage redis store. var redis = require('redis').createclient; var adapter = require('socket.io-redis'); var pub = redis(port, host, {}); var sub = redis(port, host, { detect_buffers: true}); io.adapter(adapter({ pubclient: pub, subclient: sub })); http://www.ibm.com/developerworks/library/wa-bluemix-html5chat/index.html article solve problem. step 4 contain answer. code: var redis = require('redis'); var redisclient = redis.createclient(port, host); redisclient.lpush('messages', json.stringify(data)); // push redis redisclient.lrange('messages', 0, 99, function(err, reply) { //reply contains messages });

python - TypeError: object of type 'int' has no len() -

Image
i've tried lot of ways solve problem can't find answer error: typeerror: object of type 'int' has no len() here code: def calculadeltat(tn, tm, fr, t, p): return (tn * fr * t) - (p * t) - (tm * t) deltat = calculadeltat def calculadeltar(rn, fv, rm, mt, r): return (rn * fv * r) - (rm * mt * r) deltar = calculadeltar def calculadeltav(vn, vm, mr, v): return (vn * v) - (vm * mr * v) deltav = calculadeltav import matplotlib.pyplot plt tmax = 10 tp = [0] * tmax tn = 0.2 fr = 0.6 tm = 0.3 p = 0.1 t = [0] * tmax t[0] = 10 rn = 0.4 fv = 0.6 rm = 0.1 mt = 0.2 r = [0] * tmax r[0] = 10 vn = 0.5 vm = 0.8 mr = 0.8 v = [0] * tmax v[0] = 10 print(len(v)) print(len(r)) print(len(t)) print(len(tp)) in range (1, tmax): t[i] = t[i-1] + deltat(tn, fr, tm, t[i-1], p) tp[i] = plt.plot(tp, t) plt.axis(0, 10, 10, 1000) plt.ylabel('t[tubarões]') plt.xlabel('tempo[em anos]') plt.title(r't em função de tempo'

Meteor create 'your project name' -

how computer know download project when type in "meteor create .... " terminal when meteor create app creates folder named app in current directory. so, if in /users/documents , meteor create app , app in /users/documents/app . see docs: http://docs.meteor.com/#/basic/ books: http://meteortips.com/book/ , https://www.discovermeteor.com/

android - RxJava - Consuming a GroupedObservable -

given following code: bcxclient .fetchtodos() .flatmap(new func1<list<bcxtodo>, observable<bcxtodo>>() { @override public observable<bcxtodo> call(list<bcxtodo> bcxtodos) { return observable.from(bcxtodos); } }) .groupby(new func1<bcxtodo, bcxtodolist>() { @override public bcxtodolist call(bcxtodo bcxtodo) { return bcxtodo.todolist; } }) .tolist(); which returns list<groupedobservable<>> . in code, need count how many objects there in each groupedobservable. if use count() function returns observable<int> . following code won't work: @override public int getchildrencount(int groupposition) { int count; mtodolist.get(groupposition) .count() .subscribe( new action1<integer>() { @override public void call(integer integer) { count = integer; } }); return count; } if make local v

java - Android View type at runtime -

i'm creating app used gridview display set of items. each of these items defined follows: <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.myapp.customviews.tile android:layout_width="wrap_content" android:layout_weight="1" android:scaletype="fitcenter" android:layout_height="match_parent" android:id="@+id/tile" /> </linearlayout> in onitemclickhandler want check if type of view id r.id.tile (my custom view class mentioned above) com.example.myapp.customviews.emptytile . class child of tile class. currently i'm checking if class emptytile follows: linearlayout tilelayout = (linearlayout) gridview.getchi

Android Studio Gradle Error - Protocol Family Unavailable -

so relatively new android dev. , have been getting android studio set on computers. have set fine on mac. when downloaded , installed on windows 8.1 desktop gradle build seems fail every time. error message stating protocol family unavailable. i've tried several things including uninstalling , reinstalling android studio. note: did try said work here gradle project refresh failed - protocol family unavailable yet did not solve problem me. i had problem , referenced thread didn't work me. what did work setting _java_options environment variable make java use ipv4. _java_options = -djava.net.preferipv4stack=true note android studio sets variable in vmoptions file. reason, isn't used java vm started android studio run gradle daemon. after did that, started work ok , gradle build project. i hope helps.

C++ Templates : define an array -

i have template template <class t, int size=0> class gpr and want declare array example int [5], requires specify size example 5. if write : gpr<int, 5> ap; does mean have int[5] or need modify place of int: gpr<new int[5], 5> app; ?? or gpr<double, 5> pda = new double[5]; ?? it dependent on class implementation. can access using gpr ap; , gpr app; create array of template object.

import - What are the rules for importing with "as" in Python without using from -

i trying import following function in python 2.7 import scipy.signal.savgol_filter sgolay i received following error: importerror: no module named savgol_filter savgol_filter function, not module, error makes sense. question is, not possible import, without use of word "from" besides module? in other words, following works: from scipy.signal import savgol_filter sgolay but in general, following "sub_part" need module? import my_module.sub_part some_name i've seen lots of writing suggesting "sub_part" not need module. there tricky going on scipy making not work? thanks, jim in general, if import thing , import thing.subthing , import thing.subthing.subsubthing , etc., far-right thing needs module. from form allows importing things aren't modules. if want definitive statement of forms of import statement , allows, python language reference explains in great detail, it's pretty dense read.

multithreading - SocketServer Python with multiple requests -

i'm coding python server (with socketserver) raspberry pi. server wait incoming clients , activate components relay , leds remote connection. first project i'm having trouble: in main create object , send arraylist of components want control; led own functions server.server(componentlist) while true: stuff in server.py launch server , set settings class server(): def __init__(self, componentlist): self.componentlist = componentlist self.current_component = 0 self.server = socket.threadedtcpserver((settings.hostname,settings.port), socket.threadedtcprequesthandler) self.server_thread = threading.thread(target=self.server.serve_forever) self.server_thread.daemon = true self.server_thread.start() self.server.set_componentlist(self.componentlist) self.server.set_current_component(self.current_component) def set_current_component(self, current_component): self.current_component = current_component def get_current_component(self

php - Auto generating a pincode depending upon the location selected in HTML form -

i working on website intended offer services depending upon location of user. problem is: how auto generate pin code text field depending upon location selected in drop down list? project based on php http://pastebin.com/5bcbdj1u - here html form http://pastebin.com/ajzd1gl2 - here php file used in action tag of form

python - Dictionary column in pandas dataframe -

i've got csv i'm reading pandas dataframe. 1 of columns in form of dictionary. here example: cola, colb, colc, coldd 20, 30, {"ab":"1", "we":"2", "as":"3"},"string" how can turn dataframe looks this: cola, colb, ab, we, as, coldd 20, 30, "1", "2", "3", "string" edit fixed question, looks string needs parsed, not dict object. so starting 1 row df col col b col c col d 0 20 30 {u'we': 2, u'ab': 1, u'as': 3} string1 edit: based on comment op, i'm assuming need convert string first import ast df["colc"] = df["colc"].map(lambda d : ast.literal_eval(d)) then convert col c dict, transpose , join original df dfnew = df.join(pd.dataframe(df["col c"].to_dict()).t) dfnew which gives this col col b col c col

ruby on rails - service nginx restart fails -

i checked config syntax run nginx -t results: nginx: configuration file /etc/nginx/nginx.conf syntax ok nginx: configuration file /etc/nginx/nginx.conf test successful but when run service nginx restart goes fail. i have config file named a.com in sites-enabled folder, here's content: server { listen 80 default_server; listen [::]:80 default_server ipv6only=on; server_name a.com; # root /usr/share/nginx/html; # index index.html index.htm; root /home/a/public; client_max_body_size 10g; location / { proxy_pass http://localhost:3000; proxy_set_header x-forwarded-for $proxy_add_x_forwarded_for; proxy_set_header host $http_host; proxy_set_header x-forwarded-proto $scheme; proxy_buffering off; } } i'm @ ubuntu 14.10 , want deploy rails server. i kill nginx's process manually, start nginx again, solved problem.

javascript - Talking to C++ library with Node.js -

i have node.js express web application , need talk optimization library named cbc coin-or: https://projects.coin-or.org/cbc what best way talk library using node.js? create node.js wrapper around c++ library or...? if care performance, writing addon (and/or possibly using nan let addon work across major node.js/io.js versions) wraps library best solution. if taking considerable performance hit not concern, use ffi call "directly" library javascript.

objective c - How to create a key per initiated object using NSUserdefaults -

i have custom nsobject , instantiate object using manager. my nsobjets passed mutable array can access properties(name) via uipickerview once save method initialised. when close app, objects disappear expected. i save objects in nsuserdefaults have implemented nsuserdefaults in manager. save objects loaded when application launched in uipickerviewcontroller. however application crashes when load uipickerviewcontroller. here log after crash: terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[pacsserver encodewithcoder:]: unrecognized selector sent instance 0x7fd0a2e7fa20' pacsserver.h #import <foundation/foundation.h> @interface pacsserver : nsobject @property ( nonatomic) nsstring *pacsname; @property (nonatomic) nsstring*username; @property ( nonatomic) nsstring*password; @property (nonatomic) nsstring *wadourl; @property ( nonatomic) nsstring *apidirectory; @property ( nonatomic) nsstring *dataarrayincludesusernamepa