Posts

Showing posts from May, 2011

c# - how to get currently position of index in "Richtextbox" -

this question has answer here: windows forms richtextbox cursor position 3 answers how restore caret position or change color of text without making selection in richtextbox 2 answers richtextbox , caret position 1 answer i want insert text current position of index in richtextbox as know should use richtextbox.text = richtextbox.text.insert(int startindex, string value); what need int startindex what should write instead of access current position of index?

java - How can i stop sound when another sound is going to play android studio -

how can stop sound when button clicked. want stop current audio when im going play audio. dont know wrong code first 1 sound im going trying do. please correct code according not hard code sorry bad english. public void playmusic() { sound = mediaplayer.create(topics.this, r.raw.schapter1); if (sound.isplaying()) { sound.pause(); sound2.stop(); sound3.stop(); sound4.stop(); sound5.stop(); sound.release(); sound2.release(); sound3.release(); sound4.release(); sound5.release(); } else { sound.start(); } } public void ch2playmusic() { sound2 = mediaplayer.create(topics.this, r.raw.schapter2); if (sound2.isplaying()) { sound2.pause(); sound2.release(); } else { sound2.start(); } } public void ch3playmusic()...

Best way of combining Django template tags and javascript compression for security -

i programming website uses django server backend. the website allows users different levels of privilege log in. according privilege each user has, should able see different elements of html , javascript of webpage (ie: administrators can see full website, managers can see less elements, normal users less, etc). easiest way feed every user same website , send them variable telling browser parts of site show , hide don't solution since savvy user "hack" variable , have access information shouldn't have. so, in order keep website easy mantain having single version keep bit of security between different levels of privilege, use django template tags: {% if administator %} ... { % endif %} this works fine html. if want same javascript, unable automatically compress javascript using yuglify or similar libraries since aren't able process django template tags in middle of javascript file... addmitedly manually see tags suppossed go , add them after compres...

cmake - Install EXPORT requires target from subproject -

i'm trying write cmake script installing project i'm working on. part of necessary install(export lib_exports ...) lib_exports i've been using export property in various install(targets ...) . i have superbuild structure uses add_subdirectory build projects (sdl2, civetweb) project depends on. my problem when use target_link_libraries add link subproject (sdl2-static sdl2, c-library civetweb) cmake complains these dependencies aren't in export set. cmake error: install(export "lib_exports" ...) includes target "sc2api" requires target "c-library" not in export set. cmake error: install(export "lib_exports" ...) includes target "sc2renderer" requires target "sdl2-static" not in export set. the way know add targets export set using install(targets ... export lib_exports) can't install target subdirectory hasn't created. install(files ... export lib_exports) if find sure library file...

javascript - XSS safe img src insertion -

how safely push user influenced url dom, namely src attribute of img ? <img> won't execute else valid img , scripting in svg limited. casual onload tricks won't work aswell because input quoted. enough ensure safe dom insertion via img? the snippet simplified, there checks url being valid url. edit: http://foo" onerror="alert(&apos;xss&apos;)" " is not valid url, see here: http://foo " onerror="alert('xss')" ". can assume url sure valid url. see https://en.wikipedia.org/wiki/percent-encoding#types_of_uri_characters , check if javascript string url , https://jsfiddle.net/mppkgd7u/ var user = 'random/url/path'; // kind of user generated string var url = 'http://' + user; // guaranteed url document.getelementbyid('view').innerhtml = '<img src="'+url+'">'; console.log(document.getelementbyid('view').innerhtml); <div id=view...

terminal - SCP command to move directories from local machine to server -

i using macbook air terminal (my local machine) transfer on directory large number of images onto server. images located 2 subdirectores called "folder1" , "folder2" under /users/viv/images/data. want copy contents of directory on server can ssh into. ssh using command ssh udacity@54.91.119.34 question how copy contents of local machine onto server, tried using following command: scp -r /users/viv/images/data udacity@54.91.119.34 but ends creating new directory called udacity$54.91.119.34 , copying contents of data directory onto local machine please adice on how should proceed data can copied onto server. in advance you need add colon @ end, followed destination directory (leave blank home directory of user): scp -r /users/viv/images/data udacity@54.91.119.34:

vector - What does the comma mean in the arctan operator? -

i reading the answers question finding angle between 2 vectors in 3d space. signed angle between 2 3d vectors same origin within same plane . answer shown here: atan2((vb x va) . vn, va . vb) is need, don't understand commas operator is. know exes , dots cross products , dot products respectively. don't think commas inner products (same thing dot products)? perhaps, syntax of programming language? the language (i think 1 ) matlab, , comma argument separator (not operator 2 ) in method call. 1 - consistent context found expression, though suspect author using matlab syntax way of expressing mathematical concept. 2 - according https://au.mathworks.com/help/matlab/matlab_prog/matlab-operators-and-special-characters.html

python 2.7 - Why round(15.0)==15.0 is false? -

input 4 integer n , x[0] , x[1] , x[2] n = a*x[0] + b*x[1] + c*x[2] , n<=4000 find maxi = a+b+c (a,b,c>=0) when ran n=3164 , x = [42, 430, 1309] . answer must 15. why round(15.0)==15.0 false? found when tried print i, j, tf, ti, maxi in line 17: x = [0, 0, 0] n, x[0], x[1], x[2] = map(float, raw_input().split()) x.sort(reverse=true) #suppose x[0]>=x[1]>=x[2] maxi=0 if x[2] == 1.0: print int(n) else: in range(int(n/x[0])+1): #first loop find a: <= n/x[0] j in range(int(n/x[1])+1): #second loop find b: b <= n/x[1] #used math find equation found: tf = float(i*(1.0-x[0]/x[2]) + j*(1.0-x[1]/x[2]) + n/x[2]) ti = int(round(tf)) if tf > n or tf <0: break if ti==tf , ti >= maxi: #find satisfactory value maxi = ti #print i, j, ti, tf, maxi print maxi

Can't find all roots in Newtons-Raphson method (Python) -

the code using work fine 2 of 4 roots of function, can't seem make work 4 roots. from numpy import * scipy import * import numpy np def f(x): return np.arctan(2*(x - 1)) - np.log(abs(x)) def fprime(x): return (16/5)*((x - (5/4))**2)-1 def newtonraphson(x0,e=1.0e-3): val in range(1, 15): dx = - f(x0)/fprime(x0) print(dx) x0 = x0 + dx if abs(dx) < e: return x0,val print('too many iterations\n') root,numiter = newtonraphson(-1.0) print ('root =',root) print ('number of iterations =',numiter) the roots should -0.300098, 0.425412, 1, 4.09946 when use -1.0, root -0.300098, , when use 1, root 1, can't seem other 2 roots. need code work? thanks your code good, problem function - it's complicated method. can either use more sophisticated root finding method or can decrease dx , increase number of iterations. instance can use dx/1000 , 1.5 million maximum iterations. giv...

html - Bootstrap Dropdown Partially Blocked Behind Page Content -

i have altered bootstrap dropdown in 2 ways: the dropdown appears on hover, not on click the li drops down still clickable link the dropdown functionality working properly, when mouse down dropdown's li s dropdown disappears when 2nd or third item. far can tell, happens regardless of content on page below it. i'm not sure problem coming from, i've checked css instances of z-index . you can see dropdown issue live here when hover on menu item "tools". paste html and/or css here, i'm not sure problem lies, i'd putting extravagant amount of code and/or guessing.... hope helps replace below css * { font-family: "raleway", sans-serif; color: #333232; position: relative; z-index: 10; } with * { font-family: "raleway", sans-serif; color: #333232; position: relative; } just remove z-index elements,i think have set z-index individual elements.then no need set elements.

Does Maven plugin change the action of Run button (green triangle) in Eclipse? -

Image
i know maven helps build project, e.g. create war. in eclipse benefits add? does add magic when press run or helps dependencies? it not default change run action. but, illustrated in article , adds run configuration possibility define "run action", trigger maven builds:

java - How the super and this keywords work in a subclass method -

this question has answer here: scope , use of super keyword in java 1 answer class feline { public string type = "f "; public feline() { system.out.print("feline "); } } public class cougar extends feline { public cougar() { system.out.print("cougar "); } void go() { type = "c "; system.out.print(this.type + super.type); } public static void main(string[] args) { new cougar().go(); } } in code output coming feline cougar c c , when changing subclass variable string type = "c" means assigning new string type answer coming feline cougar f f please let me know how , super keyword working in subclass method? type unqualified name, , refers local variable , parameter , or field . this.type refers field accessible current class...

how to access json data fetched from sharepoint list in javascript array -

i unable filter json data fetched sharepoint list match , delete particular value. value of stringdata is: "\"[{alllinks:\\\"link9\\\",linkurl:\\\"http://www.link9.com\\\"},{alllinks:\\\"link6\\\",linkurl:\\\"http://www.link6.com\\\"}]\"" this code: function removeselecteditemfromlist(x){ $.ajax({ url: url, type: "get", headers: {"accept": "application/json;odata=verbose"}, success: function (data) { var stringdata = json.stringify(data.d.results[0].alllinks); alert(stringdata); for(var i=0; i<stringdata.length; i++){ if(stringdata[i].alllinks === x){ stringdata.splice(i,1); alert(i); break; }} }, error: function() { alert('fail'); } });}

c++ - openGL .obj not load properly -

Image
i'm trying draw .obj file c++ , opengl aid of https://github.com/chrislundquist/opengl-model-loaders . can read .obj file missing i didn't understand how affect normals drawing , lighting objects think problem normals model(){ vertices = std::vector<vec3f>(); triangles = std::vector<unsigned>(); normals = std::vector<vec3f>(); uvs = std::vector<vec3f>(); vaoid[0] = 0; vboid[0] = 0; } load(char* filename) { // read // .obj file // here... objfile.close(); triangles.resize(triangles.size()); normals.resize(normals.size()); uvs.resize(uvs.size()); glgenvertexarrays(1, &vaoid[0]); glbindvertexarray(vaoid[0]); glgenbuffers(1, vboid); glbindbuffer(gl_array_buffer, vboid[0]); glbufferdata(gl_array_buffer, vertices.size() * sizeof(vertices[0]), &vertices[0], gl_static_draw); glvertexattribpointer((gluint)0, 3, gl_float, gl_false,...

php - How to check multiple variables if has values? -

how can check if has values if 1 missing echo else. try isset same, miss think. $da1="da1"; $ba2=""; $za3="za3"; if (!empty($da1)||!empty($ba2)||!empty($za3)) { echo $da1.$ba2.$za3; }else{ echo "one missing"; } my output : da1za3 use && instead || if (!empty($da1) && !empty($ba2) && !empty($za3)) { echo $da1.$ba2.$za3; }else{ echo "one mising"; }

python - pyserial reading serial port and show on web page in flask -

i want read , write data serial port pyserial in flask . want through web page. codes 1 below. writing data on web page without problems, can not read data, runtime error during reading. how can implement solution? i'm trying ways read data serial port. not know best way me. best way me display data serial port user connected web page? i received error: 0 def serial runtime error exception in thread thread-1: traceback (most recent call last): file "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner self.run() file "/usr/lib/python2.7/threading.py", line 505, in run self.__target(*self.__args, **self.__kwargs) file "__init__.py", line 46, in serialread return jsonify(result='serial runtime error') file "/usr/local/lib/python2.7/dist-packages/flask/json.py", line 251, in jsonify if current_app.config['jsonify_prettyprint_regular'] , not request.is_xhr: file "/usr/local/...

javascript - Unable to link js file to html to load local files -

what i'm trying do load html file content block on page .load function in linked .js file using local server. what i'm using html css javascript/jquery wamp chrome windows 10 the problem i can inside page, can't working when using linked files (as matter of fact, can't any javascript work when use linked files), , i'd rather able maintain separate .js file. what i've done checked spelling checked file paths read similar questions , comments (didn't help) restarted computer (why not?) before using wamp, tried starting chrome local file access allowed. worked several minutes... until didn't anymore. notes i'm new javascript , jquery. the linked .css files have never given me trouble. yes, nav.html in same directory index.html. yes, js folder in same directory index.html, , design.js indeed inside folder. wamp icon green , able set virtualhost succesfully. code doesn't work me index.html <html> ...

python - Pandaic way to check whether a dataframe has any rows -

this question has answer here: how check whether pandas dataframe empty? 3 answers given dataframe df , i'd apply condition df[condition] , retrieve subset. want check if there rows in subset - tell me condition valid one. in [551]: df out[551]: col1 0 1 1 2 2 3 3 4 4 5 5 3 6 1 7 2 8 3 what want check this: if df[condition] has rows: what best way check whether filtered dataframe has rows? here's methods don't work: if df[df.col1 == 1]: gives valueerror: truth value of dataframe ambiguous. if df[df.col1 == 1].any(): gives valueerror i suppose can test len . there other ways? you use df.empty : df_conditional = df.loc[df['column_name'] == some_value] if not df_conditional.empty: ... # process dataframe results

sql server - MYDOMAIN\MSSQLUser. xp_delete_file() returned error 2, 'The system cannot find the file specified.' [SQLSTATE 42000] (Error 22049). The step failed -

mydomain\mssqluser. xp_delete_file() returned error 2, 'the system cannot find file specified.' [sqlstate 42000] (error 22049). step failed. i getting error while tried execute job below script declare @delete_date nvarchar(50), @delete_date_time datetime; set @delete_date_time = dateadd(day, -7, getdate()) set @delete_date = (select ( replace( convert( nvarchar, @delete_date_time, 111), '/', '-') + 't' + convert( nvarchar, @delete_date_time, 108))) execute xp_delete_file 0, n'location', n'bak', @delete_date, 1 when run script works fine. when tried run on job displays above error.

c# - Microsoft.Azure.Mobile Namespace Issue [UWP] -

once had problem microsoft.azure.mobile nuget package somehow figured out. last night, repaired visual studio , error has came , couldn't fix it. i've installed microsoft.azure.mobile package using statements give error. the type or namespace name 'azure' not exist in namespace 'microsoft' (are missing assembly reference?) i guess have install extension or sdk don't know can't find solution on documentation. can me? thanks. according description, checked issue. found microsoft.azure.mobile 0.14.2 has dependencies follows: uap 10.0 microsoft.netcore.universalwindowsplatform (>= 5.2.2) newtonsoft.json (>= 6.0.1) sqlite-net-pcl (>= 1.3.1) i created uwp app targeting version windows 10 (10.0; build 10240) , install package successfully. seems package has not been installed , there dependencies not resolved. need check packages referenced , try locate cause. provide project.json file or sample pr...

javascript - Node Webpack eval() sourcemaps -

i struggling setting node project typescript. workflow is: run node script using nodemon. node script creates webpack compiler instance , sets filesystem memoryfs. webpack config includes loaders typescript , babel. after webpack has finished compiling, if there errors, throw then, if not fetch result memoryfs , eval() run code. all of works fine. tried add sourcemaps support. added banner plugin in webpack adds 'source-map-support'. in webpack, set devtool 'source-map'. in tsconfig.json, have sourcemaps option enabled. in src/index.ts throw error, , @ runtime node doesn't tell me did error occur. (the sourcemap) but if run webpack normally, , run using node dist/bundle.js . working. i think there problem because of me using eval() run compiled output. src/index.ts: console.log('hello world'); throw new error('not'); build.js: const path = require('path'); const webpack = require('webpack'); const memoryfs = require...

MYSQL join two tables and list oldest entry -

i have 2 tables data select. helpdesk system , collects information ticket activity. table #1 ticket_id log_type entry_date 1 ticket_created 1471442825 1 ticket_closed 1471442825 2 ticket_created 1438035457 2 ticket_closed 1438035269 3 ticket_created 1438034956 3 ticket_closed 1438034121 table #2 ticket_id customer_name status 1 bill open 2 john closed 3 mark canncelled what ticket_id customer_name log_type entry_date 1 bill ticket_created 1471442825 2 john ticket_created 1471442825 3 mark ticket_created 1471442825 where oldest entry_date 5 days or more (to list outdated tickets). i have tried several joins didn’t succeed. you can use join min(entry_date) , e.g.: select t2.ticket_id, t2.customer_name, t1.log_type, t1.date table_2 t2,...

c# - How to find the field that is trying to be being serialized -

i have pretty complex object, called fullreport reference, many members , lists of complex objects holds data report. have service class used on place in fullreport , other objects contained in fullreport. service class should never serialized each field of type should have marked nonserialized when serialize fullreport getting "not marked serializable" error service class. trying use windbg answer in question suggests struggling attach. can give me other advice on how find field service class not marked nonserialized?

php - Pass Json data using Jquery Ajax then display response -

why not working? jquery take value on change , send using ajax in json format php file. same jquery take response , append it. $(#ordersummary) never display success me verify response. $(document).ready(function(){ $("#prodcat").change(function(){ var prodid = $(this).val(); $("#ordersummary").append(prodid); $.ajax({ type: 'post', url: 'getproduct.php', data: {'prodcat':prodid}, datatype: 'json', success:function(response){ $("#ordersummary").append(success); var len = response.length; $("#product").empty(); for( var = 0; i<len; i++){ var name = response[i]['name']; var detail = response[i]['detail']; var price = response[i]['price']; $("#product").append("<option value='"+name+"'>"+name+"</option>") } ...

Rvest scraping result is empty list -

i've simple question: tried scrape odds webpage result blank list library(rvest) url<- 'http://www.betexplorer.com/soccer/italy/serie-a-2016-2017/' html <- read_html(url) odds <- html_nodes(html, '.table-matches__odds , .colored span') odds <- html_text(odds) also tried use xpath instead of css selector had same result. library(rvest) url<- 'http://www.betexplorer.com/soccer/italy/serie-a-2016-2017/' html <- read_html(url) odds <- html_nodes(html, xpath='//*[contains(concat( " ", @class, " " ), concat( " ", "table-matches__odds", " " ))]') odds <- html_text(odds)

rabbitmq - How to deliver events to a shard? -

my app consumes events rabbitmq queue events , updates application state , acks rmq (or nacks if event malformed). each event contains customerid identifier randomly generated string of fixed length. i want scale app horizontally several nodes giving particular range of customers. ideally if had n nodes available, expression hash(customerid) mod n give me owner node customerid. please suggest possible setup, give me guarantees every event processed no event processed twice

error when execute android sdkmanager command in windows -

i using android sdk manager of android studio. show me error after run sdkmanger --list exception in thread "main" java.lang.nosuchfielderror: fn_aapt2 @ com.android.sdklib.buildtoolinfo.<init>(buildtoolinfo.java:352) @ com.android.sdklib.buildtoolinfo.fromstandarddirectorylayout(buildtoolinfo.java:224) @ com.android.sdklib.repository.legacy.local.localsdk.scanbuildtools(localsdk.java:898) @ com.android.sdklib.repository.legacy.local.localsdk.getpkgsinfos(localsdk.java:544) @ com.android.sdklib.repository.legacy.legacylocalrepoloader.parselegacylocalpackage(legacylocalrepoloader.java:100) @ com.android.repository.impl.manager.localrepoloaderimpl.parsepackages(localrepoloaderimpl.java:167) @ com.android.repository.impl.manager.localrepoloaderimpl.getpackages(localrepoloaderimpl.java:124) @ com.android.repository.impl.manager.repomanagerimpl$loadtask.run(repomanagerimpl.java:517) @ com.android.r...

date - Getting time range between midnight and current time JDK 8 -

i have method calculate midnigt , current time long values: /** * returns time range between midnight , current time in milliseconds. * * @param zoneid time zone id. * @return {@code long} array, @ index: 0 - midnight time; 1 - current time. */ public static long[] todaydaterange(zoneid zoneid) { long[] toreturn = new long[2]; localtime midnight = localtime.midnight; localdate today = localdate.now(zoneid); localdatetime todaymidnight = localdatetime.of(today, midnight); zoneddatetime todaymidnightzdt = todaymidnight.atzone(zoneid); toreturn[0] = todaymidnightzdt.toinstant().toepochmilli(); zoneddatetime nowzdt = localdatetime.now().atzone(zoneid); toreturn[1] = nowzdt.toinstant().toepochmilli(); return toreturn; } perhaps there simpler way that? you do: zoneddatetime nowzdt = zoneddatetime.now(zoneid); zoneddatetime todayatmidnightzdt = nowzdt.with(localtime.midnight); i can't think of simpler way it. localdatet...

qgis how to filter multiple layers -

how filter multiple layers has same attribute value? have tried using phyton code : layer.setsubsetstring('"alias" = \'janmos\'') my problem how reset code different value? i have looked @ plugin multiple layer selection, unsuccessful in using it. regards

arduino - Changing Sender ID for SMS sent through GSM SIM900A -

i wanted inquire if there way in can change sender id of sms. sending out sms through sim900a gsm module , want receiever have sms id such "kfc" example instead of phone number +92xxxxxxxxxx? when send message directly arduino, not possible mask number. if want have id should make use of message service providers. requires perform http request, gsm module should support that. gsm900a supports http request can go that.i found similar question in arduino forum . in can request php code contain codes invocation of message services.you can refer this more details online message services.

C++ conditional operator with void operand(s) -

i’m trying understand following excerpt c++ standard (iso/iec 14882:2003, newer versions same): 5.16 conditional operator 2 if either second or third operand has type (possibly cv-qualified) void, lvalue-to-rvalue (4.1), array-to-pointer (4.2), , function-to-pointer (4.3) standard conversions performed on second , third operands, ... i inclined thinking in context, when operand function call, type of operand taken (although not) function return type. if so, yields example of void type. i imagine throw expression surmised have type void in context, independently of type of throw operand. example. are 2 assumptions right? there other cases? many thanks about throw, yes, there no result, type void , type of throw operand irrelevant. i'm not sure how relevant question seems odd. about functions, don't know why type of operand not function return type if operand function call. else be? it's operand function (as opposed function call) functio...

entity framework - Unable to initialize database -

i unable iniitialize database. steps simple explained here. here . error not explainatory guess something wrong around connection string couldn't figured out. can please see me. error " @ system.data.common.dbconnectionoptions.getkeyvaluepair(string connectionstring, int32 currentposition, stringbuilder buffer, string& keyname, string& keyvalue)\r\n at system.data.common.dbconnectionoptions.parseinternal(dictionary 2 parsetable, string connectionstring, boolean buildchain, dictionary 2 synonyms)\r\n t system.data.common.dbconnectionoptions..ctor(string connectionstring, dictionary 2 synonyms)\r\n @ system.data.sqlclient.sqlconnectionstring..ctor(string connectionstring)\r\n @ system.data.sqlclient.sqlconnectionfactory.createconnectionoptions(string connectionstring, dbconnectionoptions previous)\r\n @ system.data.providerbase.dbconnectionfactory.getconnectionpoolgroup(dbconnectionpoolkey key, dbconnectionpoolgroup...

ARP Spoofing using python scapy not working -

i had done arp spoofing using scapy python code. mac address in target's pc gateway has been changed pc's mac address , mac adres of target pc in router's cache has been chnged mac addres. want forward these packets respective location though pc. can see traffic between target pc , gateway.but it's not working. import os import sys import threading import signal import logging logging.getlogger("scapy.runtime").setlevel(logging.error) scapy.all import * our_mac='d8:5d:e2:0c:58:87' print 'enter target ip:' target_ip = raw_input() print 'enter gateway ip' gateway_ip = raw_input() packet_count = 50 # turn off output conf.verb = 0 def get_mac(ip_address): responses,unanswered =srp(ether(dst="ff:ff:ff:ff:ff:ff")/arp(pdst=ip_address),timeout=2,retry=10) # return mac address response s,r in responses: return r[ether].src return none gateway_mac = get_mac(gateway_ip) if gateway_mac none: ...

webpack - how to load the .vue files of a vue project with node.js -

i want analize current router config of project vue2. because wanna use cli generate vue component. before have load current route register info. when require router.js under router directory. node throws syntaxerror: unexpected token import . try many ways fix didn't work. please tell me right way load router config. thanks! //to load router config const routerpath = path.join(process.cwd(), 'src', 'router', 'index.js'); if (existssync(routerpath)) { routes = require(routerpath) } //error import vue "vue"; ^^^^^^ syntaxerror: unexpected token import @ object. (/users/mosx/projects/mjb-cli/lib/check-components.js:28:33) @ module._compile (module.js:570:32) @ object.module._extensions..js (module.js:579:10) @ module.load (module.js:487:32) @ trymoduleload (module.js:446:12) @ function.module._load (module.js:438:3) @ module.require (module.js:4...

swift3 - How to compare different values in firebase? -

i have 2 models, user , post , function observing posts. need send post on user feed, comparing data, example: if user.location == post.location & user.interest == post.interest {print("post.id")} models: class user { var name: string? var location: string? var interest: string? } class post { var name: string? var location: string? var interest: string? } function: func loadposts() { self.tableview.reloaddata() // self.activityindicatorview.startanimating() api.feed.observefeed(withid: api.user.current_user!.uid) { (post) in guard let postid = post.uid else { return } self.fetchuser(uid: postid, completed: { self.posts.insert(post, at: 0) self.activityindicatorview.stopanimating() self.tableview.reloaddata() }) } }

java - how to mock ElasticSearch Client for unit testing in scala -

i want mock elasticsearch client test code without running es service trying import java.nio.file.files class campaignestest val file= files.createtempdirectory("tempesdata") def getclient():mocktransportclient={ val settings = settings.builder() .put("http.enabled", "false") .put("path.data", file.tostring()).build(); val client = new mocktransportclient(settings); client } class campaigntestsearch extends playspec{ val campaignestest= new campaignestest val client=campaignestest.getclient val response = client.preparesearch("dbtest") .settypes(campaign_collection_name) .setsearchtype(searchtype.dfs_query_then_fetch) .addfields("uuid","campaignname","artworkid","activationdate","_source") .setquery(query) .execute() .actionget() } getting exception these lines campaignestest lin...

Output RFC 3339 Timestamp in Java -

i want output timestamp pst offset (e.g., 2008-11-13t13:23:30-08:00). java.util.simpledateformat not seem output timezone offsets in hour:minute format, excludes colon. there simple way timestamp in java? // want 2008-11-13t12:23:30-08:00 string timestamp = new simpledateformat("yyyy-mm-dd't'h:m:ssz").format(new date()); system.out.println(timestamp); // prints "2008-11-13t12:23:30-0800" see difference? also, simpledateformat cannot parse example above. throws parseexception . // throws parseexception new simpledateformat("yyyy-mm-dd't'h:m:ssz").parse("2008-11-13t13:23:30-08:00") starting in java 7, there's x pattern string iso8601 time zone. strings in format describe, use xxx . see documentation . sample: system.out.println(new simpledateformat("yyyy-mm-dd't'hh:mm:ssxxx") .format(new date())); result: 2014-03-31t14:11:29+02:00

ios - Add Provisioning profile without adding account in xcode: 8.3.3 -

Image
i have created new project in xcode , want sign in development mode.it asks me login developer account. don't have account, have provisioning profiles , certificates. have tried many ways din't work. tried off auto signing don't also. please check screenshot. how did create provisioning profile , certificates if don't have developer account? a developer account needed, since profiles , certificates "linked" specific account.

PowerShell advanced function output PipelineVariable doesn't work -

i created advanced function mac address vm running on vmware esxi. function get-macfromvm { [cmdletbinding(supportsshouldprocess=$true)] param( # name of vm of want obtain mac address. [parameter(mandatory=$true, valuefrompipeline=$true, valuefrompipelinebypropertyname=$true)] [string[]] $name ) begin {} process { foreach ($item in $name) { if ($pscmdlet.shouldprocess($item, "getting mac address")) { get-vm $item -pipelinevariable vm | get-networkadapter | select-object @{n="name"; e={$vm.name}}, @{n="clientid"; e={$_.macaddress -replace ":","-"}} } } } end {} } so far works perfect. can use in of following ways , results back. it accepts either single or array of string via named parameter or pipeline input...

rstudio - R crashes when STM model converge -

Image
relatively r crashes when stm model converge. see image below 1 example after 30h+ estimation session. has happened on 2 different computers, different data sizes. have not been able identify specific patterns leading these crashes—as crashes not seem deterministic. the model estimation settings # full year <- year(df$date) # year data environment stmfit.full <- stm(out$documents, out$vocab, k = 0, prevalence =~ s(year) , max.em.its = 150, init.type = "spectral", seed = 300, verbose = t) any ideas how solve this? additional information: a) > #systeminfo > > library(stm) stm v1.2.2 (2017-03-28) loaded. see ?stm help. > > sessioninfo() r version 3.4.1 (2017-06-30) platform: x86_64-w64-mingw32/x64 (64-bit) running under: windows >= 8 x64 (build > 9200) > > matrix products: default > > locale: [1] lc_collate=swedish_sweden.1252 > lc_ctype=swedish_sweden.1252 lc_monetary=swedish_sweden.1252 > lc...

compiler construction - depth first traversal of a tree using generators in python -

at moment, i'm programming compiler small subset of python in python. managed construct syntax tree got problems coding tree traversal (which essential generating code). i'll first go along showing data structures: class abstractsyntaxtree(object): def __init__(self, startsymbol): self.root = node(startsymbol, val=none) self.nodes = [self.root] def addnode(self, name, val, parentid): parent = self.nodes[parentid] self.nodes.append(node(name=name, val=val, parent=parent)) return len(self.nodes)-1 def getlastid(self): return len(self.nodes)-1 def __iter__(self): node in self.root: yield node this node definition: class node: def __init__(self, name, val, parent=none): self.name = name self.val = val self.parent = parent self.children = [] if parent: parent.children.append(self) def __iter__(self): yield self ...

php - MySQL error message, mysql_connect(), any way to fix it? -

so error message: php deprecated: mysql_connect(): mysql extension deprecated , removed in future: use mysqli or pdo instead this affected piece of code: class wdclient { var $dblink; // database link var $prefix; // table prefix var $script; // script running /** * construct new directory object. */ function wdclient() { error_reporting(e_all ^ e_notice); $this->prefix = wddbprefix; // connect database $this->dblink = mysql_connect(wddbhost, wddbuser, wddbpasswd); // select database mysql_select_db(wddbname, $this->dblink) or die('sorry, site unavailable!'); } where wddbprefix , wddbhost , wddbuser , wddbpasswd , wddbname defined in config file. i have tried using mysqli_connect instead of mysql_connect it's not working. note: never use mysql, use method! //mysqli information $db_host = ...

python - imshow and plot side by side -

Image
i'm trying put side-by-side numpy array displayed image , seaborn distplot of same array. i've came following function: def visualize(arr): f, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw = {'width_ratios': [1, 3]}) ax1.imshow(arr) flat = arr.flatten() x = flat[~np.isnan(flat)] sns.distplot(x, ax=ax2) plt.show() which produces: as can see, image has smaller height plot. how can modify function in order have same height plot , imshow? i want following placement of image , plot: there many ways tackle this. of following give more or less same image a. reduce available space you may reduce available space such both plots constrained same vertical margins. can done by reducing figure height fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(6,2.3), ...) using subplots_adjust limit margins fig.subplots_adjust(top=0.7, bottom=0.3) b. use insetposition you may use mpl_toolkits.axes_grid1.inset_locator.insetpositi...