Posts

Showing posts from April, 2012

JavaScript: difference in efficiency of indexOf method on String and Array -

i curious whether there exists difference in efficiency indexof method available both array , string in javascript. thought indexof less efficient on string on array, , new testing results support this. example: var arr = ['abc', 'ab', 'abz', '1']; var str = 'abcababz1'; var needle = 'abxx'; //concatenate make them bigger (var = 0; < 30; i++) { arr = arr.concat(arr); str = str.concat(str); } arr.push(needle); //append needle last str = str.concat(needle); then used start , end timestamp arr.indexof(needle); // faster! str.indexof(needle); i did testing in node, new testing results showed: time used on array is: 35 time used on string is: 57 so array more efficient indexof string. new testing creates worst case scenario -- needle @ end of string or array. edit: if indexof more efficient on array, wondering if should first split string (delimited comma, example) array before using indexof method se

c# - FillPie() in OnPaint caussing an error after minimizinig -

i've encountered problem handling onpaint event. have custom class: namespace winformsconsumer { public class cookie { public point point{get; set;} public color color { get; set; } public int angle { get; set; } public cookie(point point, color color, int angle) { point = point; color = color; angle = angle; } } } i defined helper method (taken class paintservice taken webservice): public nullable<point> startdraw(int startx, int starty, int width, int height) { try { int x = rnd.next(startx, width); int y = rnd.next(starty + height); return (new point(x, y)); } catch (argumentoutofrangeexception e) { console.writeline(e.message); return null; } } later on, i've created form. in have: public parti

elixir - returning a list gives (Poison.EncodeError) unable to encode value -

io.puts(inspect( contacts )) gives: [%hellotable.contact{__meta__: #ecto.schema.metadata<:loaded>, id: 37, inserted_at: #ecto.datetime<2015-10-22t12:50:43z>, name: "gumbo", phone: "(801) 555-55555", updated_at: #ecto.datetime<2015-10-22t12:50:43z>}] and view looks like: defmodule hellotable.contactview use hellotable.web, :view def render("index.json", %{contacts: contacts}) io.puts(inspect( contacts )) contacts end end as try render view get: ** (poison.encodeerror) unable encode value: {nil, "contacts"} you need either implement poison.encoder protocol hellotable.contact described in encoding ecto model json in elixir or return map render function using render_many/4 : defmodule hellotable.contactview use hellotable.web, :view def render("index.json", %{contacts: contacts}) render_many(contacts, __module__, "contact.json") end def render(&

stack list debug assertion failed c++ -

when try run code, show me debug assertion failed .any 1 can me, doing stack list,in header file, create struct has 3 variable, string * s, int numoflength, stackframe * next void stack::push(string& s) { stackframeptr temp_ptr; temp_ptr=new stackframe; temp_ptr->str=new string[s.size()]; (temp_ptr->str)[0]=s; cout<<temp_ptr->str[0]<<endl; temp_ptr->num_char=sizeofstring(s); if(empty()) { top=temp_ptr; temp_ptr->next=null; } else { temp_ptr->next=top; top=temp_ptr; } } code push think maybe errors because of function. string stack::pop() { if(empty()) exit(1); string * name; stackframeptr temp; temp=top; name=top->str; top=top->next; delete temp; return *name; } #include &l

algorithm - To find an optimal solution for a dynamic programming issue -

right now, we're struggling how best design solution below problem: you have funnel can take 3kgs of fruit. aim make fruit juice, following grades of each fruit. (grade non-unit number. can assume grade constant across each gram of juice) - apple: 5 banana: 0.5 oranges: 9 you making juice on hourly basis. grade of each fruit in juice can vary between +20% -20% of required grade every hour. however, end of day, final grades of fruit should not vary more 5% of required grade. your input different mixed-fruit juices of anywhere between 400-500g. know grades of each fruit in each of these input juices. (assume mixture of banana, apple , orange.) when input juice, can either put directly in funnel, or store in fridge later use. if store in fridge, need let warm 5 seconds before can use in juice. your aim maximise number of input juices put directly in funnel while maintaining hourly , daily averages. main problem daily variance lower hourly variance.

java - Implementing interface comparators -

say have simple interface wish comparable based on feature: interface organism extends comparable<organism> { string getname(); int getcomplexity(); @override default int compareto(organism other) { return this.getcomplexity() - other.getcomplexity(); } } each implementing class must return unique complexity 2 instances of class have same complexity , 2 instance of different class have different complexity. natural ordering 'group' instances of classes together. i want implement interface in class overrides default comparison comparing 2 instance of class within class's group of instances in order. use following pattern: class bacteria implements organism { enum shape {rod, round, spiral}; private final shape shape; @override public int compareto(organism other) { if (other instanceof bacteria) return this.shape.compareto((bacteria)other.shape); else return organism.sup

android - i am not getting the device Registration id from the google and even not called GCMIntentService -

i not getting device registration id google , not called gcmintentservice using google create server key.. below manifest file not getting device register key google package="com.example.isquare.pushexample" > <receiver android:name="com.google.android.gcm.gcmbroadcastreceiver" android:permission="com.google.android.c2dm.permission.send" > <intent-filter> <action android:name="com.google.android.c2dm.intent.receive" /> <action android:name="com.google.android.c2dm.intent.registration" /> <category android:name="com.example.isquare.pushexample" /> </intent-filter> </receiver> <service android:name=".myintentservice" /> </application> <uses-permission android:name="android.permission.internet" /> <!-- gcm requires g

ios - Rounded rect using UIRectCorner in Swift not working -

Image
i trying create rounded rect uitableviewcell have created in storyboard. using swift 2 in xcode 7. have 2 views in prototype cell, topview , bottom view. want topview have top corners rounds, , bottomview have corners rounded. in awakefromnib (may go somewhere else better later): ... self.topview.backgroundcolor = uicolor.redcolor() self.bottomview.backgroundcolor = uicolor.graycolor() self.setmasktoview(self.topview, corners:uirectcorner.topleft.union(uirectcorner.topright)) self.setmasktoview(self.bottomview, corners: uirectcorner.bottomleft.union(uirectcorner.bottomright)) ... in separate function (based on answer stack overflow post): func setmasktoview(view : uiview, corners: uirectcorner) { let rounded = uibezierpath(roundedrect: self.bounds, byroundingcorners: corners, cornerradii: cgsize(width: 10, height: 10)) let mask = cashapelayer() mask.path = rounded.cgpath view.layer.mask = mask } note, tried [.topright, .topleft] instead of union(), ba

python - Plotly.js connecting to Django Rest Framework API - is this possible and if so how? -

i testing use of plotly in our company's web application. know plotly has it's own api possible connect django rest framework api since python based? if possible - syntax like? here have far: div id="mydiv"></div> <script> var trace1 = { x: [1, 2, 3, 4], y: [10, 15, 13, 17], type: 'scatter' }; var trace2 = { x: [1, 2, 3, 4], y: [16, 5, 11, 9], type: 'scatter' }; var data = [trace1, trace2]; plotly.newplot('mydiv', data); </script> instead of hard-coding data in 'x' , 'y' - want point json in django rest framework. database mysql. appreciated!!! thanks!

arrays - PHP Return results based on two timestamps within 30mins -

bit of newb , stuck... appreciated. bit of preface, did have earlier, pretty achieved needed, got point didn't want take more of time anymore (i ask lot of him already). i have base time of '7am' example, retrieve 30 minutes of results 'past' 7am, help, results before , after 7am. here code: $timearrayone = array(array("time"=>"2015-10-01 06:45:00"),array("time"=>"2015-10-01 07:15:00"),array("time"=>"2015-10-01 07:29:00"),array("time"=>"2015-10-01 07:31:00")); $msg = ''; $closest = false; $closestresult = false; foreach ($timearrayone $result) { // foreach $basetime $loggedtime = $result['time']; // set base time $basetime = new datetime("2015-10-01 07:00:00"); // set time 2 $timetwo = new datetime($loggedtime); // subtract bas

c++ - Overload resolution gets different result between gcc and clang -

struct { a(int);}; struct b { explicit b(a); b(const b&);}; b b({0}); gcc 5.1.0 gives error /dev/fd/63:3:8: error: call of overloaded 'b(<brace-enclosed initializer list>)' ambiguous /dev/fd/63:3:8: note: candidates are: /dev/fd/63:2:27: note: b::b(const b&) /dev/fd/63:2:21: note: b::b(a) while clang 3.6.0 succeeds. which 1 right? why? for gcc 5.1.0: http://melpon.org/wandbox/permlink/pve9eyxgu26nex6x for clang 3.6.0: http://melpon.org/wandbox/permlink/woi1md2dc519spw0 this may similar direct list initialization compiles successfully, normal direct initialization fails, why? gcc , clang same result. but different question. b(a) explicit here. gcc , clang different results. the difference can reduced struct { explicit a(int); }; struct b { b(int); }; void f(a); void f(b); int main() { f({ 1 }); } on gcc fails, in accordance standard (which says list initialization, explicit constructors considered - can yield ambiguity - no

javascript - Create Piwik plugin which extends device-detector plugin -

i tryed creat piwik plugin based on devicedetection plugin there point didn't understood, , hope 1 of can me. this plugin add new features detection system. but have question. how can make interacting te current version of devicedetection. because right did module, , module work himself, add informations devicedetection thank you

c# - UserControlViewModel doesn't update binded property in UserControl -

i want able change property in main window user controls view model. this connection mainwindow i bind property view model usercontrol mainwindowviewmodel my property lies here, updated when user control property changes usercontrol1 its dependency property that's binded main window view model returns value usercontrolviewmodel usercontrol1viewmodel the logic changes property (which supposed update mainwindowviewmodel) lies here. i can binding between of them, problem when update property bottom layer (usercontrolviewmodel), not update property neither in usercontrol or in mainwindowviewmodel. here code (i have uploaded project on google drive ) mainwindow.xaml <window x:class="wpfapplicationviewtoviewmodel.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expressio

stateful - Accumulator factory in Haskell -

now, @ start of adventure programming have problems understanding basic concepts. here 1 related haskell or perhaps functional paradigm. here general statement of accumulator factory problem, http://rosettacode.org/wiki/accumulator_factory [write function that] takes number n , returns function (lets call g), takes number i, , returns n incremented accumulation of every call of function g(i). works numeric type-- i.e. can take both ints , floats , returns functions can take both ints , floats. (it not enough convert input floats. accumulator has seen integers must return integers.) (i.e., if language doesn't allow numeric polymorphism, have use overloading or that) generates functions return sum of every number ever passed them, not recent. (this requires piece of state hold accumulated value, in turn means pure functional languages can't used task.) returns real function, meaning can use wherever use function had defined in ordinary way in text of

datetime - c++ get years between date chosen by user and actual date(counting days,months,years) -

i tried doing this: struct den_t { int day, month, year; }; int main() { struct den_t* datum = new struct den_t; struct den_t* dnes = new struct den_t; time_t thetime = time(null); struct tm atime; localtime_s(&atime, &thetime); dnes->day = atime.tm_mday; dnes->month = atime.tm_mon + 1; dnes->year = atime.tm_yday + 1900; cin >> datum->day >> datum->month >> datum->year; if (dnes->year - datum->year >= 18 ) cout << "full aged " << endl; else cout << "not full aged " << endl; system("pause"); return 0; } but somehow cant understand what should compare , decrement ,could explain me what else need tell people's date example in float comparing year,month , day of actual time , date user inputs in program? using these libraries: http://howardhinnant.github.io/date/date.h

android - I've been busy for a long time finding out how to draw a line between one (GPS) points and one marker on the map in my application. can someone? -

i have different files geolocation , markers :d want draw line... position (using gps) marker inputed in application. if clicked 1 marker choose there line :) thank i'm new please me.. //this locationhelper public static googlemap getstorelist(googlemap googlemap){ // create marker markeroptions seveneleven = new markeroptions().position(new latlng(14.616737, 120.982916)).title("7-eleven"); googlemap.addmarker(seveneleven); markeroptions sevenelevenrecto = new markeroptions().position(new latlng(14.601643, 120.988580)).title("7-eleven recto"); googlemap.addmarker(sevenelevenrecto); markeroptions newestgroceryencoldstore = new markeroptions().position(new latlng(14.597770, 120.983253)).title("newest grocery , cold store"); googlemap.addmarker(newestgroceryencoldstore); markeroptions savemorestacruz = new markeroptions().position(new latlng(14.601845, 120.981116)).title("save

jquery - Getting ul height of bootstrap dropdown with max-height set always results in max-height -

i'm writing conditional logic detect bootstrap dropdown in relation window , conditionally add class dropup dropdown expand upwards. i have 3 dropdowns inside of table columns, , 3 dropdowns have different amount of items in them. here's example of one. <td class="form-group" ng-controller="dropupcontroller up"> <div class="btn-group" dropdown keyboard-nav ng-class="{ 'dropup': up.isdropup }" ng-click="up.toggledropup($event)"> <button type="button" class="btn btn-default" dropdown-toggle> {{ othercontroller.text }} <span class="caret"></span> </button> <ul class="dropdown-menu" role="menu" aria-labelledby="simple-btn-keyboard-nav"> <li ng-repeat="item in othercontroller.collection" role="menuitem" ng-class=&q

Android Parse Facebook Login JSON Null -

when have new user login through facebook on app, make newmerequest in order grab information new user. code use working fine, lately i've noticed new user signups through facebook on app have been lacking required data pulling facebook. i noticed json newmerequest turning out null (i've been running code on test database using facebook profile on , on , deleting account test iteration) , sometimes it's not null. additionally have been having issues lately app saying uh oh. user canceled facebook login , doesn't happen 100% of time. code portion of "uh oh....": list<string> permissions = arrays.aslist("public_profile", "email"); parsefacebookutils.loginwithreadpermissionsinbackground(this, permissions, new logincallback() { @override public void done(parseuser user, parseexception err) { if (user == null) { log.d(application.tag, "uh oh. user cancelled facebook login.&qu

node.js - Google prediction API v1.6 - How can I make server to server call? -

i'm experimenting google prediction api v1.6. i've followed getting started section, , created model using explorer api . now, model ready , prediction results explorer satisfying. now when i'm trying move forward (using nodejs), i'm lost ... i've looked @ this library couldn't figure out how make call prediction.trainedmodels.predict without client side consent screen. faced same problem, here found: 1 you'll need create service account. go google developers console click apis & auth > credentials add credentials service account, download generated service account's public/private key recommendation: application can complete these tasks either using google apis client library language, or directly interacting oauth 2.0 system using http. however, mechanics of server-to-server authentication interactions require applications create , cryptographically sign json web tokens (jwts), , it's easy make ser

apache - htaccess www sub domain redirect -

my problem i have sub domain pointing different server. server has ssl, when user types in sub domain: https://my.maindomain.co works great. using htaccess i'm trying redirect users type in following web address: https://www.my.maindomain.co or http:// equivalent correct version ( https://my.maindomain.co ). i thought below work nicely not: # rule removing www on sub domains rewritecond %{http_host} ^www\.([^.]+\.maindomain\.co)$ [nc] rewriterule ^ https://%1%{request_uri} [r=301,l] anybody me out this? for reference placing code in htaccess on maindomain.co server, hosted on different server my.maindomain.co you can use rule subdomain on server sub domain hosted. should take care of requirements. rewriteengine on rewritecond %{https} !^on [or] rewritecond %{http_host} !^my\.example\.co$ [nc] rewriterule ^ https://my.example.co%{request_uri} [r=301,l] note must have valid ssl certificate www.my.example.co work if enter www.my.example.co . otherwise s

python - Manually-defined axis labels for Matplotlib imshow() -

Image
the following code: import matplotlib.pyplot plt import numpy np data = np.random.randint(0, 100, size=(10, 10)) plt.imshow(data, cmap='jet', interpolation='nearest') plt.show() gives following figure: however, instead of axis labels corresponding index in array, want manually define them. example, instead of axis labels being (0, 2, 4, 6, 8) above, want them (0, 10, 20, 30 ...). here code have tried this: import matplotlib.pyplot plt import numpy np data = np.random.randint(0, 100, size=(10, 10)) labels = range(0, 100, 10) plt.imshow(data, cmap='jet', interpolation='nearest') plt.xticks(labels) plt.yticks(labels) plt.show() however, gives following figure: how can achieve figure appearance first one, axis labels second one? define axes , modify xticklabels, not axis itself. this: fig, ax1 = plt.subplots(1,1) data = np.random.randint(0, 100, size=(10, 10)) ax1.imshow(data, cmap='jet', interpolation='nearest

How to Create a folder in external sdcard in Android 4.4.2(Kitkat) API level 19 -

i try lot create folder in sd card in android 4.4.2 version. try following code string dirname="test"; file file = new file(environment.getexternalstoragedirectory(), dirname); boolean status = file.mkdir(); if (status) toast.maketext(mainactivity.this, "directory created successfully", toast.length_short) .show(); else toast.maketext(mainactivity.this, "directory create failed", toast.length_short).show(); but creates folder in internal storage. and try code is string path=system.getenv("secondary_storage"); file file=new file(path +"/test123"); file.mkdir(); it creates folder in external sdcard in android 4.1 not in android 4.4.2 so how can create folder in external sdcard in andro

ssl - Google Maps iFrame Embed Mixed Content -

can't seem find answer 1 in searches. apparently, google maps available via ssl, still loads insecure content/assets. i'm trying find fix this. <iframe src="https://www.google.com/maps/d/embed?mid=z6wx5r5bs180.knlguyxhh1tc" height="550"></iframe> if talking about: loading mixed (insecure) display content " http://www.gstatic.com/gmeviewer/images/no_results-000.png " on secure page it has been reported (yesterday, oct 21 2015) google team: https://productforums.google.com/forum/#!topic/maps/d2bbvr-aola and said fixed: sha mymaps team said: it fixed in few days.

osx - sublime text not opening from command line tmux -

i have sublime text alias can call terminal on macos. since started using tmux, running following command opens sublime not on current directory. it's aliases not accepting arguments on tmux. subl . without tmux command works fine. any known issue tmux alias arguments? this answer superuser did trick me. brew install reattach-to-user-namespace and append following ~/.tmux.conf set-option -g default-command "reattach-to-user-namespace -l zsh" lastly, source config file tmux tmux source ~/.tmux.conf i use subl . time! it's shame you've trained not use helpful command.

oop - PHP taking variable from a class to another page -

i newbie @ php oop.so have problem. i have user class, want control if there member id or nickname.but page want control if user exists, cant reach $query. this staff class php file public static function info($id = null, $nick = null){ if($id){ $query = mysql_query("select * staff yetkili_id = '$id' "); }elseif($nick) { $query = mysql_query("select * staff yetkili_nick = '$nick'"); } if(mysql_num_rows($query) > 0){ return $query; } } and page want take info of user <?php staff::info(1); $row = mysql_fetch_array($query); print_r($row); ?> and error warning: mysql_fetch_array(): supplied argument not valid mysql result resource in c:\appserv\www\oneriyor\admin\login.php on line 3 i dont know solution.if can me guys appreciate. as @frederico says, have variable scope misunderstanding. your $query inside function. can use inside. try move &quo

On Android Drawer Two icons Appear on ActionBar, Need Only One Icon -

Image
i implementing navigation drawer in android app. problem 2 icons appear on actionbar. have added actionbardrawertoggle , seems second icon displayed actionbardrawertoggle. please tell me error in code. please tell me wheat error. and here complete code package com.example.newdrawer; import android.os.bundle; import android.app.activity; import android.content.res.configuration; import android.support.v4.app.actionbardrawertoggle; import android.support.v4.widget.drawerlayout; import android.view.menu; import android.view.menuitem; import android.view.view; import android.widget.adapterview; import android.widget.arrayadapter; import android.widget.listview; import android.widget.toast; public class mainactivity extends activity { drawerlayout mdrawerlayout; actionbardrawertoggle mactionbardrawertoggle; listview listview; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview

java - Display data fromSQLite in TableLayout -

please me...i'm new android development , trying retrieve sqlite data tablelayout . program retrieve information belongs name , display in tablelayout . when click button in workdetailstable.java , crashed. displaydata.java public class displaydata extends appcompatactivity { tablelayout table_layout; infoapi sqlcon; public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.displaydata); mydatabasehelper db=new mydatabasehelper(this); infoapi i1=new infoapi(this); sqlcon=new infoapi(this); setrequestedorientation(activityinfo.screen_orientation_landscape); table_layout = (tablelayout) findviewbyid(r.id.tablelayout1); final string name1 = getintent().getextras().getstring("name"); // pass workdetailstable.java toast.maketext(getapplicationcontext(), name1, toast.length_short).show(); if (name1.equals("x x x"))

android - Did Google places API have information about nearby Restaurant menus? -

i want make app foodpanda. have searched lot how foodpanda gettinng menu of different restaurants did't find helpful. question "did google places api provide restaurants menu or foodpanda have own database?" any appreciated. in advance. the google places api not provide menu information. e.g. place details documentation google places api web service shows opening_hours , reviews fields, nothing menus.

ios - Search Bar in a table view -

i have tableview application searchbar showing array list of groceries. after search made user click on grocery , send second tableview. working fine, problem is: in next (second) table view information grocery searchbar still there , keyboard well. how can dismiss keyboard , searchbar should not appear in second table view. more welcome :) // dictionarytableviewcontroller.swift import uikit class dictionarytableviewcontroller: uitableviewcontroller, uisearchresultsupdating { var searchcontroller:uisearchcontroller! var searchresults:[dictionary] = [] var dictionaries:[dictionary] =[ dictionary (word: "grocery1", definition: "this grocery1 definition"), dictionary (word: "grocery2", definition: "this grocery2 definition"), dictionary (word: "grocery3", definition: "this grocery3 definition"), dictionary (word: "grocery4", definition: &q

caching - Add cache headers to all new assets in a Google Cloud bucket -

i know it's possible add cache headers existing google cloud bucket objects. gsutil setmeta -h "content-type:text/html" \ -h "cache-control:public, max-age=3600" \ -h "content-disposition" gs://bucket/*.html https://cloud.google.com/storage/docs/gsutil/commands/setmeta this works existing files in bucket newly uploaded file not have these caching headers. how tell google add header every new file added bucket? fwiw: using carrierwave fog in rails guess has nothing question.

C Borland Compiler Error -

back basics borland c compiler. keep getting following message , driving me crazy cannot find semi colon should go or why expected >bcc32 -v- -w -o1 oddeven.c borland c++ 5.5.1 win32 copyright (c) 1993, 2000 borland oddeven.c: error e2378 oddeven.c 16: statement missing ; in function main() *** 1 errors in compile *** >exit code: 1 here code, in advance /* program check if given integer between 1 , 100 odd or date: 09/10/2015 */ #include <stdio.h> main() { int input; printf("\nplease enter number between 1 , 100\n"); scanf("%d", &input); printf("\nyou entered %d\n", input); //for loop used error handling for(input > 0 && input < 101) { if(input <= 0 && input > 100) { printf("error!! please enter number between 1 , 100"); }//end if 1 //modulo 2 check divisibility if(inp

database - SQL Server Trigger using IF statements -

how go writing trigger when insertion particular table has been made, checks attribute based on condition , append text attribute. how go implementing if logic this? create table sometable ( table_id number(5) not null paragraph varchar(50) ); create trigger append_text on sometable after insert begin /*pseudocode: if table_id = 5 append text "mark watney" paragraph*/ end go you need create instead of insert trigger : create trigger append_text on sometable instead of insert begin insert sometable select table_id, paragraph + case when table_id = 5 ' mark watney' else '' end inserted end go