Posts

Showing posts from February, 2014

c# - OneDrive SDK Demo itemNotFound Error -

i trying demo onedrive sdk provided mvc application, here source: github onedrive-webhooks-aspnet . having trouble running app. the problem happens after sign in, line in file "controllers/subscriptioncontroller" throws onedriveexception: var appfolder = await client.drive.special["approot"].request().getasync(); the errocode "itemnotfound" , errormessage "the application id not exist." in exception. search on found little. there issue in git space author answered own question blaming onedrive broken. i hope here @ stackoverflow can me it, much. ok, turned out simple configuration mistake. in web.config appsettings section, value of "ida:msascopes" "files.readwrite", while current onedrive api permission should "onedrive.readwrite". i new api, guess api updated after sample written. after all, hope may others have problem, , general, don't trust default values much.

sql server - What Registration Properties are needed to get Database Workbench up and running? -

i database workbench fan way back, bizarrely have not used quite awhile. i downloaded trial version , trying "register server" first step. the problem don't know use properties. need know: alias host instance "use sql server authentication" checked: username password i've tried guess way through needed where, nothing has worked. i can connect database in (c#) code connection string: "server=platypussql42;database=duckbilldata;uid=youinnocentdog;pwd=contrasena;connection timeout=0"; and have tried these values: alias: dbwbsqlserver host: platypussql42 instance: duckbilldata username: youinnocentdog password:contrasena ..and this: alias: platypussql42 host: duckbilldata instance: username: youinnocentdog password:contrasena ...but both of them, get, " [dbnetlib][connectionopen (connect()).]specified sql server not found. " what values needed? the instance not database in server connecting to.

mysql - SQL query with two different ids -

i need prevent photo_order field exceeding number of photos being associated article. have this, doesn't work. table name has been used 2 times , wrong. update articles_photos set photo_order = if(photo_order < (select count(id) articles_photos article_id = 12), photo_order + 1, 1) id = 26 how can fix above query? database mysql. i assume error getting: you can't specify target table 'articles_photos' update in clause here's 1 work around using cross join subquery: update articles_photos ap cross join (select count(id) cnt articles_photos article_id = 12) temp set ap.photo_order = if(ap.photo_order<temp.cnt,ap.photo_order+1,1) ap.id = 26; sql fiddle demo

c++ - field initializer is not constant g++ 4.8.4 -

i tried compile following code on laptop, using g++ 4.8.4: #include <algorithm> #include <iostream> #include <initializer_list> #include <tuple> struct storage { static const int num_spatial_subset = 8; static constexpr std::initializer_list<std::initializer_list<double>> vectors{ {0,0,0}, {0,1,0}, {0,0,1}, {1,1,0}, {1,0,1}, {0,1,1}, {1,0,0}, {1,1,1} }; double storage[num_spatial_subset][vectors.size()]; }; int main() { } and got error message: error: field initializer not constant constexpr std::initializer_list< std::initializer_list<double> > vectors{ {0,0,0}, {0,1,0}, {0,0,1}, {1,1,0}, {1,0,1}, {0,1,1}, {1,0,0}, {1,1,1} }; however, copy/paste same code on coliru (g++ 6.1.0), same compilation parameters , worked. can tells me wrong please ? thank you. actually, pointed out chris , baum, updating g++ 4.9 fixed it.

python - Can a Django application authenticate with MySQL using its linux user? -

the company work starting development of django business application use mysql database engine. i'm looking way keep having database credentials stored in plain-text config file. i'm coming windows/iis background vhost can impersonate existing windows/ad user, , use credentials authenticate ms sql server. as example: if django application running apache2+mod_python on ubuntu server, sane add "www-data" user mysql , let mysql verify credentials using pam module? hopefully of makes sense. in advance! mysql controls access tables own list of users, it's better create mysql users permissions. might want create roles instead of users don't have many manage: admin, read/write role, read-only role, etc. a django application runs web server user. change "impersonate" ubuntu user, if user deleted? leave "www-data" , manage database role way.

performance - Matlab: How to speed up integration (int) for computing Arc lengths? -

as part of code build geometry meshing, calculating 2d arc lengths integration. below sample code that: fun=@(ss)integral(@(t)sqrt((r0+a1*cos(1*t)+a2*cos(2*t)+a3*cos(3*t)+a4*cos(4*t)+a5*cos(5*t)+a6*cos(6*t)+a7*cos(7*t)+a8*cos(8*t)).^2 ... + (-a1*1*sin(1*t)-a2*2*sin(2*t)-a3*3*sin(3*t)-a4*4*sin(4*t)-a5*5*sin(5*t)-a6*6*sin(6*t)-a7*7*sin(7*t)-a8*8*sin(8*t)).^2),0,ss); integration on 't' , other parameters constant (i.e. r0, a1, etc) but integration takes long time, , since try many different geometries great if can find way around speed integration takes bit long. how can compute same integral in more quicker way?

javascript - Angular http$ response for text/plain file download fails with SyntaxError: Unexpected number in JSON -

i have implemented download file feature on angular-based client , node.js backend based on following solution: https://stackoverflow.com/a/20904398/1503142 . in general works, receive "syntaxerror: unexpected number in json @ position x" combined "typeerror: cannot read propery 'messages' of undefined". a few observations: everything appears working on node server-side, because response @ client. error in question reported client; no errors reported server. the log file consists of time stamp, basic log information text. text contains ascii characters using postman, response works every time, lends idea http$ code might having issue response. postman's response header information indicates response content-type->text/plain; charset=utf-8. i using angularjs v1.2.21 , node v0.12.13 here's client-side code: $http({ method: 'get', url: "/api/logging/logfiles/" + logfile, headers: { 'content-type'

forms - DJANGO Generic Views: How to use reverse() in get_absolute_url method? -

i'm trying implement generic editing views shown here : i started createview renders , submits data correctly. however, getting error when tries use reverse() return detail view page new object. here error message: noreversematch @ /work/clients/create/ reverse 'clientdetailview' arguments '('14',)' , keyword arguments '{}' not found. 0 pattern(s) tried: [] here how defined get_absolute_url() in model: def get_absolute_url(self): return reverse('clientdetailview', kwargs={'pk': self.pk}) my view called clientdetailview. i'm not sure other information helpful. here class clientdetailview: class clientdetailview(generic.detailview): model = client template_name = 'work/client_detail.html'` and here url() urls.py: url(r'^clients/(?p<pk>[0-9]+)/$', views.clientdetailview.as_view(), name='clients_detail'),` can explain doing wrong? i solved own prob

android - Java String operation - Writing efficient code -

first of all, not experienced java developer. problem sql query give return data abc bcd def efg . but, want add , after every entry so, tried this if (cursor != null) { cursor.movetofirst(); { if (cursor.getposition() == 0) { getname = cursor.getstring(cursor.getcolumnindexorthrow("name")); } else { getname = getname + "," + cursor.getstring(cursor.getcolumnindexorthrow("name")); } } while (cursor.movetonext()); } my question is okay or there way write code efficiently(like achiving same goal writing less line of code). thank you. how this: mystring = "abc bcd def efg"; string newstring = mystring.replace(" ", ", "); system.out.println(newstring); output: abc, bcd, def, efg

What does ":" mean when using bindValue() in PHP PDO? -

what : mean before id in example below? necessary? $sth->bindvalue(':id', $id, pdo::param_int); can :id variable? if pdo::param_int not necessary, why need use it? :id named placeholder prepared query. somewhere else in code there's query along lines of: select stuff id = :id that gets run through pdo's prepare function. if pdo::param_int not necessary, why need use it? safety / data consistency. see pdo::param_int important in bindparam?

java - Spring Data JPA - case insensitive query w/ pattern matching -

suppose i'm implementing search functionality simple cms package (just example), , want match posts both title , content . presumably, have sort of post entity following underlying table structure: +------------------------------------+ | post | +---------+--------------+-----------+ | post_id | integer | not null, | | title | varchar(255) | not null, | | content | clob | not null | +---------+--------------+-----------+ next, extend spring's jparepository , add search method via @query annotation, (again, example): public interface postrepository extends jparepository<post, integer> { @query("select p post p lower(p.title) lower(%:searchterm%)" + " or lower(p.content) lower(%:searchterm%) order p.title") list<post> findbysearchterm(@param("searchterm") string searchterm); } the problem spring (or maybe it's underlying jpa provider, not sure) has ha

path - Switching between python/jython implementations from dos -

so downloaded jython2.7 , have python2.7 (managed anaconda) primary interpreter. ide's totally fine switching between them, want able run pip cli different implementations without having change path variable hand every time. i'm wondering if it's possible make virtualenv contains jython, or if there other way switch between them inside terminal.

Pivot Charts in google Sheets by counting non-numeric data? -

i have dataset i'd summarize in chart form. there 30 categories counts i'd display in bar chart 300+ responses. think pivot table best way this, when create pivot table , select multiple columns, each new column added gets entered sub-set of previous column. data looks following id country age thinga thingb thingc thingd thinge thingf 1 5-9 thb thd thf 2 fi 5-9 tha thf 3 ga 5-9 tha thf 4 10-14 thc 5 10-14 thb thf 6 15-18 7 br 5-9 tha 8 15-18 t

rx java - Convert one type of list to another RXJava? (Javascript map equivalent) -

lets have observable observable<list<a>> , want convert observable observable<list<b>> . there best possible way convert list<a> list<b> . javascript's map 's implementation ideal situation. you can use observable.from(iterable<a>) observable<a> , map (a => b), , convert list<b> observable.tolist() observable.from(arrays.aslist(1, 2, 3)) .map(val -> mapinttostring(val)).tolist() e.g. observable.from(arrays.aslist(1, 2, 3)) .map(val -> val + "mapped").tolist() .toblocking().subscribe(system.out::println); yields [1mapped, 2mapped, 3mapped]

xamarin.forms - custom View Cell in listview having only button clickable -

Image
i want create viewcell stacklayout containing frame border each row. frame contains labels , 1 button. on button click have change screen. i find issue when render code on ios simulator , found out on selection of rows i.e. viewcell, grays out , show blurred selected row looks ugly. tried disable view cell solved row selection issue disabled button click on row part of it. i requires button enabled , available click , rest of part on viewcell should not clickable or available select. have use frame border purpose. provides rounded border suggest me solution can use in place of frame borders well. screenshot: <listview x:name="lstview" rowheight="150" separatorvisibility="none" ispulltorefreshenabled="false" > <listview.itemtemplate> <datatemplate> <viewcell> <stacklayout padding="10,10,10,10"> <frame outlinecolor="silver"> <gri

android - Error while using fragment manager -

package com.c2.layoutsdemo; import java.util.arraylist; import android.app.activity; import android.app.fragmentmanager; import android.os.bundle; import android.widget.arrayadapter; public class todolistactivity extends activity implements newitemfragment.onnewitemaddedlistener { also if make arraylist , addar adapter final per example, additional errors regarding initialization of arraylist. arraylist<string> todoitems; arrayadapter<string> aa; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_to_do_list); fragmentmanager fm= getfragmentmanager(); todolistfragment todolistfragment = (todolistfragment)fm.findfragmentbyid(r.layout.todolistfragment); the above line gives error : todolistfragment cannot resolved or not field todoitems = new arraylist<string>(); aa = new arrayadapter<string>(this,android.r.layout.simp

string - Capitalizing words in (Python)? -

this question has answer here: why doesn't calling python string method unless assign output? 1 answer i trying write capitalize each word in sentence. , works fine, follows: print " ".join((word.capitalize() word in raw_input().strip().split(" "))) if input 'hello world', output : hello world but tried writing differently follows : s = raw_input().strip().split(' ') word in s: word.capitalize() print ' '.join(s) and output wrong : hello world so what's wrong that, why result isn't same ?! thank you. the problem in code strings immutable , trying mutate it. if wont work loop have create new variable. s = raw_input().strip().split(' ') new_s = '' word in s: new_s += s.capitalize() print new_s or, work if use enumerate iterate on list , update s : s =

windows - Access desktop application UI -

this os dependant here goes: windows 7/8/10 i'd able access desktop application ui application (that i've written). i'd able pass mouse , keyboard inputs application external one. is possible , if so, start? there windows api can with? i know can use microsoft detours api hook direct3d applications/games, not sure regular desktop applications.

java - Number of inversions in array -

i trying find out number of inversion in array. have applied mergesort. , when merging sub arrays counted number if value of right subarray less value of left sub array. code not work if array contains lot of data. private static long getnumberofinversions(int[] a, int[] b, int left, int right) { long numberofinversions = 0; if (right > left) { int ave = (left + right) / 2; numberofinversions = getnumberofinversions(a, b, left, ave); numberofinversions += getnumberofinversions(a, b, ave + 1, right); numberofinversions += merge(a, b, left, ave + 1, right); } return numberofinversions; } public static long merge(int[] a, int b[], int left, int ave, int rigth) { int = 0, j = left, k = ave; long count = 0; while (j <= ave - 1 && k <= rigth) { if (a[j] <= a[k]) { b[i] = a[j]; i++; j++; } else {

ruby - create table rows of 4 in rails -

i have these checkboxes, i'm trying create rows of 4 checkboxes. @ moment creates 1 row. <table> <%= f.collection_check_boxes :expertise_ids, expertise.all, :id, :name |b| %> <td> <label style="margin-left:5px; margin-right:15px;" class="checkbox-inline"> <%= b.check_box %> <%= b.label %> </label> </td> <% end %> </table> iv have tried this: <table> <%= f.collection_check_boxes :expertise_ids, expertise.all, :id, :name |b| %> <% tablerows = 0 %> <td> <label style="margin-left:5px; margin-right:15px;" class="checkbox-inline"> <%= b.check_box %> <%= b.label %> <% tablerows += 1 %> <% break if tablerows == 3 %> </label> </td> <% end %> </table> im trying iterate

python - How to select or highlight all items in a QTreeWidget? -

Image
i'm trying build context menu user can right-click on qtreewidget , select items. you can use qtreeview.selectall() after setting selection mode allows multiple selection (using qabstractitemview.setselectionmode() ). example (in pyqt4 use qtgui instead of qtwidgets): from pyqt5 import qtwidgets app = qtwidgets.qapplication([]) widget = qtwidgets.qtreewidget() widget.addtoplevelitems([qtwidgets.qtreewidgetitem(['dog']), qtwidgets.qtreewidgetitem(['car'])]) widget.setselectionmode(qtwidgets.qabstractitemview.contiguousselection) widget.selectall() widget.show() app.exec_() and looks like:

Symfony3 return array from query to json -

i have problem, can't return posts array json becouse symfony returns array entity object? its code: public function indexaction() { $em = $this->getdoctrine()->getmanager(); $posts = $em->getrepository('appbundle:post')->findall(); return $this->json($posts); } i use $this->json return json data, feature added on sf3. result: [ {}, {}, {} ] i want load posts. ps. know, can use query builder, , method toarray or something, method use , dry? thx a best solution enable serializer component in symfony: #app/config/config.yml framework: serializer: ~ note: serializer component disabled default, have uncomment config line in app/config/config.yml file.

android - what if LocationListener.onLocationChanged is not called? -

in android app, making use of google play's location services determining device location.so implementing com.google.android.gms.location.locationlistener's onlocationchanged method. based on device's location settings, possible method not called.for eg, if user has set 'device only' option gps based location access available,and if user indoor gps wont work , onlocationchanged() not called. i want know how come know of @ run time alternate action can suggested user? from document itself, locationlistener used receiving notifications locationmanager when location has changed. these methods called if locationlistener has been registered location manager service using requestlocationupdates(string, long, float, locationlistener) method. also check blog understand more locationlistener in android. explains here status , behavior of gps , sample code serve guide you. hope helps know more locationlistener

android - Restrict dynamically added views from overlapping each other in relative layout -

i have relativelayout consisting button this button add text views cand dragged , dropped when clicked my problem how prevent these textvies overlapping each other when dragged , dropped on 1 another dynamic adding , dragging of textviews said looks this my main activity public class mainactivity extends activity { relativelayout droplayoutnew; button addtext; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.main); droplayoutnew = (relativelayout) findviewbyid(r.id.edtxtlayout); droplayoutnew.setondraglistener(new mydraglistener()); addtext = (button) findviewbyid(r.id.mainbutton1); addtext.setonclicklistener(new mybuttonclicklistener()); } } my clicklistener public class mybuttonclicklistener implements onclicklistener { @override public void onclick(view v) { viewgroup relativeparent = (viewgroup) v.getparent(); customedittext edttxt = new c

c++ - How to construct eigen matrix of size 1000* 1000 -

i trying construct matrix of size 1000*1000 in eigen library. tried documentation still confused. have basic knowledge of cpp. i tried following. know not right nice if complete code below int size = 1000; matrixxd a(size); matrixxd b(size); (int = 2; < size; i++ ){ a(i) = (rand()%10+1) + ((double) rand() / (rand_max)); b(i) = (rand()%10+1) + ((double) rand() / (rand_max)); } a static matrix 1000 rows , 1000 columns: eigen::matrix<double, 1000, 1000> thematrix; matrixxd dynamic variant, 1 can change number of rows and/or columns @ runtime. dynamic matrix use: eigen::matrixxd thematrix(1000,1000);

c - Does POSIX if.h require a library to use -

does using posix header file #include <net/if.h> require library linked aswell? below error when use constant header file. error: ifnamsiz undeclared #include <net/if.h> int main(int argc, char** argv) { char f[ifnamsiz]; // compiler error return 0; } if need library, whats name of it? gcc -o test test.c -lif --std=c11 not valid library. googling turning nothing quite frustrating. *ps: how find out libraries posix header requires? solution: problem because compiling --std=c11 . question describes problem , solution: why c99 complain storage sizes? from quick google , seems name defined if_namesize , not ifnamsiz . the error getting not missing library*, missing definition @ compiler step, means header file not define ifnamsiz . *) if library issue, you'd see linker errors 'missing external symbol' messages.

c# - How to update a bound combo box after updates are made to database -

i have sql server express database containing medication info. have created windows form display info on selected medication. combobox on form bound db using following: string sqlquery = "select * meds"; cmd = new sqlcommand(sqlquery, conn); sqlda.selectcommand = cmd; sqlda.fill(medsdt); cbomeds.datasource = medsdt; cbomeds.displaymember = "medname"; cbomeds.valuemember = "id"; the form has textbox ("adjamt") allows user change quantity ("supply") of selected med entering new quantity , clicking on "change" button. the database updated following code: sqlcommand cmdupdate = new sqlcommand(); string cmdtxt = "update meds set supply = '"; cmdtxt += adjamt.tostring() + "' id = '"; cmdtxt += lblid.text.tostring() + "';"; cmdupdate.commandtext = cmdtxt; cmdupdate.connection = conn; cmdupdate.executenonquery(); at point working designed, e.g. database updated. after

python selenium send_keys CONTROL, 'c' not copying actual text -

i highlight section in web page, send_keys, .send_keys(keys.control, "c") , not place intended text copy in clipboard, last thing manually copied in clipboard: from selenium import webdriver selenium.webdriver.common.keys import keys driver = webdriver.firefox() driver.get("http://www.somesite.com") driver.find_element_by_id("some id").send_keys(keys.control, "a") #this highlights section need copy elem.send_keys(keys.control, "c") # not copy text** i tried using firefox edit menu select , copy text, didn't work either , cant find online assist other possible mention of bug (tried old version of firefox, didn't solve issue). ideas?

php - how to convert this Slim Framework code into Laravel 5.2 -

// makes insert 2 tables in db. $app->post('/create_order', 'authenticate', function() use($app) { // check required params verifyrequiredparams(array('oder_data')); global $user_id; $oder_data = $app->request->post('oder_data'); $db = new dbhandler(); $id_client=$user_id; $response = array(); //parsing json array $json_a=json_decode($oder_data,true); if (!$json_a=="") { $order_type=$json_a["order_type"]; $id_reservation=$json_a["id_reservation"]; $id_order = $db->createorder($id_client, $order_type, $id_reservation); $hh=$json_a['data']; foreach($json_a['data'] $p) { $id_dish=$p['id_dish']; $amount=$p['amount']; $description=$p['description']; $note=$p['note']; $result = $db

javascript - How to `update` new value choosing from `select box` on click save button? -

how update new value choosing select box on click save button. i using ng-click function in js function update button: $scope.updatedealdetail = function updatedealdetail (){ $scope.showeditview = !$scope.showeditview; $scope.dealdetail.decisionmakerdetail.email = $scope.selectedid; } my function edit button: $scope.edituserdetail = function edituserdetail(){ $scope.showeditview = !$scope.showeditview; $scope.showsubmitview = !$scope.showsubmitview; deal.getiddata($scope.accountdetail. accountusers[0].role,$scope.accountdetail.id).then(function successcb(data){ $scope.editidoptionsdata=data; $scope.selectedid = $scope.editidoptionsdata[0].email; }); }; and html bitton click : <select ng-model="selectedid" class="form-control"> <option ng-selected="selectedid" ng-repeat="eiod in editidoptionsdata" value="{{eiod.email}}">{{eiod.email}}

How to change the element of array in swift -

Image
i'm having difficulty function: func sort(source: array<int>!) -> array<int>! { source[0] = 1 ...... return source } an error happens: why can't directly assign value specific element in array? the variable sort immutable because it's parameter. need create mutable instance. also, there's no reason have parameter , return value implicitly unwrapped optionals ! operator. func sort(source: array<int>) -> array<int> { var anothersource = source // mutable version anothersource[0] = 1 ...... return anothersource }

python - What does CPython actually do when "=" is performed on primitive type variables? -

for instance: a = some_process_that_generates_integer_result() b = someone told me b , a point same chunk of integer object, b modify reference count of object. code executed in function pyobject* ast2obj_expr(void* _o) in python-ast.c : static pyobject* ast2obj_object(void *o) { if (!o) o = py_none; py_incref((pyobject*)o); return (pyobject*)o; } ...... case num_kind: result = pytype_genericnew(num_type, null, null); if (!result) goto failed; value = ast2obj_object(o->v.num.n); if (!value) goto failed; if (pyobject_setattrstring(result, "n", value) == -1) goto failed; py_decref(value); break; however, think modifying reference count without ownership change futile. expect each variable holding primitive values (floats, integers, etc.) have own value, instead of referring same object. and in execution of simple test code, found break point in above num_kind branch never reached: def some_fun

reactjs - Why the scoping of this keyword is invalid in JSX but works in ES6? (Lexical this vs arrow functions) -

i have react component below. why this not defined when changenametwo called? see jsbin: http://jsbin.com/nuhedateru/edit?js,output then why works in typical es6 class? see jsbin: http://jsbin.com/kiyijuqiha/edit?js,output class helloworldcomponent extends react.component { constructor(props) { super(props); this.state = { name : 'yolo' } } changename = () => { this.setstate({name: 'another yolo'}); } changenametwo() { this.setstate({name: 'another yolo'}); } render() { return ( <div> <h1>hello {this.props.name}</h1> <p>name: {this.state.name}</p> <button onclick={this.changename}>change name</button> <button onclick={this.changenametwo}>change name 2</button> </div> ); } } react.render( <helloworldcomponent name="es2015/es6"/>, document.getelementbyid('react_ex

c# - Azure IoT Hub - Device Registration in portable library -

i need use microsoft.azure.devices in .net portable library found microsoft.azure.devices.client.pcl nuget package part of functionality no microsoft.azure.devices code bellow. - need register new device / find if there existing retrieve device key - there way inside portable library? registrymanager = registrymanager.createfromconnectionstring(connectionstring); device = await registrymanager.adddeviceasync(new device(deviceid)); no, don't believe there @ time. looked @ package, there no pcl in there. don't see why cant made nuget package can called pcl. can building bait , switch package support specific scenario. the code iot client available here under mit license , can repackage work scenario can called pcl.

html - Bootstrap hidden-sm-down not working -

i using boostrap 3. why <div> hidden-sm-down still visible when resize page on laptop? want hide 2 images on small devices in order have different menu. <div class="row"> <div class="col-md-7 left"> <ul class="row"> <li class="col-md-2"> <a href="">text</a> </li> <li class="col-md-2"> <a href="">text</a> </li> <li class="col-md-3"> <a href="">text</a> </li> <li class="col-md-3"> <a href="">text</a> </li> <li class="col-md-2"> <a href="">text</a> </li> </ul> </div&

javascript - manipulating json data and simple for statement -

if i'm getting data array var data = {"answer":"ok","data":[["marco","123"],["john","44245"],["wayne","645464"]]} how can inside loop iterate trough them , print inside console coresponding values marco 123 john 44254, .. marco - 123 john - 44245, ... (var = 0; < data.length; i++) { } data key of data object.you need first retrieve value of data.data return array. loop through each of these array elements values. var data = {"answer":"ok", "data":[["marco","123"],["john","44245"],["wayne","645464"]] } var getdata = data.data; //data key array getdata.foreach(function(item){ item.foreach(function(inneritem){ console.log(inneritem) }) }) jsfiddle

Center Android Wallpaper -

Image
i'm trying make app changes system wallpaper. in code image has desired minimum dimensions (from wallpapermanager). example on nexus 1 desired minimum dimensions 884x800. when image andset wallpaper automatically "left aligns" can see left side of 884x800 image (the nexus one's screen res 480x800). is there way can set wallpaper "centered"? i setting wallpaper this: wallpapermanager wallpapermanager = wallpapermanager.getinstance(getapplicationcontext()); try { wallpapermanager.setbitmap(bitmap); } catch (ioexception e) { log.e("error", e.tostring()); } note: if image 480x800 blows can see top left corner when wallpaper. here example of image 884x800: here example of looks when set wallpaper: here example of looks when use 480x800 image: have tried switch between virtual home screens? aren't @ leftmost virtual home screen?

javascript - Shadow dom Input element loses focus at keyboard event -

i using customized hotkeys chrome web browser through extension. while developing new chrome extension myself, text input inside shadow dom loses focus when type customized hotkeys. there anyway make text input inside shadow dom not lose focus?

html - Bootstrap <form> height -

i attempting have form on website using bootstrap framework, going fine except fact bootstrap doesn't seem calculating form's height. have footer right after form, in separate div tag, when view output in browser, footer covers half of form. it's bootstrap doesn't give form div automatic height. code: https://jsfiddle.net/w2s61lfo/ **the form last element in wrapper , footer last of body. sorry messy css, write messy , go , clean it. output: http://imgur.com/zoau1ik i can't post images yet, sorry!! thanks! your sticky footer correct. bootstrap columns usage wrong... bootstrap uses container wrapper div control width of content part , provide gutter around content. col-xs- , col-sm- etc., - these floating elements widths in percentage. since these divs floated, correct heights calculated when has "row" around it. row - has clearfix ( css clear) specified in it. col-* height can calculated you must have row around columns

mysql - Can a query only use one index per table? -

i have query this: ( select * mytable author_id = ? , seen null ) union ( select * mytable author_id = ? , date_time > ? ) also have these 2 indexes: (author_id, seen) (author_id, date_time) i read somewhere: a query can use 1 index per table when process where clause as see in query, there 2 separated where clause. want know, "only 1 index per table" means query can use 1 of 2 indexes or can use 1 of indexes each subquery , both indexes useful? in other word, sentence true? "always 1 of index used, , other 1 useless" that statement using 1 index no longer true mysql. instance, implements index merge optimization can take advantage of 2 indexes where clauses have or . here description in documentation. you should try form of query , see if uses index mer: select * mytable author_id = ? , (seen null or date_time > ? ); this should more efficient union version, because not incur overhead of removing duplicates.

Angular 2 two way data binding with ngModel -

first off new typescript , angular 2 , seems obvious answer can't seem work. have following model export interface ibrand { brandid: number; name: string; image: string; } then have component class import { component, oninit } '@angular/core'; import { router, routeparams } '@angular/router-deprecated' import { bootstrap } '@angular/platform-browser-dynamic'; import { ibrand } './brand'; import { brandservice } './brand.service'; @component({ selector: 'data-bind', templateurl: 'app/dashboardapp/brands/brand-list.component.html', styleurls: ['app/dashboardapp/brands/brand-list.component.css'] }) export class brandlistcomponent implements oninit { brands: ibrand[]; errormessage: string; newbrand: ibrand; pagetitle: string = 'brands'; constructor(private _brandservice: brandservice, private _router: router) { } ngoninit(): void {

ios - Create a new Realm -

i've used realm.io long time ago, you'd create or fetch existing realm passing string key (could or without.realm). now i'm building app realm.io in swift. can't seem figure out how create new realm. in docs saw realm passing realm.configuration object has fileurl , readonly proprty (true or false). anyways, touch empty file? or how can create new realm? this have, named string must dynamic in case: let config = realm.configuration( fileurl: nsbundle.mainbundle().urlforresource(named, withextension: "realm"), readonly: true ) return try! realm(configuration: config) are trying create new realm or open existing 1 readonly access? if want create new realm can use default realm this: let realm = try! realm() you can specify custom path realm should created, see more in docs . also note realm produces files when open it, it's not idea open inside app's bundle directory. see this question if want have pre-populated rea

matlab - Increase amount of a variable in Simulink -

Image
i'm working on car counting project. i'm stuck counting cars substracting previous detected car value current one. i've tried memory block previous detected car value. however, not count cars properly. returns 0, 1,255,254. edit: after uint8 block, detected car number 8 bit unsigned integer goes through.

sql - Reusing query/subquery results to assign multiple outputs depending on a column value -

i want assign 4 output values based on specific status of column, while counting how many occurrences of there are. for example select @somevariable =(select count(*) r table join table 2 t2 on r.id= t2.id getdate() between t2.start , t2.end ) adding statement such , t2.status="somestatus" works, way have to same query eachdifferent status have, possible reuse query or somehow sub query assignment of output variables based on t2.status just in case code example bit messed (just writing memory), trying do, count how many columns there particular status , fits in time frame. i've done need, having multiple queries in stored procedure, don't want keep way. you can write query single select : select @somevariable = count(*) table join table 2 t2 on r.id = t2.id getdate() between t2.start , t2.end; you can add more variables easily: select @somevariable = count(*), @somevariable2 = sum(case when t2.statu

jquery - Concatenate pseudo & class variable -

i'm using viewport selectors jquery plugin, , trying perform same task on few elements: $('#something').each(function(){ var current = $(this); if ($(this + ':in-viewport')){ console.log(current.attr('id')); } }); am doing horribly wrong? error console spitting out: uncaught error: syntax error, unrecognized expression: [object htmldivelement]:in-viewport you're concatenating this object :in-viewport string , , object being converted tostring , result [object htmldivelement]:in-viewport , illegal jquery selector . i think you're looking this: $('#something').each(function(){ var current = $(this); if ($(this).is(':in-viewport')) { console.log(current.attr('id')); } }); or in better version of specific code: $('#something:in-viewport').each(function(){ console.log($(this).attr('id')); });

mysql - How I can determine the time between dates with php and mysl? -

i want determine how time elapsed between dates, have different tables have initial time example [2016-05-28] , [13:36:42] , other time [2016-05-31] , [09:05:18] i want know, how can determine time elapsed, in case have "two days 20 hours" the language using php, mysql, framework , angularjs, recommendable side make it simple php code: <?php $dates = ['2016-05-12 05:33:02','2016-07-17 05:00:12']; $time_diff = strtotime($dates[0]) - strtotime($dates[1]); $time_diff<0?$time_diff*=-1:null; print floor($time_diff/86400) . ' days ' . floor(($time_diff % 86400) / 3600) . ' hours ' . floor(($time_diff % 3600) / 60) . ' minutes'; ?> prints: 65 days 23 hours 27 minutes

Submiting Javascript Form and Scrap with Python -

Image
i have following html/javascript code in website. represents website 2 fields: a) name="n": field mark "v" letter; b) name="id" input number max 8 characters. <tr> <td> <form name="form" method="post" action="javascript:buscar(document.form.n.value, document.form.id.value)"> <table class="aux"> <tr> <td> <select name="n" class="form"> <option value="v">v</option> </select> </td> <td> <input name="id" type="text" class="form" maxlength="8" size="8" value="id" onfocus="javascript:clear_textbox3();" onblur="javascript:valid(document.form.id);"/> </td> </tr> <tr> <td> <input type=&

Send Object as Parameter from View to Asp.net Controller with AngularJS -

i'm trying pass category object parameter of subcategory object asp.net controller. .net controller sets subcategory.supercategory object null. subcategoryobject: public class subcategory { [key] [databasegenerated(databasegeneratedoption.identity)] public int id { get; set; } public string name { get; set; } [required] public category supercategory { get; set; } } here asp.net controller: public void createsubcategory([frombody]subcategory subcategory) { system.diagnostics.debug.writeline("supercategoryname: " + subcategory.supercategory.name); } this angularjs function: $scope.savedatasubcategory = function (subcategory) { $http.post('/aaangular/createsubcategory', { name: subcategory.name, supercategory: {id: subcategory.supercategory.id, name: subcategory.supercategory.name } }) .then(function successcallback(response) { console.log(response); } , function errorcallback(response) {

javascript - Cannot Parse JSON for PhoneGap App -

i've been trying parse json phonegap app dynamically generated localstorage variable. php doing it's job, javascript isn't parsing data , displaying. my php: header("access-control-allow-origin: *"); header('content-type: application/json; charset=utf-8'); include("conn.php"); // user id $email = $_get['email']; $useridinit="select userid users email='".$email."'"; $useridgrab=mysql_query($useridinit) or die(mysql_error()); $useridq = mysql_fetch_array($useridgrab); $userid = $useridq['userid']; $data = array(); $q = mysql_query("select * msg_trans left join msg_master on msg_trans.msgid=msg_master.msgid left join users on msg_master.fromid=users.userid msg_trans.toid='".$userid."' order msg_trans.status desc"); while ($row=mysql_fetch_object($q)){ $data[]=$row; } echo json_encode($data); my js: var email = localstorage.getitem('email'); var url

java - Passing Class and Method as parameter -

i looking out way pass class , method both parameters method. have repetitive piece of code want reduce. i want this: public static void methodname(class c, method m ) { c.m.sendkeys("item"); } is possible? in java 8 can use method references passed lambda; methodname(c::m); you need specify type (arguments , return value) of function , use 1 of existing functional interfaces or define own. if example function returns boolean , takes object of class t input, can use predefined functional interface predicate : public static void methodname(item item, predicate<item> p) { p.test(item); // ... }

ruby - Testing Create method from controller -

i looking test create method in controller, checking validations , flash messages set correctly. have far is it 'is invalid invalid formatted email' @message = message.new(factorygirl.attributes_for(:message_invalid_email)) @message.valid? expect(@message.errors[:email].first).to eq("don't forget add email address") end but have seen others setup test like @message = post :create, message: { params1: value1 } what difference here , how should testing this? and when try , test flash success has been set (using shoulda gem) it 'is valid correct parameters' @message = message.new(factorygirl.attributes_for(:valid_message)) expect(@message).to be_valid expect(controller).to set_flash[:success] end i error expected flash[:success] set, no flash set this controller def create @message = message.new(message_params) respond_to |format| if @message.valid? format.js { flash.now[:success] = "thanks message, i

javascript - Use invert in an object with many entries -

i trying reverse keys/values. so , trying like: var _ = require('underscore'); var myobj = [ {'name': 'mike', 'number' : 'b1' , 'level' : 0 }, {'name': 'tom', 'number' : 'b2' , 'level' : 0 } ]; object.keys(myobj).foreach(function(k) { _.invert(myobj[k]); }); console.log(myobj); so, want receive: {'mike': 'name', 'b1' : 'number' , '0' : level }, {'tom': 'name', 'b2' : 'number' , '0' : level } but above gives me again initial object. this should want: var result = _.map(myobj, _.invert);

sql server - SQL Compare varchar variable with another varchar variable -

i have table name lines has billid (int) , linereference (varchar(100) 2 columns. each billid has linereference value. however, value in linereference might not correct. have validate linereference variable has has correct reference value based on bill id. example : declare @icountref varchar(100) = 1,2,3 billid linereference 100 1,2, 100 1,2,40,34 100 1 100 12 from above table, need update linereference column. billid linereference 100 1,2 100 1,2 100 1 100 1 i able update comparing variable : @icountref. linereference column should have values in @icountref. whatever values not there in @countref should removed. if there no matching values,then column should updated atleast number 1. --create temp table , inserting data: declare @billsrefs table ( billid int, linereference nvarchar(100) ) insert @billsrefs values (100, '1,2,'), (100, '1,2,40,34'), (100, '1'), (100,

android - send data from activity to activity class and between them fragment -

Image
my app show activity(1) .when press button ,app open fragment .after , fragment send data activity (2) , open activity (2) -that works well- . ,activity(2) edit data , send activity(1) -here problem- . i have tried many ways doesn't work when working complex screens multiple fragments , activities, recommend use event-driven library, like: eventbus otto rxjava it's going let transform this: into this: check this post detailed explanation use cases of these libraries.

javascript - Reading values from Json -

https://plnkr.co/edit/zvybaoutennkargifmky?p=preview i have added working fiddle.i want read size values flare.json file,saved in fiddle , find maximum , minimum size values. have tried using json.parse method in index.html not working.i beginner visualization. here's fork of plnkr: https://plnkr.co/edit/pxpeur2cgyzxvwswx9ef i initialized variables this: var minsize=infinity, maxsize=-infinity; and added these conditionals recurse function: if(node.size<minsize) minsize=node.size; if(node.size>maxsize) maxsize=node.size; i expect there better way this, , hope you'll share once find it.

c# - How can I protect WCF service from unauthorized access? -

edit: please note 2 things: application publicly available , users won't need have accounts . can suggest other solution wcf, if it's better. i'm developing application in c# install other applications easily. list of programs supported application stored on database on public server. only application should able access database. everyone can install application, , users do not need have accounts. now, i'm wondering how should communication between app , server like. i'm thinking of developing wcf service, can connect service (only program should access service). is there way protect wcf service unauthorized access? or maybe have better idea how should communication between app , server like? thanks in advance help! you can check below links in topic https://msdn.microsoft.com/en-us/library/ms731925.aspx https://msdn.microsoft.com/en-us/library/aa702565.aspx you can configure bindings perform username , password based authentication val

javascript - Live Sorting or Fitering a Model using Textbox in Ember -

i watching ember screencasts & stumbled upon autocomplete-widget. tried implement it's not working seems. i getting data using $.getjson , want filter using textbox. here's have tried, app = ember.application.create(); app.model = ember.object.extend({ }); app.indexroute = ember.route.extend({ redirect : function() { this.transitionto('users'); } }); app.userscontroller = ember.arraycontroller.extend({ filteredcontent : function() { var searchtext = this.get('searchtext'), regex = new regexp(searchtext, 'i'); return this.get('model').filter(function(item) { return regex.test(item.name); }); }.property('searchtext', 'model') }); app.users = app.model.extend({ id : "", name : "" }); app.usersroute = ember.route.extend({ model : function() { return app.users.findall(); }, setupcontroller : function(control

java - How to decompose my program into multiple methods? -

how decompose java program multiple methods? first stores string input, loops through extract of numbers array list. prints of these numbers along sum , product. public class assignment1 { public static void main(string[] args){ // creates scanner storing input string scanner numscanner = new scanner(system.in); string input; system.out.println("enter string of numbers compute sum , product:"); system.out.println("(enter '.' terminate program)"); input = numscanner.nextline(); // terminates program if there no input if (input.length() == 0){ system.out.println("invalid input: not enough characters"); system.exit(-1); } // terminates program if first character '.' if (input.charat(0) == '.'){ system.out.println("thank using numberscanner!"); system.exit(-1); } // defines of variables used in loops int index =