Posts

Showing posts from September, 2013

node.js - Using a value of an document as _id when importing this document to MongoDB using NodeJS -

i'm trying import object mongo. when try use value of object _id fails. error i.e: "[casterror: cast objectid failed value "11563195" @ path "_id"]" , later "[error: document must have _id before saving]" what doing wrong ? // read , import csv file. csv.frompath(filepath, { objectmode: true, headers: keys }) .on('data', function (data) { settimeout(function(){ var obj = new models[filename](data); obj._id = obj.some_id; obj.save(function (err, importedobj) { if (err) { console.log(err); } else { console.log('import: ok'); } }); }, 500); }) here used schema: var mongoose = require('mongoose'); var schema = mongoose.schema; var someschema = new schema( { some_id: string, fie

html - Horizontal scroll-bar with unknown number of child-elements and a fixed-width parent -

to clarify title: i have div, has child-elements unknown fixed-width (i used bootstrap mobile-friendly users) , want these child-elements in container can scroll horizontally. found similair: http://jsfiddle.net/kh5k7/1/ the problem is, parent has assigned width (320px), while mine might change. of course know giving width of 1000000px, nothing not fit in it, user-friendly , working 'fluidly' use width:100%; parent div demo here

Connection to MongoDB fails -

Image
i tried connect local mongodb instance, failed error message failed connect . i have run commands shown in below screenshots. error message shown there, too. my folder structure is: d:/mongodb/bin d:/mongodb/data/db d:/mongodb/log i using 32-bit windows7. your data directory doesn't exist mongodb expecting be. for simplicity can create d:/data/db , default location , mongod looking @ moment, , use data directory. alternatively if want use d:/mongodb/data/db data directory you'll need specify dbpath when starting mongod mongod --dbpath d:/mongodb/data/db this can done in configuration file .

python - How to use own algorithm to extract features in scikit-learn ( text feature extraction) -

i want use own algorithm extract features training data , fit , transform using countvectorize in scikit-learn . currently doing: from sklearn.feature_extraction.text import countvectorizer cvect_obj = countvectorizer() vects = cvect_obj.fit_transform(traning_data) fit_transform(traning_data) automatically extracts features , transforms it, want use own algorithm extract features. actually quite not possible using directly though.as rule scikit-learn add well-established algorithms. rule of thumb @ least 3 years since publications, 200+ citations , wide use , usefullness. technique provides clear-cut improvement (e.g. enhanced data structure or efficient approximation) on widely-used method considered inclusion. moreover, implementation doesn’t need in scikit-learn used scikit-learn tools, though. implement favorite algorithm in scikit-learn compatible way, upload github , listed under related projects.

php - Undefined offset error in array index -

i have while loop runs if index of array null. however, when use explode method throws undefined offset error while ($temptext[1] == null). but, if comment explode line out, no longer throws undefined offset error. i'm confused part, because $temptext[1] null whether explodes or not. why 1 of them throwing error, , other 1 isn't? , lastly, how fix this, can use while loop compare empty array index without throwing error? $temptext = null; $count = 1; $text = ","; $textx = "hello there"; while ($temptext[1] == null && $count > 0) { $count--; $temptext = explode($text,$textx,2); } p.s: i'm running snippet on phpfiddle.org. if check existance of array element using $array[1] == null , php throw notice: undefined offset: 1 , should use !isset($array[1]) instead. otherwise, code contains no errors.

winforms - C# ComboBox change active status -

i have 5 combobox controls , when item selected in combobox 1 , new list created in combobox 2 , , on down combobox 5 . need change active status according current selected item. items not selected way of selectedindexchanged event in button click event handler. have been working on code have reached impasse. here code: ///////////combo1////////////////////// int selectedindex1 = combobox1.selectedindex; object selecteditem1 = combobox1.selecteditem; if (selecteditem1.tostring() == "computers") { selecteditem1 = "32"; request.categoryid = selecteditem1.tostring(); } ///////////combo2////////////////////// int selectedindex2 = combobox2.selectedindex; object selecteditem2 = combobox2.selecteditem; if (selecteditem2.tostring() == "laptop") { selecteditem2= "1772"; request.categoryid = selecteditem2.tostring(); } the problem when not use combobox 2 selected item , no

c# - Insert rows on a existing dataset -

i have dataset called "titulos" , have 1 table there called "tb" columns name "titulo","titulo 2" , "titulo3". i'm trying insertion of rows in event onclick of button reason code doesn't work! dataset on xsd file , using visual studio 2013 c#. tried code don't know how apply in situation: northwinddataset.customersrow newcustomersrow = northwinddataset1.customers.newcustomersrow(); newcustomersrow.customerid = "alfki"; newcustomersrow.companyname = "alfreds futterkiste"; northwinddataset1.customers.rows.add(newcustomersrow); the problem shows error saying not recognize dataset... erros : "the name " ds_admissibilidade" not exist in current context a dataset disconnected copy of data. forgets if data originated database, xml file or else. when add rows dataset , change in-memory copy, not original source. you need mechanism update source. databases, table adapter or

c# - Declaring 2 similar anonymous objects -

below declaration of 2 anonymous objects. second 1 exact same copy of first 1 except there no lastrefresh element inside it. is there way declare these 2 objects without duplicating exact same portion? var routevaluesforautorefresh = new { page = @viewbag.nextpage, lastrefresh = @viewbag.lastrefresh, searchterm = request["searchterm"], searchcolumn = request["searchcolumn"], searchorder = request["searchorder"], searchdescending = (request["searchdescending"] ?? "true").tolower().indexof("true") > -1, requeststatus0 = (request["requeststatus0"] ?? "false").tolower().indexof("true") > -1, requeststatus1 = (request["requeststatus1"] ?? "true").tolower().indexof("true") > -1, requeststatus3 = (request["requeststatus3"] ?? "true").tolower().indexof("true") > -1, requeststatus5 = (re

Fortran TDMA algorithm on wiki -

i visited wiki site: https://en.wikibooks.org/wiki/algorithm_implementation/linear_algebra/tridiagonal_matrix_algorithm#fortran_90 it says a,b,c sub-diagonal, diagonal, , super-diagonal. if 'n' size of b, aren't sizes of 'a' , 'c' n-1? clear inspection both c(1) , c(n) accessed, contradicts sizes i've described. what's going on here? algorithm wrong? matrix sizes i've assumed wrong? input matrix algorithm? any appreciated! cp(n) calculated avoid awkward if statement - never used in determining x . c(n) not used. a(1) unused, expected.

java - Spring MVC having trouble getting JSP to display Controller Value -

i new spring mvc have setup test db try single flow through , have table displayed in jsp page. assume have configured wrong cannot find it. maybe naming convention. i have mysql db dao class select * table works can step it. my controller gets list of run models. no errors thrown jsp simple loads empty table. controller seems have correct info in it. model (snippet getters , setters seem work controller gets list of them fine) public class qamodel { private int idrun; private string suiteid; private string run_name; controller code @requestmapping(value="/runlist") public modelandview listrun(modelandview model) throws ioexception{ //@modelattribute system.out.println("**** controller ******"); list<qamodel> listrun = rundao.list(); model.addobject("runlist", listrun); model.setviewname("runlist"); return model; } that list of run model objects contain correct db info can see them if

php - Mysqli driver on codeigniter 3 not working -

in codeigniter version 3.0, db driver "mysql" deprecated, , new recommended driver mysql "mysqli". but queries don't work when use mysqli, , when switch "mysql" driver error displayed: a php error encountered severity: 8192 message: mysql_connect(): mysql extension deprecated , removed in future: use mysqli or pdo instead filename: mysql/mysql_driver.php line number: 136 ... switch mysqli , use sql select users.`id` `users` users.`name` = "ronaldob" , users.`password` = "123" i use `` quotes , helps alot avoiding sql keywords , see complete mysql keyword list here https://dev.mysql.com/doc/refman/5.0/en/keywords.html hope helps

node.js - Not sure how to return endpoint -

i have node/express api not sure how return results of $group. my code: router.route('/viewed_card/:invite_id') .get(function(req, res){ profile.aggregate([ {$unwind:'$contacts'}, {$unwind:'$contacts.shared'}, {$match:{'contacts.shared.invite_id':req.params.invite_id}}, {$group:{ _id:null, first_name:{$first:'$contacts.first_name'}, last_name:{$first:'$contacts.last_name'} }} ]) }) how return results? i tried doing "return" before "profile.aggregate" function. i though maybe this: router.route('/viewed_card/:invite_id') .get(function(req, res){ profile.aggregate([ {$unwind:'$contacts'}, {$unwind:'$contacts.shared'}, {$match:{'contacts.shared.invite_id':req.params.invite_id}}, {$group:{

java - Any way to stop a thread that implements Runnable using a boolean , without extending Thread ? -

consider code : public class mythread implements runnable{ private volatile static boolean running = true; public void stopthread() { running = false; } @override public void run() { while (running) { try { system.out.println("sleeping ..."); thread.sleep(15000); system.out.println("done sleeping ..."); } catch (interruptedexception e) { e.printstacktrace(); } } } public static void main(string[] args) { mythread thread = new mythread(); thread.run(); } } is possible stop thread implements runnable boolean , without extending thread ? is possible stop thread implements runnable a class implements runnable not thread. plain class no magic it, declaring single void run() method. example therefore doesn't start threads. so instead of misleadingl

How to get absolute path from Android gridview thumbnail? -

i developing android video gallery application. managed fetch thumbnails storage , show them in grid-view. now, how can original video file path clicking each thumbnail ? here code : mgridview.setadapter(madapter); mgridview .setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick( adapterview<?> adapterview, view view, int i, long l) { toast.maketext(getapplicationcontext(), "video path", toast.length_short).show(); } });

url - Throughput vs. Latency Confusion -

according article throughput , latency h "when go buy water pipe, there 2 independent parameters at: diameter of pipe , length" but think these 2 parameters related. throughput measured per unit time, long latency affect throughput, say, if droplet fast, more of them pass pipe in 1 second, can 1 me understand this? edit: confusion originated counting queuing time part of latency should not. once request handled, latency independent of throughput. let me give anology...think of car travelling on single lane road location location b..time taken car travel b latency...and number of cars travelling @ interval, maintaining latency throughput. factors affect here medium of travel ie road , no of lanes on road.

c# - Setup code for WPF control created in xaml -

is possible see how control created xaml replicated code behind? reason i'm asking create number of listview controls based on each item in collection . hope can setup 1 listview control in xaml , somehow code need reproduce more listview objects same settings in code-behind. alternatively; possible bind collection object containing items want represented listview objects control contain listview controls each item in bound collection? same way listview can create listviewitem controls if bind collection listview control. cheers unless have large hierarchy of controls, recommend follows: create list contains lists of data, list<list<data>> then create itemscontrol bound list. in itemtemplate , there listview itemssource bound datacontext .

if statement - How would I exclude them from the 2nd query? -

i commented out section check got far: echo " <div class='formtitle' style='position: relative; text-align: center; margin-top: 20px'>medals</div> <table class='profiletable' id='medaltable' style='border-top-width: 0px'> "; $mid = $_get['mid']; $result = $mysqli->query("select * ".$dbprefix."clanawards_members maa_member_id = '$mid'"); while($row = $result->fetch_assoc()) { //retrieve column names run foreach run each 1 through next query foreach($row $key => $val) { // $result = $mysqli->query("select * ".$dbprefix."clanawards exists name = '$key'"); // while($row = $result->fetch_assoc()) { // $awardname = $row['name']; // $description = $row['description']; echo " <tr&g

java - Get user data from Spotify on Android -

i want current user's data spotify. the documentation says have use command: curl -x " https://api.spotify.com/v1/me " -h "authorization: bearer {your access token}" i token string spotify. my question is: how should transform curl command java? you need language bindings , http client. lot of work has been done in android client made kaaes . in specific case, you'd use getme method documented here . returns userprivate object, contains birthdate, product, email, country, fields available in userpublic object, display_name. full documentation

c# - How to solve the event can only occur on right hand of += or -= -

i working on c# on wpf application.i have written following code public partial class mainwindow : window { public mainwindow() { radiobutton daw; initializecomponent(); if (qoneone.checked == true) { messagebox.show("correct"); } } a error occurs says event qoneone.checked can appear on left hand side of += or -= you have check property qoneone.ischecked == true . ischecked property can read or write or change current state of radiobutton . checked event, can attach handler trough += can when radiobutton state change.

select - Difficult SQL Request? -

i have table tagmusic id tagid musicid --------------------- 1 1 141 2 4 141 3 3 102 so need say: take me music id have tag id 1 , 4 (for example ). one way select tags , count how many unique results got per tag: select musicid tagmusic tagid in (1, 4) group musicid having count(*) = 2

osx - Setting `sql-mysql-program` in emacs -

there @ least 3 major overviews come when searching information on using sql emacs (due insufficient reputation can't 'afford' link them here). i can find no mention in of them of need set variable sql-mysql-program when working mysql servers. yet not m-x sql-mysql work without following advice this question set variable follows: (setq sql-mysql-program "/path/to/your/mysql") in fact, tutorials/documentation i've seen highlighting variable in above question , question "emacs-how-to-use-ssh-tunnel-to-connect-to-remote-mysql" (which again can't link because of insufficient reputation.) an alternate solution seems suggested here how work emacs , mysql , suggests changing value of emacs exec-path . the question is, of these options preferable, or matter of taste? and significance of fact none of above-linked overviews of sql/emacs mentions need emacs recognize binary? there wrong emacs? i spent long time combing sql.el source t

Jquery to Python / Django Query Dict -

i'm post ing array using jquery such: var fees = []; fees.push({ "fee":somefee0, "deadline": somedeadline0, "category": somecategory0}) }); fees.push({ "fee":somefee1, "deadline": somedeadline1, "category": somecategory1}) }); jquery.ajax({ type: 'post', url: /save/, data: {fees:fees}, success: ... when post data django app, shows such: <querydict: {u'fees[1][deadline]': [u'31'], u'fees[0][category]': [u'43'], u'fees[1][fee]': [u'fdsa'], u'fees[1][category]': [u'44'], u'fees[0][fee]': [u'fdas'], u'fees[0][deadline]': [u'31']}> how can access such use

xml - How to disable hour in calendar view in odoo? -

is there generic way disable hours in calendar views in odoo? i'm using following code: <record model="ir.ui.view" id="topay_pay_calendar_view"> <field name="name">topay_pay.calendar</field> <field name="model">topay.pay</field> <field name="arch" type="xml"> <calendar string="to pay calendar" date_start="date_start" date_end="date_exp" color="id"> <field name="name"/> <field name="amount"/> </calendar> </field> </record> for have code in xml : <xpath expr="//kanban/templates//div[@class='oe_kanban_footer_left']" position="replace"> <div class="oe_kanban_footer_left"> </div> </xpath>

error handling - catch-and-replace Rx Observable stream/sequence -

say have observable compromised of 2 remote ajax calls exposed observable's. these streams flatmaps of sponse sequence of values. var remotedata = rx.observable.merge( data1, data2); for sake of argument imagine following definitions: var data1 = rx.observable.from([1,2,3]); // multiple items! var data2 = rx.observable.throw("whoops!"); i either get data1 , data2 , fetched or if there any error use cached data. however if write var dataorcache = remotedata.catch(cacheddata) append output stream adding cached data after error. because catch merely continues sequence different observable: continues observable sequence terminated exception next observable sequence. this problematic because error might result data2 (or later in data1 steam); yet cachedata should superseded , all results err'ing source. for example, if cachedata = rx.observable.from(["cached"]) final sequence [1,2,3,"cached"] when desired goal [

How to set ASP.NET 5 environment variables on production environment -

in visual studio 2015 set following variable in project properties: aspnet_env . if set development can use: public void configure(iapplicationbuilder app, ihostingenvironment env) { if (env.isdevelopment()) { app.useerrorpage(); } } isdevelopment method check aspnet_env environment variable. on development while in visual studio 2015. when publish web application iis on production server how can set value aspnet_env ? my server windows server 2012 if using iis host application, it's possible set environment variables in web.config file this: <aspnetcore processpath="%launcher_path%" arguments="%launcher_args%" stdoutlogenabled="false" stdoutlogfile=".\logs\stdout" forwardwindowsauthtoken="false"> <environmentvariables> <environmentvariable name="aspnetcore_environment" value="qa" /> <environmentvariable name="anothervariable

java - NoSuchMethodException for public no argument constructor in Inner Class -

i defined public no-argument constructor inside inner class, , code keeps throwing nosuchmethoexception when call getconstructor() . i'm calling problem method within outer class using: addlisteners( info_boxes, infoboxlistener.class.getname() ); my inner class: public class infoboxlistener implements view.onclicklistener { public infoboxlistener() { //why isn't constructor being found? } @override public void onclick(view view) { //some code } } the method throwing exception: private void addlisteners( list<view> views, string class_name ) { try { class<?> clazz = class.forname( class_name ); constructor<?> ctor = clazz.getconstructor(); //exception ( view view : views ) { object object = ctor.newinstance(); view.setonclicklistener( (view.onclicklistener) object ); }

python - Using string to call function -

from en import verb print verb.tenses() print verb.infinitive('argue') ['infinitive', 'present participle', 'past plural', '2nd singular present', '2nd singular past', 'past', '3rd singular present', 'past participle', '1st singular present', '1st singular past', '3rd singular past', 'present plural'] argue using this . i can't find method give tenses of verb. there 1 way call each function: replace space list using verb object. how can accomplish this? the input: argue . output should be: arguing , argued , argue .. you can create list of names / parameters each name of tense. example: tense_functions = { 'infinitive': ('infinitive', {}), 'present participle': ('present_participle', {}), '1st singular present': ('present', {'person': 1}), ... } tense in verb.tenses(): options =

Jquery result from sum of array incorrect -

var answ = []; $(document).ready(function() { $("#result").click(function() { answ = []; $('input[type="radio"]:checked').each(function(){ answ.push($(this).val()); //push values in array }); var total = 0; (var = 0; < answ.length; i++) { total += answ[i] << 0; } console.log(total); }); }); $("#shlong").click(function() { console.log(answ); }); fb.ui( { method: 'feed', name: 'facebook dialogs', link: 'http://developers.facebook.com/docs/reference/dialogs/', picture: 'http://fbrell.com/f8.jpg', caption: total, description: 'dialogs provide simple, consistent interface applications interface users.', message: 'facebook dialogs easy!' }, <input type="radio" name="quiz1" value="1"> <input type="radio" name="quiz2" value="4"> <input type="radio" name="

ruby - Updating a property set as the key in DataMapper -

is possible update property in datamapper if :key set true? say, example, have model set this: class post include datamapper::resource property :slug, text, :unique => true, :key => true # ... end and made new instance of :slug => "example-post-title" . i tried update accessing stored @post = post.get("example-post-title") #=> #<post @slug="example-post-title" ...> @post.slug = "example-post-title-2" #=> "example-post-title-2" @post.save #=> true @post = post.get("example-post-title-2") #=> nil but can see slug never updated. tried using post#update method: @post = post.get("example-post-title") #=> #<post @slug="example-post-title" ...> @post.update(:slug => "example-post-title-2") #=> true @post = post.get("example-post-title-2") #=> nil looking in database, index column not changed either of these examples. remai

php - Calling an ADFS service with a .pfx certificate -

i trying connect adfs soap service receive sts token. have been given .pfx , not have username or password. first service take .pfx , give me token. use token in subsequent service calls. i given link: somecompany.com/adfs/services/trust/13/usernamemixed , wsdl. php's built in soap functionality doesn't seem support ws-* functionality don't believe can use wsdl normal soap call. simplesamlphp seems geared towards sps , idps rather consumers. have seen several other libraries looks call adfs service use usernames , passwords rather certificate. the way have found looks work writing envelope , posting that, seems tedious when doing several different soap calls. are there ways / libraries call adfs service consumer? edit: part of wsdl: <wsp:policy wsu:id="certificatewstrustbinding_iwstrustfeb2005async_policy"> <wsp:exactlyone> <wsp:all> <sp:transportbinding xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy&

php - Magento CMS URL_KEY not working. Ends up empty -

i have big issue magento. can't create new cms pages. can create 1 page have empty "url key" wont generate any. if enter 1 manually when creating page, won't save either. the second page try creating generates error in picture below ofcourse.. http://i.stack.imgur.com/oudjc.jpg this happen after upgrading version 1.8 -> 1.9.

c# - How do I accurately represent this ElasticSearch query using NEST? -

background / goal i have query in elasticsearch i'm using filters on several fields (relatively small data set , know values should in fields @ time query). idea we'll perform full-text query after we've filtered on selections made user. i'm putting elasticsearch behind webapi controller , figured made sense use nest accomplish query. the query, in plain english we have filters several fields. each inner filter or filter, they're and. in sql, pseudo-code equivalent select * table foo in (1,2,3) , bar in (4,5,6) . questions can simplify way i'm thinking query, based on see below? overlooking basic approach? seems heavy i'm new es. how represent query below in nest syntax? is nest best choice this? should using elasticsearch library instead , going lower level? the query text { "query": { "filtered": { "filter": { "bool": { "must": [ {

reactjs - React router - Nested routes not working -

my goal have http://mydomain/route1 render react component component1 , http://mydomain/route2 render component2. so, thought it's natural write routes following: <route name="route1" handler={component1}> <route name="route2" handler={component2} /> </route> <defaultroute name="home" handler={home} /> </route> http://mydomain/route1 works expected http://mydomain/route2 renders component1 instead. then read this question , changed routes follows: <route name="route1" path="route1" handler={component1} /> <route name="route2" path="route1/route2" handler={component2} /> <defaultroute name="home" handler={home} /> </route> both http://mydomain/route2 , http://mydomain/route2 work expected now. however, don't understand why former 1 not work while looks more logical , neater me. the

git - Change previous commit message after merging with another branch -

i have situation need change commit message of previous commit on branch (lets call brancha). understand can change message using interactive rebase on branch git rebase -i <commit-number> . the problem have merged branch local branch (branchb). issue need change commit message in both brancha , branchb. merge performed fast-forwarding disabled (e.g. git merge --no-ff brancha ). am correct git consider target commit in these 2 branches separate commits? reason assume git sees same commit in brancha , branchb separate because when updated commit message in brancha, same commit in branchb remained unchanged. does mean need perform interactive rebase on both branches change message on each? if way, result in issues later in terms of merging, etc.?

xslt 1.0 - How to access or retrieve mets content of an item from another item? -

my use case have item has link in item. example, item 123456789/152 has metadata field dc.relation.hasversion=123456789/717 . within item view of 123456789/152 , how can retrieve values of metadata of 123456789/717 ? example, want retrieve dc.language.iso value of 123456789/717 123456789/152 . i looked @ related items feature in dspace don't know how metadata displayed in related items list pulled items in list. i using dspace version 5.3 mirage 2 theme . edit based on schweerelos answer, below actual code. using custom metadata field dc.relation.languageversion . basically, want link other version instead of displaying value, display dc.language.iso of other version in item-view.xsl . i've incorporated answer of schweerelos question in code just displaying value of dc.relation.languageversion . sample values of dc.relation.languageversion 10665.1/9843 ; 10665.1/9844 ie not complete uri handle. thanks in advance! actual code <xsl:template name=

android - How to register callback of App Invite Dialogue -

this code working fine.i am getting invitaton. of code working . q)how show log messages of callback. q) why can not log messages in logcat. if (appinvitedialog.canshow()) { appinvitecontent content = new appinvitecontent.builder() .setapplinkurl(appurl) .build(); appinvitedialog appinvitedialog = new appinvitedialog(getactivity()); appinvitedialog.registercallback(scallbackmanager, new facebookcallback<appinvitedialog.result>() { @override public void onsuccess(appinvitedialog.result result) { log.d("invitation", "invitation sent successfully"); toast.maketext(getactivity(), "invitation sent succseesfully", toast.length_long).show(); } @override public void oncancel() { log.d("invitation"

ios - Replacing Occurrences of Strings in NSMutableArray Only Working Once -

i confounded, , perhaps have missed simple, can't find it. i'll problem in theoretical, because have done test , still cannot work stripped down code. using spritebuilder, shouldn't causing issue - can log value getting in text input, cannot value array second time - enough ranting, time code. main.h #import "content.h" #import "replaceme.h" @property content *contentinstance; @property replaceme *replacemeinstance; main.m -(void)somefunction{ _contentinstance = (content*)[ccbreader load:@"contentscene"]; [_contentinstance.changearray enumerateobjectsusingblock:^(id obj, nsuinteger idx, bool *stop) { if ([_contentinstance.base[idx] containsstring:@"one"]){ nslog(@"i contain one!"); nsstring *replace = [_content.testarray[idx] stringbyreplacingoccurrencesofstring:@"one" withstring:changethetext.string]; [_content.testarray replaceobjectatindex:idx

oauth - How do I automate authentication on a site that uses a third party like github or Facebook for login credentials when scraping? -

i trying scrape webpage on codeeval.com shows challenges user has completed , ones not completed. page https://www.codeeval.com/open_challenges/ problem use github account log codeeval.com. can't figure out how authenticate scraper through github can page. need manually login , save html file. i'd automate process. i'm using scrapy , python.

javascript - Angular JS routing no output -

i'm new angularjs , doing dan wahlin tutorial. im using 1.4.4 both angular , angular route. reason when run routing tutorial. no output here relevant code files: index.html <!doctype html> <html lang="en-us" ng-app = 'app'> <head> <meta content="text/html;charset=utf-8" http-equiv="content-type"> <meta content="utf-8" http-equiv="encoding"> </head> <body> <div ng-view></div> <script src="scripts/angular.js"></script> <script src="scripts/angular-route.js"></script> <script src="app/app.js"></script> <script src="app/controllers/new_controller.js"></script> </body> </html> new_controller.js function controller_people($scope) { $scope.person = [ { name: 'bob', gender: 'm', city: 'cinc

java - Inserting values into BLOB type in JDBC -

i have several columns of blob type in database. not these columns needed filled since contain fingerprint templates. there cases users amputated thus, not columns used. in situation, value should insert in database? code: public void insertlefthandbio(bio bio, string id) { try { string query = "insert fingerprint_left_tbl values(?,?,?,?,?,?,?,?,?,?,?,?)"; ps = super.getconnection().preparestatement(query); ps.setint(1, 0); ps.setstring(2, id); //left hand //left thumb file file = new file("left hand thumb.jpg"); inputstream stream = (inputstream) new fileinputstream(file); ps.setbytes(3, bio.getlefthandthumbtemplate().serialize()); ps.setbinarystream(4, stream); //left index file = new file("left hand index.jpg"); stream = (inputstream) new fileinputstream(file); ps.set

How to display text in place of number in angularjs materials silder -

Image
what want when click on slider, on tooltip show text in place of number. angualar-material dose not support feature right how ever can thing writing own logic or can create own slider.

android - Firebase Database listeners not firing after a while while authenticated -

i'm making app , i've run problem firebase's database , authentication services. after while, while authenticated (using firebase auth) , using app, database valueeventlisteners don't seem called, though there is data in database. how i'm adding listeners: firebasedatabase .getinstance() .getreference() .child("my_child") .addvalueeventlistener(new valueeventlistener() { @override public void ondatachange(datasnapshot datasnapshot) { log.d("app", "ondatachange"); } @override public void oncancelled(databaseerror databaseerror) { } }); stuff i've tried: checking database rules (after relog reading fine - simulated reads pass while authenticated & unauthenticated) keepsynced(true) on databasereferences adding listeners in activity's oncreate inst

sql - MySQL work with the database contains a table with millions of rows -

i not dba guy want ask few questions. i have 48 million rows in table, 10 columns. on 7 of these columns need run queries : select * `table1` `flag` = '1' - 10 millions of rows (takes 2 seconds) - on flag column have index select * table `name` '%john%' - 10k results (takes 10h) on `name column have index well i'm having problems working like , need results fast without waiting 2 seconds, in case takes 10h. i hope here me, thank guys. mysql use index on before first wildcard (%). if wildcard first symbol of "seach-string", no index used. http://dev.mysql.com/doc/refman/5.1/en/mysql-indexes.html like 'john%' - fast like '%john%' - slow i believe u should use full-text search http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

android - How to check OS of the device making the api request? -

i have android , ios app. want check @ backend programmatically api requests coming app android app or ios app i.e. want check platform/ os of user's device? possible? you can way on backend. import javax.ws.rs.get; import javax.ws.rs.headerparam; import javax.ws.rs.path; import javax.ws.rs.core.response; @path("/users") public class userservice { @get @path("/get") public response adduser(@headerparam("user-agent") string useragent) { return response.status(200) .entity("adduser called, useragent : " + useragent) .build(); } } output: adduser called, useragent : mozilla/5.0 (windows nt 6.1; rv:5.0) gecko/20100101 firefox/5.0 copied mykong

SQL Group by sex then age -

i have patients table below: patients name gender dob student m 03-mar-2001 student b f 08-dec-1985 student c f 12-sep-1990 student d m 20-may-1981 i have sql statement display result below: gender 0-19 20-29 30-39 m 1 0 1 f 0 2 0 please check below query create table #t1 (name varchar(100),gender varchar(10),dob date) insert #t1(name,gender,dob) values('student a','m','03-mar-2001') insert #t1(name,gender,dob) values('student b','f','08-dec-1985') insert #t1(name,gender,dob) values('student c','f','12-sep-1990') insert #t1(name,gender,dob) values('student d','m','20-may-1981') select gender , sum(case when datediff(yy,dob,getdate()) between 0 , 20 1 else 0 end) [0-19], sum(case when datediff(yy,dob,getdate()) between 21 , 30 1 else 0 end) [20-29], sum(case when datediff(yy,dob,get

SSRS expression to get first character from string -

i having field string values "first middle last" , want show initial characters string "fml" how can in terms of ssrs expression ? assuming field mystring has 3 words following find first character of first, second , last words. admittedly doesn't handle instances there more or less 3 words, should started if require more finesse. =left(fields!mystring.value, 1) + " " + left(mid(fields!mystring.value, instr(fields!mystring.value, " ") + 1), 1) + " " + left(mid(fields!mystring.value, instrrev(fields!mystring.value, " ") + 1), 1) edit to cope possiblity of 2 words (as suggested in commetns below) check index of spaces used ensure not same, , 3 words exist. make code follows =left(fields!mystring.value, 1) + " " + left(mid(fields!mystring.value, instr(fields!mystring.value, " ") + 1), 1) + iif(instrrev(fields!mystring.value, " ") > instr(fields!mystring.value, &q

database connection - Unable to connect MongoDb on Windows -

Image
i have installed mongodb.msi(installed in c:\program files\mongodb\server\3.0\bin) , c:\data\db created. whenever try connect mongodb results in connection fail. command promt, first run mongod.exe , mongo.exe , results in error: /bin directory need added in system variable path

c# - Deserialize nested JSON array using RestSharp -

having following json array: [{ "name": "component1", "count": 2, "bulletins": [{ "referencenumber": "00000a57", "title": "test test test", "publicationdate": "2014-07-02", "list": ["00000a57"] }, { "referencenumber": "10v240000", "title": "bla bla bla", "publicationdate": "2010-06-04", "list": ["10v240000"] }] }, { "name": "component2", "count": 2, "bulletins": [{ "referencenumber": "00-00-0a-57", "title": "information regarding bla bla", "publicationdate": "2015-05-22", "list": ["15-00-89-004", "15-00-89-004a"] }, { "referencenumber": "01-02-0b-57", "title": "u

python - error in code for raspberry pi 2 -

after getting code, errors still appear. import urllib.request import json r = urllib.request.urlopen("http://www.countdown.tfl.gov.uk/stopboard/50051").read() rr = str(r) obj = json.loads(rr) # filter b16 objects b16_objs = filter(lambda a: a['routename'] == 'b16', obj['arrivals']) if b16_objs: # first item b16 = b16_objs[0] my_estimatedwait = b16['estimatedwait'] print(my_estimatedwait) and error , im not sure how fix im new python , raspberry pi 2. thanks file "/usr/lib/python3.2/json/decoder.py", line 369, in raw_decode obj, end = self.scan_once(s, idx) stopiteration during handling of above exception, exception occurred: traceback (most recent call last): file "program6.py", line 6, in <module> obj = json.loads(rr) file "/usr/lib/python3.2/json/__init__.py", line 309, in loads return _default_decoder.decode(s) file "/usr/lib/python3.2/json/decoder.py", line 353, in decode obj, e

sql server - SQL where clause for self-referencing table -

i have following table: create table [dbo].[test] ( [id] [int] identity(1,1) not null, [title] [nvarchar](450) null, [description] [nvarchar](4000) null, [created] [datetime] null, [orgid] [int] null constraint [fk_test_orgid] foreign key references test(id), constraint [pk_test] primary key clustered ([id] asc) ) a new entry has orgid = null . if entry has been edited, new row created orgid set original parent. if entry edited multiple times, children have orgid set id of original row. created datetime provides "order". what need select newest versions. given table below, looking select id 3, 5 & 6 id title description created preid ----------------------------------------------------- 1 car orginal car 2014-01-01 null 2 house original house 2014-01-01 null 3 bike original bike 2014-01-01 null 4 car car updated 2014-06-01 1 5 car

javascript - RequireJS text plugin - minification of templates -

i'm using text plugin import templates. now, in production don't want there many xhr requests templates them in 1 go. idea have build task take template , create like: define("my-template.tpl", function() { return '<div>my content</div>' } and able , define statement has been run, requirejs still xhr request when have define("my function", ["my-template.tpl"], function() { <body of function here> }); did minification of text! plugin templates? doing wrong here? requirejs requests modules asynchronously. if want 1 single call, can build app using optimizer . not need template wrapper (as noticed yourself, won't change anything). files required using text plugin included in built file too.

javascript - Google Line Chart Add Hover Title To X Value -

Image
when hover on point in line chart/graph y value , not x value. what get: 36 speed: 120 what want: distance: 36 speed: 120 code: <script type="text/javascript" src="https://www.google.com/jsapi" ></script> <script type="text/javascript"> google.load('visualization', '1.1', {packages: ['corechart']}); google.setonloadcallback(drawchart); function drawchart() { var data = new google.visualization.datatable(); data.addcolumn('number', "distance"); data.addcolumn('number', "speed"); data.addrows(<?php echo json_encode($distancespeedarray, json_numeric_check); ?>); var options = { focustarget: 'category', backgroundcolor: 'none', chartarea: { backgroundcolor: 'transparent', left: 40, top: 40, width: 1200, heigh

database - Elasticsearchs- start with or contains on double analyezd field -

i trying make query gives the docoments start-with or contains in analayezd double field. wildcards should applied on not analyzed fields. add subfield type keyword , , use wildcard query. however, there more efficient solution using ngrams. configure subfield ngram tokenizer. see https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-ngram-tokenizer.html

css - How to do sidemenu as a overlay in ionic? -

i'm new ionic framework. need follow ionic tags sidemenu overlay. please me. the default style of sidemenu gives drag style need side menu overlay. <ion-side-menus enable-menu-with-back-views="true"> <ion-side-menu-content> <ion-nav-bar class="bar-positive"> <ion-nav-back-button> </ion-nav-back-button> <ion-nav-buttons side="left"> <button class="button button-icon button-clear ion-navicon" menu-toggle="left"> </button> </ion-nav-buttons> </ion-nav-bar> <ion-nav-view name="menucontent"></ion-nav-view> </ion-side-menu-content> <ion-side-menu side="left"> <ion-header-bar class="bar-stable"> <h1 class="title">left</h1> </ion-header-bar> <ion-content> <ion-list> <ion-item menu-close ng-click="login()"> login </ion-

Install trigger on script created from Google WebApp -

i creating webapp in google apps script creates script file in user google drive. now need install time trigger on script. how can that? official documentation allows me install triggers if call script project want install triggers. maybe can call script not webapp scope newly created project scope? here 1 way achieve (other publishing add-on) put script embedded on spreadsheet. add code on onopen adds "configure" menu item create trigger if not there yet. make copy of sheet. have user open sheet , execute menu item. this easier (for user) having dive script editor.

java - Simple Dependency injection not working -

it's first time have use dependency injection , i'm little confused. i don't understand how works. i have tried on simple example : public class stockresponse extends response { @inject brandservice $brand; public list<stockresponseitem> stock; public stockthresholdresponse() { stock = new arraylist<>(); } public static stockthresholdresponse create(list<dataitem> data) { stockresponse stock= new stockresponse(); (thresholdcheckaggregate data: d) { stockresponseitem item = new stockresponseitem(); item.id = d.thresholdid; item.brand = str.$brand.byid(d.brand); str.stockthresholds.add(item); } return str; } } but when use create() method, null pointer exception $brand . i think have misunderstood how di works can't find error. i had similar difficulties understand how di (guice out of java ee) work