Posts

Showing posts from May, 2012

javascript - JQuery append a div start tag only -

this question has answer here: jquery - how add single html tag html? 5 answers create opening div tag using jquery 2 answers is there way insert div start tag $('#adiv').append("<div class='divtoinsert>'"); but creates: <div class='divtoinsert></div> instead. i want append start tag because in middle, adding content , want insert end tag when have added content. i looking on net day unlucky enough give me hint. sure, create string variable hold open tag, concatenate content inside loop or whatever want, concatenate closing tag. can append variable element when finished. example: var yourtext = "<div>"; yourtext += //whatever want yourtext += "</div>"; $('#adiv').appen

hadoop - Apache Spark accessing the data in hdfs through cross cluster -

i running spark on amazon emr public dns is, lets say, 23.21.40.15 . now executing spark jar on cluster & want write output of spark job other amazon emr hdfs public dns 29.45.56.72 . i able access own cluster hdfs i.e. 23.21.40.15 not able write cluster 29.45.56.72 . what need spark job can access cross cluster hdfs?? if possible, can share sample code this?? when set output dir in spark job can set credentials access this: hdfs://username:password@hostname:port/pathtofolder pd: shouldn't write ips of cluster in public question ;)

asp.net - datatable to Excel in c# -

while exporting datatable excel columns fall new line. don't know problem is. code below: string attachment = "attachment; filename=test.xls"; response.clearcontent(); response.addheader("content-disposition", attachment); response.contenttype = "application/vnd.ms-excel"; string tab = ""; foreach (datacolumn dc in transposedtable.columns) { response.write(tab + dc.columnname); //tab = "\t"; } response.write("\t"); int i; foreach (datarow dr in transposedtable.rows) { response.write("\n"); tab = ""; (i = 0; < transposedtable.columns.count; i++) { response.write(tab + dr[i].tostring()); tab = "\t"; } response.write("\t"); } response.end(); i have tried many ways, didn't exact issue. issue excel in machine or code? it seems possible datarow data contains newline characters, 1 reason why newlines might appearing in

Selenium java.lang.NullPointerException with PageFactory -

i'm trying hang of pagefactory pom, not working , can not understand wrong. this first pom class home page: package pagefactory; import org.openqa.selenium.webdriver; import org.openqa.selenium.webelement; import org.openqa.selenium.support.findby; import org.openqa.selenium.support.pagefactory; public class home_page_pof { public webdriver driver; @findby(css = "div#header-profile a#header-profile-toggle") public webelement profiletogglebutton; @findby(css = "form#loginuserdataform div.footer div.add-footer a.btn.btn-link.linkicon") public webelement newregistrationbutton; public home_page_pof(webdriver driver) { this.driver = driver; pagefactory.initelements(driver, this); } } this second pom class reg. page package pagefactory; import org.openqa.selenium.webdriver; import org.openqa.selenium.webelement; import org.openqa.selenium.support.findby; import org.openqa.selenium.support.pagefactory; import org.openqa.selenium.support.ui.select;

r - Rmarkdown global_options vs opts_chunk -

i've searched around bit, , read this can't seem find difference between global_options , opts_chunk. below code chunk use @ beginning of of rmd files, i've never understood difference. appreciated. ```{r global_options, include=false} # way set options code chunks @ once # note can dynamically control options setting them value # dpi setting increased word output, cairo anti aliasing knitr::opts_chunk$set(echo=false, warning=false, message=false, dev="png", fig.width = 10, fig.height = 7, dpi=200, dev.args=list(type="cairo")) ``` setting global options apply options of chunks of code in document. global options superseded chunk options. chunk included intended set global options (by calling knitr opts_chunk command). in generally, chunks this: ```{r chunk_name, ...options...} code code code ``` your chunk called global_options , , has chunk option include=false means when document rendered, chunk executed,

jQuery responsive Datatables Customize CSS and Pagination -

Image
i using jquery , jquery datatables (1.10.1) create "responsive" datatables. trying customize 2 things 1. , feel giving own css 2. pagination , search controls. here fiddle - http://jsfiddle.net/urwyrj89/ i have added own css not seem take because css has background-color not show on ui : .tablesorter thead tr th, table.tablesorter tfoot tr th { background-color: #d6e9f8; text-align: left; border: 1px solid #ccc; font-size: 11px; padding: 4px; color: #333; } but never applies it. tried putting class directly substituting @ run time in jquery . new this, appreciate pointers ? also, want customize pagination control. instead of default view i.e. i want control below , also, positioned both on top , bottom is customization possible? pointers on how achieve ? you have apply style using rule below or use !important less preferable. table.datatable.tablesorter thead th, table.datatable.tablesorter tfoot th { back

c# - RaycastHit issues with canvas? -

this script gives message on console if hit gameobject not in canvas. when mouse button released on button located inside canvas, script doesn't debug anything. how can fix this? raycasthit hit; void update () { if(input.getmousebuttonup(0)) { ray ray = camera.main.screenpointtoray(input.mouseposition); //rayhit hit; if(physics.raycast(ray, out hit)) { // want debug.log(hit.collider.gameobject.tag); } } } you can use ui object clicked. if (input.getmousebuttondown(0)) { ray ray = camera.main.screenpointtoray(input.mouseposition); if (eventsystem.current.ispointerovergameobject()) { debug.log(eventsystem.current.currentselectedgameobject.getcomponent<text>().name); } eventsystem.current.currentselectedgameobject.getcomponent().name will return clicked object , eventsystem.current.ispointerovergameobject() will che

sorting - Sort dict by second value in tuple and return dict -

from collections import defaultdict,ordereddict tt=defaultdict (list) tt={'abcd':(23,77),'ddef':(55,22)} c=ordereddict (sorted (tt.items (),key=lambda t: t[1][1])) print (c) d=list ((k,v) k,v in c.items()) print (d) this sorts correctly c. list makes dict ordereddict d gets {'ddef':(55,22),'abcd':(23,77)} modified code. works fine now. need display top (n) keys in sorted order second element of tuple. dict seems best route, there ever 50 items in list,i need top ten in order.

javascript - Problems With Ui.prompt & Ui.alert -

here tried build series of prompts , alerts send sms messages. through input values of 2 variables (1) mobile phone number , (2) deadline making prepayment. here source: function promptprepaymentreminder() { var ui = spreadsheetapp.getui(); /* Шаг № 1: ввод мобильного телефона гостя */ var step1 = ui.prompt("Напоминание о внесении страхового депозита: шаг 1 из 3", "Введите номер мобильного телефона гостя. Например, +79522294179.", ui.buttonset.ok); var step1_button = step1.getselectedbutton(); var recipient = step1.getresponsetext(); if (step1_button == ui.button.ok) { /* Когда пользователь нажимает «Ок» на шаге № 1 */ var step2 = ui.prompt("Напоминание о внесении страхового депозита: шаг 2 из 3", "Введите точные дату и время чтобы установить дедлайн по внесению депозита. Например, 12.06.2016, 18:00.", ui.buttonset.ok_cancel); var step2_button = step2.getselectedbutton(); var prepaymentreferencelink = "berdy

c++ - Need help can't figure out why my header file function declarations won't work -

cant figure out code. how make piggybank& header work add functions in cpp file? gives me error: error 6 error c2040: 'piggybank::adddimes' : 'void (int)' differs in levels of indirection 'piggybank &(int)' h:\cosc1030\homework09\homework09\piggybank.cpp 36 1 homework09 #ifndef piggybank_h #define piggybank_h #include <iostream> using std::cout; using std::endl; class piggybank { public: piggybank(int pennies, int nickels, int dimes, int quarters); // return number of coins in bank int getpenniescount() const; int getnickelscount() const; int getdimescount() const; int getquarterscount() const; // add coins bank piggybank& addpennies(int p); piggybank& addnickels(int n); piggybank& adddimes(int d); piggybank& addquarters(int q); // withdraw coins bank, return number withdrawn int withdrawpennies(int p); int withdrawnickels(int n); int withdrawdimes(int d); int withdrawquarters(int q); void displaybalance()

Primus-websocket client side -

im trying make client side websocket using primus framework. here client side code <script src="primus/primus.js"></script> <script> // connect current url var primus = primus.connect() primus.on("open", function () { console.log("connected!") }) primus.on("data", function (data) { console.log("data =", data) }) </script> the error primus.connect not function thank you. you need to specify connection. var primus = primus.connect('ws://localhost:8000');

javascript - jQuery animation, fire a function every other second? -

im trying make upload script jquery , loading bar aswell. i got field multiple upload possibility. every file gets 2 second on loading bar. so count time have this: var length = array.length; var time = length*2; var totaltime = time*1000; // count totaltime, not milliseconds. my question is, if upload several files, 3 files. have 6 seconds in loading bar, there way make function fire every 2 seconds? have outside animation setinterval? if how stop setinterval? or possible inside animation? $(".filesupload").on("change", function() { var files = $(".filesupload").prop("files"); var names = $.map(files, function(val) { return val.name; }); totalfiles = names.length; $("#uploadbar").modal('show'); }); $("#uploadbar").on("shown.bs.modal", function() { var time = totalfiles * 2; var totaltime = time * 1000; // seconds, not milliseconds. $(".progress-ba

php - UNION SELECT tables with inner join and GET values with "ALIAS" -

so have 2 tables, matches , teams, want values match , inner join "teams" names of both teams , add them php array later on (getting in 1 sql) matches - idmatch - idlocalteam - idvisitorteam - time - half - stopped teams - idteam - name what have is $query = "select * `matches` inner join `teams` on `matches`.idlocalteam = `teams`.idteam union select * `matches` inner join `teams` on `matches`.idvisitorteam = `teams`.idteam order idmatch desc;"; if me great! alot wouldn't easier use inner join twice? it's quicker way of doing joins anyway. select * `matches` m inner join `teams` t1 on m.idlocalteam = t1.idteam inner join `teams` t2 on m.idvisitorteam = t2.idteam order m.idmatch desc; also start using aliases instead of table names identify fields in query, sql smaller.

sql server - Adding column which groups data by time -

i've got table shows: power , time , diff-days , diff-hours , diff-minutes diff columns use datediff , lag calculate difference in times between rows. (powerkw) (time) (diff-days) (diff-hours) (diff-minutes) 31011.39 2014-01-01 00:30:00 null null null 31838.74 2014-01-01 00:40:00 0 0 -10 32356.35 2014-01-01 00:50:00 0 0 -10 32358.82 2014-01-01 01:00:00 0 -1 -10 32414.15 2014-01-01 01:10:00 0 0 -10 32413.81 2014-01-01 01:20:00 0 0 -10 32412.35 2014-01-01 01:30:00 0 0 -10 32416.23 2014-01-01 01:40:00 0 0 -10 32014.94 2014-01-01 01:50:00 0 0 -10 31184.45 2014-01-01 03:40:00 0 -2 -110 32403.38 2014-01-01 03:50:00 0 0 -10 32415.07 2014-01-01 04:00:00 0 -1 -10 323

node.js - Mosca Mqtt Broker read published message -

hello using mosca mqtt broker want read message client publish topic. is there way that? in published event log packet.payload , prints clientid , topic. server.on('published', function(packet, client) { console.log('published', packet.payload); }); thank you server.on('published', function(packet, client) { console.log('published: ', packet.payload.tostring('utf8')); });

sql - How do I trace former ids using a recursive query? -

i have table of provider information (providers) contains columns reporting_unit , predesessor. predesessor either null or contains reporting_unit that row used represent. need find current reporting_unit provider is. mean reporting_unit predesessor, reporting_unit current_reporting_unit predesessor. i trying use recursive cte accomplish because of time there multiple links. the table looks this: create table providers ( reporting_unit text, predesessor text ); insert providers values (null, null), ('are88', null), ('99bx7', '99bx6'), ('99bx6', '99bx5'), ('99bx5', null) ; the results are: reporting_unit | current_reporting_unit --------------------------------------- '99bx5' | '99bx7' '99bx6' | '99bx7' my current query : with recursive current_ru ( select reporting_unit, predesessor providers predesessor null union select p.

How can I remove proxies field in symfony json -

i want remove proxies fields __initializer__: null,__cloner__: null, __isinitialized__: true, returned json have no idea. i dont want use * @serializer\exclude() because there more fields next fields. here sample json: emails: [ { id: 1, subject: "mrs. astrid wuckert", body: "excepturi.", sendcopy: false, roles: [ { __initializer__: null, __cloner__: null, __isinitialized__: true, name: "role_admin" }, { name: "role_reseller" }, { name: "role_retailer" }, { name: "role_club_shop" } ] }, ] thanks in advance. try call ignoring fields while creating normalizer: $normalilzer->setignoredattributes(["__initializer__", "__cloner__&q

output - arithmetic overflow because signed characters in C program -

we know signed char can have values -128 127 . when run below program no overflow happens though l output exceeds range of signed character. #include <stdio.h> int main() { char = 60; char j = 30; char k = 10; char l = (i*j)/k; printf("%d ", l); return 0; } the output of l 180 out of range char l , not getting error. in other scenario if take same program instead of arithmetic function if put l=180 , try print wrong answer. #include <stdio.h> int main() { char = 60; char j = 30; char k = 10; char l = 180; printf("%d ", l); return 0; } the answer in 2nd case -76 . can explain why? if virtually executing same thing getting different result. are sure did , test described in first snippet? if run, overflows wraps around expected. it makes big difference if did char l = (i*j)/k; printf("%d ", l); and if did printf("%d ", (i*j)/k); as in second

java - How can I make these data types display their values on screen? -

import java.awt.*; import javax.swing.*; public class test extends japplet{ byte january = 1; int date = 18; long year = 1995; i want screen able say: 1/18/1995 , i'm not sure of how accomplish that. use built in println() method: system.out.println(month + "//" + date + "//" + year); edit use japplet (swing) put in label: import javax.swing.jlabel; // ... other code jlabel label = new jlabel(month + "//" + date + "//" + year); // can set vertical , horizontal text positions these lines: // label1.setverticaltextposition(jlabel.bottom); // label1.sethorizontaltextposition(jlabel.center); // assuming jpanel called panel panel.add(label); (the double backslahes escape each other , print out single backslash; use + operator concatenate strings; month, date, , year automatically converted strings here)

ios - -[FBSDKLoginManager logInWithReadPermissions:fromViewController:handler:]: unrecognized selector sent to instance -

i've updated parse 1.9.1, facebook sdk v4.x, ios 9, swift 2, , xcode 7. didn't change code , added .plist keys lsapplicationqueriesschemes , app transport security settings . now, can't log facebook using class func logininbackgroundwithreadpermissions(permissions: [string]?, block: pfuserresultblock?) because error: 2015-10-30 15:24:22.433 [2905:830174] -[fbsdkloginmanager loginwithreadpermissions:fromviewcontroller:handler:]: unrecognized selector sent instance 0x15ee75d60 2015-10-30 15:24:22.437 [2905:830174] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[fbsdkloginmanager loginwithreadpermissions:fromviewcontroller:handler:]: unrecognized selector sent instance 0x15ee75d60' *** first throw call stack: (0x182f60f48 0x197b13f80 0x182f67c5c 0x182f64c00 0x182e68cac 0x1003de54c 0x1003dd36c 0x1003dd1f0 0x10024d8dc 0x100253578 0x100253de0 0x1002f8864 0x1002fc8cc 0x1002fc618 0x1002f9504 0x1002fdc68 0x1002ad868 0x10

tomcat7 - How do i pass constant values from tomcat to war file(i.e. based upon spring-boot )? -

after lot of online search & tried lot of experiments. didn't of link can full-fill requirement, choose platform. note : i using spring-boot maven project & tomcat 7.0.62 version & jdk 7. first of using embedded tomcat & produce .jar , passing dynamic parameter .jar using command line argument . now, scenario has been changed. .jar file converts .war file have excluded embedded tomcat i.e. not embedded tomcat. now want pass same list of command-line argument spring-boot project's .war file outside. from tomcat . any appreciate. you have few options in servlet container/application server: use system properties use init parameters use jndi they'll available via spring's environment work pretty you'd passed them in via command line.

Python line.replace returns UnicodeEncodeError -

i have tex file generated rst source using sphinx, encoded utf-8 without bom (according notepad++) , named final_report.tex , following content: % generated sphinx. \documentclass[letterpaper,11pt,english]{sphinxmanual} \usepackage[utf8]{inputenc} \begin{document} \chapter{preface} krimson4 nice programming language. umlauts äöüßÅö. “double quotation mark” problem. johnny’s apostrophe allows connecting multiple ports. components include data describe how ellipsis … software interoperability – dash – not ok. \end{document} now, before compile tex source pdf, want replace lines in tex file nicer results. script inspired another question . #!/usr/bin/python # -*- coding: utf-8 -*- import os newfil=os.path.join("build", "latex", "final_report.tex-new") oldfil=os.path.join("build", "latex", "final_report.tex") def freplace(old, new): open(newfil, "wt", encoding="utf-8") fout: open(oldfil

swift - What is the right code for the UIPopoverController -

what right code popovercontroller in ios 9 have anywhere right code code? @ibaction func share(sender: uibarbuttonitem) { let activityviewcontroller = uiactivityviewcontroller ( activityitems: [(webview.request?.url!.absolutestring)! nsstring], applicationactivities: nil) if uidevice.currentdevice().userinterfaceidiom == .pad { //ipad let activitypopover = uipopovercontroller(contentviewcontroller: activityviewcontroller) activitypopover.presentpopoverfrombarbuttonitem(self.sharebutton, permittedarrowdirections: uipopoverarrowdirection.any, animated: true) } else { //iphone presentviewcontroller(activityviewcontroller, animated: true, completion: nil) } } } your code ancient. should throw of away. in ios 8 , ios 9, presented controllers adapt. uiactivityviewcontroller popover on ipad, automatically. present , right thing happen. of course, have supply sourceview , sourcerect or b

post - Uber API | Requesting Access Token for Ride request returns 'invalid_grant' error -

Image
i want users request uber rides app. https://developer.uber.com/docs/rides/authentication under oauth 2.0 section @ above url, there 6 steps : 1. authorize (done) 2. receive redirect (done) 3. access token ('invalid_grant' error) the following screenshot postman. tried passing client_id, client_secret, grant_type, redirect_uri , code params, form-data , x-www-form-url-encoded. everytime returns same error. i have put ' http://localhost:3000/auth/uber/callback ' redirect url in uber app dashboard. i have tried following curl command in terminal,but returns same 'invalid_grant' error can me issue. your postman request looks correct me. best guesses @ whats going on: 1) have multiple redirects set up, , you're using 1 redirect url when authorization phase , different 1 when try , token exchange 2) you're doing authorization 1 client_id, , trying token exchange another 3) you're authorization code has been used / e

sql - How to copy data -

i want create stored procedure copy data 3 tables. these structure of 3 tables: quotes quote_id integer, note varchar(50) quote_id primary key , auto incremented using trigger windows win_id integer, quote_id integer win_id primary key (auto incremented using trigger) , quote_id here fk quotes table win_links links_id integer, win_id integer, linked_win_id integer, edge_name varchar(30) links_id primary key (auto incremented using trigger) , both win_id , linked_win_id fk windows table. i created sp this: create or alter procedure copy_quote_proc ( p_quote_id integer) declare variable v_last_inserted_quote_id integer; declare variable v_old_win_id integer; begin insert quotes (note) select note quotes quotes.quote_id = :p_quote_id returning quote_id :v_last_inserted_quote_id; select win_id windows (windows.quote_id = :p_quote_id) :v_old_win_id begin insert windows (quote_id) select :v_last_inserted_quote_id windows win_id = :v_old_win_id end the

c - Is there a way to send a signal to all threads opening a fd? -

i close socket before notify threads blocking on accept/connect , therefore sending user specific signal, not knowing tid of signal receiving threads. cannot use syscall kill(pid, signal) why not shutdown socket without notifying? each thread blocked on accept or read socket return corresponding error can parse take necessary actions

php - Why does adding if(strlen($content)): create a syntax error with an unexpected '}'? -

i don't see missing opening curly brace or not enough curly braces , yet when fine until added if(strlen($content)): $form = etcetera below. see of code commented out trying isolate bug, can't understand why throws parse error. don't see missing curly brace or curly brace. function ssp_survey_shortcode($args, $content='') { // setup our return variable $output = ''; try { // begin building our output html $output = '<div class="ssp ssp-survey">'; // survey id $survey_id = (isset($args['id'])) ?(int)$args['id'] : 0; // survey object $survey = get_post($survey_id); // if survey not valid ssp_survey post, return message if(!$survey_id || $survey->post_type !== 'ssp_survey'): $output.= '<p>the requested survey not exist.</p>'; else: // build form html $form = '';

angularjs - Retrieving selected checkbox value after page reload -

Image
i trying use cookies hide , show columns in table instead of storing selected checkbox values in database. problem having not able display selected checkbox value(s) when user initiates modal again. trying use ng-init value , set checkbox true if has been selected. modal(attempt 1) <div class="modal-header"> <h3 class="modal-title">additional collections columns</h3> </div> <div class="modal-body"> <h4>select addional columns list below display in 'collections' list</h4><br/> <div class="row"> <form name="collectionscolumnsform"> <div class="col-sm-6"> <ul> ... <li> <label class="control c control--checkbox"> <input type="checkbox" name="phone" ng-model="columns.coll_phone"

This java code compiles, but is wrong. Can you tell me what is wrong with it? -

here code, below. need this, have no clue wrong it. compiles cleanly, said, whenever run it, fails execute. thanks! import java.util.scanner; public class whatthe { public static void main(string[ ] args){ scanner scan = new scanner(system.in); int i; string s; char c; system.out.print("please enter number: "); = scan.nextint( ); system.out.println(i); system.out.println( ); system.out.print("please input 3 words separated spaces: "); s = scan.next(); system.out.println(s); system.out.println( ); system.out.print("please input something: "); s = scan.nextline(); system.out.println(s); system.out.println( ); system.out.print("please enter number: "); = scan.nextint( ); system.out.println(i); system.out.println( ); system.out.print("please input word: "); s = scan.nextline(); c = s.charat(0); system.out

spring 4 mvc aop not work -

pom this <!-- spring mvc <spring-framework.version>4.2.2.release</spring-framework.version> --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context</artifactid> <version>${spring-framework.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>${spring-framework.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-context-support</artifactid> <version>${spring-framework.version}</version> </dependency> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-aop</artifactid> <version>${spring-fram

c++ - How do I can call each other function in the different view in MFC? -

i have make view in dialog in mfc. , want call function dialog view. how can call each other function in different view? here code have attached link void cmfc_test5dlg::ondropfiles(hdrop hdropinfo) { int nfiles; char szpathname[max_path]; cstring strfilename; nfiles = ::dragqueryfile( hdropinfo, 0xffffffff, szpathname, max_path ); { ::dragqueryfile(hdropinfo, 0, szpathname, max_path); } ::dragfinish(hdropinfo); cdialog::ondropfiles(hdropinfo); dodisplayimage(); <---here call function. cdialogex::ondropfiles(hdropinfo); } and here function void ctestview::dodisplayimage() { cdc *pdc = getdc(); if (pdc != null && m_image.isvalid() ) { crect rectclient; getclientrect(rectclient); pdc->fillsolidrect(rectclient,pdc->getbkcolor()); // set windows bitmap header bitmapinfoheader bmi; bmi.bisize = sizeof(bitmapinfoheader); // size of structure bmi.biwidth = m_image.columns(); // bitmaps width in pi

python - pycadf error while installing OpenStack Liberty via devstack -Ubuntu 14.04 LTS -

Image
i trying install openstack using devstack, error : it seems me pycadf library required keystone. tryed install command : sudo install python-pycadf still getting same problem. did 1 had same problem ? thank you. please use stable , fresh pypi mirrors, suitable 1 here: http://www.pypi-mirrors.org/ by default: http://pypi.python.org/simple openstack ci uses: http://pypi.iad.openstack.org/simple for china mainland, try this: http://mirrors.aliyun.com/pypi/simple

c# - Random number generator only generating one random number -

i have following function: //function random number public static int randomnumber(int min, int max) { random random = new random(); return random.next(min, max); } how call it: byte[] mac = new byte[6]; (int x = 0; x < 6; ++x) mac[x] = (byte)(misc.randomnumber((int)0xffff, (int)0xffffff) % 256); if step loop debugger during runtime different values (which want). however, if put breakpoint 2 lines below code, members of "mac" array have equal value. why happen? every time new random() initialized using clock. means in tight loop same value lots of times. should keep single random instance , keep using next on same instance. //function random number private static readonly random random = new random(); private static readonly object synclock = new object(); public static int randomnumber(int min, int max) { lock(synclock) { // synchronize return random.next(min, max); } } edit (see comments): why need lock her

javascript - Nativescript: unable to create application... Failed to load module: ...app/main.js -

Image
i'm fiddling sample-groceries application, , i've installed nativescript , angular 2 on 2 machines , on both, same error message when try do: tns run android --emulator ios runs without problems on android, following error: unhandled exception java.lang.runtimeexception unable create application... failed load module: ...app/main.js (see image) tried older api version 22. the answers found changing app.js, can't find file. hope can help. this pretty simple issue fix; enter app folder , type: npm install tns-core-modules@latest --save and need rebuild app , should go. see: http://fluentreports.com/blog/?p=323

java - Can a child class creates object of type super class that is abstract? -

i'm not sure if asked correctly i'm given in assignment classa abstract classb extends class a then in main method of classb have: classa obj = new classb(); what's happening here , what's purpose of doing so? you can never create object abstract class. ever. period. here variable gets assigned object of abstract type, object variable refers not , never can be. distinction between reference , reference variable key concept must understood advance, once it, you'll go "a-ha!".

javascript - Array filter to return a string -

i have array , using filter function arrays check duplicates: var array = [hello, world, hello, hi, how you]; var uniquearray = array.filter(function(item, pos) { return array.indexof(item) == pos; }); return uniquearray.join(","); now return unique array string , unknown reason failing. documentation, shows returns array how can convert unique array string? add quotes strings ! var array = ['hello', 'world', 'hello', 'hi', 'how you']; var uniquearray = array.filter(function(item, pos) { return array.indexof(item) === pos; }); return uniquearray.join(",");

python - Huge array representing redundant and sparse data optimization -

i tried search answer question, exists couldn't find any, because don't know how name it. so let's point. i working on statistical model. dataset contains information 45 public transport stations , static information them (so 45 rows , around 1000 feature columns) , regularly-spaced temporal measurements (so 2 000 000 rows 10 columns). "real" amount of information in small enough (around 500 mb) processed easily. the problem statistical modules on python require simple 2d arrays, numpy's arrays. have combine data, 2 000 000 rows of measure have attach 1000+ columns of features related station in measure took place end 17 gb database... of redundant , feel waste of resource. i have idea have absolutely no idea of how : array function given , j returns value, possible me "emulate", or come fake array, pseudo array, array interface, can accepted numpy array modules? don't see why couldn't it, because array function (i:j) -> a[i][j

javascript - How to resize an nvd3 chart when the window resizes? -

i've created population pyramid in nvd3, it's not resizing it's supposed to, , cannot diagnose why. here's pen problematic code: http://codepen.io/laissezpasser/pen/qnrpxq for comparison, here's working example of responsiveness i'm trying achieve in pen above: try [resizing 1 of windowpanes in pen: http://codepen.io/laissezpasser/pen/jrbgqg reason, seems ignoring following code: nv.utils.windowresize(chart.update); return chart; your code broken, pay attention javascript console, have told errors... // why line here, you've set data! d3.select('#chart svg') .datum(data()) //<-- data not defined .transition().duration(500).call(chart); // why line here, interactivelayer not defined! interactivelayer.tooltip .headerformatter(function(d, i) { return nv.models.axis().tickformat(',')(d,i); }) removing these offending lines, fixes issue .

java - Not being able to provide custom authentication provider for the spring security -

i want have custom authentication provider spring security , have implemented @component public class apicustomauthenticationprovider implements authenticationprovider { @override public authentication authenticate(authentication authentication) throws authenticationexception { system.out.println("ahsgdvjasdhgjasjdh"); return new usernamepasswordauthenticationtoken("aman", "12345"); } @override public boolean supports(class<?> authentication) { return (usernamepasswordauthenticationtoken.class.isassignablefrom(authentication)); } } right don't have logic want see if spring security using authentication provider . i have security config file as @configuration @enablewebsecurity //@importresource("classpath:/security/spring_saml_sso_security.xml") public class securityconfig extends websecurityconfigureradapter { /*@autowired metadatageneratorfilter metadatageneratorfilter; @autowired filterchainproxy samlfilter;

android - Cordova and ajax not found rest service -

do know why when place application on mobile device , try download json, jquery mobile (ajax) returns me error 404, , if same device in browser (chrome) json response visible? does application in cordova can block access services of rest? cordova: 6.1.0 android-cordova: 5.1.1 device: nexus service: get because whitelist blocks external calls on default add plugin, if not added yet https://github.com/apache/cordova-plugin-whitelist and add meta tag html <meta http-equiv="content-security-policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'"/>

gulp rename file in same directory -

i'm trying minify , create copy without "src." part of every index.src.php file inside folder still have index.src.php available minified copy index.php: gulp.task('usemin', function() { return gulp.src('./**/index.src.php') .pipe(usemin({ inlinecss: [ minifycss, 'concat' ] })) .pipe(rename(function(path){ path.basename = path.basename.replace('min\.', ''); })) .pipe(gulp.dest('.')); }); ... far literally renames index.src.php index.php gulp-rename easier expected... gulp.task('usemin', function() { return gulp.src('./**/index.src.php') .pipe(usemin({ inlinecss: [ minifycss, 'concat' ] })) .pipe(rename({ basename: 'index' })) .pipe(gulp.dest('.')); });

eclipse rcp - Minimal JFace application making use of FilteredTree -

in rcp application have jface dialog making use of filteredtree, depends on running platformui. now want add main method dialog class, can start dialog testing purpose quickly. exception within filteredtree ctor: exception in thread "main" java.lang.noclassdeffounderror: org/eclipse/e4/core/di/injectionexception @ org.eclipse.ui.platformui.isworkbenchrunning(platformui.java:114) @ org.eclipse.ui.plugin.abstractuiplugin.imagedescriptorfromplugin(abstractuiplugin.java:669) @ org.eclipse.ui.dialogs.filteredtree.<clinit>(filteredtree.java:196) @ my.mydialog.createdialogarea(mydialog.java:361) is there simple solution? you can't add main method. eclipse has huge amount of initialization must done before plug-in code can run , requires normal eclipse main method used.

open office writer inserted audio file - change and SAVE position and Size settings -

i need in saving custom settings of inserted audio file in text file in writer. when audio file inserted width , height set @ 1.97" need them @ 0.16" the anchor set to paragraph need = character position = center - - character protect = position all changes work ok on selected audio file... when insert new audio file have change settings on again. have 100s of audio files. i have around writer on how save custom settings no luck i have try create own custom menu ... cant save custom settings try create macro... macros not work text file menu recording. search web ... no luck i hope can me. thank in advance!

javascript - Best way to split word in letters using DOM -

i have following structure. <div class="container"> <span>word</span> <span>word2</span> <span>word3</span> </div> and want output be: <span><b>w</b><b>o</b><b>r</b><b>d</b></span> to achieve use following code: let containers = document.queryselectorall('.container'); array.from(containers, x => { array.from(x.children, y => { let text = y.innertext; y.innerhtml = ''; for(let c of text) { y.innerhtml += `<b>${c}</b>`; } }); }); but dont need clear html append letters wrapper. does knows better solution achieve this? http://jsbin.com/rexaqis/edit?html,css,js,output try this: y.innerhtml = y.innerhtml.split('').map(function(element){ return '<b>' + element + '</b>'; }).join('');

c# - paypal payments pro test credit cards fail -

trying use paypal payments pro hosted pages accept credit cards on web site. i'm having trouble getting test credit cards work, give error: declined: 10544-please use different payment card. i'm not using shopping cart or making direct api calls, testing paypal payments pro asp.net c# sample paypal, this: posts credentials https://pilot-payflowpro.paypal.com , gets secure token posts secure token https://pilot-payflowlink.paypal.com display checkout page when enter visa test 4111111111111111 exp 12/19 or other test credit card above error. in sandbox no transactions recorded. what have done, following documentation: i have paypal payments pro account following settings: paypal payments pro live hosted checkout pages live payflow sdk/api (full access) live paypal express checkout live i linked business paypal account manager.paypal.com i upgraded sandbox account on developer.paypal.com - there 2 there, business , personal, upgraded business sa

node.js - Pass Variable as Key Name in DynamoDB putItem JSON array -

i have simple json array trying set map key on using variable. array uses map functionality of dynamodb , first map called 'hours' contains nested map want have key of 15. becuase want key change depending on hour of day, passed variable json array nested map key reflect that. for following hard coded 15 simplify problem. the issue dynamodb in fact run putitem in there changes variable hour string "hour" , ignores value of set variable during operation. ideas on how pass variable value key name? var hour = "15"; "hours" : {"m" : { hour : {"m" : { //the hour variable used key "action1" : {"n" : "1"}, "action2" : {"n" : "1"} } } } } use expressionattributenames: , expressionattributevalues: in params . following (using documentclient convert javascript types automatically) should point in right direction have

Authenticate to API within Javascript -

i have api able authenticate against using postman client. using postman able enter in username , password header , receive access token. i accomplish same authentication simple html page using javascript. however, unsure how craft javascript request , pass in username , password did postman. under address bar of postman there's link says "generate code" on previous versions button </> symbol. clicking link opens popup dropdownlist javascript 1 option, generate code request.

php - Where is the boundary of dependency injection -

an injection passing of dependency dependent object (a client) use it. (wiki) i understand dependency injection: private $exampleclass; private $name; public function __construct ($name, exampleclass $exampleclass) { $this->name = $name; $this->exampleclass = $exampleclass; } but still di or not? private $exampleclass; private $name; public function __construct ($name, exampleclass $exampleclass = null) { $this->name = $name; $this->exampleclass = $exampleclass ?: new exampleclass($name); } thanks in dependency injection when a needs b the application creates a , gives b . in contrast, in example, the class creates exampleclass . thus, it's not dependency injection .

angularjs - Angular Error: $injector:unpr Unknown Provider -

i getting followin error error: [$injector:unpr] unknown provider: authprovider <- auth <- loginctrl and code looks following... 'use strict'; angular.module('yapp') .controller('loginctrl', function($scope, $location,auth,$log) { $scope.submit = function(email,password) { var model = { email:'', password:'' }; $scope.model = model; auth.login(email,password) .then(function(token){ $log.info(token); },function (error){ $log.info(error); }); } }); 'use strict'; angular.module('yapp') .factory('auth', function($http,$q,$log,apihelper) { var self = this; this.login = function(email,password){ var d = $q.defer(); var requesturl = apihelper.endpoints.login; var data = { email:email, password:password };

android - How to add list of songs from storage and display it on one of my fragments -

how add list of songs inside 1 of fragment java , xml , mainactivity java , xml. this other java classes related adding songs 1- song.java public class song { private long id; private string title; private string artist; private long duration; public song(long songid, string songtitle, string songartist) { id=songid; title=songtitle; artist=songartist; } public long getid() { return id; } public string gettitle() { return title; } public string getartist() { return artist; } } 2- musicservice.java public class musicservice extends service implements mediaplayer.onpreparedlistener, mediaplayer.onerrorlistener, mediaplayer.oncompletionlistener { ////////////////////////////////// declarations //////////////////////////////////////////////////// //media player private mediaplayer player; //song list private arraylist<song> songs; //current position private int songposn; //binder private final ibinder musicbind = new musicbinder();