Posts

Showing posts from April, 2015

sql - Is it a good idea to index every column if the users can filter by any column. -

in application users can create custom tables 3 column types. text, numeric , date can have 20 columns. create sql table based on schema using nvarchar(430) text, decimal(38,6) numeric , datetime. along identity id column. there potential many of these tables created different users , data might updated users uploading new csv files. best performance during upload of user data truncate table rid of existing data batches of bulk insert. the user can make selection based on filter build can include number of columns. issue tables lot of rows have poor performance during selection. combat thought adding indexes don't know columns included in condition have index every column. for example on local sql server 1 table on million rows , condition on 6 of columns take around 8 seconds first time runs under 1 second subsequent runs. indexes on every column run in under 1 second first time query ran. performance issue amplified when test on sql azure database same query take on min

javascript - How to find by array of objects in Mongoose? -

i have mongoose.schema this: const pixelschema = mongoose.schema({ x: string, y: string, color: string, }); also have array of objects this: let pixels = [ {x: 0, 1: 0, color: 'blue'}, {x: 0, y: 1, color: 'blue'}, {x: 0, y: 2, color: 'blue'}, ] how can check 1 of elements exist in database? solution looks this, think it's inefficient. pixels.map(pixel => { pixel.find(pixel, (err, pixels) => { if (pixels) { console.log('find!'); } }); }); use array part of $or query document. $or operator lets perform logical or operation on array of 2 or more expressions , selects documents satisfy @ least 1 of expressions. so query in end should be: let pixels = [ {x: 0, y: 0, color: 'blue'}, {x: 0, y: 1, color: 'blue'}, {x: 0, y: 2, color: 'blue'}, ]; let query = { "$or": pixels }; pixel.find(query, (err, pixels) => { if (pixels) { console.log(

c# regex get strings that have a specific sequence of letters and digits -

i've searched around here haven't found satisfying answer i've decided ask. need search collection of strings find expressions like: ab 12345 ac 12345 i've tried regex [a][bc][ ]\d{5} but unfortunately in strings there also #xxab 1234567890123 ggab 12345678901 ab 123456 sab 123456789 and above expression gets these valid. i've found , tried [a][bc][ ]\d{5}$ but not match anything. so question is, there expression find strings 5 numbers followed except more numbers? from answers think not clear in exposition, strings in middle of larger string set possible string must match: my description data xxxab 12345bcd and also my second description data ref. ab 12345 and also my third description data refab 12345 and also ab 12345with description following ab 12345 space , description following the strings uppercase in database. use ?! lookahead. a[bc] \d{5}(?!\d) see demo. https://regex101.com/r/or7zj6/2

c# - MVC: start process as different user - not working -

i need run executable on server mvc controller. problem: executable sits within program files folder , read value registry. have granted execution rights on respective folder application pool. here's problem: running exe process.start(exe) start executable in turn exits error because cannot read registry value (no access). assigning local admin user processstartinfo fails: var exe = @"c:\program files (x86)\[path exe]"; var secstring = new securestring(); secstring.appendchar('character'); //... secstring.makereadonly(); var procinfo = new processstartinfo(exe, settingspath) { useshellexecute = false, username = "[username]", domain = "[domain]", password = secstring, redirectstandarderror = true, redirectstandardoutput = true, redirectstandardinput = true, verb = "runas" }; var proc = process.start(procinfo); proc.waitforexit(); this cause crash of conhost , executable. using imperson

reactjs - You may need an appropriate loader to handle this file type. with webpack -

following great tutorial - https://www.codementor.io/reactjs/tutorial/beginner-guide-setup-reactjs-environment-npm-babel-6-webpack - trying learn react. the source code looks this: import react 'react'; import {render} 'react-dom'; class app extends react.component { render () { return <p> hello react!</p>; } } render(<app/>, document.getelementbyid('app')); then making bundle via webpack -d , following webpack.config.js: var webpack = require('webpack'); var path = require('path'); var build_dir = path.resolve(__dirname, 'client/public'); var app_dir = path.resolve(__dirname, 'client/app'); var config = { entry: app_dir + '/index.jsx', output: { path: build_dir, filename: 'bundle.js' }, loaders : [ { test : /\.jsx?/, // files processed - *.js , *.jsx include : app_dir

java - Change version number using apktool -

the android manifest xml file not contain information. android.yml file does. after altering apk build command doesn't make apk file. there build.gradle file or tool can used edit version number? procedure: apktool d myapk.apk open apktool.yml, increment versioncode , save apktool b followed jarsigner , zip align similar: can change version code apk?

node.js - Mongoose advanced custom schema object type -

i couldn't find example of advanced custom schema type involving custom objects (or value-objects ) in mongoose >=4.4. imagine want use custom type like: function polygon(c) { this.bounds = [ /* data */ ]; this.npoints = /* ... */ /* ... initialize polygon ... */ }; polygon.prototype.area = function surfacearea() { /**/ }; polygon.prototype.toobject = function toobject() { return this.bounds; }; next, implement custom schematype like: function polygontype(key, options) { mongoose.schematype.call(this, key, options, 'polygontype'); } polygontype.prototype = object.create(mongoose.schematype.prototype); polygontype.prototype.cast = function(val) { if (!val) return null; if (val instanceof polygon) return val; return new polygon(val) } polygontype.prototype.default = function(val) { return new polygon(val); } how can assure that: every time new object "hydrated" db (mongoose init ), have polygon instance , not plain object.

xcode - How to check if library is used or not in an iOS app -

i have old ios project evolved on time in added many librairies. of them not longer used today. question is, how can check in ios project library used or not ? i don't think there way that. can try removing path of suspected frameworks(if @ same path, i'd suggest place them separately)from library search paths and errors(if any). hope helps.

sql - How to group by a set of numbers in a column -

i have table below. want group in such way 1-4 weeknums joined , 5-8 weeknums joined together. or in other words want monthly total below fields table1 weeknum amount 1 1000 2 1100 3 1200 4 1300 5 1400 6 1500 7 1600 8 1700 the output need below output max(weeknum) sum(amount) 4 4600 8 6200 the below answer did not work actual values below. want start 4 weeks grouping. formula (weeknum-1)/4 returns 3 groups in expected 2 weeknum group expr expected group expr 1855 463 463 1856 463 463 1857 464 463 1858 464 463 1859 464 464 1860 464 464 1861 465 464 1862 465 464 need execute query in oracle try using floor rounds number down in group by clause: select max(t.weeknum),sum(amount) table1 t group fl

ios - Swift 2.2 - Notepad app, Associate a separate textView to a cell without adding ViewController -

i trying make notes app, in different cells in tableview lead different note. name , add note , when cell clicked, have segue textview, when click on newly created cell, leads same note. wondering best way have different textview note when different cell clicked. don't want have different viewcontroller each note can add infinite number of notes. please tell me if need code, because not sure file or files of code need. thank in advance. you should have 1 listviewcontroller , 1 noteviewcontroller . on prepareforsegue in listviewcontroller , need pass information. like: let notevc = segue.destinationviewcontroller as! noteviewcontroller notevc.notetext = selectedtext //pass data note in noteviewcontroller , create class variable var notetext : string?

sorting - Sort a nested dictionary in Python -

i have following dictionary. var = = { 'black': { 'grams': 1906, 'price': 2.05}, 'blue': { 'grams': 9526, 'price': 22.88}, 'gold': { 'grams': 194, 'price': 8.24}, 'magenta': { 'grams': 6035, 'price': 56.69}, 'maroon': { 'grams': 922, 'price': 18.76}, 'mint green': { 'grams': 9961, 'price': 63.89}, 'orchid': { 'grams': 4970, 'price': 10.78}, 'tan': { 'grams': 6738, 'price': 50.54}, 'yellow': { 'grams': 6045, 'price': 54.19} } how can sort based on price . resulting dictionary below. result = { 'black': { 'grams': 1906, 'price': 2.05}, 'gold': { 'grams': 194, 'price': 8.24}, 'orchid': { 'grams': 4970, 'price': 10.78}, 'maroon': { 'grams': 922, 'pri

c# - How to choose DbConfigurationType programatically? -

i have dbcontext : [dbconfigurationtype(typeof(mysqlefconfiguration))] public class mydbcontext : dbcontext { public dbset<myclass> myclasses { get; set; } } now, if want able use dbconfigurationtype , according appsettings value? so that, change appsettings value mysql mssql , becomes: [dbconfigurationtype(typeof(mssqlefconfiguration))] public class mydbcontext : dbcontext { public dbset<myclass> myclasses { get; set; } } of course, can create factory, , use reflection create new class custom attribute. however, there solution without reflection? i have solved problem inheriting dbconfigurationtypeattribute : public class baseefconfiguration : dbconfigurationtypeattribute { public baseefconfiguration() : base(sqlconfiguration) { } public static type sqlconfiguration { { string databasetypename = configurationmanager.appsettings["databasetype"]; switch (databasetypename

c++ - How avoid use global variable in simple Slot Machine program -

this simple slot machine program , won know how not use global variable ? if helps me clarify subject, because task book offered use function, try not use global variable in particular case. my code: int wheel1, wheel2, wheel3; bool triple_equals(){ if ((wheel1 == wheel2) && (wheel2 == wheel3)){ cout << "jack pot!!! "; cout << "you win!!! "; }else{ cout << "you loose moneys!!!\n"; } } int main(){ cout << "wheel 1: \n"; cin >> wheel1; cout << "wheel 2: \n"; cin >> wheel2; cout << "wheel 3: \n"; cin >> wheel3; srand(time(0)); wheel1 = rand() % 2 + 1; wheel2 = rand() % 2 + 1; wheel3 = rand() % 2 + 1; cout << "result wheel 1: " << wheel1 << "\n"; cout << "result wheel 2: " << wheel2 << "\n"; cout <

mysql - Show random questions from a table without repetition -

i using moodle multitrack test developing career assessment test. want modify plugin show random questions, 1 question @ time. if there total of 10 questions should show first random question , after saved show random question remaining 9 questions , on. questions saved in table called 'magtest_question' fields are: id(bigint), magtestid(bigint), questiontext(longtext), questiontextformat(mediumint), sortorder(bigint). the questions sorted based on 'sortorder' column. tried changing query sort randomly. select * {magtest_question} magtestid=? order rand() but show same question again. want avoid questions attempted. how can achieve using sql query. please help. query ids of 10 questions in random order, store ids in session in array in order returned query , retrieve questions one-by-one. way issue order rand() query once , questions not repeated.

sql - Get timestamp from date & time in UTC -

i have table have date , time timezone. date_time_table +------------+--------------+ | date_t | time_tz | +------------+--------------+ | 2016-05-13 | 23:00:00 -02 | | 2016-05-14 | 13:00:00 +06 | +------------+--------------+ after run sql query 'utc' time select timetz @ time zone 'utc' date_time_tz the result is: +--------------+ | time_tz | +--------------+ | 01:00:00 +00 | | 07:00:00 +00 | +--------------+ can write sql combined date_t time_tz calculate date too? the result expect is: +------------+------------+ | date_time_tz | +------------+------------+ | 2016-05-14 01:00:00 +00 | | 2016-05-14 07:00:00 +00 | +------------+------------+ i try : select concat(date_t , ' ' ,time_tz) @ time zone 'utc' date_time_table but not work. select concat(date_t , ' ' ,time_tz)::timestamp @ time zone 'utc' date_time_table try casting this

c - Balancing branches in regard to cycles used -

i have loop several conditional branches in it. loop supposed run same amount of cycles no matter branches taken. to achieve filled shorter branches nop s (using asm("nop") ) until of equal length longer branches. achieved wanted. now have lot more branches , want automatically balance branches. compiling avr-gcc. is there way this? as requested: using atmega 1284p , avr-gcc implementation. well didn't specify whether coding in asm or in c, since use branches call "asm()"... if using c, can call millis() @ beginning of loop, , call @ end too. have calculate maximum duration of loop. subtract 2 millis values , compare difference maximum duration of loop. yea lilbit confusing, here code: #define max_duration 1000 //let's 1 second, should calculate while(yourcondition) { temp1 = millis(); //do branches temp2 = millis(); delay(max_duration-(temp2-temp1)); } while if coding in asm, have @ first disable interrupts in order not hav

android - Need to store my 4 digit encrypted PIN in keystore -

i googled store pin in key store . got confused of solution. here question :- i have encrypted pin (string). how store in keystore , retrieve it. know shared preference , local storage. heard key store more secure. so question how store string in keystore , retrieve it. the android keystore system lets store cryptographic keys in container make more difficult extract device. once keys in keystore, can used cryptographic operations key material remaining non-exportable. moreover, offers facilities restrict when , how keys can used, such requiring user authentication key use or restricting keys used in cryptographic modes. see security features section more information. the keystore system used keychain api android keystore provider feature introduced in android 4.3 (api level 18). document goes on when , how use android keystore provider. here have data need how right! click here hope it's :)

Set Language on speech recognition plugin -

how can change default language in speechrecognitionplugin : https://github.com/macdonst/speechrecognitionplugin i didn't find documentation on it. thank answers. find : recognition.lang = "es-es";

KeystoneJS, tracking updatedBy/updatedAt -

been pulling hair, google tells me nothing. can't life of me understand how intend 'track' work. from documentation, assumed straight forward this: truth.add({ title: { type: types.textarea, required: true } track: { updatedby: true } }); however, above solution renders this: error: fields must specified type function all want model store last updated item. not how 'track' intended work? missing... you should define in list schema rather model fields. you can either set track: true enable meta fields or object specific ones. var truth = new keystone.list('truth', { track: true // enables field track: {updatedby: true} // enables updatedby field }); these appear @ bottom of item page.

dockerhub - How can I pull a Docker image from a private Docker Hub repo remotely? -

i have several images in docker hub private repositories, , need pull these on remote machines using docker remote rest api. there way of authenticating remotely? these calls i'd make remotely: docker login docker pull myrepo/myimage yes there way, need specify remote host docker login myrepo.com then can access images docker pull myrepo.com/myimage and can specify tag well docker pull myrepo.com/myimage:mytag hope works you.

Delphi 7: Actual reason for a data breakpoint warning -

on delphi 7, recived warning message: "setting data breakpoint on stack location may cause program or system become unstable. set breakpoint anyway?". short description of message does not explain reason why program (or system) may become unstable. says may happen. i ask concrete explanation reason why/when program (or system) unstable. a data breakpoint triggered write operation memory @ specified location. detecting these operations, whether use of hardware breakpoint or other techniques, cannot - knowledge - cause program, let alone entire system, become unstable. there problems creating data breakpoints in stack area. these problems can lead debugger behaviours undesirable , considered "instability", due volume , frequency of breakpoints rendering debugger unusable. but only extent "system" or "program" can made unstable. the error message using abbreviated language arguably misleading in attempt convey in terms suit

Java array assignment multiple values keeping the initial array -

is there way in java assign multiple values array in 1 statment later can still able append same array other values? e.g. having string array defined length of 4 string[] kids = new string[4]; i assign multiple values (2 values example) array in 1 statment; maybe close array init kids = {"x", "y"}; or array redefinition kids = new string[] {"x", "y"}; but without loosing initial array later need add other values e.g. if(newkid) { kids[3] = "z"; } or there no way achieve , have assign values 1 one kids[0] = "x"; kids[1] = "y"; if(newkid) { kids[3] = "z"; } you need copy array initialized values larger array: string[] kids = arrays.copyof(new string[]{ "x", "y" }, 4); kids[2] = "z"; alternative copy solution: string[] kids = new string[4]; system.arraycopy(new string[]{"x", "y"}, 0, kids, 0, 2); kids[2] = "z&

Full text search in MySQL (PHP) with letters under ft_min_word_len -

my ft_min_word_len in mysql set 4. when try full text search 2 or 3 letters, no results. i'm using code full-text search these short words: $table = $this->db->shop_products(); $where = ''; preg_match_all("~[\\pl\\pn_]+('[\\pl\\pn_]+)*~u", stripslashes($find), $matches); foreach($matches[0] $part) { $isfirst = empty($where); $regexp = "regexp '" . addslashes($part) . "'"; if(!$isfirst) $where .= " , ("; $where .= "name {$regexp} or content {$regexp}"; if(!$isfirst) $where .= ")"; } return $table->where($where)->limit(5)->fetchall(); this code works fine, has problem diacritic, č, á, é, í... . example, have product called bé , when want find be , not show me product, because doesn't have same letters. note: i'm using notorm mysql queries, hope know how work $table->where(... . so found solution, php, not mysql. right in foreach put

java - Is there a data structure for storing boolean expressions? -

i need store boolean expressions this: x1 , x2 , x3 or (x4 , x5) , (not x6) each x variable boolean expression == or != values. problem store nested and , or clauses (inside and/or inside each other) , wrap them not . wrapping depth can deep. does java sdk have data structure these expressions? in java 8 functional interface predicate<t> way go. here java docs . and here various examples . so in use case follows: public static predicate<integer> equals(integer compare) { return -> i.equals(compare); } public static predicate<integer> complex() { return equals(1).and(equals(2)).and(equals(3)).or(equals(4).and(equals(5))).and(equals(6).negate()); } remember — java 8 onwards!

python - How to add two solutions -

so code works, want print 2 solutions off text-file. problem includes trying print out 2 lines in text file, when keywords used if 'word' == print , want print 2 lines. appreciated. have tried various different things. problem = false while problem == false: foo = open("solutions.txt","r") print("what wrong device?") issue=input() if (('wet' in issue) or ('water' in issue)): solutions = foo.readlines() print(solutions[0]) problem = true if (('cracked' in issue) or ('dropped' in issue)): solutions = foo.readlines() print(solutions[1]) problem = true if solutions fixed, should move file opening , reading outside loop. match between keywords , solution index can done dictionary. problem = false foo = open("solutions.txt","r") solutions = foo.readlines() problemlistdict = {'wet':0, 'water':0, &

android - When click on OptionMenu it shows black background on kitkat -

when clicking on optionmenuitem on toolbar shows black background . getting issue on kitkat device , working on lollipop , higher // toolbar using <android.support.v7.widget.toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorprimary" android:minheight="?attr/actionbarsize" local:popuptheme="@style/mycustompopuptheme" local:theme="@style/toolbarcustomtheme" /> // mycustompopuptheme theme works correctly <style name="mycustompopuptheme" parent="themeoverlay.appcompat.light"> <item name="windownotitl

wpf - Property similar to Label.Target for a custom templated control -

i have control template contains generic contentpresenter . contentpresenter contain accesstext (possibly amongst other things), accesskey should focus whole control. how do that? here specific simplified example case. (i know implemented in several other ways (e.g. usercontrol ), need way various reasons). made up, there minor omissions; point show idea. imagine want add header textbox . subclass textboxex , add 2 dependency properties header , headertemplate , headeredcontentcontrol . (code trivial , omitted). then assign template textboxex along these lines: <controltemplate targettype="textboxex"> <stackpanel> <contentpresenter name="part_header" content="{templatebinding header}" contenttemplate="{templatebinding headertemplate}" recognizesaccesskey="true" /> <textbox ... /> <!--or other components similar functionality--> </stackpanel> </controlte

How to use Anylogic Database Query tool to insert table values in code -

i have started using anylogic 7.3. trying use "insert database query" tool inside anylogic in order insert values database table have created in anylogic. table created has many values , insert each time value column2 based on value of column 1 changing until loop satisfied. i anylogic choose , insert value in column 2 database given value in column 1 equal xx ( variable having value in function). assign value "probofwin". xx changing since inside loop. in "insert database query" tool selecting table name "prob low bid" choosing column2 "n_3" value column. choice condition selecting column1 "x" choosing equals , typing "xx" variable in code function. code generated anylogic inside loop. probofwin = (double) selectfrom(prob_low_bid) .where(prob_low_bid.x.eq(xx)) .firstresult(prob_low_bid.n_3); } thank you

codenameone - getAppHomePath() seems to throw a wrong path in Simulator? -

i have problem getapphomepath() method, 1 returns "file://home/" in debugger, afterwards filenotfoundexception. code throws exception: filename = "100004_2016-06-29.jpg" apphomepath = filesystemstorage.getinstance().getapphomepath(); img = image.createimage(storage.getinstance().createinputstream(apphomepath + filename)); exceptionmessage: java.io.filenotfoundexception: c:\users\xyz\.cn1\file___home_100004_2016-06-29.jpg (das system kann die angegebene datei nicht finden) so seems adds prefix "file___home_" corrupts path, have file "100004_2016-06-29.jpg" stored under path. the snippet creates file under path below: img = image.createimage(filesystemstorage.getinstance().openinputstream(filepath)); outputstream os = storage.getinstance().createoutputstream(newfilename); imageio.getimageio().save(img, os, imageio.format_jpeg, 1.0f); the filepath variable returned imagegallery, under %temp%. anyway storing file works, reading

windows phone 8.1 - How to get duration of speech synthesizer stream -

how can measure duration of speechsynthesierstream before playing please? speechsynthesizer ss = new speechsynthesizer(); speechsynthesisstream sss; ss.voice = speechsynthesizer.allvoices[3]; sss = await ss.synthesizetexttostreamasync("hello world."); mediaelement mediaelement = new mediaelement(); mediaelement.setsource(sss, sss.contenttype); //here want duration mediaelement.play(); this code works fine , speaks "hello world.". after time mediaelement.naturalduration has correct value. need know duration of speech possible , before playing speech. added handler mediaelement.mediaopen, "setsource" doesn't fire event. thank you. in order mediaopen fire, need attach mediaelement visual tree. once you've attached mediaelement visual tree, naturalduration should available within mediaopen event.

shell - staging all files except specific files using glob patterns in git -

i trying stage new created files , others edited files staging area in git using git add command. want stage except *.java files (in current directory , in every sub directory in project). tried work no success. pwd: /d/myproject nothing of these worked: git add !(*.java) git add \!\(\*.java\) git add \!\(*.java\) git add !\(\*.java\) could me work please? , somehow possible use regular expressions instead of globs here? you use find : find . -type f ! -iname '*.java' -exec git add {} + you can skip paths matching pattern using ! -ipath <pattern> , e.g: find . -type f ! -iname '*.java' ! -ipath './a/b/*c*' -exec git add {} +

javascript - Merge is not defined ImmutableJS -

Image
i'm trying merge state data have in module, console logs "merge not defined" similar mergedeep. can tell me doing wrong?

oracle11g - Oracle trigger before and after insert -

is possible create 1 trigger in oracle fires before , after data got inserted table? begin if inserting -- code should run before insertion: :new.cr_timestamp := systimestamp; if :new.id null select sq_table_id.nextval :new.id dual; end if; -- want code run after insertion.. end if; end; so there flag indicates if before or after insertion? it can written below. create or replace trigger compound_trigger_name [insert|delete|update [of column] on table compound trigger --executed before dml statement before statement begin null; end before statement; --executed aftereach row change- :new, :old available after each row begin null; end after each row; --executed after dml statement after statement begin null; end after statement; end compound_trigger_name;

How to set to my code below charset CODE 737 php-laravel -

public function downloadtxt() { $txt = ""; $datas = user::select('home_id','home_firstname','home_lastname') ->orderby('home_id','desc') ->take(input::get('number')) ->get(); foreach($datas $data){ $txt .= 100000+$data['home_id'].' '.$data['home_firstname'].' '.$data['home_lastname'].php_eol; } //$txtname = 'mytxt.txt'; $headers = ['content-type: text/plain', 'test'=>'yoyo', 'content-disposition'=>sprintf('attachment; filename="%s"', input::get('name')), 'x-booyah'=>'workyworky', //'content-length'=>sizeof($datas) ]; return response::make($txt , 200, $headers ); } how can iconv charset utf-8 code 737 dont know symbol 'utf-8'

ios - Why does my SwiftR framework code fails while building with GreenhouseCI? -

i trying implement signalr using swiftr framework available here . framework integrated ipad app. however, when checkin code private repository on github, greenhouse ci kicks in , build fails. ci unable find swiftr references. error1: use of undeclared type 'hub' code: var hub: hub ! (problem statement in bold) error2: 'signalr' unavailable: cannot find swift declaration class code: var hubconnection: signalr ! (problem statement in bold) error3: 'swiftr' unavailable: cannot find swift declaration class code: hubconnection = swiftr .connect(url) { [weak self] connection in} (problem statement in bold) the code builds fine on local machine running xcode 7.3.1 targeted ios 8.4 , over. ci environment running xcode 7.3.1. however, ci build fails above errors. okay, has been long time since asked question , took me time identify issue , resolve. after research , serious thoughts, realised app running on machine running simulator however, fa

android - Robolectric app testing with Firebase -

i'm trying write simple robolectric test presenter, uses firebase database , firebase auth. every time i'm trying start test, throwes illegalstateexception. java.lang.illegalstateexception: firebaseapp name [default] doesn't exist. @ com.google.firebase.firebaseapp.getinstance(unknown source) @ com.google.firebase.firebaseapp.getinstance(unknown source) @ com.google.firebase.auth.firebaseauth.getinstance(unknown source) my test quite simple @runwith(robolectrictestrunner.class) @config(constants = buildconfig.class) public class loginpresentertest { private loginpresenter presenter; private loginmvpview view; @before public void beforeeachtest() { presenter = new loginpresenter(); view = new loginfragment(); } @test public void attachview_shouldattachviewtothepresenter() { presenter.attachview(view); assertsame(presenter.getmvpview(), view); } } while in presenter constructor firebase

elasticsearch - Elasticsearc - nGram filter preserve/keep original token -

i applying ngram-filter string field: "custom_ngram": { "type": "ngram", "min_gram": 3, "max_gram": 10 } but result loose tokens shorter or longer ngram range. original tokens "iq" or "a4" example can not found. i applying language specific analysis before ngram, avoid copying whole field. looking expand tokens ngrams. any ideas or ngram-suggestions? here example of 1 of analyzers use custom_ngram filter: "french": { "type":"custom", "tokenizer": "standard", "filter": [ "french_elision", "lowercase", "french_stop", "custom_ascii_folding", "french_stemmer", "custom_ngram" ] } you have no option use multi fields , index field different analyzer able keep shorter terms well. that: "text&quo

Qlikview - join columnin expressions -

i have 2 column: col1 col2 d b e c f i want in expression join columns , col b c d e any idea? t1: load * inline [ col1 b c ]; t2: load * inline [ col2 d e f ]; t: load col1 col resident t1; load col2 col resident t2; drop tables t1,t2;

python - ImportError: No module named 'twisted.scripts_twistw -

i try use twisted run flask app. when run command below: twistd web --wsgi myproject.main in command prompt got error saying: importerror: no module named 'twisted.scripts_twistw does this? ps: i'm using anaconda 4.1.6 in windows 10.

All Mapping info in Rest using Spring -

i creating rest api using spring mvc. want create rest api list uri mapping (from controller class) , there basic mapping information requestmethod, mediatype, , other mapping information document user uses rest api. currently have used component-scan tag <context-component-scan base-package="..." use-default-filter="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.controller" /> </context-component-scan> and trying access instance of requestmappinghandlermapping since has such data wasn't able to. my first question using component scan tag spring provide instance of requestmappinghandlermapping can somehow autowire of controller class ? then have used requestmappinghandlermapping externally bean in distacher servlet. <bean name='handlermapping' class='org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping'> &

php - how can i get mysql record like a data? -

hi question weird i'll explane in here. i want record cv examples , user informations. have 2 table that; cv *id *format users *id *name *age in format cell include html tags , $name , $age tags that; <p> name <b>$name</b> , im <b>$age</b> years old. <p> my codes that; $sqlcv = mysql_fetch_array(mysql_query("select * cv id='2'")); $text = $sqlcv['format']; $sqluser = mysql_fetch_array(mysql_query("select * users id='3'")); $name = $sqluser['name']; $age = $sqluser['age']; echo $text; result; name $name , im $age years old. html tags works name , age not shown :( hope can explane one you can use sprintf() echo sprintf("hi im %s , im %d years old.", "darius", $age);

c++ - structures and pointer arithmetic -

#include <iostream> #include <cmath> using namespace std; struct demo{ int one; int two; int three; }; int main() { demo d1; demo *dptr=&d1; *dptr=1 ; ++dptr; *dptr=2; ++dptr; *dptr=3; return 0; } please explain why above code looks logical in fact not work in line 13 of code. log error: no match ' operator= ' in ' *dptr=1 ' demo d1; demo *dptr=&d1; *dptr=1 ; ++dptr; dptr=2; ++dptr; dptr=3; dptr pointer pointing demo struct. so, *dptr = 1 same d1 = 1; , that's not valid. plus, having pointer of type , doing ++ on pointer applies pointer arithmetic type, shoving pointer sizeof(demo) , that's not want here. you'll need create int pointer casting it, using pointer read 3 fields int* dptr=reinterpret_cast<int*>(&d1); padding can still ruin da

c# - How to Serialize object to binary? -

i'm creating phone book in windows forms, , need write contactlist in binaryform save data. what best way it? shall write several fields seperately, or can write , read full object? contact has fields : guid id string name string lastname string email string phonenumber class (needs serializable ): [serializable] public class sometype { public int x { set; get; } public int y { set; get; } } using binary writer: public static byte[] serialize(sometype obj) { byte[] bytes = null; using (var stream = new memorystream()) { using (var writer = new binarywriter(stream)) { writer.write(obj.x); writer.write(obj.y); } bytes = stream.toarray(); } return bytes; } public static sometype deserialize(byte[] data) { var obj = new sometype(); using (var stream = new memorystream(data)) { using (var reader = new binaryreader(stream)) { obj.

javascript - Error getting the .last() -

i have this structure i want last message, im trying use .last() function: $('#user-chat-' + data.de).find('#load-msgs').last().html() but jquery returns results inside div, not last result. knows why im getting error? (the selector correct, im getting result, don't last) thanks! $(document).ready(function(){ $("#load-msgs").last().find('div span').html() //or $("#load-msgs div span").last().html() }) here working fiddle the html script : <div class="row" id="load-msgs"> <div class="col-md-10 col-sm-12 col-xs-12 "> <span class="message-box message-other" data-toggle="tooltip" data-placement="right" title="18:28"> lewpwa </span> </div> <div class="col-md-10 col-sm-12 col-xs-12 "> <span class="message-box message-other&q

python - How can I acquire data from live experimentation and do a live 2D plot using threads? -

i need take data instrument , live 2d plot them. can without threads, slow ... how proceed without having errors "qobject::setparent: cannot set parent, new parent in different thread", "qapplication: object event filter cannot in different thread" , "qpixmap: not safe use pixmaps outside gui thread". used code test: import threading import time import numpy np import matplotlib.pyplot plt class mythread (threading.thread): def __init__(self, threadid, name, counter): threading.thread.__init__(self) self.threadid = threadid self.name = name self.counter = counter s=(6,6) self.x=np.zeros(s) def run(self): print "starting " + self.name threadlock.acquire() if self.threadid==1: acquire_data(self.x) count_to_three(self.name,1) plot_it(self.x) count_to_three(self.name,1) print "exiting "

javascript - Very large graphs with d3 force layout -

i'm trying support large graphs (50k-200k nodes). d3 force layout extremely slow "tick" operation. each tick take few seconds. wonder if 1 these possible: splitting loading (doing example 10 ticks, draw , after rest 1 @ time) handling "heavy nodes" , throw neighbors somewhere close. running similar d3 forcelayout @ server , send ui final positions thanks!

Visual Studio 2015 does not recognize typescript -

Image
i have angular2 project , want edit visual studio 2015. typescript extension installed visual studio 2015 can see on picture. then open project follow: and visual studio 2015 not recognize typescript file extension , code: do miss plugins? create new web application based on asp.net , long have typescript extension install have more success.

Uitable matlab with drop down menu -

Image
i have create uitable in matlab drop downmenu. somehow drop down menu doesn't updated switch/case i tried substituting switch/case if else condition. drop down menu gets updated doesn't give me desired output! to simulate please run code below any idea or pointers ? function [] =foouitable() f = figure('position',[100 100 400 150]); % column names , column format columnname = {'available','options','suboptions'}; columnformat = {'logical','bank',{'checkbox' 'selectsuboptions'}}; % define data d = {false 'reconstruction' 'checkbox';... false 'segmentation' 'checkbox';... false 'computertomography' 'checkbox';... false, 'ultrasound', 'checkbox';... false, 'acousticemission', 'checkbox'}; % create uitable t = uitable('data', d,... 'columnwidth', {70 120 100},... 'column

c# - Is there a way to prevent from Windows AutoScale my forms? -

one of forms takes screenshot of desktop , uses form background drawing on it. when windows setting "desktop/screen resolution/make text , other items larger or smaller" greater 100% screen.bounds smaller image.size. background image bigger form. streching screenshot image couses blurring. solution proper size screenshot? preventing windows autoscaling form or way of screenshot? sendkeys.sendwait("{prtsc}"); image img= clipboard.getimage(); this.backgroundimage = img; debug.print("img.size=" + img.size.tostring()); debug.print("screen.size=" + screen.primaryscreen.bounds);

how do i overwrite to a specific part of a text file in python -

for example if in text file have, explosion,bomb,duck jim,sam,daniel and wanted change daniel in file, nothing else affected. how achieve without overwriting whole file. you can use fileinput import fileinput fileinput.fileinput(filetosearch, inplace=true, backup='.bak') file: line in file: print(line.replace(texttosearch, texttoreplace), end='') #testtosearch:- daniel #texttoreplace:- newname or if want keep more simple, operation in reading 1 file , writing replaced content in second file. , overrite it! f1 = open('orgfile.txt', 'r') f2 = open('orgfilerep.txt', 'w') line in f1: f2.write(line.replace('texttosearch', 'texttoreplace'), end=' ') f1.close() f2.close()

swift - How to remove white border and table cell space of table in IOS -

Image
i studying ios book "beginning ios9 programming swift" , there exercise table views. created project step step according steps in book. page got : there spacing between each table cell, , width of table not 100% of simulator. how can make better? i want page : the lines appear under each cell called "separator lines", can remove them selecting "separator style" "none" in attributes inspector. see image http://i.stack.imgur.com/cnglu.png to remove white space, have cover whole superview i.e cover whole cell of tableview image. this: http://i.stack.imgur.com/zp5mx.png

websocket - Error in NonGUIDriver java.lang.IllegalArgumentException in JMeter -

i getting following error , after trying run jmeter on the console . working fine in gui mode . error in nonguidriver java.lang.illegalargumentexception: problem loading xml from:'/users/omaroof/desktop/mywork/apache-jmeter-3.0/bin/sockettestingcoapp.jmx', missing class com.thoughtworks.xstream.converters.conversionexception: jmeter.plugins.functional.samplers.websocket.websocketsampler : jmeter.plugins.functional.samplers.websocket.websocketsampler --

Excel function to cut data between to fixed character strings -

Image
i have following text in excel cell: sampleid: s-2016-011451 submitterid: eirossme sample name: t1 btms - 6/26/16 10:00 pm lot nbr: productid : i need cut data reads as: t1 btms 6/26/16 22:00 i can format date using text($cell,"mm/dd/yy hh:mm") can't =mid(...) truncate data between "name:" , " - ". 1st: =mid(b2;63;26) 2nd: =mid(b5;1;8) 3rd: =mid(b5;11;18) 4th: =concatenate(b7;b8) if want cut between name: , - , use: =find("name: ";b2) =find(" -";b2) and then: =mid(b2, find("name: ";b2)+5;find(" -";b2)-find("name: ";b2)-5) i.e.:

c# - Azure - Not Redirecting to Default Page and showing "Could not load file or assembly 'DotNetOpenAuth.Core'" Error -

i have been working project split following: (1) client application (html5, css3, js / angularjs) , (2) webapi. it works fine locally, when run application, however, when deployed application azure , attempt access client application, below error: could not load file or assembly 'dotnetopenauth.core, version=4.0.0.0, culture=neutral, publickeytoken=2780ccd10d57b246' or 1 of dependencies. located assembly's manifest definition not match assembly reference. (exception hresult: 0x80131040) when type /index.html within browser, default page loads correctly, however, redirection happens automatically, without showing error. i have set redirection default page in iis well, not redirecting default. i reading of other questions similar error, however, not have packages.config file since client application have, html5 / css , js application. i not have packages.config file as know, error message shows missing/mismatching .net framework assembly. ba

ide - PyCharm Directly Open Python File -

i switched pycharm couple of months ago, can't figure out how rid of welcome screen when open files. more specifically, i've set mac open .py files using pycharm. however, when double click on .py file, it's welcome screen opens , not .py file. how pycharm open python script in editor, without showing me welcome screen? pycharm displays welcome screen when no project open. screen, can access major starting points of pycharm. welcome screen appears when close current project in instance of pycharm. if working multiple projects, closing project results in closing pycharm window in running, except last project, closing show welcome screen.

vb.net - How does visual know what form I want? -

so have folowing code form. public class tab public personas, formaciones, avisos, cursos list(of object) [lots of code] end class on form want formaciones list, can just: listbox1.datasource = tab.formaciones and works, perfectly. but.. how? tab class, not instance of it, vb able understand want instance of class. what happen if there mor 1 tab open? how work internally? this part of default application framework enabled when creating vb.net winforms applications. its intent migration vb6 creates singletons of each form. if want different instances, can disable/ignore framework , write own start methods. more details: singleton forms: https://msdn.microsoft.com/en-us/library/ms233839.aspx enable/disable: https://msdn.microsoft.com/en-us/library/17k74w0c(v=vs.100).aspx full article: https://visualstudiomagazine.com/articles/2007/10/01/enable-the-application-framework-in-vb.aspx

php - Yii2: Config global template for all forms fields -

i have this: <?php use app\models\location; use yii\helpers\html; use yii\widgets\activeform; use yii\helpers\arrayhelper; use app\models\role; ?> <?php $form = activeform::begin(); ?> <div class="row"> <div class="col-sm-6"> <?= $form->field($model, 'roleid', yii::$app->formtemplate->fieldtemplate())->dropdownlist(arrayhelper::map(role::find()->all(), 'id', 'name'), array('prompt' => '-- select role --', 'class' => 'form-control select2')); ?> </div> <div class="col-sm-6"> <?= $form->field($model, 'published')->checkbox(['label' => ''], true)->label($model->getattributelabel('published'), ['class' => 'form-label semibold']); ?> </div> </div> i

console - How to use Terminal View in Eclipse -

by default projects run in eclipse has console output bring focus console window , display output there. eclipse has local terminal option. there configuration activate output destination running project? before upgrading neon using ansi plugin console, isn't installing in current version ( ansi-escape-console ). while might temporary glitch, time learn how use local terminal alternative. i'm trying have ansi escape codes displayed in scripts like: #!/bin/bash red='\033[0;31m' nc='\033[0m' printf "hello... ${red}this red highlighted text ${nc}.\n" update: able ansi escape in console plugin marketplace installed. still know how specify output local terminal view option. there difference between console view , terminal view. console view the console view facility output of applications running in ide of eclipse (for test , debugging). terminal view the terminal view terminal emulator access local computer's

unity3d - Fatal error- Monodevelop-Unity failed to start -

Image
i installed unity monodevelop seems not been installed tried open script in unity nothing come out, saying should find software opens when have set preferences monodevelop(built-in). then reinstalled again, time, contains visual studio too. can open visual studio. when tried open monodevelop, following pop-up apear. but have installed 2 things /net , gtk. shown below. problem? 1st time-- install gtk after install unity(no monodev) 2nd time-- install monodevelop unity went monodev website , says xamarin studio not monodevelop you messed in first step. you have uninstall gtk , else installed during time. includes unity too.if possible, system restore , set restore date time before installed of this. now, install unity, make sure monodevelop selected unity , install it. don't install gtk or other software. when using unity, monodevelop must installed unity , not other website. reason because using customized version of monodevelop .

python - Converting string.decode('utf8') from python2 to python3 -

i converting code python2 python3. in python2, can following things: >>> c = '\xe5\xb8\x90\xe6\x88\xb7' >>> print c 帐户 >>> c.decode('utf8') u'\u5e10\u6237' how can same output (u'\u5e10\u6237') in python3? edit for else problem, realized after looking @ the responses make use of result each character needs treated individual element. escaped unicode representation '\u5e10\u6237' string not naturally divide parts correspond original chinese characters. >>> c = '帐户' >>> type(c.encode('unicode-escape').decode('ascii')) <class 'str'> >>> [l l in c.encode('unicode-escape').decode('ascii')] ['\\', 'u', '5', 'e', '1', '0', '\\', 'u', '6', '2', '3', '7'] you have separate each character in input string , translate separately array unl

Session management using json web tokens in microservices -

i trying figure out how manage sessions using json web tokens in microservice architecture. looking @ design in article have in mind client send request first goes through firewall. request contain opaque/reference token firewall sends authorization server. authorization server responds value token containing session information user. firewall passes request along value token api, , value token propagated different microservices required fulfill request. i have 2 questions: how should updates session information in value token handled? elaborate, when session info in token gets updated, needs updated in authorization server. should each service changes token talk authorization server? should microservices use single token store session info? or better each service have personalized token? if it's latter, please explain how adjust design. a very(!) significant "fly in ointment" of kind of design ... requires careful advance thought on part ... is: