Posts

Showing posts from January, 2014

Mongoose: Embed a model as array of another model -

i have menu items have roles make links them restrictive. 1. rolemodel.js const menuroleschema = new mongoose.schema ({ name: { type: string, unique: true}, { _id: true }); exports.menurolemodel = mongoose.model('menurolemodel', menuroleschema, 'menu_role'); 2. menuitemmodel.js const menuitemschema = new mongoose.schema({ ...... roles: [ { type: menurolemodel } ] }); 3. menuitemseed.js const data = [ { ..... "roles": [{"name": "rolea"}], }, { .... "roles": [{"name": "rolea"}, {"name": "roleb"}], } ] my menuitemmodel not populating in database, , naturally no errors provided. how structure schema seed data laid out roles works? thanks this did trick me: 1. rolemodel.js (1)export const menuroleschema = new mongoose.

c++ - Type-specific static declaration in a template function -

i've written following snippet: // fix mingw 4.9.2 bug - std::log2 missing there template <typename t> t log2 (t value) { static const t l2 = std::log(t(2)); return std::log(value) / l2; } obviously, l2 should unique each t type because is of type t . work way per c++ standard? note once instantiated log2<double> and log2<float> are 2 different functions. both own static variable. after template instantiation, same situation if had 2 functions: double log2(double) { static double x; /*...*/ } and float log2(float) { static float x; /*...*/ } this nicely explained here in example around 6:00.

javascript - I can't connect to my websocket because its handshake Sec-WebSocket-Accept header value is incorrect -

i'm doing first test, trying use phpwebsocket . i set handshake sec-websocket-accept header value following: $accept=base64_encode(sha1($key."258eafa5-e914-47da-95ca-c5ab0dc85b11", true)); /* $key has $buffer value */ so run websocket php file (that creates connection), okay. so run test html contains script try connect phpwebsocket i'm using, , in browser console error: fc.js:43 websocket connection 'ws://localhost:8000/petstack/inc/server.php' failed: error during websocket handshake: incorrect 'sec-websocket-accept' header value but found error during websocket handshake: incorrect 'sec-websocket-accept' header value php , solved defining buffer limit , problem that? i don't understand how define buffer limit , case it's problem, please explain me. it wasn't me made phpwebsocket, i'm using it. well, line of variable $upgrade in phpwebsocket file, sets headers. "http/1.1 101 web s

Beginner Java: Returning values from methods -

before begin i'd state i'm beginner when comes writing code in general apologise if i'm asking may seem extremely basic. with being said i'm struggling returning methods in code. able write program without splitting methods have told when coding practice split in methods debugging can easier. the following code seems have few major flaws. public static boolean hybridnot() { string typecar = input("hybrid or electric?"); boolean electric = false; if (typecar.equalsignorecase("electric")) { electric = true; } else if (typecar.equalsignorecase("hybrid")) { electric = false; } else { print("sorry didn't understand that"); } return; } public static boolean solarnot() { string panelsmaybe = input("solar panel?"); boolean solarpanel = false; if (panelsmaybe.equalsignorecase("yes")) { solarpanel = true; } else if (panelsmaybe.equalsignorecase("

php - Put limit on wordpress custom fields -

i trying limit wordpress custom fields fetching through loop , want first 2 results. not familiar php. here code below using, <?php $gallery_data = get_post_meta( $post->id, 'gallery_data', true ); if ( isset( $gallery_data['image_url'] ) ) { for( $i = 0; $i < count( $gallery_data['image_url'] ); $i++ ) { ?> <div class="clearfix audio-block"> <span class="play-btn in-spa" play-url="<?php esc_html_e( $gallery_data['image_url'][$i] ); ?>"> <a href=""> <i class="glyphicon glyphicon-play"></i></a> </span> <span class="recite-nam in-spa"> <?php esc_html_e( $gallery_data['text_url'][$i] ); ?> </span> </div> <?php } } ?>

linux - What is the global attribute of a network interface? -

i saw following line of code in code repo work on: ip addr | grep 'inet .*global' | cut -f 6 -d ' ' | cut -f1 -d '/' | head -n 1 i want understand " global " attribute mean part of network interface attribute? i hope asking in right place... thanks lot, matan ip addr convert ifa_scope struct ifaddrmsg string, struct ifaddrmsg how ip command information kernel ( http://man7.org/linux/man-pages/man7/rtnetlink.7.html ). about ifa_scope: scope of address. default rt_scope_universe (which corresponds value 0) , field set value ifconfig/ip, although diferent value can chosen. main exception address in reange 127.x.x.x, given rt_scope_host scop. see chapter 30 more details. (c) understanding linux network internals and rt_scope_universe converted ip string value "global". about scope of address, helps decide use or not interface job. example if want communication inside machine, can choose 1 of network

symfony 2 composer line command -

i have little problem updating bundle in symfony 2 installed composer composer seems doesn't work correctly. no matter put in command line, composer shows version, available commands , that's all. nothing more. doing nothing. did have similar problem? jacob what use? if use windows try open cmd , type this: composer this command shows information composer, if not, need add route in environment variables (variable: path).

javascript - webpack-dev-server watches and compiles files correctly, but browser can't access them -

Image
edit : link github repo example hosted here in case wants run it i'm getting near exact same problem user (you can find question here ), in running webpack-dev-server compile , watch files correctly (seeing console output in terminal), browser still can't view site correctly. webpack.config.js file: var webpack = require('webpack'), path = require('path'), // webpack plugins copywebpackplugin = require('copy-webpack-plugin'); var config = { context: path.join(__dirname,'app'), entry: './index.js', output: { path: path.join(__dirname, 'public'), filename: 'bundle.js', publicpath: path.join(__dirname, 'public') }, devserver: { // contentbase: './public/' }, plugins: [ // copies html public directory new copywebpackplugin([ { from: path.join(__dirname, 'app', 'index.html'),

wordpress - Error establishing a database connection on my newly hosted wp website -

i in difficult situation..i dont have knowledge in hosting websites far. have developed wordpress website , trying host in presently woking server working domain. before static website. host provider www.networksolutions.com.. did hosting was, 1. exported database working website in local server (xampp). 2. exported database file opened dreamweaver , edited localhost , repalce domain name (www.abc.com) say.. 3.edited wp_config file below define('db_name', 'my_db'); /** mysql database username */ define('db_user', 'my_usernm'); //before 'root' /** mysql database password */ define('db_password', 'my_pass'); //before null /** mysql hostname */ define('db_host', 'www.abc.com'); //before 'localhost' 4.uploaded database file in web server , transfer website folder in /htdocs using filezilla 5.redifined domain pointing old folder new folder jst uploaded www.oldabc.com -> htdo

makefile - Make always rebuilding dependencies -

when use makefile without variable targets, things work fine preamble: mkdir -p data touch $@ data/a: preamble touch $@ data/b: data/a touch $@ data/c: data/a touch $@ data/d: data/b data/c touch $@ diamond: data/a data/b data/c data/d touch $@ .phony: clean clean: rm -rf ${data} diamond preamble however, when introduce target variable tasks involved run. data="data" preamble: mkdir -p ${data} touch $@ ${data}/a: preamble touch $@ ${data}/b: data/a touch $@ ${data}/c: data/a touch $@ ${data}/d: data/b data/c touch $@ diamond: ${data}/a ${data}/b ${data}/c ${data}/d touch $@ .phony: clean clean: rm -rf ${data} diamond preamble these executed touch "data"/a touch "data"/b touch "data"/c touch "data"/d touch diamond what correct way include variables in target? i recommend not

syntax - What's the difference between eq, eql, equal and equalp, in Common Lisp? -

what's difference between eq , eql , equal , equalp , in common lisp? understand of them check types, of them check across types that, which? when 1 better use others? from common lisp: equality predicates (eq x y) true if , if x , y same identical object. the eql predicate true if arguments eq , or if numbers of same type same value, or if character objects represent same character. the equal predicate true if arguments structurally similar (isomorphic) objects. rough rule of thumb 2 objects equal if , if printed representations same. two objects equalp if equal; if characters , satisfy char-equal, ignores alphabetic case , other attributes of characters; if numbers , have same numerical value, if of different types; or if have components equalp . here examples same page linked above: (eq 'a 'b) false. (eq 'a 'a) true. (eq 3 3) might true or false, depending on implementation. (eq 3 3.0) false. (eq 3.0 3.0) migh

Reference a .NET 3.5 DLL from ASP.NET Core project -

i have dll compiled under .net 3.5 represents poco data model. client application limited .net 3.5 , dll must shared both client , server, recompiling dll isn't option. i attempting rewrite server rest api asp.net core mvc project (using 1.0 release , preview 2 tools under vs2015). tried updating project.json so-called "bin syntax" shown below, package restore log shows bunch of errors such as: error: package microsoft.netcore.app 1.0.0 not compatible net35 (.netframework,version=v3.5). package microsoft.netcore.app 1.0.0 supports: netcoreapp1.0 (.netcoreapp,version=v1.0) "frameworks": { "netcoreapp1.0": { "imports": [ "dotnet5.6", "portable-net45+win8" ] }, "net35": { "bin": { "assembly": "c:\\source\\externaldllsdebug\\datadef.dll" } } i tried setting nuget package in dll folder making folder new nuget source. opened package fine failed when attempted im

python - How do I specify two required arguments, including a subcommand, using 'argparse'? -

is there way specify 2 required arguments in argparse , 1 corresponds subcommand, , required subcommands. the closest can manage seems with import argparse parser = argparse.argumentparser() subparsers = parser.add_subparsers(help='', dest='command', metavar='command', title='required arguments', description='two arguments required') parser.add_argument('config', metavar='config', action='store', help='the config use') cmda_parser = subparsers.add_parser('cmda', help='a first command') cmdb_parser = subparsers.add_parser('cmdb', help='the second operation') cmdc_parser = subparsers.add_parser('cmdc', help='yet thing') print(parser.parse_args()) which gives usage: enigma.py [-h] command ... config positional arguments: config config use optional arguments: -h, --help show message , exit required argume

java - Floating p:calendar when scrolling -

Image
i using primefaces 5.0.5 glassfish server 3.1.2.2. i added <p:calendar> inside <ui:fragment> included in xhtml page. when open select menu , scroll mouse wheel, panel float page. i've checked this question similar issue not on same component. the same trick doesnt work calendar. i've tried appending components around none of them works. any feedback , comment appreciated. many thanks. <h:panelgrid columns="2" id="..." style="margin: 0px 0px 30px 15px;"> <h:outputtext value="#{msg['startdate']}:"/> <p:calendar pattern="dd-mm-yyyy" convertermessage="#{msg['ocs.invalidstartdateformat']}" value="#{cc.attrs.inputobject.usagehistorystartdate}" disabled="#{cc.attrs.inputobject.usagehistorybillingperiodoption != 'custom_date_range'}" showon="button">

javascript - Event listener only for a variable -

i have following code: var right = document.getelementsbyclassname("dreapta")[0]; function scaletext(){ right.style.backgroundcolor = "#111"; right.style.color = "white"; } right.addeventlistener('click', scaletext, false); can explain me why event not working? the problem html,i had audio tag had removed. working :).ty guys , sorry bothering.

sql - Check if database is used by another C# Application -

is there way check if sql server database ( .mdf file) opened/used c# application? i installing c# application on multiple computers. these apps using single/same database. want determine if 1 of apps using or doing query database. possible? use system stored procedure sp_who2 . once result filter database name. can application name "programname" column. run below sql statement in sql server management studio, exec sp_who2

I was trying to make an app that automatically detects the OTP send via the default Android messaging app -

here code: btnsend.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { final string sentotp = randomnum(); if (!etnumber.gettext().tostring().trim().equals("")) { uri uri = uri.parse("smsto:" + etnumber.gettext().tostring().trim()); intent smsintent = new intent(intent.action_sendto, uri); smsintent.setflags(intent.flag_activity_new_task); smsintent.putextra("sms_body", sentotp); startactivity(smsintent); inish(); intent = new intent(sendactivity.this, checkeractivity.class); i.setflags(intent.flag_activity_new_task); i.putextra("generatedotp", sentotp); startactivity(i); finish(); toast.maketext(sendactivity.this, "enter phone number!!", toast.length_long).show(); } } }); upon clicking button, messaging app opens , backgrounded checkeractivity started. want whe

algorithm - Deleting a node A[i] from a Max-Heap -

Image
clrs exercise: 6.5-8 the operation heap-delete(a,i) deletes item in node i heap a . give implementation of heap-delete runs in o(lg n) time n-element max-heap. i wonder if algorithm wrong input a[10]={84,22,19,21,3,10,6,5,20} (index starts 1) , a[6]=10 being deleted. replacing last node a[6] result in violating heap property, overlooking parent value. i wrote algorithm , wanted know if works right or going wrong ? heap-delete(a,i) a[i]=a[a.heapsize] a.heapsize-=1 while i>1 , a[parent(i)]<a[i] swap a[i] a[parent(i)] i=parent(i); when deleting node max heap, first thing need swap target element last element, delete last element. now, we're faced problem of fixing max heap since moved element around. let's refer element moved x . there 3 cases: x greater parent x less parent x equal parent if x equal parent, that's easy - nothing. if x less parent, need max-heapify (which i'm assuming understand how wor

java - Named parameters in JDBC -

are there named parameters in jdbc instead of positional ones, @name , @city in ado.net query below? select * customers name=@name , city = @city jdbc not support named parameters. unless bound using plain jdbc (which causes pain, let me tell that) suggest use springs excellent jdbctemplate can used without whole ioc container. namedparameterjdbctemplate supports named parameters, can use them that: namedparameterjdbctemplate jdbctemplate = new namedparameterjdbctemplate(datasource); mapsqlparametersource paramsource = new mapsqlparametersource(); paramsource.addvalue("name", name); paramsource.addvalue("city", city); jdbctemplate.queryforrowset("select * customers name = :name , city = :city", paramsource);

javascript - How to access the object returned from $save in angular -

the object returned of type d {$$state: object} $$state:object status:1 value:g $promise:undefined $resolved:true id:5271 name:"insidious" $$state private method in angular. need id ?

android - Google Play Dev Console automation of creating a new app -

i know how automate creating new app google play store. know it's possible generate screenshots, create apk , upload listing information etc. how can create app initially? want create new package , all. there way automate this? i read fastlane documentation code here: https://github.com/googlesamples/android-play-publisher-api/tree/master/v2/python i read documentation here: https://developers.google.com/android-publisher/#publishing so far i'm not finding creating new package name. the official google api doesn't allow creating of new applications. more information on github https://github.com/fastlane/fastlane/issues/4215 https://github.com/fastlane/fastlane/issues/3740 https://github.com/fastlane/fastlane/issues/3694

javascript - Why jQuery submits this form? -

i don't understand why pressing on either button add or remove , form automatically submitted. able add/remove text inputs dynamically, pressing on above mentioned buttons, , code working. added form , weird auto-submit behaviour... this jquery script: var counter = 3; $("#add").click(function() { counter = counter + 1; $("#ingredienti").append('<input type="text" name="'+counter+'" class="form-control" placeholder="inserisci ingrediente '+counter+' e quantit&agrave;" style="margin-bottom:.5em;">'); $("input[name='numero_ingredienti']").value(counter); }); $("#remove").click(function() { $("input[name="+counter+"]").remove(); counter = counter - 1; if(counter<0){counter=0;}; $("input[name='numero_ingredienti']").value(counter); }); this form: <form action='salva_ri

node.js - `node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX -

i bought myself mac book after using windows long time. i trying work on meanjs project had been working on. doing npm install on project throws error failed execute '/usr/local/bin/node /usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js build --fallback-to-build --module=/users/aayush/work/lishn/repo/lishn-alpha/node_modules/grunt-node-inspector/node_modules/node-inspector/node_modules/v8-debug/build/debug/v0.4.6/node-v46-darwin-x64/debug.node --module_name=debug --module_path=/users/aayush/work/lishn/repo/lishn-alpha/node_modules/grunt-node-inspector/node_modules/node-inspector/node_modules/v8-debug/build/debug/v0.4.6/node-v46-darwin-x64' (1) npm err! darwin 15.0.0 npm err! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" npm err! node v4.1.1 npm err! npm v2.14.4 npm err! code elifecycle > > npm err! v8-debug@0.4.6 install: `node-pre-gyp install --fallback-to-build` npm err! exit status 1 npm err! np

javascript - how can I collect form input in date format and display it on page -

i trying take form input of type date , display on page. nothing being displayed when function checkin(){ var date = document.getelementbyid("cindate").value; var datearray = date.split("/");<!-- puts date datearray-> var s = document.getelementbyid("datei"); s.textcontent = datearray[1]"th of july";<!-- shows 2nd index of datearray on page-> } <form id="myform"> <!-- collects checkin date form input --> check in date: <input type="date" name="checkin" id="cindate"> <button onclick="checkin()" >submit</button> </form> <h1 class="al">hotel room availability</h1> <p class="al">you want check in on <span id="datei"></span> <!-- shows checkin date --> </p> for solve problem can use co

design - Creating a YAML based list vs. a model in Rails -

i have app consists of restaurant model instances. 1 of essential attributes these restaurants labeling cuisine falls under. i'm @ odds myself in regards designing this. on 1 hand thought of creating cuisine model , creating either hmt or habtm association between restaurants , cuisines . more came across post shows how create pre-defined set of attributes. take answer 1 step further i'm assuming (in case) i'd add string-based cuisine column restaurant model , setup select box in restaurant form save selected value. what wondering efficient way of doing this? goal able query restaurants based cuisine(s) fall under. wasn't sure if model best choice due serving join table in sense name attribute. wasn't sure if having table minute optimal. on other hand didn't know if using yaml conducive since values dummy strings no tangible records on file i'd have model instance. can me sort out confusion? there many benefits of normalizing many

parsing - Find the first and follow set of a given grammar in java -

i have been given problem complete, , algorithms find first , follow, problem cant quite find data structure implement find these sets. import java.util.stack; public class firstfollowset { private final string[] term_tokens = { "begin", "end", ";", "if", "then", "else", "fi", "i", "=", "+", "-", "*", "/", "(", ")", "const" }; private final static string[] non_term_tokens = { "start", "prog", "block", "body", "s", "e", "t", "f" }; private static rulestack rules; private stack<string> firstset; private stack<string> followset; private boolean is_terminal(string str) { boolean test = false; (int = 0; < term_tokens.length; i++) { if (str.equals(term_tokens[i])) test = true; } return te

html - Tricky horizontal center in css : floating elements only -

i can't find way align button in middle of floating elements. button { float:left; } header { overflow: hidden; background: #222; } header a, header label { display: block; padding: 20px; color: #fff; text-decoration: none; line-height: 20px; } header a:hover, header label:hover { color: #aaa; } header label { float: right; padding: 18px 20px; cursor: pointer; } header label:after { content: "\2261"; font-size: 1.8em; } .logo { float: left; font-weight: bold; font-size: 1.5em; } nav { float: right; max-height: 0; width: 100%; -webkit-transition: max-height 0.3s; -moz-transition: max-height 0.3s; -o-transition: max-height 0.3s; transition: max-height 0.3s; } nav ul { margin: 0; padding: 0; padding-bottom: 10px; } nav li { display: block; text-align: center; } nav { padding: 10px; width: 100%; } #nav { displ

mysql - Is this query are ok? (multiple JOIN's in SQL) -

i have query: select matches.id, matches.player1, matches.player2, users.firstname firstname, tournaments.tid tid, users.tempsalt salt matches inner join tournaments on matches.tid = tournaments.tid inner join users on matches.uid = users.uid ((matches.status = 0) or (matches.status = 1)) , (tournaments.status <> 3) , (users.tempsalt = '324234324234') three tables - matches , tournaments , users matches (id, tid, uid, player1, player2, status) users (id, uid, firstname, tempsalt) tournaments (id, tid, status) added: matches[1,3,2,john,mark,0] [2,3,null,piter,sara,1] users[1,3,alex,346] [2,4,sam,32423] tournaments[1,3,2] wanna in result: [1,john,mark,sam,3,32423] , null [2,piter,sara,null,3,null] if matches.uid null no results. want results when matches.uid null too. is possible in 1 sql query? use left join , put conditions of joined tables in on clause select m.id, m.player1, m.player2, u.firstname firstname, u.te

javascript - ngAnimate replace one div with another -

lets have following: <div class="container"> <div class="row> <div id="first" ng-show="condition" class="in-out">content here...</div> <div id="second" ng-hide="condition" class="in-out">other content here...</div> </div> </div> <style> .in-out.ng-hide-add, .in-out.ng-hide-remove { transition:1s linear all; } .in-out.ng-hide-add { //opacity: 0; } .in-out.ng-hide-add.ng-hide-add-active { opacity: 0; } .in-out.ng-hide-remove { //opacity: 1; } .in-out.ng-hide-remove.ng-hide-remove-active { opacity: 1; } </style> how can gracefully replace 1 div other. means following: first visible, second not condition changes - first fades away second fades in in place of first all without altering size of main container

javascript - Can't focus on a <td> element in my table on click event -

i have table , when click on button want set contenteditable true, do, , put focus on td element client sees cursor blinking in cell. i can't seem focus work on licensename cell. know 'tabledata' variable contains correct element, i've checked in browser debugger. here i've tried. editlicensesdetails = function (e) { var tablerow = $(e.target).parent().parent(); $(tablerow).css('background-color', '#dff0d8'); $(tablerow).children('[contenteditable]').attr("contenteditable", "true"); var tabledata = $(tablerow).children('[contenteditable]')[0]; $(tabledata).focus(); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table id="tablelicensedetails" style="width:100%;"> <tr> <th>edit</th>

ios - UIButton not working in UITableview -

Image
have uitableviewcell --> inside have 4 different uiview , 3 of views has uibuttons. want make uibutton clickable. first time buttons clickable when go next screen , come back, buttons don't work. please let me know how implement this? thanks! phmytripview *tripsview=[[phmytripview alloc] initwithframe:cgrectmake(10, 5, self.frame.size.width-20, cell.frame.size.height)]; tripsview.onbaggageclick = ^{ [weakself handlebaggagepurchasetapped]; }; if ([data count]>0) { [tripsview filltripdata:[data firstobject]]; [tripsview showancillaries:self.predictivemanager.upcomingcdairbookinginfo]; } [cell bringsubviewtofront:tripsview.bagsbutton]; [cell.viewplaceholder addsubview:tripsview]; this happens because cells reusable , if go scr

In C, how to print a string from a multidimensional array? -

i have following program take 5 user entered names , print them out. i need ask each name 1 one, prompt user either print list of names or add name list. names must stored in 2 dimensional array, though don't see why couldn't done regular array. my code accepts names no issues, fails print anything. includes print tests monitor error happens. test number 6 not print, there must issue printf("name: %s", names[x][y]); what error? #include <stdio.h> int main() { int x; int y; char names[5][51] = {{'\0'},{'\0'}}; printf("enter names: "); (x = 0; x <5; x++) { printf("\nprinttest 1"); (y = 0; y < 1; y++) { printf("\nprinttest 2"); scanf("%50s",&names[x][y]); } } printf("\nprinttest 3"); (x = 0; x < 5; x++) { printf("\nprinttest 4"); (y = 0; y < 1; y++) { p

orc - I am using spark 1.4 and trying to save as orcfile with compression snappy but it saves as zlib -

here code: val df=hivecontext.write.format("orc").options("orc.compression","snappy").save( "xyz") but file saved zlib. please help. you try adding conf "spark.io.compression.codec=snappy" spark-shell / spark-submit: spark-shell --conf spark.io.compression.codec=snappy #rest of command.. also, writing orc format (assuming in spark >= 1.5) can use: mydf.orc("/some/path") the "orc" method doing '.format("orc").save("/some/path")'.

WPF Canvas to animated gif with transparent background to display on svg canvas -

in web project, need dynamically render xaml frames animated gif. it's working - i'm rendering each frame png code: // save current canvas transform var transform = surface.layouttransform; // reset current transform (in case scaled or rotated) surface.layouttransform = null; // size of canvas var size = new system.windows.size(surface.width, surface.height); // measure , arrange surface // important surface.measure(size); surface.arrange(new rect(size)); // create render bitmap , push surface var renderbitmap = new rendertargetbitmap( (int)size.width, (int)size.height, 96d, 96d, pixelformats.pbgra32); renderbitmap.render(surface); bitmap bmp; // create file stream saving image using (var stream = new memorystream()) { // use png encoder our

javascript - Why does this give me an error? -

var nop = {}; var f = {}; [nop.foo] = (f.foo || undefined); note f.foo not present. returns following error: uncaught typeerror: cannot read property 'symbol(symbol.iterator)' of undefined why? it seems reason destructuring [nope.foo] not matching (whatever) you'd better change so: var nop = {}; var f = {}; [nop.foo] = [(f.foo || 23)]; console.log(nop)

Ruby On Rails - NoMethodError -

hy guys... i'm learning ruby on rail don't know whats going on on page, error: nomethoderror in contacts#new showing /home/ubuntu/workspace/simplecodecasts_saas/app/views/contacts/new.html.erb line #7 raised: undefined method `name' # this new.html.erb <div class="row"> <div class="col-md-4 col-md-offset-4"> <div class="well"> <%= form_for @contact |f| %> <div class="form-group"> <%= f.label :name %> <%= f.text_field :name, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :email %> <%= f.email_field :email, class: 'form-control' %> </div> <div class="form-group"> <%= f.label :comments %> <%= f.text_area :comments, class: 'form-control' %> </div&

python - How to convert a scipy row matrix into a numpy array -

consider following example: import numpy np import scipy.sparse = scipy.sparse.csr_matrix((2,2)) b = a.sum(axis=0) the matrix b has form matrix([[ 0., 0.]]) however, i'd become array this: array([ 0., 0.]) this can done b = np.asarray(b)[0] , not seem elegant, compared matlab's b(:) . there more elegant way this? b.a1 job. in [83]: out[83]: <2x2 sparse matrix of type '<class 'numpy.float64'>' 0 stored elements in compressed sparse row format> in [84]: a.a out[84]: array([[ 0., 0.], [ 0., 0.]]) in [85]: b=a.sum(axis=0) in [86]: b out[86]: matrix([[ 0., 0.]]) in [87]: b.a1 out[87]: array([ 0., 0.]) in [88]: a.a.sum(axis=0) # way out[88]: array([ 0., 0.]) you can vote this, or add top grossing answer here: numpy matrix array :) a sparse matrix. sparse sum performed matrix product (an appropriate matrix of 1s). result dense matrix. sparse matrix has toarray() method, .a shortcut. d

amazon web services - AWS-SDK: SQS How identify messages that were not deleted in BatchDeleteOperation -

deletemessagesparams := &sqs.deletemessagebatchinput{ entries: messagestodelete, // array of type *sqs.deletemessagebatchrequestentry queueurl: aws.string(queue_url), } if resp , err := svc.deletemessagebatch(deletemessagesparams); err != nil { log.println("batch delete failed: ", err.error()) }else{ log.println("batch delete successful: ", resp) } i'm using batch delete in sqs. when batch deletion operation successful, resp contains messageid's of messages deletion successful. in-case of error or when messages not deleted queue, err contain messageid's batch deletion failed?? in case of partial success when performing batch deletes, service return 200 ok , response object have 2 fields successful , failed. the failed have list of "batchresulterrorentry" type of objects containing message ids , reason failures.

excel - Color Fill Conditional Formatting -

Image
i need writing custom conditional formatting rule color fills cell based on difference of 2 columns. have attached image of spreadsheet reference. basically, difference of each pair of cells in columns f , h correspond color fill shown in color legend below. example, difference of f3 , h3 (100% - 100% = 0%) shows obligation met appropriation corresponding row h3 highlighted in green. however, difference of f9 , h9 (90% - 76% = 24%) shows obligation not met appropriation corresponding row h9 highlighted in red. please let me know if there way besides individual color filling cells. helpful in future work. here's how set up. it's essential have rules ordered shown in image them apply correctly. based on screenshot, seems there's supposed yellow highlight if actual value <10% below goal value. question didn't specify that, i've added in -- can ignore if it's not needed , red/green rules work expect.

visual studio 2015 - The EntityFramework package is not installed on project ASP.NET Beta8 -

trying entity framework 7 work in asp.net 5 beta8 project. have references entityframework.sqlserver 7.0.0-beta8 , entityframework.commands 7.0.0-beta8 packages in references. yet when go nuget package manager console , type: enable-migrations entityframework package not installed on project "my project" and add-migration add-migration initialmigration entityframework package not installed on project "my project" the default project in console set correct project. the migrations experience in asp.net 5 still work-in-progress. following steps overly complex , simplified time reach stable release. now have model, can use migrations create database you. open command prompt (windows key + r, type cmd, click ok) use cd command navigate project directory run dnvm use 1.0.0-beta8 run dnx ef migrations add myfirstmigration scaffold migration create initial set of tables model. run dnx ef database update apply new migration datab

node.js - Segfault with NodeJs -

i'm trying execute test mocha in node , it's stopping segmentation fault. in process of gathering intelligence on problem, noticed: i updated node , modules i deleted node_modules , re npm install after using bunch of console.log located problem after render method returns , componentdidupdate of react component fires when using iron-node there's no segfault. test passing with node, segfault occur when run problematic test (with mocha's it.only(...) ) i'd file issue don't know how reproduce yet. any idea/help more welcome :) edit: for me doesn't make sense if you, got using tool: https://github.com/ddopson/node-segfault-handler pid 19289 received sigsegv address: 0x38 /home/guillaume/documents/random_projects/cookies/node_modules/segfault-handler/build/release/segfault-handler.node(+0x1a1b)[0x7fb63afb7a1b] /usr/lib/libpthread.so.0(+0x10f00)[0x7fb640bb1f00] /usr/bin/node(_zn2v88internal9fieldtype7asclassev+0x15)[0x94a515] /usr/bin/n

node.js - Unable to execute chunkfile function of blessc module of npm Node js -

brief: building node function chunk huge css approach: function splitfiles(source) { chunkfile(source, { sourcemaps: true }).then(function(parsedcss) { console.log("complete!"); }); } splitfiles(source); error: referenceerror: chunkfile not defined i rookie @ node js. appretiated. note: have node , bless installed. able chunk files using dos notation. want use api approach. update: var bl = require('bless'); //also tried require('blessc') function splitfiles(source) { bl.chunkfile(source, { sourcemaps: true }).then(function(parsedcss) { console.log("complete!"); }); } splitfiles(source); error: error: cannot find module 'blessc'

php - how can change custom messages errors at login action in laravel 5.2 -

i'm new user use in laravel 5.2 framework. i have problem modify validator error messages @ login action . change other part of action example register , resetpasspord ... but can't find login action. found link when searched @ google not me, i know laravel use route::auth(); in route file login action can change error message language !? i test sample code @ requests\request.php this: public function messages() { return [ 'required' => 'test error message', 'email.unique' => 'test error message', ]; } but wasn't change !!! i dont change action sample login in laravel, , create custom login, wanna modify validator custom messages in app or part of login action i'm sorry if language english not prefect thank you one: in config/app.php change 'locale' => 'en' 'locale' => 'es' two: copy files in directory resources/lang/en resour

c++ - How to fix this template: -

template <typename in,typename out,bool isvector> out foo(in x){ if (isvector){ return x[0]; } else { return x; } } after asking this question wrongly assumed, above code compile e.g. foo<double,double,false>; as as foo<std::vector<double>,double,true>; however, if 1 of if-branches never gets executed, checked correctness , above not compile. how can fix it? the code above simplified, dont know how fix it, function templates cannot have partial specialization... you can "extract" template parameters want specialize on, make them template parameters of structure, , write function remaining template parameters static member function: template<bool isvector = true> struct bar { template<typename in> static auto foo(in input) { return input[0]; } }; template<> struct bar<false> { template<typename in> static auto foo(in input) { re

JsViews Data-Link Helper Function -

i have following helper defined: $.views.helpers({ total: function(lines) { var total = 0; (var = 0; < lines.length; i++) { total += lines[i].price * lines[i].quantity; } return total; } }); then have have following code data link model view: var model = { lines: [] }; $("#lines").link(true, model); finally within view have following: <span data-link="~total(lines)"></span> however whenever observably add or remove items array doesn't update total. read pass in lines.length function , indeed updated total each time added or removed item. when observably updated quantity property against of lines total did not update. i'd appreciate if show me how this. thanks yes, found https://github.com/borismoore/jsviews/issues/280 , there not declarative syntax depending on "all". after v1.0 feature added - along lines of total.depends = "lines**";

How to simulate mouse clicks as fast as possible in Java? -

i'm simulating mouse clicks , want fast possible. currently i'm using robot class this: private static int millisecondclickdelay = 25; public static void leftclickmouse(){ main.robot.mousepress(inputevent.button1_down_mask); main.robot.mouserelease(inputevent.button1_down_mask); main.robot.delay(millisecondclickdelay); main.robot.mousemove(0, 0); } unfortunately have use delay, or else race condition mouse moves before release registered. 25 lowest delay can use without encountering problem, task i'm doing takes 14 seconds this. i've gotten down 6 seconds 5 millisecond delay, result horribly inconsistent. can simulate clicks way? thanks in advance. update: i've updated function this: public static synchronized void leftclickmouse(){ main.robot.mousepress(inputevent.button1_down_mask); main.robot.mouserelease(inputevent.button1_down_mask); main.robot.waitforidle(); main.robot.mousemove(0, 0); } the robot.waitfo

javascript - Making an Ajax request in Amazon S3 using a Lambda function -

i'm trying fetch json response weatherdata coming netatmo cloud, using lambda function/javascript in amazon s3 aws. first trying fetch token using following method. seems dollar sign not recognized. gives? function getnetatmodata(){ var clientid = "******"; var clientsecret = "******"; var userid="******@******.com"; var parola="******"; var formuserpass = { client_id: clientid, client_secret: clientsecret, username: userid, password: parola, scope: 'read_station', grant_type: 'password' }; $.ajax({ async: false, url: "https://api.netatmo.net/oauth2/token", type: "post", datatype: "json", data: formuserpass, success: function(token){ // awesome token.. } }); console.log("http request successful..."); } looks trying use jquery ajax method. if jquery isn't loaded won't work. i'm not familiar aws lambda interface if possible loa

jquery - Issue with calling multiple JSON files -

so have looked around , found information on how call 2 json files using jquery. while able call both files getting following error: var weather = data.data.weather; if comment out 1 of variables (dataurl2) calls in json file works no problem. below sample of js var zipcode = '27560'; var appid = '96afa96cadeb7165258ae95b77fdc'; var startdate = '2015-10-01'; var enddate = '2015-10-31'; var timeperiod ='24'; var dataurl = '//api.worldweatheronline.com/premium/v1/past-weather.ashx?q='+ zipcode +'&format=json&date='+ startdate +'&enddate='+ enddate +'&tp='+ timeperiod +'&key='+ appid var dataurl2 = '//westbrookfl.com/wp-content/plugins/csanalytics/lib/data/data-channeldata.php' //creates table citation data jquery.when( jquery.getjson(dataurl), jquery.getjson(dataurl2) ).then(function (