Posts

Showing posts from March, 2011

Can't restart mysql local server -

yesterday, local sql server crashed, , after trying restarting it, had typical error showing me permission problem. trying fix it, made kinda worse. still have permission problem, don't know how fix it. that's after mysql restart: mysqld: can't find file: './mysql/plugin.frm' (errno: 13 - permission denied) 2015-04-26 12:48:32 1663 [error] can't open mysql.plugin table. please run mysql_upgrade create it. 2015-04-26 12:48:32 1663 [note] innodb: using atomics ref count buffer pool pages 2015-04-26 12:48:32 1663 [note] innodb: innodb memory heap disabled 2015-04-26 12:48:32 1663 [note] innodb: mutexes , rw_locks use gcc atomic builtins 2015-04-26 12:48:32 1663 [note] innodb: memory barrier not used 2015-04-26 12:48:32 1663 [note] innodb: compressed tables use zlib 1.2.3 2015-04-26 12:48:32 1663 [note] innodb: using cpu crc32 instructions 2015-04-26 12:48:32 1663 [note] innodb: initializing buffer pool, size = 128.0m 2015-04-26 12:48:32 1663 [note] innodb:

java - How to get the id of a button in a listview -

i have customized widget textview , button. list view contains list of customized widget. want know on button there clicked. in facebook each post has react button , when click on go specific page. use below code create custom list. can create holder class hold button , textview object. helpful detect button click using holder class. class myadpter extends arrayadapter { int layout; arraylist<data> arr; context con; public myadpter(context context, int textviewresourceid, arraylist<data> objects) { super(context, textviewresourceid, objects); layout=textviewresourceid; arr= objects; con=context; // todo auto-generated constructor stub } @override public view getview(int position, view convertview, viewgroup parent) { // todo auto-generated method stub fi

mysql - PHP- How to get URL on user click in iFrame showing another website -

i using iframe in application, in website shown (bbc news). on website users can login. after user logs in want track urls specific user visits in iframe , store these urls mysql database. since mentioned bbc, i'm assuming iframe loading cross domain therefore not possible ( http://en.wikipedia.org/wiki/same-origin_policy ). can detect mouse entering iframe, , unreliably, leaving it. a way around proxy content of iframe locally server. there can insert sort of tracking code or use function similar top.parentfunction(); returns reference parent of current window or subframe.

csv - Python Error; UnicodeEncodeError: 'ascii' codec can't encode character u'\u2026' -

i trying extract data json file contains tweets , write csv. file contains kinds of characters, i'm guessing why error message: unicodeencodeerror: 'ascii' codec can't encode character u'\u2026' i guess have convert output utf-8 before writing csv file, have not been able that. have found similar questions here on stackoverflow, not i've not been able adapt solutions problem (i should add not familiar python. i'm social scientist, not programmer) import csv import json fieldnames = ['id', 'text'] open('my_source_file', 'r') f, open('my_output', 'a') out: writer = csv.dictwriter( out, fieldnames=fieldnames, delimiter=',', quoting=csv.quote_all) line in f: tweet = json.loads(line) user = tweet['user'] output = { 'text': tweet['text'], 'id': tweet['id'], } wr

xcode - Count from 100 to 1 with a different interval -

i'm trying make countdown in swift not rely on specific time, time interval choose. example want countdown 100-99 take approximately 4 hours. possible in way? you can use nstimer run specific task after given time , specify whether or not want repeat itself. method you're looking scheduledtimerwithtimeinterval . example, please @ this post . for more informations, please @ apple's nstimer class reference , section titled scheduling timers in run loops .

java - Activity with fragment who can take two differents fragments and rotation of device -

i'm new android, java, ... , new fragment. have activity (a) shows list using fragment (b). selecting item of list, same fragment changed show lis using fragment (c). works except when rotate device while shows second list (c). when shown first list (b), if rotate device, works perfectly. error logcat: 04-26 11:30:32.769: e/androidruntime(2882): fatal exception: main 04-26 11:30:32.769: e/androidruntime(2882): java.lang.runtimeexception: unable start activity componentinfo{com.example.traffic/com.example.traffic.listtriplines}: android.support.v4.app.fragment$instantiationexception: unable instantiate fragment com.example.traffic.listpoints: make sure class name exists, public, , has empty constructor public (...) 04-26 11:30:32.769: e/androidruntime(2882): caused by: android.support.v4.app.fragment$instantiationexception: unable instantiate fragment com.example.traffic.listpoints: make sure class name exists, public, , has empty constructor public (...) 04-

Why won't my program work in python? -

hi 11 yrs old , teaching myself how code. set myself task make times table quiz asks 10 questions , inputs random numbers. however, code not working , not know why. using python 2.7.5. code: print("here quiz test knowledge") print("") print("question 1") import random print random.randint(1,10) print ("times") import random print random.randint(1,10) answer = raw_input ("make choice: ") if answer == ran1*ran2: print "that correct" correct=correct +1 else: print "that incorrect!" i can not spot why not working have not put loop in yet asks 1 question. when run else highlighted in red not know why. python works without brackets. replaced "spaces or tabs". , import once, beginning. this should work import random print("here quiz test knowledge") print("") print("question 1") print random.randint(1,10) print ("times") print random.randint(1,10) ans

logic - How to prove the mutual equivalence of peirce, classic, excluded_middle, de_morgan_not_and_not and implies_to_or without using intuition in coq -

i simplified proof procedure of mutual equivalence of peirce, classic, excluded_middle, de_morgan_not_and_not , implies_to_or written in git@github.com:b-rich/sf.git following. theorem excluded_middle_irrefutable: forall (p:prop), ~ ~ (p \/ ~ p). proof. intros. unfold not. intros. apply h. right. intros. apply h. left. apply h0. qed. definition peirce := forall p q: prop, ((p->q)->p)->p. definition classic := forall p : prop, ~~p -> p. definition excluded_middle := forall p : prop, p \/ ~p. definition de_morgan_not_and_not := forall p q: prop, ~(~p /\ ~q) -> p\/q. definition implies_to_or := forall p q: prop, (p->q) -> (~p\/q). theorem peirce_classic : peirce -> classic. proof. compute. intros. specialize (h p false). apply h. intros. apply h. contradiction h0. qed. theorem classic_excluded_middle : classic -> excluded_middle. proof. compute. intros. apply h. intros. apply h0. right.

design patterns - Difference between Layers and Pipes and filters? -

what difference between these 2 design patterns? seems similar me, 1 processing unit (layer or filter) data procession , pull / push data processing unit. unit n communicates n+1 , n-1 unit, there interfaces defining functionality 1 particular unit offers. what difference? edit: maybe 1 difference should data flow. in layers flow can top-down , bottom-up and/or communication between layers inside. in pipes , filters data flow starts @ unit 1 , goes unit n (not back). organization wise may looks both layers , pipe , filters patters similar (one component taking input , passing result another) functionally not. architectural patterns. if go definition : pipes , filters pattern divide larger processing task sequence of smaller, independent processing steps (filters) connected channels (pipes). while in layer pattern, each layer communicates adjacent layers , responsible processing of own, passing requests layer below , answering requests layer above it. co

java - Why in JVM Integer is stored as byte and short? -

Image
here 1 snippet of code public class classifier { public static void main(string[] args) { integer x = -127;//this uses bipush integer y = 127;//this use bipush integer z= -129;//this use sipush integer p=32767;//maximum range of short still sipush integer = 128; // use sipush integer b = 129786;// invokes virtual method integer class } } here partial byte code of stack=1, locals=7, args_size=1 0: bipush -127 2: invokestatic #16 // method java/lang/integer.valueo f:(i)ljava/lang/integer; 5: astore_1 6: bipush 127 8: invokestatic #16 // method java/lang/integer.valueo f:(i)ljava/lang/integer; 11: astore_2 12: sipush -129 15: invokestatic #16 // method java/lang/integer.valueo f:(i)ljava/lang/integer; 18: astore_3 19: sipush 32767 22: invokes

R nls function and starting values -

Image
i'm wondering how can find/choose starting values nls function i'm getting errors put in. want confirm can use nls function data set. data [1] 108 128 93 96 107 126 105 137 78 117 111 131 106 123 112 90 79 106 120 [20] 91 100 103 112 138 61 57 97 100 95 92 78 week = (1:31) > data.fit = nls(data~m*(((p+q)^2/p)*exp((p+q)*week)/(1+(q/p)*exp(-(p+q)*week))^2), start=c(m=?, p=?, q=?)) if change function bit , use nls2 starting values can converge. model using is: log(data) = .lin1 + .lin2 * log((exp((p+q)*week)/(1+(q/p)*exp(-(p+q)*week))^2))) +error in model .lin1 = log(m*(((p+q)^2/p)) , when .lin2=1 reduces model in question (except multiplicative rather additive error , fact parameterization different when appropriately reduced gives same predictions). 4 parameter rather 3 parameter model. the linear parameters .lin1 , .lin2. using algorithm = "plinear" not require starting values these parameters. rhs of plinear formulas sp

javascript - How to centrally align text in HTML canvas? -

i making small javascript game when ran small issue: text not centrally aligned. simple example: var txt="lorem ipsum"; context.filltext(txt,100,100); now problem beginning of text @ point 100,100. later when change value of txt longer sentence, still drawn staring 100,100 , reducing aesthetic appeal of program. my question is, there way draw text in such way coordinates given mark center of text , not beginning? you can use textalign: context.textalign = "center";

pcap - How to analyse packet infromation from a traffic dump file in C++? -

i write c console program due dump network traffic "pcap" library. want packet information (e.g. protocol-type, sender-ip, etc) binary file. my code : #include "stdafx.h" #include <pcap.h> #include <stdio.h> #include <stdlib.h> #include <errno.h> #ifndef win32 #include <sys/socket.h> #include <netinet/in.h> #else #include <winsock.h> #endif #define line_len 16 void dispatcher_handler(u_char *, const struct pcap_pkthdr *, const u_char *); int main(int argc, char **argv) { pcap_t *fp; char errbuf[pcap_errbuf_size]; char source[pcap_buf_size]; if(argc != 2){ printf("usage: %s filename", argv[0]); return -1; } /* create source string according new winpcap syntax */ if(pcap_createsrcstr(source, // variable keep source string pcap_src_file, // want open file null, // remote host null, // port on remote host

javascript - Before Html 5 validation trigger event? -

this question has answer here: an invalid form control name='' not focusable 25 answers i have html 5 form input elements contains required constraint. user can view form in edit or view mode. means, hiding input controls if form in view mode , showing span instead. there submit button. whenever user click submit button , form in view mode get, an invalid form control name='' not focusable. i tried show form in edit mode during form submit event getting error prior submit event invocation. how fix error? there event before validation happens? per user2909164 's answer in question , adding novalidate attribute form should fix issue: <form name="myform" novalidate>

c# - how to pass information from one class to another -

i using function take states of both classes how should generate function, right i'm doing if((b1.fxmin>s.xmin&&s.ymin==b1.fymax)&&b1.fxmin<s.xmax&&s.ymin==b1.fymax)) { collides=true; b1.isfiring=false; } else if((b1.fxmin>s1.xmin&&s1.ymin==b1.fymax)&&b1.fxmin<s1.xmax&&s1.ymin==b1.fymax)) { collides1=true; b1.isfiring=false; } in project bullet hit spider , if collides spider vanish, b1 object of class bullet , s1 , s spiders. i have 7 spiders in game , have created 7 collides variable , 7 if statements means when ever increase spider need add collide variable , if statement i tried in bullet class couldn't succeed. how should pass spider object bullet class? you can pass spider bullet class follows: // bullet.h class spider; class bullet { ... bool iscolliding(const spider &s); } // bullet.cpp #include "spider.h" // or whatever header you'

python - OOP - organising big classes -

i starting write big python library area of mathematics. so have data structure (defined in class a) represents mathematical model. i have bunch of smaller functions, have put in a: a.f(), a.g(),... which more or less "helper functions" needed calculate more important functions a.x(), a.y(),... end user interested in. all of these functions of course depend on data in a. but number of methods in growing , growing , getting confusing. how 1 split such class smaller pieces. lets say, data structure basic operations in , "methods" calculations on structure? what usual approach , pythonic approach? you can use pure functional approach , move methods class users not supposed call on object instance separate files. in pure functional approach functions don't depend on internal state, have no side effects , calculate return value based on arguments provided. an example illustration replacing following: # shape.py class shape: def

sql server 2008 - Using case max date() does not return all parent rows -

hi following query not return projects , stores. shows store has @ least 1 status date filled. how can projects projects table , stores stores table , show status date stores (wherever filled). select projectname,store, max(case when activity = 'visited' date else null end) visited, max(case when activity = 'notvisited' date else null end) notvisited, max(case when activity = 'finished' date else null end) finished table1 t inner join project p on t.projectid = p.projectid inner join store s on t.storeid = s.storeid inner join activity on t.activityid = a.activityid group projectname,store

c# - XAML using radio buttons to enable and disable textbox with databinding -

i trying figure out how enable , disable textboxes radio buttons , data binding. seems should able bind textbox isenabled boolean , modify value can't quite work. want have several sets of radio buttons , textboxes want generic way handle problem. tried use converter since not using x:names not sure helpful in case. can them enable/disable radio buttons not want do. code shows solution trying first textbox. xaml code <grid> <stackpanel> <radiobutton groupname="grp1" content="enable textbox" isenabled="{binding bttn1, mode=twoway}" ischecked="{binding bttn1}" checked="radiobutton_checked" unchecked="radiobutton_unchecked" /> <radiobutton groupname="grp1" content="disable textbox" isenabled="{binding bttn2}" /> <textbox isenabled="{binding txtbx1, mode=twoway}" bindinggroup="{binding grp1}" ></text

sql server - Write Sql Query -

we have table 3 columns ( name_of_office , month , amount ), below: name_of_office month amount ------------------------------------ divisionbhopal 04 125 divisionbhopal 05 50 divisionbhopal 06 100 divisionbhopal 10 125 divisionsagar 04 600 divisionsagar 05 520 divisionsagar 06 400 divisionsagar 10 100 financial year month should used calculation. by formula start sum april selected month. suppose user select month of june (from dropdown) calculation should performed this name_of_office sum upto previous month present month total amount ----------------------------------------------------------------------------------------- divisionbhopa april + may june april + may+ june divisionsagar april + may june april + may+ june here not add oct amount because selected month june want data

c# - Convert Sql query to linq contains conditional OrderBy / ThenBy clause -

tablea contains list of recent items user has accessed, user has option pin/remove list. what trying list has order below query. select * tablea order ispinned desc, case when ispinned = 1 date end asc, case when ispinned = 0 date end desc but in linq fails. have tried below. _lst = _lst.orderbydescending( x => x.ispinned).thenbydescending(x=>x.accessdate).tolist(); . _lst = (from data in _lst orderby data.ispinned, data.ispinned ? data.date : data.date descending select data ).tolist(); try: _lst = _lst.orderbydescending(x => x.ispinned) .thenby(x=> x.ispinned ? x.accessdate.ticks : x.accessdate.ticks * -1 ) .tolist();

javascript - Call ajax from dynamic generated tag and fetch value from ajax -

i have fetched data ajax like update var = document.createelement('a'); a.setattribute('id', tr_job_room); a.setattribute('onclick', 'getgroupsdata(this.id)'); var audiolength; var ul_ul_li_a = document.createelement('a'); ul_ul_li_a.setattribute('class', 'dropdown-toggle'); ul_ul_li_a.setattribute('href', '#'); ul_ul_li_a.innerhtml = "audios"; ul_ul_li_a.setattribute('id', tr_job_room); if (audiolength > 0) { alert("audiolength"+audiolength); $(ul_ul_li_a).on('click', function () { alert(audiolength+"sdasds"); varid = this.id; audiosplay(varid); scriptpanel(); gettxtdata(); }); } and ajax is: // display groups data function getgroupsdata(arg) { $.ajax( { type: "post", url: '@url.action("getgroupsdata")', datatype: "json",

javascript - Cordova Android Back button event doesnt fire -

it doesn't fire! tried everything. funny thing menu button works fine: //... //if (isdevice) { document.addeventlistener("deviceready", ondeviceready, false); //} //... function ondeviceready() { document.addeventlistener("backbutton", onbackkeydown, false); document.addeventlistener("menubutton", onmenukeydown, false); //document.addeventlistener("searchbutton", onmenukeydown, false); } function onbackkeydown() { alert('doesnt work!'); } function onmenukeydown() { alert('works fine!'); } and although i'm in doubt believe working earlier week! :/ idea what's going on? bug? appreciate in advance, thx, mim cordova -v: 4.3.0 tested on: android 4.2.2 updating cordova, android sdk , build tools resolved problem completely! guess way cordova build works bit messy! looks pulls repositories everytime regardless of compatibility other dependencies (even own version) although prob

c# - Unity Game Engine Crashing When Trying To Update The Vertex Positions Of A Mesh In Real Time Using A Script -

so in unity i’ve created script generates plane mesh made of triangles. plane has 400 vertices (20x20 grid) 361 squares made of 2 triangles comprising 3 vertices each (2166 indices). mentioned vertices, indices , normals set in start() function vertices being loaded vector3 array called vertices, indices being loaded array of single floats , normals being loaded array of vector3. these assigned mesh (representing plane) int start() function so: mesh.vertices = vertices; mesh.triangles = triangles; mesh.normals = normals; in update() function function called calculates new positions every single vertex in plane mesh (400): void update () { updatemesh (); mesh.vertices = vertices; } with updatemesh function looking this: void updatemesh() { //this function update position of each vertex in

Multiple readers in spring batch -

i have requirement implement in spring batch,i need read file , db ,the data needs processed , written email i have gone through spring batch documentation unable find chunktasklet read data multiple readers so have read 2 different sources of data(one file , db,each need have own mapper) regards tar i see 2 options depending on how data structured: spring batch relies heavily on composition when building batch components. 1 option create custom composite itemreader delegates other readers (ones spring batch provides or otherwise) , provides logic assemble single object based on results of delegated itemreader s. you use itemreader provide base information (say database) , use , itemprocessor enrich item (say reading file). either of above normal ways handle type of input scenario.

ruby - Rails returning all of second level association -

i have 3 models interested in: region, seat , user. region has many seats , seats have many available users. i'd know efficient way in rails retrieve of available users seats sit under particular region. thanks in advance. try: user.joins(seat: :region).where(regions: { id: region_id_here })

How should I declare global variables in my C++ project? -

i have 2 matrices global variables. however, when run project, apache mach-o linker error in xcode says global variables declared more once. i've determined problem placement of global variables , imports of header files. my svd.h here: #ifndef __netflix_project__svd__ #define __netflix_project__svd__ #include <stdio.h> #include "datamanager.h" const float global_avg_set1 = 3.608609; const float global_avg_set2 = 3.608859; const int total_users = 458293; const int total_movies = 17770; double **user_feature_table = new double *[total_users]; double **movie_feature_table = new double *[total_movies]; void initialize(int num_features); void train(); double predictrating(int user, int movie); #endif /* defined(__netflix_project__svd__) */ my svd.cpp here: #include "svd.h" void initialize(int num_features) { for(int = 0; < total_users; i++) { user_feature_table[i] = new double[num_features]; for(int k = 0; k

php - Echoing an array using json_encode -

using javascript application making server side request search functionality. works queries, not others. for queries request returns no response, despite fact testing query in workbench returns thousands of records. tried turning on errors - no errors generated. tried increasing memory limit - that's not culprit. tried output pdo errors/warnings - nothing generated, pdo returns records, verified using var_dump, shown below. so conclude, in below code, seems work flawlessly, until final line responsible encoding array json object - echos nothing. i appreciate assistance in resolving this. php error_reporting(e_all); ini_set('display_errors', 1); ini_set('memory_limit', '2048m'); $db = new pdo('mysql:host=localhost;dbname=mydb', 'root', ''); $search = $_get['search']; $searchby = ( isset($_get['searchby']) && !empty($_get['searchby']) ) ? $_get['searchby'] : 'name'; $s

exception - Python error pop up not working -

writing code , broke somehow , can't remember working, been using python few weeks , after working on literally day, i'm more little frustrated... # program calculate delivery order totals graphics import * #error window def errorwindow(): errwin = graphwin("error", 200, 200) errwin.setcoords(0.0, 0.0, 4.0, 4.0) errwin.setbackground(color_rgb(33,158,87)) text(point(2, 3), "this not valid order").draw(errwin) text(point(2, 2.5), "please try again").draw(errwin) outline = rectangle(point(1.5,1), point(2.5,2)) outline.setfill('white') outline.draw(errwin) okbutton = text(point(2,1.5),"ok") okbutton.draw(errwin) done=errwin.getmouse() if (done.getx() > 1.5 , done.getx() < 2.5): errwin.close() def main(): win = graphwin("brandi's bagel house", 500, 500) win.setcoords(0.0, 0.0, 10.0, 10.0) win.setbackground(color_rgb(33,158,87)) #banner banner = rectangle(point(0, 8), point(10, 10))

c - Program Priority on Lubuntu -

given single processor virtual machine running lubuntu, wondering if possible tie processor no other program can run instructions. example, if program , program b run @ same time, possible set priority of program (in source using setpriority() function) run before program b , tie processor program b cannot execute? with right priviliges possible call 'sched_setscheduler' give process real time priority. such process not interrupted ordinary processes or other real time processes lower priority. such real time processes lose cpu when give doing call sleep or waiting io. given cpu able work again , cpu not needed real time process higher priority.

pandas - Unable to call value_counts on a new column -

i created new column in dataset so: df['new_col'] = [ true if v > 0 else false v in df.old_col ] when call value_counts() on new column, works when do df['new_col'].value_counts() # works fine but df.new_col.value_counts() gives error: attributeerror: 'list' object has no attribute 'value_counts' i'm pretty confused why happens...can not use dot syntax on new columns? advice appreciated, thanks! as noted alexander, looks you've set attribute rather new series. must assign new column using bracket notation: in [11]: df = pd.dataframe([[1, 2], [3, 4]], columns=['a', 'b']) in [12]: df['c'] = [1, 2] in [13]: type(df.c) out[13]: pandas.core.series.series without assigning attribute (and pandas doesn't know want column): in [14]: df.d = [1, 2] in [15]: type(df.d) out[15]: list you can't access attribute using bracket notation: in [16]: df['d'] keyerror: 'd'

c - How to read -1 char from stdin? -

i desperate trying figure out how can read char value -1/255 because functions means eof. example if enter characters extended ascii low high (decimal value) end -1/255 eof not array. created small code express problem. #include <stdio.h> #include <string.h> #include <stdlib.h> #define buffersize 1024 int main(void){ char c; unsigned int *array = (unsigned int*)calloc(buffersize,sizeof(unsigned int)), = 0; while (1){ c = fgetc(stdin); if (c == eof) break; array[i] = c; i++; } array[i] = 0; unsigned char *string = (unsigned char *)malloc(i); for(int j = 0;j < i;j++) string[j] = array[j]; free(array); //working "string" return 0; } i mode if (c == eof) break; like this c = fgetc(stdin); array[i] = c; i++; if (c == eof) break; but ofcourse, program read control character user input keyboard (for example ctrl+d - linux). tried opening stdin binary found out posix systems carries files binary. using qt, gcc

c# - Why does my floating point value have an `E` character when I convert it to a string? -

txtdebuglog.invoke(new methodinvoker(delegate() { fps.frame(); ggg = fps.getfps(); txtdebuglog.text = string.format("{0}\r\n{1}", ggg, txtdebuglog.text); }) txtdebuglog textbox. using breakpoint see on ggg in example it's value is: 0.00000102593151 then click on continue , see in textbox : 1.025932e-06 your floating point value ggg has small value. when convert string, happens in call string.format("{0}\r\n{1}", ggg, txtdebuglog.text); it converted string uses exponential format represent value. can read exponential format is, referred scientific notation, here . if want use different format, have specify yourself. many standard formats available, can explicitly specify when doing conversion. conversion of double string using specific format can done calling double.tostring(format) method. several standard formats available , listed there, including output them. the default format used if not specify one, gene

New to Firebase, have a few questions about custom user auth and storing data on Android. -

i'm implementing firebase in android app , have few questions. 1) i'll using custom auth , docs perform token generation on "secure server", because secret exposed. mean it's not safe within login activity class, or secure? 2) i'll sending several required values database upon registration (username, password, etc). done this... var token = tokengenerator.createtoken( {uid: "custom:1", username: "string", password: "string"}); ? if so, how securely store passwords? 3) i'll saving images database, of quite large (iphone 6 , galaxy s6 take ridiculous pictures). fine store byte[], along other info image (uploader, data, etc)? or there better way it? sorry long post, want make sure know i'm doing before diving in :) 1) i'll using custom auth , docs perform token generation on "secure server", because secret exposed. mean it's not safe within login activity class, or secur

javascript - How to add Backbone Model global function -

i need add function models, can´t how recognize model "this" scope variable. function model can reseted defaults , data-object parameter: backbone.model.prototype.reset = function( data ){ this.set(this.defaults); $.each( data, function( key, value ){ this.set( key, value ); }); } your code seems legit. value of this defined @ runtime , depends on how call method. if use modelinstance.reset() value of this modelinstance . however, mutating prototype of 3rd party considered bad practice should avoided. better practice create abstract model , have of model implement it. it like: var abstracrtmodel = backbone.model.extend({ reset: function (data, options) { this.clear(options); this.set(_.defaults({}, data || {}, this.defaults || {}), options); } }); the api of model.set permits passing data hash, don't need inner loop.

android - Can a write to remote DB operation be in a separate aynchronous thread? (Delphi) -

delphi xe8. mobile application running on ios , android storing data local sqllite db. background thread transfer data local db remote enterprise database using rest. wondering if operation of sending data remote database server using rest can asynchronously execute in thread of own, or thread need synchronized main ui thread? background data transfer thread have no interactions with, or dependency on, main ui. read committed records local db (which have been written main ui thread) , make rest operations write remote database. here example, how create separate service, use need, using thread. delphi , android services here source code delphi xe7 delphi xe7 source code

rails f.submit checking another table -

i understand in form_for, i'm able validate form's table in model, if wanted validate "f.submit"ted data against table? specifically, staff can checkout radio in checkout model/table if both staff , radio exists in own respective tables. how go passing in staff , radio table checkout validation criteria? thanks! forms in rails not linked validation (not in same way symfony2) display error messages. you can nest resources in forms fields_for used accepts_nested_attributes_for . <%= form_for(@member) |f| %> <%= f.text_field(:name) %> <%= fields_for :avatar, @member.avatar |avatar_fields| %> <%= avatar_fields.text :url %> <% end %> <% end %> class member < activerecord::base has_one :avatar accepts_nested_attributes_for :avatar end you can create validation model association validates_associated or passing validates: true when declaring association. see this question details. class m

c++ cx - Disable open up menu on Space/Enter in Xaml -

i have bottom menu bar. unknown reason, when pressing enter/space button, default behavior commands shown or first action executed, depending on state extremely undesirable handling key events entire page . tried setting istabstop="false" not help. there way eliminate baked-in behavior? <page.bottomappbar> <commandbar istabstop="false" closeddisplaymode="minimal"> <!-- buttons --> </commandbar> </page.bottomappbar>

lua - In trepl or luajit, how can I find the source code of a library I'm using? -

let's i'm working lua library installed using luarocks, , want see definition of function library. in ipython in use ??function_name to see definition in terminal, in matlab use which function_name then use editor @ path returned which. how similar find function definition lua library? in 'plain' lua/jit, can debug.getinfo ( func ) , table containing (among others) fields short_src , source , linedefined . for lua functions, short_src filename or stdin if defined in repl. ( source has different format, filenames prefixed @ , = prefix used c functions or stuff defined interactively, , load ed functions, actual string loaded.) you can pack in function like function sourceof( f ) local info = debug.getinfo( f, "s" ) return info.short_src, info.linedefined end or maybe start editor , point there, e.g. (for vim) function viewsource( f ) -- info & check it's file local info = debug.

angularjs - Referencing local angular.js does not work -

i'm beginning work angularjs , having trouble working local copy of angular.js file. below sample trying work. when reference cdn script, page correctly displays 'hello, world'. when reference local script, binding not occur. browser able locate local angular.js file, doesn't seem perform binding. <html ng-app> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.4/angular.js"></script> <!--<script src="scripts/angular.js"></script>--> <script> function hellocontroller($scope) { $scope.greeting = { text: "hello" }; } </script> </head> <body> <div ng-controller="hellocontroller"> <p>{{greeting.text}}, world</p> </div> </body> </html> if starting out 1.3.15 this: <html ng-app="main.app">

javascript - Knex.js insert from select -

i'm trying generate query following via knex.js: insert table` ("column1", "column2") select "someval", 12345) not exists ( select 1 table "column2" = 12345 ) basically, want insert values if particular value not exist. knex.js doesn't seem know how this; if call knex.insert() (with no values), generates "insert default values" query. i tried following: pg.insert() .into(tablename) .select(_.values(data)) .wherenotexists( pg.select(1) .from(tablename) .where(blah) ); but still gives me default values thing. tried adding .columns(object.keys(data)) in hopes insert() honor that, no luck. is possible generate query want knex, or have build raw query, without knex.js methods? i believe select needs passed insert: pg.insert(knex.select().from("tablenametosel

arrays - random move tic tac toe in c -

alright, i'm new @ coding in c , have lot of copy , paste in code. (it's final project, don't have time optimize , shorten until end if time permits). anyway, i'm gonna avoid posting code reason. i'm gonna post relevant part i'm trying do. i need game pick random number 1-9 , use number select move on board. added printf in part of code make sure number being picked, when go scanf, game gives blinking prompt , not continue. does see wrong or need post other section of code? appreciated!! have included 1 player portion of game , when computer supposed move. removed win checks , re printing of board. let me know if guys need see else didn't want have huge block of code. if (player == 1) { for(k=0;k<9;k++) // 9 moves max. { printf("\n\n"); // print board again. printf(" %c | %c | %c\n", board[0][0], board[0][1], board[0][2]); printf("---+---+---\n"); printf(" %c

javascript - Truncate <a> tag text -

Image
in below code i'm attempting truncate <a> tag text : <a href='test'> <script> truncate("truncate text"); </script> </a>   function truncate(string){ if (string.length > 5) return string.substring(0,5)+'...'; else return string; }; https://jsfiddle.net/fcq6o4lz/6/ but returns error uncaught referenceerror: truncate not defined how can function invoked within <a> tag ? why the reason error because computer hasn't run code defined truncate yet. function running before page finishes loading, includes javascript. put code in window.onload settimeout safe. window.onload = function(){settimeout(function () { truncate("truncate text"); },1);}; how also, unlike languages such php. return won't place text. like: <a id="result-location" href='test'> <script> window.onload = function