Posts

Showing posts from February, 2011

javascript - Automatically create grunt environment -

i'm little lost how should proceed, don't know start. i've been working on few wordpress sites lately, create dev environment using npm grunt. i set folder , npm init. install grunt plugins need such as: watch, sass, uglify etc... download wordpress , set gruntfile.js example sass compile wordpress theme's stylesheet. usual (i hope). the thing rather repeating same step on , on i'd automate ( same config step each site ). so here question, how go creating script automaticaly install grunt plugins , configure them, download latest wordpress , set theme files ( domain name etc...)? i don't need explanation on how these steps few pointers on start , tools use great. being quite novice in script writing information use. try yeoman . there yeoman generator wordperss boilerplate. uses gulp instead grunt, has same idea need.

java - CSRF token protection with AJAX GET method -

i'm bit confused online information. i'm using csrf protection using spring security on back-end. i wanted ask safe send csrf token angular front-end, while i'm passing token within http header using ajax method? because according spring docs shouldn't use method, on other hand doesn't if it's okay use ajax when pass in http header. second, if shouldn't use get, how use rest service & csrf protection? should give method or csrf protection? since requests should not modify state on server , should "read-only" csrf protection should not needed requests. the problem leakage related browser usage because requests not contain body , token sent request parameter. csrf token visible through shoulder surfing, stored bookmark, appear in browser history or logged on server (altough logging applies ajax requests). since talking ajax requests of leakage not apply, although setting in header may in case of urls appearing in logs, ...

swift - Why is URLSession not resuming on iOS 10? -

in ios download manager rcdownload object holds title, url, download state , resume data location of download i have block variable called defaultsession looks this: lazy var defaultsession: urlsession = { let configuration = urlsessionconfiguration.background(withidentifier: "rcbackgrounddownloader") configuration.isdiscretionary = false configuration.sessionsendslaunchevents = true let session = urlsession(configuration: configuration, delegate: self, delegatequeue: nil) return session }() my app able pause , resume downloads and resume function looks this: func resume(download: rcdownload) { var data: data! { data = try data(contentsof: download.getresumedataurl()) } catch {} download.downloadstate = downloadstatus.downloading if data != nil { download.downloadtask = self.defaultsession.downloadtask(withresumedata: data) download.dow...

hibernate - How to enable classpath scanning for @Entity classes in Spring boot -

all attempts @ classpath scanning of @entity classes failed in spring boot application. common solution found on web , didn't work - localcontainerentitymanagerfactorybean factory = new localcontainerentitymanagerfactorybean(); factory.setjpavendoradapter(vendoradapter); factory.setpackagestoscan("com.acme.domain"); @entityscan on @configuration class did not work either. all entities , mappings listed in orm.xml , had move using @entity annotations. one solution got me half way there - <persistence-unit> <provider>org.hibernate.ejb.hibernatepersistence</provider> <mapping-file>meta-inf/orm.xml</mapping-file> <class>com.acme.domain.entity</class> <shared-cache-mode>none</shared-cache-mode> </persistence-unit> this way use @entity annotations if listed entity classes in persistence.xml. the solution didn't find while searching, listed on spring data jpa web page - cl...

ios - Displaying an alert on a new View Controller -

i have button sends me on view controller. trying display alert on next view controller. in viewdidload() method of new controller, create new uialertcontroller , display following let alertcontroller = uialertcontroller(title: "default style", message: "a standard alert.", preferredstyle: .alert) let cancelaction = uialertaction(title: "cancel", style: .cancel) { (action) in // ... } alertcontroller.addaction(cancelaction) let okaction = uialertaction(title: "ok", style: .default) { (action) in // ... } alertcontroller.addaction(okaction) self.presentviewcontroller(alertcontroller, animated: true) { // ... } note example taken nshipster website offers nice articles ios. can find article uialertcontroller here . explain other stuff can class, display action sheet example.

python - ipython notebook matplotlib plot for dataframe throwing non gui exception -

when try plot dataframe in notbook , seeing 'non gui' exception being thrown. import pandas pd import sys,os import numpy np import matplotlib.pyplot plt %matplotlib inline %pylab inline ts = pd.series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) df = pd.dataframe(np.random.randn(1000, 4), index=ts.index, columns=list('abcd')) df = df.cumsum() plt.figure(); df.plot(); #<-- exception here there plot displayed , first column of df plotted , see exception. when try plot series , dont see issue. here exception trace : (looks trying plot df 'interactive' plot, there other function / parameter try not 'interactive') ...\anaconda2\lib\site-packages\pandas\tools\plotting.pyc in __call__(self, x, y, kind, ax, subplots, sharex, sharey, layout, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, secondary_y, sort_columns, **kwd...

ios - HowTo find simulator directory -

i'm looking specific location in filesystem of ios simulators downloaded via xcode. i've been looking in usual locations /applications/xcode.app/contents/developer/platforms/iphonesimulator.platform/developer/sdks or ~/library/developer/coresimulator no luck. does know specific location they're downloaded into? thanks, constantin they installed /library/developer/coresimulator/profiles/runtimes

swift - Debug iOS App Share Extension with Contacts -

i starting out ios app share extension , dutifully followed instructions xcode 8.1 create new target. great, gave me simple boilerplate code , scheme. put breakpoints on code view generated , tried run extension target. it asks me app. hm, didn't see contacts, chose app instead. app appears in simulator. close (home) app , start contacts. go share contact , extension shows!!! tap , generic dialog appears. but nothing shows in debugger or in log print. what switch missing?

Omitting <p> tags from html output made by pandoc -

pandoc wraps html output in html paragraph element . e.g. running echo hello | pandoc -t html gives <p>hello</p> . is possible instruct pandoc not so?

html - how do I retrieve an input variable onto a javascript controller in angular? -

i have search input field , trying send input javascript variable i'd use. in angular input <input ng-model="searchtext" placeholder="search"> controller.js angular.module('searchkingapp') .controller('mainctrl', function($scope){ //which code can put under here? //and end having var searcheditem = //the string have searched for.. i have javascript file located in different place html file. thanks alot in advance. you this. var app = angular.module("sampleapp", []); app.controller("samplecontroller", ["$scope", function($scope) { $scope.searchtext = "hello"; $scope.search = function() { console.log($scope.searchtext); } } ]); <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script> <div ng-app="sampleapp"> <div ng-controller="samplecontroller...

java - Camunda Executionlistener implementation with timestamp -

hey guys im new camunda, want measure execution time process start end can't find proper coding example listener. come is public void notify (delegateexecution execution) throws exception { // happens when start event executed long starttime = system.currenttimemillis(); // happens when token has reached end event long stoptime = system.currenttimemillis(); long elapsedtime = stoptime - starttime; system.out.println(elapsedtime); } i set class in modeler start , end event hope right. thanks in advance :) the engine measure you. can't print duration of process instance listener process, because process instance still running. can check duration in database table act_hi_procinst . also can use historyservice engine: public class processinstancehistory { @inject historyservice historyservice; public list<historicprocessinstance> historicprocessinstances() { return historyservice.createhistoricprocessinstancequery().l...

java - Application IncomingHandler sometimes not receiving Service message -

i'm building android app , i'm struggling handling reconnection. so flow this: 1. connect token have 2. user connecting server socket.io 2.a) have active token - positive response server => happy 2.b) have no token or token not in database - have new token server - new request made that - in response user trying connect 1 more time now code: application main function i'm running make sure connected public static boolean issocketconnected = false; //declared in androidapplication public static boolean isservicebound = false; //declared in androidapplication public volatile boolean allownextsocketconnection = true; //declared in same calss _runmeplease_ private void runmeplease() { //running in new thread if (androidapplication.isservicebound) { if (androidapplication.issocketconnected) { allownextsocketconnection = false; connected = true; logger.log("we ...

vb6 - how do force enable button in menu items using handles value and make sure click even fires -

how enable menu item , make sure click fires? . i have app1 , app2 app2 has 3 menu items gold silver bronze i setted option enabled = false in 3 item click events have msgbox, when clicked know msgbox fired , working. ======================================= app1 has code below , have image drag app1 windows handle value , menu handles value, each menu handle value insert text2.text , enable menu button. public declare function enablewindow lib "user32" (byval hwnd long, byval fenable long) long private sub command5_click() enablewindow text2.text, 1 ' enable < api call controllenabled = true ' sets swich end sub when enable each menu item using handle value menu item becomes clickable , when click it, dont fire msgbox ? how come module 'public verables public controllenabled boolean public cursorposition point public targeting boolean 'user defined type public type rect left long top long right long ...

angular - Publish font through npm for use in project -

i've created set of music glyphs (notes, dotted notes, , time signatures) use in web-application i'm developing using angular2, wasn't able find font glyphs felt appropriate application. hierarchy font follows fonts notes.eot notes.svg notes.ttf notes.woff package.json (from npm init) readme.txt selection.json (from npm init) style.css i'm not sure steps need take here publish npm (i'm happy share these glyph sets through npm), , haven't been able find article or stackoverflow answer helps me. appreciate list of steps publish , use these glyphsets in project. the npm publish command publish entire npm-managed directory, based on version tag have in package.json protip: versioning using npm version major , npm version minor , , npm version patch commands, don't manually bump them. npm version command updates package.json and automatically creates git version tag project can push github. see https://medium.com/@jdaudier/how-...

javascript - cannot export function in Express -

i'm trying implement passport.js , problem in way of exporting function in model: user model file (user.js) looks like: var mongoose = require('mongoose'); var schema = mongoose.schema; var passportlocalmongoose = require('passport-local-mongoose'); var bcrypt = require('bcrypt'); var userschema = mongoose.schema({ username: string, password: string }); userschema.plugin(passportlocalmongoose); userschema.methods = { getuserbyusername: function(username, callback){ var query = {username: username}; userschema.findone(query, callback); /*userschema.findone(query, function(err, user) { callback(err, user); }); */ }, getuserbyid: function(id, callback){ userschema.findbyid(id, callback); }, comparepassword: function(candidatepassword, hash, callback){ bcrypt.compare(candidatepassword, hash, function(err, ismatch) { if(err) throw err; callbac...

Visual Studio - Stuck on Loading/Initializing Solution after installing Xamarin.Auth Nuget Package -

Image
i installed xamarin.auth nuget package , since project has been taking forever load/initialize each time . i tried earlier versions without package , load instantly . anyone faced issue before , idea how fix ? i tried using older versions , setting package again same thing happens . it takes long time , not responding ...but , after while - loads (5-20mins every time) note : downloaded , tied sample project , same things happens 1 , packages causing issue : https://developer.xamarin.com/samples/xamarin-forms/webservices/todoawsauth/ https://developer.xamarin.com/guides/xamarin-forms/web-services/authentication/oauth/ if can try , works - might vs settings the sample project xamarin.auth nuget package installed working fine on vs2015 update 3 nuget package manager 3.4.4 installed. and following vs settings nuget package. please check vs settings nuget packages. in addition, please open nuget.org site in browser directly check whether site opened in brows...

enums - Output not printing after switch case utilized Java -

i'm working on using enum / switch case along zeller's formula saying day of year specific date be. code printing right days before implemented enum / switch portion of code (below). after put in enum/ switch case, when run in drjava prompt day, month , year, nothing prints once goes through switch case import java.util.*; public class zeller { public enum daysoftheweek { sunday, monday, tuesday, wednesday, thursday, friday, saturday; } private static int value; public zeller (int value){ this.value = value; } public int getvalue(){ return this.value; } public static void main(string[] args) { determineday(value); // create scanner scanner input = new scanner(system.in); // prompt user enter year, month , day system.out.print("enter month: 1-12: "); int month = input.nextint(); system.out.print("enter day of month: 1-31: "); int day = input.nextint()...

What kind of error is there in C code snippet? -

i examining errors in different c programs , differentiating between them. currently, confused type of error there in code. #include <stdio.h> int main(void) { in/*hello*/z; double/*world*/y; printf("hello world"); return 0; } when run program, compilation error : prog.c: in function 'main': prog.c:4:5: error: unknown type name 'in' in/*this example*/z; ^ prog.c:5:30: warning: unused variable 'y' [-wunused-variable] double/*is error?*/y; ^ prog.c:4:29: warning: unused variable 'z' [-wunused-variable] in/*this example*/z; ^ i know warning not prevent compiling, there error error: unknown type name 'in' so, syntax or semantic error ? there syntax error. first of have clarify thing: have understand what's difference between syntax , semantics . syntax "grammar rules" of programming language, whe...

recursion - How to make recursive singly linked list (C++) -

my book asking me make recursive definition of singly linked list. have no idea @ how that. can please me out sample? thanks it's normal linked list except iteration performed recursion rather loops. first, little light reading: what recursion , when should use it? for example, loop-based function find last node be: node * getlast(node * current) { while (current->next == null) { // loop until no more nodes current = current.next; } return current; // return last node } while recursive version checks if current node last , calls next node if there next node. node * getlast(node * current) { if (current->next == null) { // found last node. return return current; } else { // see if next node last node return getlast(current->next); } }

inno setup - How to show a message box for a specified time? -

is there way show message box specified time (that means, message box close when specified time elapses) ? windows api has function showing message box specified time, reason function undocumented, means not officially supported , may subject change. that function called messageboxtimeout , , has export in user32.dll library, makes me feel thing function lacks official documentation. knows... the following script shows how display message box 5 seconds before wizard form shown. if user doesn't click ok button, nor manually close window, message box automatically closed when 5 seconds period elapses: [code] #ifdef unicode #define aw "w" #else #define aw "a" #endif const mb_timedout = 32000; mb_iconerror = $10; mb_iconquestion = $20; mb_iconwarning = $30; mb_iconinformation = $40; function messageboxtimeout(hwnd: hwnd; lptext: string; lpcaption: string; utype: uint; wlanguageid: word; dwmilliseconds: dword): integer; external...

Angular 2, catching 401 in @ngrx/effects -

i've got @ngrx/store , effects working fine, however, realized there a lot of api calls (in effects), , if of returns 401 error should redirect user login page. problem is: don't want check in every single effect, ton code same thing. let's example have code this: sample effect @effect() getme$ = this.actions$ .oftype(get_me) .map(action => action.payload) .switchmap(payload => this.userservice.me() .map(res => ({ type: get_me_success, payload: res })) .catch(() => observable.of({ type: get_me_failure })) ); userservice.me() me(): observable<user> { return this.apiservice.get(`/auth/me`); } apiservice.get() get(endpoint: string): observable<any> { return this.http.get(`${this.base}${endpoint}`, this.options()) .map(res => res.json()); } this works fine, i'm not sure how handle case when api return 401 . should redirect user globally in case? should create action case? should dispatch ac...

slack api - Look a message's text from events api response -

i'm using slacks events api , have setup subscription reactions_added event. when reaction added message, slack send me post body details of dispatched event described here . the problem i'm having want details, text of message users have reacted can parse/store etc specific message. assumed message return type of uuid respond callback , text, i'm find difficult specific message. the endpoint see available channels.history , doesn't seem give me granularity i'm looking for. so tl;dr is: how via slacks api, messages text sent events api? give information have event_ts, channel , message ts thought enough. i'm using ruby slack-api gem fwiw. you can indeed use method channels.history ( https://api.slack.com/methods/channels.history ) retrieve message public channel . reaction_added dispatched event includes channel id , timestamp of original message (in item ) , combination of channelid + timestamp should unique. be careful use correct t...

c# - Separated elements overlooked, now combined -

currently in process of learning mvc , think it's interfering html code. have basic navigational menu list , 2 <li> items seem combine one. way make sure 2 separated when live? @if ((request.url.absolutepath.tostring().tolower() != "/home/index") && (request.url.absolutepath.tostring() != "/")) { <nav data-spy="affix" data-offset-top="500" style="border-radius:0px; left: 0" ng-hide="sidebar" id="nav"> <img src="~/content/images/open.png" ng-model="sidebar" id="sidebaropen" style="left:0px; top:0;"/> <div id="sidebar" style="left: -200px"> <ul> <li><a href="@url.action("index", "home")" id="navheader"> home </a></li> <li><br /></li> <li><a hre...

java - Maven Jaxb2 plugin throwin error "undefined element declaration 's:schema' " -

i trying generate classes using maven jaxb2 plugin . receiving below exception : org.xml.sax.saxparseexception; systemid: http://someip/dummywsdl.asmx?wsdl; linenumber: 32; columnnumber: 41; undefined element declaration 's:schema' @ com.sun.xml.xsom.impl.parser.parsercontext$1.reporterror(parsercontext.java:180) @ com.sun.xml.xsom.impl.parser.ngccruntimeex.reporterror(ngccruntimeex.java:175) @ com.sun.xml.xsom.impl.parser.delayedref.resolve(delayedref.java:110) @ com.sun.xml.xsom.impl.parser.delayedref.run(delayedref.java:85) @ com.sun.xml.xsom.impl.parser.parsercontext.getresult(parsercontext.java:135) @ com.sun.xml.xsom.parser.xsomparser.getresult(xsomparser.java:214) @ com.sun.tools.xjc.modelloader.loadwsdl(modelloader.java:412) @ com.sun.tools.xjc.modelloader.load(modelloader.java:170) @ com.sun.tools.xjc.modelloader.load(modelloader.java:119) @ org.jvnet.mjiip.v_2_2.xjc22mojo.loadmodel(xjc22mojo.java:50) @ org.jvnet.mjiip.v_2_2.xjc22mojo.doexecute(xjc22mojo.java:40)...

html - Why won't my divs line up? -

here html <!doctype html> <html> <head> <title> oaki softworks </title> <link href='style.css' rel='stylesheet' type='text/css'> <link rel="icon" href="favicon.png"> </head> <body> <div id="navigation"> <div style="height:20px;width=15%;float:right;"> <a href="https://www.facebook.com/oakisoftworks/?fref=ts"><img src="facebook_icon.png" class="social_media_icon"></a> <img src="instagram_icon.png" class="social_media_icon"> <img src="twitter_icon.png" class="social_media_icon"> <img src="youtube_icon.png" class="social_media_icon"> </div> <div class="navigation_tile">contact us</div> <div ...

ios - Perform action when opening app for the second time -

when open app fires events viewdidload , viewdidappear form view controller when close , run again not call of them. any idea? you need read on application states. here link found online outlining different states: http://www.techrepublic.com/blog/software-engineer/understand-the-states-and-transitions-of-an-ios-app/ what want notified when app becomes active. probably easiest way implement function applicationdidbecomeactive() in app delegate. called when app becomes active foreground app either on launch, or when returns foreground active app. note if want notification sent object other app delegate can listen uiapplicationdidbecomeactive notification.

plsql - How to call a stored procedure dynamically? -

Image
for rec in ( select procedure_name datamart_process_steps order procedure_order ) loop execute rec; end loop; i have procedure manages series of procedures table datamart_process_steps , , need run every procedure within table dynamically. oracle sql developer not way executing procedures; throws syntax error. proper way achieve task? execute 'begin ' || rec || '; end'; i have tried after reading through tutorial on stored procedures, has issue single quotes. help. if need more detail or code please ask. thank in advance. the execute command sql*plus/sql developer shorthand anonymous pl/sql block. isn't valid inside other pl/sql, including inside master procedure. dynamic calls within pl/sql use unrelated execute immediate statement , , syntax diagram shows immediate keyword not optional. the dynamic sql statement in case needs anonymous pl/sql block around cursor-supplied procedure name, you've ...

javascript - Can an image be created from a new canvas object? -

i'm attempting create new canvas, clipping operations on image, , returning new image. but, without doing image, error when trying render image method returns. the htmlimageelement provided in 'broken' state. here code: let image = imageutils.getimage("path_to_my_image.jpg"); let canvas = document.createelement("canvas"); canvas.width = texture.width; canvas.height = texture.height; let g = canvas.getcontext("2d"); g.drawimage(image, 0, 0); let newimage = new image(); newimage.src = canvas.todataurl("image/jpeg"); return newimage; i'm able render image if don't try generate new canvas object, know that's not issue. i've searched around quite bit , haven't seen on topic.

android - alert dialog weird behaviour -

Image
i have same problem of weird background apearing below dialog question custom alert dialog looking weird on android 4.x ,i tried solution didn't work here output of alert dialog after applying solution in link , can see title becomes below blue border after importing android.support.v7.app.alertdialog ,here code import android.app.dialog; import android.support.v7.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.os.build; import android.os.bundle; public class alert { dialog dialog; public alert(context context){ alertdialog.builder alertdialog; alertdialog = new alertdialog.builder(context, android.r.style.theme_holo_light_dialog); // alertdialogc alertdialog.settitle("title"); charsequence colors[] = new charsequence[] {"test1", "test2", "test3", "test4"}; alertdialog.setitems(colors, new di...

Delete element from array java using for-statement -

this question has answer here: how remove objects array in java? 18 answers please see code below. the task make code replaces element inserted user , replacement for-statement can used (this task requirement). rest of elements saved. e.g. when input "1" following output expected "0 2 3 4" please modification of for-statement following after line "system.out.println("the following element de deleted "+removedelement);". if possible please advise on both options when "<" , ">" symbols can used. import java.util.scanner; public class mainclass { public static void main(string[] args) { int basearray [] = {0, 1, 2, 3, 4}; system.out.println("existing array:"); for(int = 0; < basearray.length; i++){ system.out.println(basearray[i]); } system.out.prin...

JavaFX: draw canvas by a pressed button through the Controller -

i'd use button in order tu things drawn on javafx canvas. package sample; import javafx.fxml.fxml; import javafx.scene.canvas.canvas; import javafx.scene.canvas.graphicscontext; import javafx.scene.control.button; import javafx.scene.paint.color; import javafx.scene.shape.arctype; import javafx.scene.control.label; public class controller { @fxml canvas canvas1; @fxml label label; public void onbuttonpress(){ system.out.println("test"); canvas canvas1 = new canvas(300, 250); graphicscontext gc = canvas1.getgraphicscontext2d(); drawshapes(gc); label.settext("test"); } public void drawshapes(graphicscontext gc) { gc.setfill(color.green); gc.setstroke(color.blue); gc.setlinewidth(5); gc.strokeline(40, 10, 10, 40); gc.filloval(10, 60, 30, 30); } } when press button, nothing happens. canvas in xml file defined follows: <canvas fx:id=...

Parse JSON with R -

i new r, more use it, more see how powerful on sas or spss. 1 of major benefits, see them, ability , analyze data web. imagine possible (and maybe straightforward), looking parse json data publicly available on web. not programmer stretch, , instruction can provide appreciated. if point me basic working example, can work through it. rjsonio omegahat package provides facilities reading , writing data in json format. rjson not use s4/s3 methods , not readily extensible, still useful. unfortunately, not used vectorized operations , slow non-trivial data. similarly, reading json data r, slow , not scale large data, should issue. update (new package 2013-12-03): jsonlite : package fork of rjsonio package. builds on parser rjsonio , implements different mapping between r objects , json strings. c code in package rjsonio package, r code has been rewritten scratch. in addition drop-in replacements fromjson , tojson , package has functions serialize objects. further...

java - Using Cipher.doFinal(byte[] b) decrypts faster after first decryption? -

i have following code: keygenerator keygen = keygenerator.getinstance("aes"); keygen.init(128); secretkey msecretkey = keygen.generatekey(); public byte[] encrypt(byte[] data) { try { cipher c = cipher.getinstance("aes/cbc/pkcs5padding"); secretkeyspec k = new secretkeyspec(msecretkey.getencoded(), "aes"); c.init(cipher.encrypt_mode, k); byte[] encrypteddata = c.dofinal(data); return bytes.concat(c.getiv(), encrypteddata); } catch (exception e) { e.printstacktrace(); } return null; } public byte[] decrypt(byte[] encrypteddata) { try { byte[] iv = arrays.copyofrange(encrypteddata, 0, 16); secretkeyspec k = new secretkeyspec(msecretkey.getencoded(), "aes"); cipher c = cipher.getinstance("aes/cbc/pkcs5padding"); c.init(cipher.decrypt_mode, k, new ivparameterspec(iv)); byte[] decrypted = c.dofinal(arrays.copyofrange(encryptedd...

c# - How to use cards within `Dialog` -

i trying use fluent api create simple flow. instead of using plain text want use rich visual components. here example. public async task<httpresponsemessage> post([frombody]activity activity) { var yn = chain .posttochain() .select(m => createyesnoprompt(activity)) //this dialog should provide buttons user .posttouser() .waittobot() .select(x => x.text) .switch ( chain.case ( s => s == "s", new contextualselector<string, idialog<string>>((context, item) => chain.return("yes")) ), chain.default<string, idialog<string>>((context, text) => chain.return("no")) ) .unwrap() .posttouser(); await conversation.sendasync(activity, () => yn); return request.cr...

java - Adding non linear function TinyGp -

i trying extend function set of tinygp software include non linear functions, such sin, cos , tan. problem is, growing tree functions take single paramater , performing crossover of tree containing functions 1 parameter functions source code of printing method outlined below. int grow( char [] buffer, int pos, int max, int depth ) { char prim = (char) rd.nextint(2); int one_child; if ( pos >= max ) return( -1 ); if ( pos == 0 ) prim = 1; if ( prim == 0 || depth == 0 ) { prim = (char) rd.nextint(varnumber + randomnumber); buffer[pos] = prim; return(pos+1); } else { prim = (char) (rd.nextint(fset_end - fset_start + 1) + fset_start); switch(prim) { case add: case sub: case mul: case div: buffer[pos] = prim; one_child = grow( buffer, pos+1, max,depth-1); if ( one_child < 0 ) return( -1 ); return( grow( buffer, one_child, max,depth-1 ) ); } } return( 0 ); // should never here }

Python .strip method not working -

i have function begins this: def solve_eq(string1): string1.strip(' ') return string1 i'm inputting string '1 + 2 * 3 ** 4' return statement not stripping spaces @ , can't figure out why. i've tried .replace() no luck. strip not remove whitespace everywhere, @ beginning , end. try this: def solve_eq(string1): return string1.replace(' ','') using strip() in case redundant (obviously, commentators!). p.s. bonus helpful snippet before take break (thanks op!): import re a_string = re.sub(' +', ' ', a_string).strip()

CHECK constraints in Seqeulize PostgreSQL ORM (Node.js) -

i'm using sequelize orm postgresql engine. when using raw queries can create table , have columns 'check' constraints such create table products ( product_no integer, name text, price numeric check (price > 0) ); in docs cannot find way in sequelize when defining models. there way of doing this? don't want reinvent wheel ;) thanks!! take @ validations section . var product = sequelize.define('product', { price: { validate: { min: 0 // allow values >= 0 } } }); you can set custom validation rules: var product = sequelize.define('product', { price: { validate: { ispositive: function (value) { return value > 0; // don't allow 0. } } } });

python - Beautiful Soup Not Finding HTML Element -

we attempting find html element "c_pagination_list" on following forever21 page: http://www.forever21.com/product/category.aspx?br=21men&category=mens-tops . however, when use beautifulsoup element, returns empty or none. below following ways attempted element: numberarray = soup.findall('div', attrs={ 'class' : 'c_pagination_list'}) number = soup.find('div', class_='c_pagination_list') number = soup.select('div.c_pagination_list') can explain proper syntax getting information or we're missing here? use this: numberarray = soup.findall('div', {'class': 'c_pagination_list'}) i think should work.

matlab - How can I create an array of matrices from a single matrix by using first column as index? -

suppose, have following matrix, 1 2 3 4 5 6 7 8 2 3 4 5 6 7 8 1 3 4 5 6 7 8 1 2 4 5 6 7 8 1 2 3 1 8 7 6 5 4 3 2 2 7 6 5 4 3 2 9 3 6 5 4 3 2 9 8 4 5 4 3 2 9 8 7 i want create array of 4 matrices, classified according column # 1. for instance, output should following, [ 2 3 4 5 6 7 8 8 7 6 5 4 3 2 3 4 5 6 7 8 1 7 6 5 4 3 2 9 4 5 6 7 8 1 2 6 5 4 3 2 9 8 5 6 7 8 1 2 3 5 4 3 2 9 8 7 ] my target apply this parzen function each of them. is following? function [retval] = bayes (train, test) classcounts = rows(unique(train(:,1))); pdfmx = ones(rows(test), classcounts); variance = 0.25; pdf = parzen(train(:,2:end), test(:,2:end), variance); cl=1:classcounts clidx = train(:,1) == cl; mu(:,cl) = train(clidx,2:end); end retval = mu; endfunction this code generating following error, >...

nlp - How to get a tree visualization for google nl api? -

Image
how can develop tree syntax analysis in google nl api. stanford corenlp uses brat annotation tool generate tree. can use generate dependency parse tree json response google nl api, if how? thanks in advance :) there's demo ui -- go nl api home page , scroll down interactive demo. there can put in sentence, click on "syntax" , pretty tree shows parse tree. in actual demo, can mouse on tokens see more detail, morphology. this individual examples. if want visualize these things programatically, you'll have implement yourself, or use existing tools.

python - Possible to run flask web app on linux server without web access and access through tunnel? -

i work on linux cluster behind firewall. not have web access. i had idea try run flask , direct port know open (5901 vnc), , tunnel port , view in browser. it's not working far. possible @ all? here i'm doing: helloflask.py from flask import flask app = flask(__name__) @app.route("/") def hello(): return "hello world!" if __name__ == "__main__": app.run(host='0.0.0.0', port=5901) #app.run() i run python helloflask.py then ssh -l 5901:<inner server>:5901 <outer server> then navigate localhost:5901 . nothing. tried links localhost:5901 , links <server>:5901 , again nothing. is possible there way this? you can : run flask app or notebook on remote server on port. example port 5000. on local machine run below command establish ssh tunnelling : ssh -d 8123 -f -c -q -n username@remotesrrver the port 8123 arbitrary here can allowed port on local machine. setup 1 o...

javascript - ng-repeat works with <p>, <ul><li>, etc, but fails on select using exact same source -

part of app populate list of common phone , tablet models based on mobile os choice shown here: <div class="input-field col s3"> <label class="active">environment (os)</label> <select ng-model="environment" ng-change="listbrowsers()"> <option value="" disabled>select os</option> <option ng-repeat="os in oses">{{os}}</option> </select> </div> and snippet of $scope.listbrowsers() context (from controller).... $scope.listbrowsers = function() { $scope.browsers = machinedataservice.getbrowsers($scope.environment); $scope.browser1 = null; $scope.notmobile(); //calls function determine mobile-ness $scope.getmobiledevices($scope.environment); return $scope.browsers; } next 'getmobiledevices' scope function calls named service method: t...

java - Isn't iterator a built-in function, why do I have to import it? -

// inside class public void playround() { iterator<player> itr = players.iterator(); while(itr.hasnext()){ player player =itr.next(); player.play(par); } // supply code! } it says : exception in thread "main" java.lang.error: unresolved compilation problem: iterator cannot resolved type isn't iterator built in function? i forced import : import java.util.iterator; if want resolve issue, there way avoid importing iterator. reason why cannot import iterator though save me lot of time, because project not allowed import other import java.util.arraylist; furthermore, using eclipse write code. in word - no. there's nothing "magical" iterator . it's class java.util package, , if want use should either import or reference qualified name: java.util.iterator<player> itr = players.iterator(); but guess forbidden requirements. instead, use enhanced for loo...

algorithm - How to find framerate of video using c++ opencv 2.4.10? -

actually,i trying detect , track vehicles video using c++ opencv 2.4.10.i did so.now,i want find frame rate of output video.i want know if there way find out.can suggest me blog or tutorial this? thank you. something may help. #include <iostream> #include <opencv2/opencv.hpp> //for opencv3 #include <opencv/cv.hpp> //for opencv2 int main(int argc, const char * argv[]) { cv::videocapture video("video.mp4"); double fps = video.get(cv::cap_prop_fps); std::cout << "frames per second : " << fps << std::endl; video.release(); return 0; }

Grouped Column sorting in SSRS -

i have quarterly revenue report ssrs. quarters shown based on year selected. revenue report q1-16 q2-16 company 2,114 6,213 company b 1,167 2,330 company c 6,219 4,639 company d 1,450 1,125 company e 9,540 1,650 i need enable interactive sorting on quarter name. tried suggestions recommended. none of them working. sorting enabled on quarter name. when click on quarter name, revenues not getting sorted. have group total row each company.

javascript - js ecwid url redirect -

i have been trying set redirects range of ecwid urls starting /shop /shop#!/~/ lead /shop#!/~/cart i have come code: var wrong_url = ['http://example.com/shop','http://example.com/shop#','http://example.com/shop#!','http://example.com/shop#!/','http://example.com/shop#!/~','http://example.com/shop#!/~/']; var current_url = document.url; (i=0;i<wrong_url.length;i++) { if (current_url==wrong_url[i]) { document.location.replace('http://example.com/shop#!/~/cart'); break; } } it works right there problem. when @ /shop#!/~/cart , manually change url to, say, /shop#!/~/ won't redirected until refresh page. believe has ajax behavior of ecwid shopping cart can't figure out how fight it. need help? vitaly ecwid here. the issue in current version of script doesn't detect changes url described. so need create handler such situations separately. example, can this: ...

asp.net mvc - MVC unsure how to retrieve related objects in a model -

i pass viewmodel view looks this assessment questions [0] questiontext questionid [1] questiontext questionid answers [0] theanswer questionid basically view has list of questions , list of answers may have chosen. i need display questions , chosen answer link between question , answer questionid this razor code in view loops questions @foreach (var question in model.assessment.questions) { <li class="row"> <div class="span9"> @html.raw(question.questiontext) </div> <div class="span3"> @html.raw(<--no idea put here-->) </div> </li> } how can retrieve selected answer question? edit here models public class assessment { public int id { get; set; } public status status { get; set; } public datetime a...

python - Try- except ValueError loop -

def enternumber(): number = input("please enter number convert binary. ") while true: try: int(number) convertdenary() except valueerror: enternumber() def convertdenary(): binarynumber = ['','','','','','','',''] print(enternumber()) if enternumber() > 128: enternumber() - 128 binarynumber[0] == 1 enternumber() the try- except valueerror loop intend however, won't break. i've tried adding in break under int(number), removing while true: , added in convertdenary() see if force subroutine stop , start other still doesn't work. i infinite loop of "please enter number convert binary." ideas? def converttobinary(number): if number > 1: converttobinary(number//2) elif number<1: enternumber() print(number % 2,end = '') def entern...

mysql - How can I get all business data AS WELL as if current user is following them? -

in mysql how can write query fetch business data, , @ same time (or not if better way) check if user following business? have following relationship table determine if user following business (status=1 mean person following): create table if not exists `relationship_user_follows_business` ( `user_id` int(10) unsigned not null, `business_id` int(10) unsigned not null, `status` tinyint(3) unsigned not null default '0' comment '1=following, 0=not following' ) engine=innodb default charset=utf8mb4; alter table `relationship_user_follows_business` add unique key `unique_user_business_id` (`user_id`,`business_id`); assume business table holds data on different businesses name, phone number, etc. want return of business data in query (business.*). want append status (0 or 1) end of each business row determine if user following business. have tried following query not work because narrowing results show business if there relationship row. wish show businesses r...