Posts

Showing posts from February, 2015

javascript - Why isn't the else block firing? -

i'm making html canvas game (tron), , i'm want game detect when player hits border of canvas. have if statement checks if player in contact either own trail or opponents, , works fine, parameter being outside of canvas ( y >= 780 ) doesn't seem doing anything. added snippet. there's library key event handling in there, that's not code (the library no longer necessary after made changes shouldn't have problem). time. /*! keydrown - v1.2.2 - 2016-03-23 - http://jeremyckahn.github.com/keydrown */ !function(a){var b=function(){var b={};b.foreach=function(a,b){var c;for(c in a)a.hasownproperty(c)&&b(a[c],c)};var c=b.foreach;b.gettranspose=function(a){var b={};return c(a,function(a,c){b[a]=c}),b},b.indexof=function(a,b){if(a.indexof)return a.indexof(b);var c,d=a.length;for(c=0;d>c;c++)if(a[c]===b)return c;return-1};var d=b.indexof;return b.pushunique=function(a,b){return-1===d(a,b)?(a.push(b),!0):!1},b.removevalue=function(a,b){var c=d(a,b);r...

sorting two times based on status and title java android -

well have class named data: public class data implements comparable<data>{ public string title; public string description; public string inststatus; public int imageid; data(string title, string description, int imageid,string inststatus) { this.title = title; this.description = description; this.imageid = imageid; this.inststatus = inststatus; } @override public int compareto(data another) { if(this.inststatus.equals("present")){ return this.title.compareto(another.title); }else // not present return this.inststatus.compareto(another.inststatus); // ascending } } now if see class comparing based on title in ascending order want sorting on 2 rules inststatus has 2 values :- "present" , "not present" 1. inststatus = "present" should come on top , after that, of them should sort in ascending order 2. inststatus = "not p...

c# - Asp.net Core + Entity Framework 7 optimizations? -

have few questions how ef7 + asp.net core works... 1) assume following tables: users pk=id, etc. roles pk=id, etc. userroles fk=users.id,roles.id when (pseudo) _context.users.where(x => x.username == "bob").include(...userroles...).theninclude(...roles...) , debug output, appears ef7 doing optimization , pulls minimal stuff needs populate user poco bob , roles? going hit database every time run statement? i.e. lets first time run it, bob has role of "user". if update table give him role of "admin", going re-pull everything? if delete roll, next time run query, going re-sync everything? 2) appears, in ef7, can't scaffold stored procs, correct? have schema similar this: tablea tableatob tableb tablebtoc tablec if catch drift, tablea has m:m relationship tableb (tied tableatob) , tableb has m:m relationship tablec. what i'm after tablec.name values tablea.name="blah", need join 5 of tables together. if in ef7 table scaff...

linux - Move directories Excluding file -

i have 40 directories , 1 shell.sh file in directory. want move directories other directory excluding shell.sh file. 40 directory move other directory , shell.sh don't move remain same directory. there solution ?? go mentioned directory , run in terminal: find . -maxdepth 1 ! -path . -type d -exec mv '{}' destination_path \; this work directories spaces in name

node.js - Debugging in Loopback (Node) -

Image
i'm running issues , question when debug in loopback (probably same node server/node inspector). for reason in node inspector (slc debug or node-debug) when try use console option or add watch expression, hitting return doesn't process command returns cursor next line. have bad version of node inspector? in loopback able have access full application object when running in debug mode (which thing) , can use application object perform domain functions - e.g. m.models.accounts.count(function(err,returncount) { console.log(returncount) }; ); above i'm getting count of number of accounts in database. i'd prefer not deal promises , write m.models.accounts.count(). is there library or way this?

rest - Stripe API: What's my account ID? How to default it in GET /v1/accounts/? -

i'm beginning play stripe api, , i've hit don't understand: how determine identifer (e.g., acct_abcd1234blablabla ) of own stripe account? i'm not seeing sort of account identifier in temporary stripe test account (although maybe i'm not looking under proper tab of account settings pane). now, documentation " retrieve account " says: arguments account [optional] identifier of account retrieved. if none provided, default account of api key. and seems omitting account identifier uri would be reasonable way of getting one's own account identifier, since should property of returned json object. can't figure out how omit argument in way causes account object returned. given example invocation, explicit account identfier argument, looks like: curl https://api.stripe.com/v1/accounts/acct_abcd1234blablabla -u sk_test_foobarbaz: my expectation omitting final element of uri me default. if that: curl https://api.stripe.com/v...

node.js - Mongoose: Sort by latest Comment.creationDate in comments array of a forum post -

i have following object let threadschema = mongoose.schema({ author: { type: mongoose.schema.types.objectid, required: true, ref: 'user' }, title: { type: string, required: true }, content: { type: string, required: true }, id: { type: number, required: true, unique: true }, answers: [{ type: mongoose.schema.types.objectid, default: [], ref: 'answer' }] }) like can see, array of answer objects: let answerschema = mongoose.schema({ thread: { type: mongoose.schema.types.objectid, // article required: true, ref: 'thread' }, author: { type: mongoose.schema.types.objectid, // user required: true, ref: 'user' }, creationdate: { type: date, required: true }, content: { type: string, required: true } }) and want is, in mongoose query db, sort threads ones latest (newest) answers in them. i tried stupid as: th...

ruby on rails - Using Sidekiq to run more complex jobs -

edit: simple, forgot pass in site , token i have setup sidekiq , redis on heroku , able work simple jobs this: order_worker.rb class orderworker include sidekiq::worker sidekiq_options retry: false def perform(num_orders) x=3*5 end end but more complex jobs keep failing according sidekiq web ui. need include shopifyapi , faker somehow? i'm not super clear on being run. entire app, gems , being created in worker dyno? order_worker.rb class orderworker include sidekiq::worker sidekiq_options retry: false def perform(num_orders) include shopifyapi include faker # initialize session session = shopifyapi::session.new(site, token) shopifyapi::base.activate_session(session) #create orders num_orders.times new_order = shopifyapi::order.new( :line_items => [ shopifyapi::lineitem.new( :quantity => 1, ...

sql server - Azure SQL Performance/Best Practices: Partitioned Data vs Lots of rows -

scenario: multiple customers create "objects" stored inside of "customerobject" table. let's looks this: customerobject : id bigint customerid bigint type int jsondynamicproperties nvarchar(max) each customer create somewhere around 50,000 objects. there around 1000 customers. total objects system need track around 50-75 million. read , write operations split 50/50 environment: asp.net core entity framework core azure sql my question in reference performance , best practices: at point (if ever) make sense give each customer own objects table vs having objects live in same table? does having 1000 or more tables have more of performance impact having 50-70 million rows in single table hitting time? when using entity framework core, can hydrate customerobject data model using different tables, depending on customer running query? are there other immediate gotchas can point out come mind? thanks guidance can provide! sql ...

c# - Adding audioClip from the Resources folder through code -

Image
how can add , play short audioclip name in code in unity? tested lot of samples internet doesn't work. audiosource audio = gameobject.addcomponent<audiosource>(); audio.play((audioclip)resources.load("clip1"));​ to second line: assets/resources/clickaction.cs(14,55): error cs1525: unexpected symbol `' audiosource.play() not take audioclip parameter. audiosource.playoneshot() does. pawel talked except no code example provided in answer. this play prototype looks like: public void play(); public void play(ulong delay); none of them takes audioclip parameter. so should be: audiosource audio = gameobject.addcomponent<audiosource>(); audio.playoneshot((audioclip)resources.load("clip1")); you can still use the play() function question must first assign audiosource.clip (audioclip)resources.load("clip1"); before calling play() function. so, should work too: audiosource audio = gameobj...

AngularJS - Put $http interceptor in separate file -

how can put interceptor in separate file , push in $httpprovider within configuration block. here's configuration block @ moment: (function() { 'use strict'; angular .module('app') .config(config); config.$inject = ['$httpprovider']; function config($httpprovider) { $httpprovider.defaults.withcredentials = true; $httpprovider.defaults.usexdomain = true; $httpprovider.interceptors.push(['$injector', '$q', function($injector, $q) { return { responseerror: function(response) { var toastr = $injector.get('toastr'); var lodash = $injector.get('lodash'); toastr.error(lodash.get(response, 'data.message', 'alguma coisa deu errado.')); if (response.status !== 401) { return $q.reject(response); } var userservice = $injector.get('userservice'); if (userservice.islogged()) { ...

javascript - Choosing between Angular.js and Angular 2 -

what angular 2 major differences predecessor angular.js? thanks! i recommend leaning forward , learning angular 2. @ point, primary reason learn v1 if need work on existing project written in angular 1.

if statement - "if" and "else if" commands are not working in c++ -

i in process of making chat bot , experimenting @ point. "if" commands not working , when enter "moodtoday" skips right else command. (capitalization of "moodtoday" not error) any , appreciated #include <fstream> #include <cmath> using namespace std; int main() { char name[50], moodtoday[50]; cout << "a few things should know @ time..." << endl << "1. can't process last names." << endl << "2. can't process acronyms." << endl; system("pause"); cout << endl << endl << "what name?" << endl; cin >> name; cout << "hello " << name << "." << endl << "how today?" << endl; cin >> moodtoday; //can't figure out... if ((moodtoday == "sad") || (moodtoday == "bad") || (moodtoday ==...

debugging - C Why Variable is unused? -

i need debugging program, how come program tells me have unused variable, have defined table mst[num_pt] right after create structure. ive tried moving around , defining in other places assigning mst[0] @ other places no luck. have syntax error? snippet of code referring near end thought might have entire program. #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]) { file *fp; int max_x, max_y, num_pt; int *x_coordinate, *y_coordinate; int inputfile = 0, outputfile = 0; int i; int count,dist,spot; char black[24],white[24]; typedef struct{ char colour[24]; int x; int y; int pos; }table; strcpy(black,"black"); strcpy(white,"white"); if (argc == 1) { /* generate random instances, accepting parameters stdin */ return 1; } (i = 1; < argc; i++) { if (strcmp (argv[i], "-i") == 0) inputfile = i+1; else if (s...

rust - Mismatched types when displaying a matrix with a for loop -

inspired code provided evilone in post how print vec? . display matrix, wrote code following: use std::{ops, fmt}; #[derive(partialeq, debug)] pub struct matrix<t> { data: vec<t>, row: usize, col: usize, } impl<t: copy> matrix<t> { pub fn new(row: usize, col: usize, values: &[t]) -> matrix<t> { matrix { data: values.to_vec(), row: row, col: col, } } } //// display impl<t: fmt::display> fmt::display matrix<t> { fn fmt(&self, f: &mut fmt::formatter) -> fmt::result { let n_row = self.row; let n_col = self.col; let data = self.data; in 0.. n_row { let mut each_row = string::new(); j in 0.. n_col { let idx = * n_col + j; let each_element = data[idx]; each_row.push_str(&each_element.to_string()); each_row.push...

php - CakePHP - Error saving form with partial table data to database -

i have new user form in cakephp 3 gathers basic data user, such username, email, name, phone, etc. supposed saved users table, has additional data gathered in form, such if account admin, timestamp account created, etc. of these other fields have default values specified in database, such 0 false on admin field, or current_timestamp timestamp. others i'm not saving form nullable no default values. the issue i'm having when form submitted, returns generic error the user not saved. please, try again . i've used print_r gather request data debug() $user data, , request looks good, while $user has this field required data wanted database insert default values. what doing wrong, , why won't form submit values give , database set defaults rest? my controller: public function signup() { // set page-specific values $this->set('cakepage', false); if (!$this->request->session()->check('session.timestamp...

python - Pandas join on columns with different names -

i have 2 different data frames want perform sql operations on. unfortunately, case data i'm working with, spelling different. see below example thought syntax userid belongs df1 , username belongs df2. me out? # not working - assume syntax issue? pd.merge(df1, df2, on = [['userid'=='username', 'column1']], how = 'left') when names different, use xxx_on parameters instead of on= : pd.merge(df1, df2, left_on= ['userid', 'column1'], right_on= ['username', 'column1'], how = 'left')

numpy - Similarity Measure/Matrix for data (recommender system)- Python -

i new machine learning , trying try out following problem. input 2 arrays of descriptions same length, , output array of similarity scores of first string first array compared first string in second array etc. each item in array(numpy array) string of description. can write function find out how similar between 2 strings calculating how many identical , co-occurring word ids there are, , assign score (one possible weight can based on frequency of co-occurrence vs sum of frequency of individual word id). apply function 2 arrays array of scores. please let me know if there other approaches want to consider well. thanks! data: array(['0/1/2/3/4/5/6/5/7/8/9/3/10', '11/12/13/14/15/15/16/17/12', '18/19/20/21/22/23/24/25', '26/27/28/29/30/31/32/33/34/35/36/37/38/39/33/34/40/41', '5/42/43/15/44/45/46/47/48/26/49/50/51/52/49/53/54/51/55/56/22', '57/58/59/60/61/49/62/23/57/58/63/57/58', '64/65/66/63/67/68/...

Mixing creation and migration scripts with Flyway -

can flyway used mix creation , migration scripts that: new installations run schema creation script existing installations run migration scripts, , never see creation scripts of subsequent versions ? e.g. given: db/create/v1/v1__schema.sql db/create/v2/v2__schema.sql db/create/v3/v3__schema.sql db/migration/v1/v1.1__migratea.sql db/migration/v2/v2.1__migrateb.sql db/migration/v2/v2.2__migratec.sql an existing v1 installation run following v3: db/migration/v1/v1.1__migratea.sql db/migration/v2/v2.1__migrateb.sql db/migration/v2/v2.2__migratec.sql it never run following, these represent schema-only sql produced mysqldump: db/create/v2/v2__schema.sql db/create/v3/v3__schema.sql a new v3 installation run: db/create/v3/v3__schema.sql the above conflicts approach recommended upgrade scenario when using flyway required data populated independently of migration. it looks should possible use flyway.locations support this, installations need include path ...

html - Pinterest rich pin not working & validator fails? -

Image
we've been struggling problem several months yet no avail. rich pins on pinterest used work our site stopped working , 1 after rich pins (clickable title , price) disappeared pins of our site. for example, product , have open graph information front in head section of html code: <meta property="og:type" content="product" /> <meta property="og:title" content="backless gray lace tulle flower girl dress big bow" /> <meta property="og:description" content="this dress made of high quality lace , tulle fabric; unique cross straight neckline in front; big ... shop use nyc2018 9% off today!" /> <meta property="og:url" content="http://www.princessly.com/backless-gray-lace-tulle-flower-girl-dress-with-big-bow.html" /> <meta property="og:site_name" content="princessly.com" /> <meta property="og:price:amount" content="49.62" /> <...

dataframe - Pass the additional argument "nrow" (no. of rows) to the as.data.frame function in R? -

(reproducible example given) how pass additional argument nrow as.data.frame in r? in ?as.data.frame , given: as.data.frame(x, row.names = null, optional = false, ...) ... additional arguments passed or methods. with co-worker matrix(..., nrow) , is: set.seed(1) df <- as.data.frame(matrix(c(rnorm(5),rnorm(5), rnorm(5)), nrow=5, byrow=true)) df # v1 v2 v3 # 1 -0.6264538 0.1836433 -0.8356286 # 2 1.5952808 0.3295078 -0.8204684 # 3 0.4874291 0.7383247 0.5757814 # 4 -0.3053884 1.5117812 0.3898432 # 5 -0.6212406 -2.2146999 1.1249309 without matrix(..., nrow) simulator, is: set.seed(1) df <- as.data.frame(c(rnorm(5),rnorm(5), rnorm(5))) df # c(rnorm(5), rnorm(5), rnorm(5)) # 1 -0.6264538 # 2 0.1836433 # .................................. # 15 1.1249309 i want pass nrow argument as.data.frame replace job of matrix(...,nrow) . file of as.data.frame seems achieva...

javascript - jQuery DataTable : Individual column searching on table header -

Image
i have followed steps on individual column searching (text inputs) , individual column searching (select inputs) use multiple filters on jquery datatable , there multiple filters on footer. on other hand, want move these filters header of datatable, cannot align them horizontally displayed on image below. there examples custom filtering - range search , not aligned well. possible this? $(document).ready(function() { // setup - add text input each footer cell $('#example tfoot th').each( function () { var title = $(this).text(); $(this).html( '<input type="text" placeholder="search '+title+'" />' ); } ); // datatable var table = $('#example').datatable(); // apply search table.columns().every( function () { var = this; $( 'input', this.footer() ).on( 'keyup change', function () { if ( that.search() !== this.value ) { ...

javascript - HTML child selector with predefined parameter -

i have function input element triggers ng-blur method $event parameter: $scope.markfield = function(event) { } <tr> <td><input type="text" value="1" id="inputquantity" ng-blur="markfield($event);"></td> <td><input type="text" value="1" id="inputbruto"></td> <td><input type="text" value="1" id="inputneto"></td> </tr> what need find values of other 2 inputs (inputbruto , inputneto) in row when ng-blur clicked. how this? edit: i passing $event parameter because know can this: $(event.target).parent().parent() - row 3 inputs are. but don't know how use row later input id. it nice if possible: $("#rowid > td > input[id=inputbruto]"); edit: i've managed find / change input[id=inputbruto] with: $(event.currenttarget).parent().parent().find("input[id=inpu...

java - Why is the value I'm getting different for 2 similar programs below even though i only changed the type for the method's value -

code 1: class 1 import java.text.numberformat; public class testing2 { int balance; void addinterest(int rate) { balance += balance*(rate/100); } void display() { numberformat currency = numberformat.getcurrencyinstance(); system.out.print ("the balance "); system.out.print(currency.format(balance)); } } class 2 import java.util.random; public class testing { public static void main (string args[]) { testing2 atesting = new testing2(); random myrandom = new random(); atesting.balance = myrandom.nextint(501); int rate2 = 5; system.out.println("current balance: " + atesting.balance); system.out.println("current rate: " + rate2); atesting.addinterest(rate2); atesting.display(); system.out.println(); } } output: current balance: 327 current rate: 5 balance myr327.00 code 2: class 1 import java.text.numberformat; public class testing2 { double balance; void addinterest...

swift - How to go backwards with TabBarControllers -

i have tab bar controller setup 1 of items (i called settings) in tab bar directs navigation controller 2 view controllers. first being settings page, second being page user can more advanced things. user pretty clicks setting tab directed page can click button leads him allows him change advanced items. when user finished changing items, able direct him home page using code. self.tabbarcontroller?.selectedindex = 0 the issue i'm having when user clicks "settings" tab, directed more advanced view controller instead of original settings page. how can make restarts @ settings page instead of advanced view of settings.

c++ - Continuous keyboard movements -

now making game there 2 plates on both sides of screen (i.e. left , right). , ball bounces in screen. when touches either of plates bounces back. if touches left or right edge of screen it's game over. have control plates arrow keys or standard (w, a, s, d) keys. problem when press w or movement keys moves once stops. i have press many times make move. want continuous movement when press , hold of movement keys. using allegro 5 dev c++ on windows 7 pc. the event processing logic should respond keypresses , update velocity of plate, , update logic should move plate according velocity. here's pseudocode: while running: # event processing event in queue: if event keypress: if key w: velocityy -= 10 if key s: velocityy += 10 if event keyrelease: if key w: velocityy += 10 if key s: velocityy -= 10 # update posy += velocity...

javascript - Processing google photo reference to get the image url -

i ham using node.js , have photo reference string , want access image returned. i have following code , getting in body. locations.foreach(function(loc) { var photoref; if (loc.photos && array.isarray(loc.photos)) { photoref = loc.photos[0].photo_reference; var url_in = 'https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference=' + photoref + '&key=' + key; request(url_in, function (error, response, body) { if (!error && response.statuscode == 200) { console.log(body); // show html google homepage. } }); } }); i want string image url. object representing webpage. any appreciated. it not possible image url per documentation url not returned api. https://lh3.googleusercontent.com/-b8fwohhu2_k/vtdyjefjrhi/aaaaaaaaad8/jsjamjx4xya/s1600-w400/ your image url already imageurl = 'https://maps.googleapis.com/maps/api/place/photo...

delphi - removing duplicated text inside a string -

i have string got text this str := 'hi there name vlark , images <img src=""><img src=""> images need controlled <img src=""><img src=""><img src=""><img src="">'; this string have 6 images tags <img wanted control on tags if string have more 3 images tags leave first 3 , remove rest image tags . couldnt figure out how can in coding strategy: find position , length of complete enclosed tags: <img , > if count larger 3, remove tag. function removeexcessivetags( const s: string): string; var tags,cp,p : integer; begin tags := 0; cp := 1; result := s; repeat cp := pos('<img',result,cp); if (cp > 0) begin // find end of tag p := pos('>',result,cp+4); if (p > 0) begin inc(tags); if (tags > 3) begin // delete tag if more 3 tags delete(result,cp,p-cp+1); ...

php - “No such file or directory in..” -

i have folder in htdocs named includes have example header.php. have file outside folder namned index.php. use include("includes/header.php"); in index.php file include header, "include(includes/header.php): failed open stream: no such file or directory in /home/lih/public_html/index.php". doing wrong? perhaps important add, works on computer not work on servers. <!doctype html> <html lang="sv"> <head> <title><?= $site_title . $divider . $page_title; ?></title> <meta charset="utf-8"> <link rel="stylesheet" href="css/mainmenu.css" type="text/css"> </head> <body> <div id="container"> <header id="mainheader"> <h1>välkommen</h1> <!--inkluderar mainmenu--> <?php include("includes/mainmenu.php"); ?> </header> ...

webpack async load code at runtime -

i asynchronously load javascript in app. if code load in file like: require.ensure([], function() { require('./file').x(); }); but same code user writes in browser. in other words code doesn't come file anymore string. how this?

lexicographically smallest and largest substring in java using length k -

input: welcometojava length:3 output: now smallest string:ava now largest string:wel // assign string want process variable inputstr = "welcometojava" // define , array each sub-string. string[] substrs = new string[input.length()-2]; // fill our container iterating 0 through place of last sub string. for(int = 0; < inputstr.length()-2; i++){ // assign array members sub strings input string each starting position substrs[i] = inputstr.substring(i,i+3); } // sort , print results. arrays.sort(substrs); for(int = 0; < args.length; i++) system.out.println(substrs[i]);

java - Error while Running Activity must be exorted or contain an intent-filter -

Image
i getting error while running mainactivity or app. main androidmanifest.xml file: <?xml version="1.0" encoding="utf-8"?> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/apptheme"> <activity android:name=".mainactivity" /> <intent-filter > <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> <service android:name=".delayedmessageservice" android:exported="false" > </service> </application> </manifest> my android version: 2.2.2 tried invalidate cache & restart, didn't help. did follow few other tutorials didn't either. p...

c++ - How to get descriptions for HRESULT error codes for WinRT / Windows 10 Store code? -

i'm converting win32 app uwp , writing windows store integration code using windows.services.store namespace. win32 c++ implemented via com interface methods seem return failures via hresult error codes. so thought nice convert hresult codes descriptions can displayed end-users. i tried following method: int noserror = (int)hresult; lpvoid lpmsgbuf; if(formatmessage(format_message_allocate_buffer | format_message_from_system | format_message_ignore_inserts, null, noserror, makelangid(lang_neutral, sublang_default), (lptstr) &lpmsgbuf, 0, null)) { //success localfree(lpmsgbuf); } but unfortunately doesn't work. instance, formatmessage returns false , error code error_mr_mid_not_found following hresult values got experimentally running windows store integration code: 0x80072eff 0x803f6107 do have idea how descriptions hresult codes used in windows 10? edit: following suggested sunius below came following code retrieve d...