Posts

Showing posts from April, 2014

java - For loop cannot convert from int to double[] -

for reading lot of lines i've made loop start reading line 0 way line 61166. if try compile file cannot convert int double[] though variables not integers. have done wrong? tbh beginner if it's java. school exercise int m = 61166; int[] l = new int[m]; double[] p = new double[m] ; double[] q = new double[m]; (p = 0; p < m ; p++); the issue trying use array loop index/incrementer. in theory, this: int m = 61166; int[] l = new int[m]; double[] p = new double[m] ; double[] q = new double[m]; (p[0] = 0; p[0] < m ; p[0]++); but don't think make program run way want too. think might want this: int m = 61166; ...

Retrieve "id" field values via VisualVM OQL query -

getting obj.id oql query in java visualvm (1.8.0_45) returns javascript object id (a long value) instead of value of java field. in other words javascript id field shadows java object id field. java object value can seen in instances browser, how retrieve via visualvm oql? currently there no way access java object id field. bug in oql.

A simulation the game of craps java -

this code supposed simulating game of craps: getting right win , losses turn out can't probability correct. suggestions? please instructions are: in game of craps, pass line bet proceeds follows. 2 six-sided dice rolled; first roll of dice in craps round called “come out roll.” come-out roll of 7 or 11 automatically wins, , come out roll of 2, 3, or 12 automatically loses. if 4, 5, 6, 8, 9, or 10 rolled on come out roll, number becomes point. player keeps rolling dice until either 7 or point rolled. if point rolled first, player wins bet. if 7 rolled first, player loses. write program simulates game of craps using these rules without human input. instead of asking wager, program should calculate whether player win or lose. the program should simulate rolling 2 dice , calculate sum. add loop program plays 10,000 games.add counters count how many times player wins, , how many times player loses. @ end of 10,000 games, compute probability of winning [i.e., wins / (wins + losse...

C++ How to define array of objects (Eclipse arduino) -

going nuts trying define array of objects. thanks. // menu.h #ifndef menu_h_ #define menu_h_ #include "wstring.h" class menu { public: menu(string label); void addchild(string label); string getlabel(); private: menu childmenus[10]; ==> field 'childmenus' has incomplete type 'menu [10] string label; }; #endif /* menu_h_ */ you have object within object class. menu should not use in itself. you use array of object pointers, should work: menu* childmenus[10]; you access childmenus array so: childmenus[0]->getlabel();

chatbot - Deleting "Account linking" on facebook not working -

dears, working on facebook messenger chatbot. described on facebook developers site, have been able use account linking , got users linked. when user linked need remove linking dialog, , described on facebook developers website used delete request result in "account linking url removed" in chat window dialog still exists.here code using delete account linking url : request({ method: 'delete', uri: 'https://graph.facebook.com/v2.6/me/thread_settings', qs: { access_token: fb_page_token }, json: { recipient: { id: event.sender.id }, "setting_type":"account_linking" } }, (err, res, body) => { // deal ...

json - Displaying questions for a quiz using javascript -

i doing javascriptissexy.com learning path. having trouble figuring out best way display quiz questions. question beginner javascript student. how should tackle approach of developing behavior of quiz app. if @ code have stored questions in json. how can display questions user or can answer question , interact program? var questions = [{ questions: "what name of biggest part of human brain?", choices : ["cerebrum", "thalamus","medulla", "cerebellum"], correstanswer: 0 }, { questions: "the colored part of human eye controls how light passes through pupil called the?", choices: ["pupil", "rods", "iris", "cornea"], correctanswer: 2 }, { questions: "what name of substance gives skin , hair pigment?", choices: ["dermis", "melanin", "swear gland", "epiderms"], correctanswer: 1 }, { questions: "the muscles foun...

ruby - rails return tuples with common attributes -

i want display movies selected director. routes , controller work fine. however, filtered movies shown in view same. example, have 4 movies of 2 have same director. want show these 2 different tuples in view page, shown 2 tuples same. controller code: def find_movies_by_same_director @movie = movie.find(params[:id]) @director = @movie.director if (not @director.nil?) , (not @director.empty?) #@movies = movie.find_all_by_director(@director) if (not @director.nil?) , (not @director.empty?); @movies = movie.find_by_sql("select * movies i.director == '#{@director}'") render :director else flash[:notice] = "'#{@movie.title}' has no director information" redirect_to root_path end end i try both ways, find_by_sql , find_by_all, find tuples, both same results. view code: %tbody - @movies.each |movie| %tr %th= @movie.title %th= @movie.rating %th= @movie.release_date i'm new rails, comments or...

dynamic html generation in polymer -

i trying generate div dynamically based on properties in fabric.canvas.object. the following excerpts code. class polymer2fabricedit extends polymer.element { static is() { return 'polymer-2-fabric-edit' } static config() { return { properties: { canvas: { type: object, value: null }, ctx: { type: object, value: null }, canvaswidth: { type: number, value: 300 }, canvasheight: { type: number, value: 300 }, topproperty: { type: number, value: 0, notify: true }, observers: [ ] } } constructor() { super(); console.log('created'); } connectedcallback() { super.connectedcallback(); console.log('attached'); } ready() { super.ready(); this.canvas = new fabric.canvas(this.$.c, {isdrawingmode: false}); cons...

xdebug - Does PhpStorm debugging require a local PHP server or just interpreter? -

i'm using phpstorm 6.0.3 php (7.0.13) on windows 7. (i.e., i'm not using full blown local server xampp or mamp. simple php, no database, etc). when try debug, phpstorm reports: connection xdebug not established. validate installation. when validate says xdebug installed. i've tried: disabling firewall (just in case). disabling antivirus confirmed i'm "listening php debug connections" (and tried off) it occurred me maybe need "full blown" server (like xampp or mamp).

json - One activity using with two adapter in android -

im using recyclerview , expandablelistview in activity, both load data 1 layout, have tried use activity call 1 adapter seem unsuccess. this activity (use 2 adapters): public class detaillistcaractivitydemo extends appcompatactivity { private recyclerview mrecyclerview, exrecyclerview; private gridlayoutmanager mlayoutmanager; private recycleradapter madapter; private expandablelistadapter exadapter; private context context; private arraylist<gettersetter> feeditemlist; // private list<item> itemslistdata; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_detail_list_car_demo); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); getsupportactionbar().setdisplayhomeasupenabled(true); collapsingtoolbarlayout collapsingtoolbar = (collapsingtoolbarlayout) findviewbyid(r.id.collapsing_toolbar); collapsingtoolbar.set...

Deleting Shared preferences in android -

in current app made set of passpoints , want there option delete them different activity. saw few questions similar on stackoverflow , tried follow instructions , tinker little nothing worked. wrong code? first activity: ( activity preferences i'm trying delete ) public void setdefaults() { sharedpreferences mprefs = getsharedpreferences(resett_passpoints, 0); sharedpreferences.editor editor = mprefs.edit(); editor.putstring(resett_passpoints,identifier); editor.commit(); } second activity : ( activity i'm trying delete ) public void deletedefaults(){ sharedpreferences mprefs = getsharedpreferences(activity1.resett_passpoints, 0); string str = mprefs.getstring(activity1.resett_passpoints, activity1.identifier); if (str.equals(activity1.identifier)){ sharedpreferences.editor editor = mprefs.edit(); editor.clear(); editor.commit(); } } also, know use intents ".put extra" way of doing don't want...

ios - Objective C NSDictionary: How can I sort my NSDictionary keys based on the key's value -

i have nsdictonary equals following value. = { order = 3; }; b = { order = 1; }; c = { order = 2; }; i need sort keys a,b , c based on order number least greatest. in example, keys should display following b,c , a. how achieve this? the order of keys of nsmutabledictionary (a, b, c in case) decided system. have no control of that. but can use nsmutablearray (not nsarray since immutable, i.e. cannot modified) achieve goal. each element in array separate nsdictionary 2 key-value pairs - 1 key , 1 order, make things simpler. this code need: nsmutablearray *arrayofdictionaries = [@[ @{ @"key" : @"a", @"order" : @3 }, @{ @"key" : @"b", @"order" : @1 }, @{ @"key" : @"c", @"order" : @2 }, ...

sql - Merge Statement inserting duplicate rows? -

for eternity have been spending time on this, can't seem find cause why merge statement inserts duplicate rows. here tables. table inventory productid | productname | productcode | quantity | location 1 | stabilo | code123 | 3 | basement 2 | parker pen | code456 | 4 | basement table incomingstocks requestnumber | productid | productname | productcode | quantity | deliverylocation request123 | 2 | parker pen | code456 | 3 | basement request123 | 3 | eraser | code789 | 5 | basement one request number = multiple items, fast food delivery can contain multiple orders in 1 transaction number. when run query... merge inventory t1 using incomingstocks t2 on t1.productcode = t2.productcode , t2.requestnumber = 'request123' , t2.deliverylocation= 'basement' when matched update set t1.quantity = t1.qua...

vvv wordpress - Vagrant loop cannot destroy & cannot up -

i using vvv , have issue want start fresh. want delete vagrant-local. find machine destroy this. global status θ69° [sayth:~/vagrant-local] develop 38m51s ± vagrant global-status id name provider state directory ------------------------------------------------------------------------- c9e69c8 default virtualbox poweroff /home/sayth/python-script-examples 83f3b91 default virtualbox poweroff /home/sayth/vagrant-local above shows information known vagrant environments on machine. data cached , may not up-to-date. interact of machines, can go directory , run vagrant, or can use id directly vagrant commands directory. example: "vagrant destroy 1a2b3c4d" now stuck if try , destroy fails requesting machine up, cannot machine has error. cannot destroy θ73° [sayth:~/vagrant-local] develop 40m40s ± vagrant destroy 83f3b91 ==> default: running triggers before destroy... ==> default: executing command "vagr...

parameter passing - Creating a PUT request in Ruby on Rails? -

i want able use put request edit title of song uploaded in ruby on rails application. def update @sound_byte = soundbyte.find(params[:id]) #error here @sound_byte.update!(sound_byte_params) flash[:success] = "the soundbyte title changed." redirect_to sound_byte_path end private def sound_byte_params params.require(:sound_byte).permit(:mpeg, :mpeg_file_name) end i end getting error this: couldn't find soundbyte 'id'=song_name any ideas of how fix issue? using paperclip gem enable audio/mpeg file uploads. edit: here views code <%= link_to "edit", sound_byte_path(sound_byte.mpeg_file_name), class: "btn btn-primary btn-lg btn-xlarge", :method => :put %> in view page, pass string sound_byte.mpeg_file_name params, in controller, use id @sound_byte = soundbyte.find(params[:id]) . try this <%= link_to "edit", sound_byte_path(sound_byte.id), class: "btn btn-primary btn-lg btn-xla...

python - Custom lookup is not being registered in Django -

i've created custom lookup. i'm using query, however, when so, error related field got invalid lookup: lcb thrown. i'm assuming because custom lookup isn't being registered properly. you'll see below, i've tried several things , i'm lost issue is. here's code: tenants/views.py from main.lookups import * def find_tenants(request, house_id): house = houselisting.objects.get(pk=house_id) applications = housingapplication.objects.filter(date_from__gte=house.available_from) applications = applications.filter(pets__lcb=house.allowed_pets.values_list('id', flat=true)) context = {'house': house, 'applications': applications} return render(request, 'landlords/find-tenants.html', context) main/lookups.py from django.db.models import lookup, manytomanyfield # custom lookups @manytomanyfield.register_lookup class listcontainedby(lookup): lookup_name = 'lcb' def as_sql(self, co...

java - Get distance between two different latitude and longitude in android? -

i have used locationa.distanceto(locationb); , have copy pasted method written haversine formula. the actual distance between 2 geopoints 25m result of 6894.52192658389 using above methods. followed this: creating method using haversine formula, android v2 , find distance between 2 points on map using google map api v2 checked distance using free tool http://www.onlineconversion.com/map_greatcircle_distance.htm you can try code below : public static float distfrom(float lat1, float lng1, float lat2, float lng2) { double earthradius = 6371000; //meters double dlat = math.toradians(lat2-lat1); double dlng = math.toradians(lng2-lng1); double = math.sin(dlat/2) * math.sin(dlat/2) + math.cos(math.toradians(lat1)) * math.cos(math.toradians(lat2)) * math.sin(dlng/2) * math.sin(dlng/2); double c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a)); float dist = (float) (earthradius * c); return dist; } it...

javascript - Updating properties of JS "class" based on other properties? -

i'm relatively new javascript , trying create simple physics engine game type project working on. in order this, created understand js equivalent of class can create new copies of each object want. problem want able update value such x position , have update things such x middle position (x center of object on screen). know possible using object literal , getter, want able create new objects @ realtime based on what's on screen , couldn't figure out how use make work. here's general idea of trying do: var object = function (xpos, ypos, width, height) { this.xpos = xpos; this.ypos = ypos; function getxmid (xp) { return xp + width/2; } this.xmid = getxmid (this.xpos); function getymid (yp) { return yp + height/2; } this.ymid = getymid (this.ypos); } var ball = new object (10, 20, 50, 50); ball.xpos = 50; console.log (ball.xmid); // want output 75 instead of 45 you're changing 1 property, , expecting other properties update, unfortunately do...

PHP ERROR : mysqli_stmt_bind_param() Number of variables doesn't match number of parameters in prepared statement -

i facing problem in php file, error comming parameters in third statement, can not find it. here php file: $client = "test"; $resto = "test"; $st1 = mysqli_query($con, "select client_id clients email = '$client'"); $res1 = mysqli_fetch_array($st1); $clientid = $res1["client_id"]; echo "client id = "; echo $clientid; $st2 = mysqli_query($con, "select restaurant_id restaurants email = '$resto'"); $res2 = mysqli_fetch_array($st2); $restaurantid = $res2["restaurant_id"]; echo "resto id = "; echo $restaurantid; $statement = mysqli_prepare($con, "insert reservations (resto_id, client_id) values ($restaurantid,$clientid)"); mysqli_stmt_bind_param($statement,"ii",$restaurantid,$clientid); mysqli_stmt_execute($statement); $response = array(); $response["success"] = true; echo json_encode($response); thank in advance help. change statement bello...

Sending email with PHP on Centos 6.4 and Nginx server -

this question has answer here: php mail function doesn't complete sending of e-mail 22 answers please not mark duplicate issue . have tried recommended steps (checking error logs, checking syntax, header info.. etc..) troubleshoot mod has pointed me , steps did not work. receiving permission issue , can not seem figure out why. error is: "nov 13 14:19:08 centos64 sendmail[6611]: uadjj80j006611: syserr(nginx): queueup: cannot create queue file ./qfuadjj80j006611, euid=498, fd=-1, fp=0x0: permission denied ~" original message : would sending email using php on nginx centos 6.4 server. new want first verify if current setup correct , diagnose exact issue before start tweaking config files. goal: able send users in sql database email alerts, etc.. if have large user-base sending lot of emails.. in php.ini file see.. sendmail_path = /usr/sbin/...

angular services - AngularJS need to store userdata , should be available to entire application -

i need store userdata, should available entire application, should accessible required controllers, after searching found few options store. using service controllers $sessionstorage $localstorage of above u please tell me best practice? or there other solution other above 3. using simple google search might have told lot best thing? there no single best thing it's depends upon use case. services best way interchange data between controllers. if don't want persist data(if data don't want there if page reloaded) can use service, if want persist data can use localstorage.

mysql - how to simulate slow update sql? -

Image
dba told me there slow sql should optimize, and there 10 same update sql , longest time 56 seconds. the business logic of sql that, if user wins award , should decrease 1 stock of award. i think caused high concurrent, in case exist lock competion. decided repropduce in local environment, let many thread execute update operation simultaneously, cannot reproduce above slow sql, below experiment result: thred count|100|500|1000|2000 -----|-----|-----|-----|----- took time(ms)|149|490|1064|1996 even 2000 update sql execute concurrently, need 1996 ms execute all. how reprduce these slow sql? my code @test public void test_concurrent_update() throws interruptedexception { int nthreads = 50; //thread count executorservice pool = executors.newfixedthreadpool(nthreads); final countdownlatch startlatch = new countdownlatch(nthreads); final countdownlatch endlatch = new countdownlatch(nthreads); long starttime = system.currenttimemillis(); (int = 0; ...

powershell - Content Type Hub and Content Type Subscriber Timer Jobs not showing in CA -

i set single server sp2016 installation. trying content type hub feature work when go central administration , under the job definitions not see 2 timer jobs should there default after installation. these 2 "content type hub" , "content type subscriber" timer jobs. i created web application , site collections powershell. if use ui create web application see "content type subscriber" job associated new web application listed there still in no "content type hub" timer job listed. the managed meta data service application fine , working without issues terms displaying them across various site collections. any ideas may going on here?

java - Print any exit path, from any arbitrary point to outside grid? -

this question asked in interview. given grid 4x4, give arbitrary point suppose point (2,2)(index starting 0), there want start, print 1 path there can exit grid. allow move left , right , top , botton . in following grid, 1 - represents block, 0 : can move. 1 0 1 1 0 0 0 0 1 1 0 1 1 1 1 1 exit path above grid is, (2, 2)=> (1, 2) => (1, 1) => (0, 1) i tried solve problem ( below ), through dfs, not able find solution how print 1 of path, following printing path, want print path. public boolean isvalidmove(point point){ if(array[point.getx()][point.gety()]==0){ return true; } return false; } public void printtraversal(int [][] array, int m, int n, point start){ boolean [] visited = boolean[m*n]; arrays.fill(visited, false); int index = start.getx()*m+ start.gety(); boolean[index] = true; stack<point> stack = new stack<point>(); stack.push(start); while(!stack.isempty()){ point point = stack.pop(); ...

php - Access character in a string with square braces doesn't output correctly -

i have string , want access ä character. outputs question mark instead of correct character. here code. $array = array('ä', 'b', 'c'); $string = 'äbc'; echo $string; // äbc echo '<br />'; echo $string[0]; // ? echo '<br />'; echo $array[0]; // ä demo can tell me why? updated echo strlen($string); // returns 4 echo mb_substr($string, 0, 1); // ä depending on charset, letter ä multi-byte letter. when access string using array access, returns first byte. in case of multi-byte ä returns non printable control character. accessing array using array-access returns first element, regardless of it's length, in case multi-byte ä.

Plot a matrix in graph with two axis in matlab -

i need plot nxn matrix 'm' full of zeros, show cases m(x,y) different 0. t_max = 10; % set maximum number of iterations n = 10; % dimension n*n d = 1; % probability of changing place x = randi([1 n]); % random row y = randi([1 n]); % random column grid = zeros(10); % set empty gride n*n grid(x,y) = 1; % put agent in random place t=1:t_max newgrid = randomwalk1(grid,d); % call function random walk 1 agent end i tried image(m) it's not giving satisfying results since need keep track of element different 0, hold on doesn't work in case. you looking spy() function. type spy(m) , see happens.

c# - How to order by date from new to oldest? -

i'm having trouble sorting list of dates newest oldest. ideas? my code follow: public async task<iactionresult> prices() { var allresults = result in _context.reviews orderby result.date descending select result; return view(await allresults.tolistasync()); } i receive following error message: cs1061 'dbset' not contain definition 'orderbydescending' , no extension method 'orderbydescending' accepting first argument of type 'dbset' found (are missing using directive or assembly reference?) add using system.linq; that solve problem.

javascript - Merge two objects but only existing properties -

i have 2 objects. , want merge 2 objects property value present first object. obj1 : { "name": "", "age": "" } obj2 : { "name": "leo", "age": "14", "company": "aero", "shift": "night" } the output want is: obj1 : { "name": "leo", "age": "14" } the company , shift no need merge because 2 property not present in obj1 . the code i've done far is: object.assign({}, obj1, obj2); but it's not give me right output. gives is: merge : { "name": "leo", "age": "14", "company": "aero", "shift": "night" } could me how achieve output this: merge : { "name": "leo", "age"...

Symfony override parameters based on host -

i'd load or overwrite parameters depending on host. example, change database or email parameters. so, created bundle (to reuse in future projects) following extension: class pceservicesmulticonfigextension extends extension { /** * {@inheritdoc} */ public function load(array $configs, containerbuilder $container) { $configuration = new configuration(); $config = $this->processconfiguration($configuration, $configs); $rootdir = $container->getparameter('kernel.root_dir'); $request = request::createfromglobals(); $loader = new loader\yamlfileloader($container, new filelocator(__dir__.'/../resources/config')); $loader->load('services.yml'); // load parameters depending on current host $paramloader = new loader\yamlfileloader($container, new filelocator($rootdir.'/config')); // access root config directory $host = $request->gethttphost(); if ($hos...

haskell - Does the expressiveness of monads come at the expense of code reuse? -

when compare binary operations of applicative , monad type class (<*>) :: applicative f => f (a -> b) -> f -> f b (=<<) :: monad m => (a -> m b) -> m -> m b two differences become apparent: ap expects normal, pure function, whereas bind expects monadic action, must return monad of same type with ap sequence of actions determined applicative, whereas bind monadic action can determine control flow so monads give me additional expressive power. however, since no longer accept normal, pure functions, expressiveness seems come @ expense of code reuse. my conclusion might naive or false, since have merely little experience haskell , monadic computations. light in dark appreciated! code reuse advantage if can reuse code want. ghci> putstrln =<< getline sulfur sulfur ghci> here, (=<<) picks string result produced in io context getline , feeds putstrln , prints said result. ghci> :t getline g...

unity3d - Unity - How to Smooth Out Constant Velocity on Rigidbody2D -

i setting constant velocity character movement in 2d game. since using method character seems shaking little. there way fix , smooth movement out? here set velocity in update function: constantvelocity = new vector3 (playerinputx * speed, playerinputy * speed, 0); i apply velocity the rigidbody2d component in fixedupdate function. there 2 ways this. you can use time.fixeddeltatime smoothen player movement. you can try low pass filtering on our constantvelocity.

java - I am using Javafx and I am trying to manipulate code within a .css file but cannot -

the problem code wish change string assigned defaultimg change background image of application. not receive runtime or compile error when running application. "client.css" file not being updated. messing up? there buttons called "img1" - "img6". these located near bottom of code. in these methods open file writer clear , rewrite code within css document. thank in advance helping me out. //settings application: s_windowpane = new gridpane(); s_windowpane.setpadding(new insets(35)); s_windowpane.sethgap(0); s_windowpane.setvgap(0); s_windowpane.setid("settingspane"); s_buttonpane = new gridpane(); s_buttonpane.setpadding(new insets(15)); s_buttonpane.sethgap(0); s_buttonpane.setvgap(20); s_buttonpane.setalignment(pos.bottom_center); s_buttonpane.setid("buttonpane"); s_bkgrndimagepane = new gridpane(); s_bkgrndimagepane.setprefwidth(500); s_bkgrndimagepane.setprefheight(300...

java - How to switch between activities with the same bluetooth connection address, how to do that? -

i have 3 activities: devicelistactivity: lists out paired device list , after clicking on 1 paired device switches mainactivity . mainactivity: receives bluetooth address , initiates connection bluetoothsocket , starts thread receive text arduino, after switch thread mainactivity addactivity2 same connection. have same program mainactivity in addactivity2 too. main issue: want stop running thread of mainactivity while switching mainactivity addactivity2 , start thread of addactivity2 . how ?? *big issue facing: switching between 2 activities ( mainactivity , addactivity2 ) same address. issue lies in threads. here's devicelistactivity public class devicelistactivity extends activity { private static final string tag = "devicelistactivity"; private static final boolean d = true; // string send on mainactivity public static string extra_device_address = "device_address"; private bluetoothadapter mbtadapter; p...