Friday 15 March 2013

java - Java8 dynamic proxy and default methods -



java - Java8 dynamic proxy and default methods -

having dynamic proxy interface default methods, how invoke default method? using defaultmethod.invoke(this, ...) proxy invocation handler called (which somehow correct, cause have no implementing class interface).

i have workaround using asm create class implementing interface , delegating such calls instance of class. not solution, if default method calls other interface methods (you delegator ping-pong). jls surprisingly silent question...

here little code example:

class="lang-java prettyprint-override">public class java8proxy implements invocationhandler { public interface withdefaultmethod { void somemethod(); default void somedefaultmethod() { system.out.println("default method invoked!"); } } @test public void invoketest() { withdefaultmethod proxy = (withdefaultmethod) proxy.newproxyinstance( withdefaultmethod.class.getclassloader(), new class<?>[] { withdefaultmethod.class }, this); proxy.somedefaultmethod(); } @override public object invoke(object proxy, method method, object[] args) throws throwable { // assuming not knowing interface before runtime (i wouldn't utilize // proxy, i?) // here line printed out? // loop // method.invoke(this, args); homecoming null; } }

you can utilize methodhandles type in invocationhandler.

if (method.isdefault()) { homecoming methodhandles.lookup() .in(method.getdeclaringclass()) .unreflectspecial(method, method.getdeclaringclass()) .bindto(proxy) .invokewitharguments(args); }

java java-8

dbunit - gradle test doesn't work well -



dbunit - gradle test doesn't work well -

when run test in intellij, works well, if run command line like

gradle test or gradle clean test

it rerurns java.io.filenotfoundexception

string file_path = "sample/src/test/resources/" idataset insertdataset = new flatxmldataset(new fileinputstream(file_path + "com/sample/mst.xml"));

project construction is:

testproject

sample src main test java com sample test.java resources com sample mst.xml wrong, should do?

you should alter file loading code to:

getclass().getclassloader().getresourceasstream("mst.xml")

gradle dbunit

sql - why does LIMIT 2 take orders of magnitude longer than LIMIT 1 in this query? -



sql - why does LIMIT 2 take orders of magnitude longer than LIMIT 1 in this query? -

i'm on postgresql 9.3. should reproduce on table 100,000+ rows. explain analyze shows many more rows getting scanned limit 2, can't figure out why.

limit 1:

explain analyze base of operations ( select *, row_number() on () rownum a_big_table ), filter ( select rownum, true thing base of operations ) select * base of operations left bring together filter using (rownum) filter.thing limit 1

result:

limit (cost=283512.19..283517.66 rows=1 width=2114) (actual time=0.019..0.019 rows=1 loops=1) cte base of operations -> windowagg (cost=0.00..188702.69 rows=4740475 width=101) (actual time=0.008..0.008 rows=1 loops=1) -> seq scan on a_big_table (cost=0.00..129446.75 rows=4740475 width=101) (actual time=0.003..0.003 rows=1 loops=1) cte filter -> cte scan on base of operations base_1 (cost=0.00..94809.50 rows=4740475 width=8) (actual time=0.000..0.000 rows=1 loops=1) -> nested loop (cost=0.00..307677626611.24 rows=56180269915 width=2114) (actual time=0.018..0.018 rows=1 loops=1) bring together filter: (base.rownum = filter.rownum) -> cte scan on base of operations (cost=0.00..94809.50 rows=4740475 width=2113) (actual time=0.011..0.011 rows=1 loops=1) -> cte scan on filter (cost=0.00..94809.50 rows=2370238 width=9) (actual time=0.002..0.002 rows=1 loops=1) filter: thing total runtime: 0.057 ms

limit 2:

explain analyze base of operations ( select *, row_number() on () rownum a_big_table ), filter ( select rownum, true thing base of operations ) select * base of operations left bring together filter using (rownum) filter.thing limit 2

result:

limit (cost=283512.19..283523.14 rows=2 width=2114) (actual time=0.018..14162.283 rows=2 loops=1) cte base of operations -> windowagg (cost=0.00..188702.69 rows=4740475 width=101) (actual time=0.008..4443.359 rows=4714243 loops=1) -> seq scan on a_big_table (cost=0.00..129446.75 rows=4740475 width=101) (actual time=0.002..1421.622 rows=4714243 loops=1) cte filter -> cte scan on base of operations base_1 (cost=0.00..94809.50 rows=4740475 width=8) (actual time=0.001..10214.684 rows=4714243 loops=1) -> nested loop (cost=0.00..307677626611.24 rows=56180269915 width=2114) (actual time=0.018..14162.280 rows=2 loops=1) bring together filter: (base.rownum = filter.rownum) rows removed bring together filter: 4714243 -> cte scan on base of operations (cost=0.00..94809.50 rows=4740475 width=2113) (actual time=0.011..0.028 rows=2 loops=1) -> cte scan on filter (cost=0.00..94809.50 rows=2370238 width=9) (actual time=0.009..6595.770 rows=2357122 loops=2) filter: thing total runtime: 14247.374 ms

engine first runs, limits. so, can see much more rows.

sql postgresql join common-table-expression window-functions

c# - Setting per request value for ServicePointManager.SecurityProtocol -



c# - Setting per request value for ServicePointManager.SecurityProtocol -

this question has reply here:

set securityprotocol (ssl3 or tls) on .net httpwebrequest per request 4 answers

in c# able set static value ssl3 or tls, e.g.

servicepointmanager.securityprotocol = securityprotocoltype.tls;

or:

servicepointmanager.securityprotocol = securityprotocoltype.ssl3;

but (i believe) impact future httpwebrequest objects in application.

is there way set given httpwebrequest or @ to the lowest degree given uri?

note have seen this:

uri uri = new uri(url); servicepoint sp = servicepointmanager.findservicepoint(uri);

but servicepoint not have securityprotocol property.

at nowadays thinking have set static global property prior creating new httpwebrequest.

this doesn't sense right , means:

i have create sure multiple threads not doing @ same time. i not sure point setting has been 'used' (i.e. when phone call webrequest.getresponse() servicepointmanager.securityprotocol accessed , bound uri?).

realised has been covered here:

how utilize ssl3 instead of tls in particular httpwebrequest?

and here:

set securityprotocol (ssl3 or tls) on .net httpwebrequest per request

confirming fears. users appear spinning separate app domain work around this. still think might possible thread locking if defined @ point setting bound particular web request object.

c# ssl httpwebrequest

Replying on the same thread in a mailing list using git send-email -



Replying on the same thread in a mailing list using git send-email -

i had submitted patch organisation's mailing list , need send revised version of patch on same thread using git send-email. have set chainreplyto value false. had tried earlier:

git send-email --no-chain-reply-to --to="mailing-list@organisation.org" --in-reply-to="[org-devel] [patch] added functionality" added-functionality.patch

this creating new thread instead of replying existing one. right way of replying?

refer tutorial. might reply http://burzalodowa.wordpress.com/2013/10/05/how-to-send-patches-with-git-send-email/

git email mailing-list

sockets - Runing class method multiple times parallel in Python -



sockets - Runing class method multiple times parallel in Python -

i have implemented python socket server. sends image info multiple cameras client. request handler class looks like:

class requesthandler(socketserver.baserequesthandler): def handle(self): while true: info = self.request.recv(1024) if data.endswith('0000000050'): # client requests info camera_id, camera_path in _video_devices.iteritems(): message = self.create_image_transfer_message(camera_id, camera_path) self.request.sendto(message, self.client_address) def create_image_transfer_message(self, camera_id, camera_path): # somecode ...

i forced stick socket server because of client. works problem works sequentially, there big delays between photographic camera images beingness uploaded. create transfer messages in parallel little delay between calls.

i tried utilize pool class multiprocessing:

import multiprocessing class requesthandler(socketserver.baserequesthandler): def handle(self): ... pool = multiprocessing.pool(processes=4) messages = [pool.apply(self.create_image_transfer_message, args=(camera_id, camera_path)) camid, campath in _video_devices.iteritems()]

but throws:

picklingerror: can't pickle <type 'function'>: attribute lookup __builtin__.function failed

i want know if there way create transfer messages in parallel defined delay between calls?

edit:

i create response messages using info multiple cameras. problem is, if run image grabbing routines close each other image artifacts, because usb bus overloaded. figured out, calling image grabbing sequentially 0.2 sec delay solve problem. cameras not sending info whole time image grabbing function running, delayed parallel cal result in images little delay between them.

i think you're on right path already, no need throw away work.

here's reply how utilize class method multiprocessing found via google after searching "multiprocessing class method"

from multiprocessing import pool import time pool = pool(processes=2) def unwrap_self_f(arg, **kwarg): homecoming c.create_image_transfer_message(*arg, **kwarg) class requesthandler(socketserver.baserequesthandler): @classmethod def create_image_transfer_message(cls, camera_id, camera_path): # logic goes here def handle(self): while true: info = self.request.recv(1024) if not data.endswith('0000000050'): # client requests info go on pool.map(unwrap_self_f, ( (camera_id, camera_path) camera_id, camera_path in _video_devices.iteritems() ) )

note, if want homecoming values workers you'll need explore using shared resource see reply here - how can recover homecoming value of function passed multiprocessing.process?

python sockets multiprocessing socketserver

How to change image permission with PHP and chmod? -



How to change image permission with PHP and chmod? -

as want display uploaded images on website message: "you don't have permission access /funproject/uploads/328/20.jpg on server".

i had problem before , solved using chmod somehow deleted solution , can't create now.

i got function that:

function upload_image($image_temp, $image_ext, $album_id) { $album_id = (int)$album_id; mysql_query("insert `images` values ('', '".$_session['user_id']."', '$album_id', unix_timestamp(), '$image_ext')"); $image_id = mysql_insert_id(); $image_file = $image_id.'.'.$image_ext; move_uploaded_file($image_temp, 'uploads/'.$album_id.'/'.$image_file); create_thumb('uploads/'.$album_id.'/', $image_file, 'uploads/thumbs/'.$album_id.'/'); }

what have tried (and doesn't work):

mysql_query("insert `images` values ('', '".$_session['user_id']."', '$album_id', unix_timestamp(), '$image_ext')"); chmod($image_file, 0755);

how can alter permission of uploaded image using chmod in function?

that worked!

mysql_query("insert `images` values ('', '".$_session['user_id']."', '$album_id', unix_timestamp(), '$image_ext')"); chmod("/somedir/uploads", 775);

php chmod

ruby on rails - undefined method `stringify_keys' for Object -



ruby on rails - undefined method `stringify_keys' for Object -

i new world of ruby , rails (started week ago, background php). i've got class here acts factory.

i next error :

undefined method `stringify_keys' #

i understand constructor (.new) expects hash instead of object (why ?) but, although spent couple of hours searching www, didn't come viable solution @ point.

i want inject soap object constructor. constructor pretty straightforward, puts object parameter in instance variable supposed store it. i've been looking methods turn object proper hash saw bunch of old posts rather dirty hacks. i'd rather quit programming utilize them ^^.

i never thought doing cause headache...

thanks tips !

class="snippet-code-html lang-html prettyprint-override">class webservices::webservicefactory def initialize (type, url, login, password, protocol = "soap") @type, @protocol, @url, @login, @password = type, protocol, url, login, password case @protocol.capitalize when "soap" requestor = webservices::soap::soap.new(url, login, password) end @class = @type.constantize.new(requestor) end def getservice homecoming @class end end

the initialize method can take whatever arguments define, doesn't need hash, , in fact, code above looks have 5 arguments can of type.

are wanting pass soap object argument of initialize?

if are, (assuming using version of ruby >= 2.0)

class webservices::webservicefactory def initialize(requestor:, type:) @class = type.constantize.new(requestor) end end

if want class handle details of creating soap object, maybe work you:

module webservices class webservicefactory services = { soap: 'webservices::soap::soap' } def initialize(type:, protocol: :soap, params: {}) homecoming unless services.key?(protocol.to_sym) requestor = services[protocol.to_sym].constantize.new(params[:url], params[:login], params[:password]) @class = type.constantize.new(requestor) end end end

ruby-on-rails

Concatenating two strings in C -



Concatenating two strings in C -

so have create function concatenate 2 strings in c; function creates new string concatenating str1 , str2. function has phone call malloc() or calloc() allocate memory new string.the function returns new string.

after executing next phone call printf() in main test function: printf ( “%s\n”, mystrcat( “hello”, “world!” )); printout on screen has helloworld!

here's code far; can't quite understand why not work. doesn't anything... compiles , runs nil displayed.

#include <stdio.h> #include <stdlib.h> #include <string.h> char *my_strcat( const char * const str1, const char * const str2); int main() { printf("%s", my_strcat("hello", "world")); // test function. output of print statement supposed helloworld } char *my_strcat( const char * const str1, const char * const str2) { char *temp1 = str1; // initializing pointer first string char *temp2 = str2; // initializing pointer sec string // dynamically allocating memory concatenated string = length of string 1 + length of string 2 + 1 null indicator thing. char *final_string = (char*)malloc (strlen(str1) + strlen(str2) + 1); while (*temp1 != '\0') //while loop loop through first string. goes long temp1 not nail end of string { *final_string = *temp1; // sets each successive element of final string equal each successive element of temp1 temp1++; // increments address of temp1 can feed new element @ new address final_string++; // increments address of final string can take new element @ new address } while (*temp2 != '\0') // same above, except string 2. { *final_string = *temp2; temp2++; final_string++; } *final_string = '\0'; // adds null terminator thing signify string homecoming final_string; //returns final string. }

you're returning final_string, it's been incremented during course of study of algorithm point null terminator - not origin of string.

you need alter allocation like:

char *final_string_return = malloc(strlen(str1) + strlen(str2) + 1); char *final_string = final_string_return;

and later on:

return final_string_return;

c string

android - I don't obtain change color of AppCompat -



android - I don't obtain change color of AppCompat -

i'm having same problem, generate theme via x , after add together project , did correctly references in styles.xml, don't work.

my manifest.xml this:

<uses-sdk android:minsdkversion="8" android:targetsdkversion="21" />

was generated file below in http://jgilfelt.github.io/android-actionbarstylegenerator

styles_custom.xml, add together in res/values/styles.xml:

<style name="appbasetheme" parent="theme.appcompat.light"> </style>

<style name="apptheme" parent="appbasetheme"> <!-- customizations not specific particular api-level can go here. --> <item name="actionbaritembackground">@drawable/selectable_background_custom</item> <item name="popupmenustyle">@style/popupmenu.custom</item> <item name="dropdownlistviewstyle">@style/dropdownlistview.custom</item> <item name="actionbartabstyle">@style/actionbartabstyle.custom</item> <item name="actiondropdownstyle">@style/dropdownnav.custom</item> <item name="actionbarstyle">@style/actionbar.solid.custom</item> <item name="actionmodebackground">@drawable/cab_background_top_custom</item> <item name="actionmodesplitbackground">@drawable/cab_background_bottom_custom</item> <item name="actionmodeclosebuttonstyle">@style/actionbutton.closemode.custom</item> </style>

and in res/value-v14/styles.xml

<style name="appbasetheme" parent="theme.appcompat.light.darkactionbar"> <!-- api 14 theme customizations can go here. --> <item name="android:actionbaritembackground">@drawable/selectable_background_custom</item> <item name="android:popupmenustyle">@style/popupmenu.custom</item> <item name="android:dropdownlistviewstyle">@style/dropdownlistview.custom</item> <item name="android:actionbartabstyle">@style/actionbartabstyle.custom</item> <item name="android:actiondropdownstyle">@style/dropdownnav.custom</item> <item name="android:actionbarstyle">@style/actionbar.solid.custom</item> <item name="android:actionmodebackground">@drawable/cab_background_top_custom</item> <item name="android:actionmodesplitbackground">@drawable/cab_background_bottom_custom</item> <item name="android:actionmodeclosebuttonstyle">@style/actionbutton.closemode.custom</item> </style>

well can help me, or give me best directions, please?

tks. :d

appcompat library project. need reference library project in android project. first need dowload library through sdk manager .

to download back upwards library through sdk manager:-

refer link:- https://developer.android.com/tools/support-library/setup.html

in above link read topic :-adding libraries resources ( inlcudes many steps why giving link )

after completing these steps :-

you can add together library application project:

step 1:- in project explorer, right-click project , select properties.

step2:- in category panel on left side of dialog, select android.

step 3:- in library pane, click add together button.

step 4:- select library project , click ok. example, appcompat project should listed android-support-v7-appcompat.

step 5:- in properties window, click ok

note :-if app using back upwards library compatibility on devices running versions lower android 3.0, custom theme should utilize theme.appcompat theme (or 1 of descendants) parent theme.

android

c - yacc gets zero value from non terminal -



c - yacc gets zero value from non terminal -

i making c- compiler next [compiler construction, principles , practice]. , have made parser using yacc 1 rule in yacc making error.

return_stmt : homecoming semi { $$ = newstmtnode(returnk);} | homecoming look semi { $$ = newstmtnode(returnk); $$->child[0] = $1; }

when parsing homecoming statement using "return look semi" rule $1 has value zero. whole source below %% /* grammar c- */

program : declaration_list { savedtree = $1; } ; declaration_list : declaration_list declaration { yystype t = $1; if (t != null) { while (t->sibling != null) t = t->sibling; t->sibling = $2; $$ = $1; } else $$ = $2; } | declaration { $$ =$1; } ; declaration : var_declaration { $$ = $1; } | fun_declaration { $$ = $1; } ; var_declaration : type_specifier id semi { $$ = newexpnode(vark); $$->type = (exptype)$1; $$->attr.name = namestackpop(); $$->lineno = savedlineno; } | type_specifier id lbrace num rbrace semi { $$ = newexpnode(vararrayk); $$->type = (exptype)$1; $$->attr.name = namestackpop(); $$->lineno = savedlineno; $$->child[0] = $4; } ; type_specifier : int { $$ = integer; } | void { $$ = void; } ; fun_declaration : type_specifier id lparen params rparen compound_stmt { $$ = newstmtnode(functionk); $$->type = (exptype)$1; $$->attr.name = namestackpop(); $$->lineno = savedlineno; $$->child[0] = $4; $$->child[1] = $6; } ; params : param_list { $$ = $1; } | void { $$ = newexpnode(singleparamk); $$->type = void; } ; param_list : param_list comma param { yystype t = $1; if (t != null) { while (t->sibling != null) t = t->sibling; t->sibling = $3; $$ = $1; } else $$ = $3; } | param { $$ = $1; } ; param : type_specifier id { $$ = newexpnode(singleparamk); $$->type = (exptype)$1; $$->attr.name = namestackpop(); } | type_specifier id lbrace rbrace { $$ = newexpnode(arrayparamk); $$->type = (exptype)$1; $$->attr.name = namestackpop(); $$->lineno = savedlineno; } ; compound_stmt : lcurly local_declarations statement_list rcurly { $$ = newstmtnode(compoundk); $$->child[0] = $2; $$->child[1] = $3; } ; local_declarations : local_declarations var_declaration { yystype t = $1; if (t != null) { while (t->sibling != null) t = t->sibling; t->sibling = $2; $$ = $1; } else $$ = $2; } | empty { $$ = $1; } ; statement_list : statement_list statement { yystype t = $1; if (t != null) { while (t->sibling != null) t = t->sibling; t->sibling = $2; $$ = $1; } else $$ = $2; } | empty { $$ = $1; } ; statement : expression_stmt { $$ = $1; } | compound_stmt { $$ = $1; } | selection_stmt { $$ = $1; } | iteration_stmt { $$ = $1; } | return_stmt { $$ = $1; } ; expression_stmt : look semi { $$ = $1;} | semi { $$ = null; } ; selection_stmt : if lparen look rparen statement { $$ = newstmtnode(ifk); $$->child[0] = $3; $$->child[1] = $5; $$->attr.withelse = false; } | if lparen look rparen statement else statement { $$ = newstmtnode(ifk); $$->child[0] = $3; $$->child[1] = $5; $$->child[2] = $7; $$->attr.withelse = true; } ; iteration_stmt : while lparen look rparen statement { $$ = newstmtnode(whilek); $$->child[0] = $3; $$->child[1] = $5; } ; return_stmt : homecoming semi { $$ = newstmtnode(returnk);} | homecoming look semi { $$ = newstmtnode(returnk); $$->child[0] = $1; } ; look : var assign look { $$ = newexpnode(assignk); $$->type = integer; $$->child[0] = $1; $$->child[1] = $3; } | simple_expression { $$ = $1; } ; var : id { $$ = newexpnode(idk); $$->type = integer; $$->attr.name = namestackpop(); } | id lbrace look rbrace { $$ = newexpnode(idk); $$->attr.name = namestackpop(); $$->child[0] = $3; } ; simple_expression : additive_expression relop additive_expression { $$ = newexpnode(opk); $$->type = integer; $$->child[0] = $1; $$->child[1] = $3; $$->attr.op = $2; } | additive_expression { $$ = $1; } ; relop : le { $$ = le; } | lt { $$ = lt; } | gt { $$ = gt; } | ge { $$ = ge; } | eq { $$ = eq; } | ne { $$ = ne; } ; additive_expression : additive_expression addop term { $$ = newexpnode(opk); $$->type = integer; $$->child[0] = $1; $$->child[1] = $3; $$->attr.op = $2; } | term { $$ = $1; } ; addop : plus { $$ = plus; } | minus { $$ = minus; } ; term : term mulop factor { $$ = newexpnode(opk); $$->type = integer; $$->child[0] = $1; $$->child[1] = $3; $$->attr.op = $2; } | factor { $$ = $1; } ; mulop : times { $$ = times; } | on { $$ = over; } ; factor : lparen look rparen { $$ = $2; } | var { $$ = $1; } | phone call { $$ = $1; } | num { $$ = newexpnode(constk); $$->type = integer; $$->attr.val = atoi(tokenstring); } ; phone call : id lparen args rparen { $$ = newexpnode(callk); $$->attr.name = namestackpop(); $$->child[0] = $3; $$->lineno = savedlineno; } ; args : arg_list { $$ = $1; } | empty { $$ = $1; } ; arg_list : arg_list comma look { yystype t = $1; if (t != null) { while (t->sibling != null) t = t->sibling; t->sibling = $3; $$ = $1; } else $$ = $3; } | look { $$ = $1; } ; empty : { $$ = null;} ; %%

when debug using printf, confirmed other nonterminal rule "return look semi" has right value(pointer of tree node). wrong yacc file?

the $1 return token. $2 should expression.

c compiler-construction yacc

ruby on rails - FATAL: You must set node['postgresql']['password']['postgres'] in chef-solo mode when using posgtresql cookbook -



ruby on rails - FATAL: You must set node['postgresql']['password']['postgres'] in chef-solo mode when using posgtresql cookbook -

so included cookbook 'postgresql', {} in cheffile. have box downloaded , installed vagrant, when run vagrant provision, gives me error:

fatal: must set node['postgresql']['password']['postgres'] in chef-solo mode

i saw somewhere should add together line:

default['postgresql']['password']['postgres'] = "mypassword"

in default.rb file in postgresql cookbook. if add together , vagrant provision again, line gets deleted , run same error again.

what problem here?

you can set node info in vagrantfile using chef.json. example:

vagrant.configure("2") |config| # ... config.vm.provision "chef_solo" |chef| # ... chef.json = { postgresql: { password: { postgres: "mypassword" } } } end end

see vagrant docs more information.

ruby-on-rails postgresql vagrant chef

c# - wpf datagrid filling data -



c# - wpf datagrid filling data -

there problem fill datagrid dynamic source. example, want fill datagrid objects has various parameters. parameters display dynamic info database. columns count may changed , parameters count may changed counts equals. fill headers:

private void datasoursechanged(sourcelist sourcelist) { columns.clear(); columns.add(new datagridtextcolumn()); if (sourcelist != null) { foreach (var item in sourcelist.columnsheaders) columns.add(new datagridtextcolumn { header = item }); } } public class sourcelist { private readonly ilist _columnsheaders; private readonly ilist _rowsheaders; private readonly ilist _datarows; public ilist columnsheaders { { homecoming _columnsheaders; } } public ilist rowsheaders { { homecoming _rowsheaders; } } public ilist datarows { { homecoming _datarows; } } public sourcelist(ilist rowsheaders, ilist columnsheaders, ilist datarows) { _rowsheaders = rowsheaders; _columnsheaders = columnsheaders; _datarows = datarows; } }

i want fill headers , rows (rows merge of _rowsheaders[i] in first column , other columns _datarows[i]) rows fills objects has properties. may fill datagrid dynamic length?

there not solutions create custom grid derives system.windows.controls.grid , create custom logic fill grid

public static readonly dependencyproperty customsourceproperty = dependencyproperty.register( "customsource", typeof(sourcelist), typeof(interactivegrid), new frameworkpropertymetadata(null, frameworkpropertymetadataoptions.bindstwowaybydefault, customsourcechanged ) ); [category("group properties")] public sourcelist customsource { { homecoming (sourcelist)getvalue(customsourceproperty); } set { setvalue(customsourceproperty, value); } } private void customsourcechanged(sourcelist sourcelist) { //... } private static void customsourcechanged(dependencyobject d, dependencypropertychangedeventargs e) { ((interactivegrid)d).customsourcechanged((sourcelist)e.newvalue); }

c# wpf datagrid

c - What is the scope of free() in dynamically allocated memory? -



c - What is the scope of free() in dynamically allocated memory? -

let's have next code:

typedef struct { int numbars; bartype *bars; } footype; foo = (footype *) malloc(sizeof(footype)); foo->bars = (bartype *) malloc(sizeof(bartype));

will calling free(foo) free bars or need this:

free(foo->bars); free(foo);

intuitively, sense calling free(foo) should plenty - if don't need phone call free(foo->numbars) shouldn't need phone call free(foo->bars). didn't have manually allocate memory numbars, while did bars.

for every malloc need 1 free. nil done "automatically" you.

note that, contrary claim, not have allocate memory bars, don't have allocate memory numbars. however, are allocating memory *bars.

a single star can create big difference in c...

c malloc free dynamic-memory-allocation dynamic-allocation

configuration - How to configure Xcode to compile not supported language, e.g. Fortran? -



configuration - How to configure Xcode to compile not supported language, e.g. Fortran? -

i utilize xcode under mac os x compile , run programme written in language not supported, e.g. fortran. assuming have compiler installed, e.g. gfortran or ifort, steps in xcode project settings create possible compile , run program?

i have created new, empty project since fortran not supported (only c,c++,objective-c , swift selectable in command line tool application). created simple fortran file. guess have add together several things builds tab in project settings create compile , run (it works command line). these steps?

add external build scheme target project. external build scheme targets/projects allow build projects in languages xcode doesn't natively support. external build scheme target/project in other section under os x on left side of assistant. when click next button, you'll asked location of build tool. come in path fortran compiler. when build project, xcode utilize fortran compiler building.

configuration fortran xcode6

python - Splitting a list with a separator -



python - Splitting a list with a separator -

i have written function gets 2 arguments: list , one value nowadays in list given (sep). purpose of function split given list , homecoming multiple lists in list without value specified in sec argument of written fuction. def split_list([1,2,3,2,1],2) ---> result [[1],[3],[1]]. functionality of spliting result keeps sec value of function (sep) in separated lists. couldnt think of way how solve problem. in advance

def split_list(l, sep): occurence = [i i, x in enumerate(l) if x == sep] newlist=[] newlist.append(l[:occurence[0]]) in range(0,len(occurence)): j=i+1 if j < len(occurence): newlist.append(l[occurence[i]:occurence[j]]) i+=1 newlist.append(l[occurence[-1]:]) homecoming newlist

how this:

def split_list(l, sep): nl = [[]] el in l: if el == sep: nl.append([]) else: # append lastly list nl[-1].append(el) homecoming nl

or method, using list of occurences:

def split_list(l, sep): # occurences o = [i i, x in enumerate(l) if x == sep] nl = [] # first piece nl.append(l[:o[0]]) # middle slices in range(1, len(o)): nl.append(l[o[i-1]+1:o[i]]) # lastly piece nl.append(l[o[-1]+1:]) homecoming nl

python

c++ - Handling multiple keypressess at the same time in SDL -



c++ - Handling multiple keypressess at the same time in SDL -

i'm making simple top downwards 2d shooter, move wasd , shoot in direction you're looking @ space. can move , shoot fine, can't them both @ same time. illustration if i'm shooting , start moving, character stop shooting until release , press space again, , if start moving in direction have release , press space again.

here's main method:

int main(int argc, char* args[]) { if (!init()) { log("failed initialize!\n"); } else { log("initialized sdl , sdl subsystems. \nloading assets:\n"); if (!loadassets()) { printf("failed load assets!\n"); } else { log("all assets loaded successfully.\n"); bool running = true; sdl_event e; std::vector<shot> shots; ltimer shottimer; float cooldown = 250.0f; float previouscooldown = 0.0f; player player; log("game running.\n"); shottimer.start(); while (running) { while (sdl_pollevent(&e) != 0) { if (e.type == sdl_quit) { log("sdl_quit event triggered.\n"); running = false; } else if (e.type == sdl_keydown) { switch (e.key.keysym.sym) { case sdlk_escape: { running = false; break; } } } player.handleevent(e); if (sdl_getticks() - previouscooldown > cooldown) { previouscooldown = sdl_getticks(); shots = shoot(e, player, shots); } } player.move(); (int = 0; < shots.size(); i++) { shots[i].move(); } /*if (shottimer.getticks() >= cooldown) shottimer.restart();*/ sdl_setrenderdrawcolor(renderer, 0xff, 0xff, 0xff, 0xff); sdl_renderclear(renderer); background.render(0, 0); (int = 0; < shots.size(); i++) { shots[i].render(); } player.render(); sdl_renderpresent(renderer); } } } close(); homecoming 0; }

here's shoot() function, what's causing this:

std::vector<shot> shoot(sdl_event& e, player player, std::vector<shot> shots) { bool shoot = false; if (e.type = sdl_keydown && e.key.repeat == 1) { switch (e.key.keysym.sym) { case sdlk_space: { shoot = true; break; } } } else if (e.type = sdl_keyup && e.key.repeat == 1) { switch (e.key.keysym.sym) { case sdlk_space: { shoot = false; break; } } } if (shoot) { shot newshot(player.getdir(), player); shots.push_back(newshot); } homecoming shots; }

and how move player

void player::handleevent(sdl_event& e) { if (e.type == sdl_keydown && e.key.repeat == 0) { switch (e.key.keysym.sym) { case sdlk_w: mvely -= player_vel; mdir = 0; break; case sdlk_s: mvely += player_vel; mdir = 1; break; case sdlk_d: mvelx += player_vel; mdir = 2; break; case sdlk_a: mvelx -= player_vel; mdir = 3; break; } } else if (e.type == sdl_keyup && e.key.repeat == 0) { switch (e.key.keysym.sym) { case sdlk_w: mvely += player_vel; break; case sdlk_s: mvely -= player_vel; break; case sdlk_d: mvelx -= player_vel; break; case sdlk_a: mvelx += player_vel; break; } } }

separate event polling rest of game logic.

poll events once per frame in separate function , store state of keystates array. then, when need state, check array.

c++ sdl sdl-2

c# - One datagridview and data from two databases and usb. How to start? -



c# - One datagridview and data from two databases and usb. How to start? -

i have windows form looks this: http://s28.postimg.org/y9ezkreod/datagridview_plan.png view plan can see i'd have 1 datagridview , info multiple sources specific columns. deliver links or materials read because don't know how start , search? info sql server be:

id_model|| model_name ||ordered_added_features (of device)|| serial_code (of added features)

mysql:

|| date_of_last_soft_update|| 2 more...

usb:

instaled_sofrware_id|| if sd card present|| ...

this not "code-it-for-me" site may give illustration code , i´m sure help you!

for sql- , mysql-connection next links helpful:

sql:sql-connection

mysql:mysql-connection

you have utilize "splitcontainer" spread screen/form picture.

i hope solved problem! have nice day!

c# mysql sql-server-2008 datagridview

javascript - submit form inside a href link html -



javascript - submit form inside a href link html -

please help me in case, case 3 submit buttons submit different values, me need alter submit form link href html, same, how can this?

there submit forms:

<input type="submit" value="2" maxlength="1" name="post_request"> <input type="submit" value="3" maxlength="1" name="post_request"> <input type="submit" value="4" maxlength="1" name="post_request">

p.s. how send submit form, it's not problem, problem how send submit name , value.

thanks

<a href="someurl?post_request=2">value 2</a>

is equivalent of

<form method="get" action="someurl"> <input type="submit" value="2" maxlength="1" name="post_request"> </form>

if want utilize post type you'll need populate hidden input using javascript

javascript html forms

php - array_key_exists always returning false -



php - array_key_exists always returning false -

i have code, written in php homecoming foo if bar given , bar if foo given. have attempted, , seemingly failed add together grab if other foo or bar input "unknown output".

<?php echo("<html><body bgcolor='#ffffff'><h1>welcome</h1>"); $input = $_get["foobar"]; $array = array( "foo" => "bar", "bar" => "foo", ); function getvalue($value) { if(array_key_exists($value, $array)) { homecoming $array[$value]; } else { homecoming "unknown"; } } echo ("input: ". $input .", output: ". getvalue($input)); echo("<br><br>"); print_r($array); echo("</body></html>"); ?>

however, appears array_key_exists returning false when go page either page.php?foobar=foo or page.php?foobar=bar this:

welcome input: bar, output: unknown array ( [foo] => bar [bar] => foo )

or opposite input switched foo output remains "unknown".

basic php: variables defined in "parent" scope not visible in "child" scopes:

$array = array(...); // global scope, top-level of script function getvalue($value) { if(array_key_exists($value, $array)) { ^^^^^^^---undefined local variable, function scope

you should have @ least

global $array;

at start of getvalue function.

php

java - Passing random numbers into an instance of an object -



java - Passing random numbers into an instance of an object -

my homework asking me math game in prompt user reply math questions , show them answer. i've created mathgameclass, when create instance of mathgame, asks me set in 2 ints, don't know because i'm trying generate them randomly.

question: how random numbers class pass instance of mathgame?

below mathgame class

underneath main instance of mathgame i'm trying figure out.

import java.util.random; public class mathgame { private int operand1; private int operand2; private int solution; public mathgame (int operand1, int operand2) { this.operand1 = operand1; this.operand2 = operand2; } public int genrandom1() { random rand = new random(); int randnum = rand.nextint(0) + 20; randnum = operand1; homecoming operand1; } public int genrandom2() { random rand = new random(); int randnum2 = rand.nextint(0) + 20; randnum2 = operand2; homecoming operand2; } public int getoperand1() { homecoming operand1; } public int getoperand2() { homecoming operand2; } public string question() { homecoming "what is" + operand1 + operand2 + "?"; } public string solution() { int solution = operand1 + operand2; homecoming "the right reply is: " + solution; } }

i error in instance of mathgame since need have 2 ints go through, don't know ints because they're supposed randomly generated, did in class.

import java.util.scanner; public class mathgamemain { public static void main(string[] args) { scanner scan = new scanner(system.in); mathgame game1 = new mathgame(); } }

you want alter this:

import java.util.random; public class mathgame { private int operand1; private int operand2; private int solution; public mathgame () { this.operand1 = getrandom(); this.operand2 = getrandom(); } public int getrandom() { random rand = new random(); int randnum = rand.nextint(20); homecoming randnum; } public int getoperand1() { homecoming operand1; } public int getoperand2() { homecoming operand2; } public string question() { homecoming "what is" + operand1 + " + " + operand2 + "?"; } public string solution() { int solution = operand1 + operand2; homecoming "the right reply is: " + solution; } }

you should generate random numbers when mathgame initialized. no need pass numbers if going randomly generate them.

java variables math random

forms - symfony2.5 maxlength deprecated -



forms - symfony2.5 maxlength deprecated -

i know why max_length in form type deprecated?

and how accomplish desired effect cleanest way ?

see related issue on github. alternative add together html attribute textarea. can manually add together via attributes:

$builder->add('field', 'textarea', array( 'attr' => array('maxlength' => 255), ));

forms symfony2

java - Validate Pojo's in OSGi -



java - Validate Pojo's in OSGi -

i validate anootated pojos (jsr 303) hibernatevalidator in osgi. unit tests works fine on osgi doesn't work.

here's validator method:

public static void validate(object o) throws validationexception { validatorfactory mill = validation.bydefaultprovider().providerresolver(new osgiservicediscoverer()).configure() .buildvalidatorfactory(); validator validator = factory.getvalidator(); set<constraintviolation<object>> validatorresult = null; if (o instanceof messagecontentslist) { messagecontentslist messagelist = (messagecontentslist) o; validatorresult = validator.validate(messagelist.get(0)); } else { validatorresult = validator.validate(o); } if (!validatorresult.isempty()) { stringbuffer sb = new stringbuffer(); (constraintviolation<object> v : validatorresult) { sb.append(v.getpropertypath() + " " + v.getmessage() + ", "); } string msg = sb.tostring().substring(0, sb.tostring().length() - 1); throw new validationexception(msg); } }

and here discoverer:

public class osgiservicediscoverer implements validationproviderresolver { @override public list<validationprovider<?>> getvalidationproviders() { list<validationprovider<?>> providers = new arraylist<validationprovider<?>>(1); providers.add(new hibernatevalidator()); homecoming providers; } }

in pom i've added next imports osgi:

javax.validation, javax.validation.bootstrap, javax.validation.constraints, javax.validation.spi, org.hibernate.validator,

has thought i'm doing wrong?

thx

i've found solution myself. reason was, annotated classes in seperate bundle validation , there haven't add together javax.validation dependencies. annotations ignored , validation has no functionality

java maven osgi

Java interceptor priority -



Java interceptor priority -

this might trivial question many of swear couldn't find reply anywhere else:

let's have class this

@interceptors(interceptor1.class) class myclass { @interceptors({interceptor2.class, interceptors3.class}) public void mymethod() {...} }

when mymethod called interceptors executed , in order?

interceptor2, interceptor3 or interceptor1, interceptor2, interceptor3 or interceptor2, interceptor3, interceptor1?

thanks in advance

quoting documentation

by default ordering of interceptors when invoking method are

external interceptors

default interceptors, if present

class interceptors, if present

method interceptors, if present

interceptor method on bean class (using @aroundinvoke)

within each grouping (default, class, method) order of interceptors left right defined in @interceptors annotation, , xml interceptors.

java java-ee annotations interceptor

json - JQuery get() results conversion -



json - JQuery get() results conversion -

i trying info outside domain not have access to. end goal able display table, or later dynamic chart. problem domain requesting info allows either homecoming datatype of "script", or "jsonp". other datattypes give me "no 'access-control-allow-origin' header nowadays on requested resource. origin 'null' hence not allowed access." error. file need access .csv file. tried using next code:

$(document).ready(function(){ $("#test").click(function(){ var url = "outsidedomain.com"; $.get( url, function (data) { var datastr = new string(data); datatotable(datastr); }, "script"); }); });

when utilize above code, receive "resource interpreted script transferred mime type application/csv" warning, , "uncaught syntaxerror: unexpected identifier" error. how , manipulate info in .csv file using jquery under these circumstances?

jquery json jsonp

string - When Unicode decoding should be interrupted with an exception? -



string - When Unicode decoding should be interrupted with an exception? -

i'm working on bringing unicode back upwards narrow-string application, , while looking @ how carefree handle it's all-char * strings, not weighed downwards thinking of possibility of invalid string, made me think of following:

when decoding unicode, programmer presented 3 choices on how handle ill-formed strings — ignore decoding errors, stripping invalid characters out of resulting string, stumble on first decoding error, or replace can't decoded replacement characters.

i don't ignoring approach because of security reasons - it's easy create string might on first glance, becomes evil after stripping designed errors. replacing errors replacement characters much improve in case — might worse, there clear visual indication went not planned, replacement characters don't allow words merge different meaning.

but real-life use-cases of throwing exception or stopping decoding after first error? point of such "validation"? let's assume function got apparently invalid utf8 string - programmer supposed knowledge?

string unicode utf-8 utf8-decode

php - W3 total cache plugin multiple instances install -



php - W3 total cache plugin multiple instances install -

i have installed "w3 total cache" plugin, environment has right 1 instance, , works ok. how can replicate configuration on multiple instances? i'm using elasticbeanstalk amazon.

php wordpress wordpress-plugin

composer php - Error when using the "use" in php -



composer php - Error when using the "use" in php -

in code, server returns error when using term "use". illustration next code:

use spire\settings; utilize spire\resources; utilize spire\utils; utilize symfony\component\httpfoundation\request; utilize symfony\component\httpfoundation\response; utilize silex\application;

the server returns me next error:

php parse error: syntax error, unexpected t_string, expecting t_constant_encapsed_string or '(' in /home/inoshare/public_html/api/app.php on line 8

what wrong server configuration?

@touchmx,please check below notes.

notes :

(1) create sure it's running php 5.3 or later.

(2) if running before version won't have back upwards namespaces.

please check phpinfo() php version.

php composer-php

c# - Is it possible to get the canonical user id from AWS IAM users, from the .NET API? -



c# - Is it possible to get the canonical user id from AWS IAM users, from the .NET API? -

i have created user, credentials, , bucket. need grant bucket access user.

is there way canonicaluser value code? iam user object provides arn, path, userid , username values, none of these valid grant.

using (var s3 = new amazon.s3.amazons3client("[user_key]", "[secret_user_key]", regionendpoint.getbysystemname("eu-west-1"))) { var response = s3.getacl("[bucket_id]"); var acl = response.accesscontrollist; acl.addgrant( new s3grantee() { canonicaluser = **???** }, new s3permission(s3permission.full_control) ); s3.putacl( new putaclrequest() { accesscontrollist = acl, bucketname = "[bucket_id]" } ); }

no, not possible canonical user id code - you've nail odd , legacy aspect due different way manage access permissions s3 resources, see aws team's response how find out canonical id iam user?:

you can not add together iam users acl's grantee. i'll have documentation updated clarify iam users not supported in acl's. there few solutions can utilize grant user access amazon s3 content: [...]

you might indeed want reconsider using more versatile s3 bucket policies instead (see below) - however, if have access account's root credentials, might find canonical user id associated aws account outlined in specifying principal in policy (mind you, doesn't work iam user credentials):

go http://aws.amazon.com , my account/console drop-down menu, select security credentials. sign in using appropriate business relationship credentials. click account identifiers.

i shall emphasize 1 time again aws recommends utilize iam users these days, see e.g. root business relationship credentials vs. iam user credentials:

because can't command privileges of root business relationship credentials, should store them in safe place , instead utilize aws identity , access management (iam) user credentials day-to-day interaction aws.

this canonical user id requirement s3 rare exception, , said considered legacy artifact due s3's acl layer predating iam, best avoided, if possible.

c# .net amazon-web-services amazon-s3 amazon-iam

seo - BreadCrumb URL in Wordpress VertiMagazine Theme -



seo - BreadCrumb URL in Wordpress VertiMagazine Theme -

how can create urls of blogpost breadcrumb this

home>facebook status>love status

i have tried in seo plugins , seo yoast still there no alternative that. please give me brief reply how should modify theme create url appears in breadcrumbs in google search. here url http://love-status.com

you can implement breadcrumbs blog using wordpress seo yoast plugin , bit of php code . visit next link more detail -> https://managewp.com/breadcrumbs-wordpress-seo-by-yoast

wordpress seo breadcrumbs

vba - syntax error in update statement run-time error 3144 -



vba - syntax error in update statement run-time error 3144 -

i got syntax error in update statement.run-time error: 3144 utilize next code

currentdb.execute "update product " & _ " set [product name] = '" & me.txtname & "'" & _ ", [cost of product] = " & me.txtcost & "" & _ ", [weight] = " & me.txtweight & "" & _ ", [group] = '" & me.cmbgroup & "'" & _ ", [group id] = '" & me.txtgroupid & "'" & _ ", [ordered] = " & me.txtordered & "" & _ " [roduct name] = " & me.txtname.tag & ""

what can problem? if makes sense, me.txtcost , me.txtweight , me.txtordered number

thanks help!

two problems see:

typo in where [roduct name] (should where [product name]) missing quotes around me.txtname.tag @ end of statement

try instead:

currentdb.execute "update product " & _ " set [product name] = '" & me.txtname & "'" & _ ", [cost of product] = " & me.txtcost & "" & _ ", [weight] = " & me.txtweight & "" & _ ", [group] = '" & me.cmbgroup & "'" & _ ", [group id] = '" & me.txtgroupid & "'" & _ ", [ordered] = " & me.txtordered & "" & _ " [product name] = '" & me.txtname.tag & "'"

vba ms-access

android - Joda-Time confusion for converting DateTimeField to text/String -



android - Joda-Time confusion for converting DateTimeField to text/String -

i have joda datetimefield object called starttime localtime. meaning contains hr (ranging 0-23), minute, (0-59), , sec (0-59).

now when phone call method: starttime.getchronology().hourofday().getasshorttext(int fieldvalue, locale l) bit confused; locale understand when datetimefield api here there not explanation should input fieldvalue.

is there document describing integers refer fieldvalue?

now; i've tried doing starttime.getchronology().hourofday().tostring() not work. simply returns text: datetimefield[hourofday].

following documentation link have given, argument fieldvalue described numerical value of associated field. in case, hour-of-day-value, hence number between 0 , 23.

as far know, method getasshorttext(...) not produce text hour-of-day, yield digits in string-form. method rather designed fields have special text form months or weekdays. illustration demonstrating triviality of approach (the code meaningless utilize case):

localtime time = new localtime(14, 45, 30); string text = time.getchronology().hourofday().getasshorttext(12, locale.french); system.out.println("hour-of-day 12 text: " + text); // output: hour-of-day 12 text: 12

maybe confused because have field constants in jdk-class java.util.calendar in mind, there field constants denote field identifiers, not field values. same function (namely identifying fields) achieved datetimefield-objects in joda-time.

android jodatime localtime

javascript - Node.js convert buffer to Int8Array -



javascript - Node.js convert buffer to Int8Array -

in client side, converting typedarray blob , transmitting server, check if info correct, want compare first 5 values on client side , server side,

on client side:

var filereader = new filereader(); filereader.onload = function() { callback(new int8array(this.result)); }; filereader.readasarraybuffer(blob);

(from read first 5 values in callback fn)

but on server, found code convert blob buffer, , understanding, buffer , arraybuffer not same, var buffer1 = new buffer( blob, 'binary' );

does buffer have similar dataview of arraybuffer, how read first 5 values of buffer1 integers able in client side?

javascript node.js buffer blob

css3 - CSS: divs not stacking -



css3 - CSS: divs not stacking -

i using pocketgrid create website responsive.

the way pocketgrid works "thirty-block" class should stack on top of "seventy-block" class, when cut down size of browser of mobile device. isn't happening. going wrong?

this html looks like:

<div class="wrapper block-group"> <div class="top-bar block"> <p>some text</p> </div> <div class="header block-group"> <div class="focus-area block-group"> <div class="logo thirty-block block"> <p><span class="text-logo">loremlogo</span></p> <p><span class = "tagline">lorem ipsum dolor sit down amet</span></p> </div> <div class="seventy-block block"> <p>test</p> </div> </div> <!-end focus-area --> </div> <!-end header--> </div> <!-end wrapper-->

this css looks like:

/*! pocketgrid 1.1.0 * copyright 2013 arnaud leray * mit license */ /* border-box-sizing */ .block-group, .block, .block-group:after, .block:after, .block-group:before, .block:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /* clearfix */ .block-group { *zoom: 1; } .block-group:before, .block-group:after { display: table; content: ""; line-height: 0; } .block-group:after { clear: both; } .block-group { /* ul/li compatibility */ list-style-type: none; padding: 0; margin: 0; } /* nested grid */ .block-group > .block-group { clear: none; float: left; margin: 0 !important; } /* default block */ .block { float: left; width: 100%; } .header{ width: 100%; } .focus-area { width: 100%; } .thirty-block { width: 30%; background-color: green; } .seventy-block { width: 70%; height: 100px; background-color: blue; }

it seems you've sorted farther , future help else having similar issue or media queries here's illustration showing similar navigation, mobile media query change.

http://jsfiddle.net/vmggcv0g/

using next query alter list item state on mobiles (when screen less 480px):

@media screen , (max-width : 480px)

along box-sizing property allow padding , borders on list items (with out property item width exceed 100% width include 1px border):

-webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box;

here's great css-tricks article explaining box-sizing property , css box model further:

http://css-tricks.com/box-sizing/

css css3 pocketgrid

javascript - Backbone Inline HTML Templates versus External Templating -



javascript - Backbone Inline HTML Templates versus External Templating -

my backbone app has inline html templates follows:

<body> <div id="container"> <header></header> <nav></nav> <div id="pagecontent"></div> <footer></footer> </div> <!-- featured articles/homepage template --> <script type="text/template" id="featuredarticles"> <link rel="stylesheet" href="css/homepagecontent.css" /> <section id="banner"></section> <aside> <div></div> <div></div> </aside> <section id="main"></section> <section id="opinion"> <div></div> <div></div> <div></div> </section> <section id="travel"> <div></div> <div></div> <div></div> </section> </script> <!-- content articles template --> <script type="text/template" id="contentarticles"> <link rel="stylesheet" href="css/categorypagecontent.css" /> <section id="main"></section> <aside></aside> </script> <!-- require.js reference --> <script src="/js/libs/require.js" data-main="/js/app.js"></script> </body>

can / should externalize html instead. if so, how externalize (i.e. using view) follows:

<!-- featured articles/homepage template --> <script type="text/template" id="featuredarticles"> <!-- html rendered externally --> </script> <!-- content articles template --> <script type="text/template" id="contentarticles"> <!-- html rendered externally --> </script>

here snippet of how render template view:

define(['underscore', 'backbone', 'collections/bannercollection', 'collections/featuredarticlescollection', ], function (_, backbone, bannercollection, featuredarticlescollection) { var featuredarticlesview = backbone.view.extend({ el: $('#pagecontent'), initialize: function () { this.render(); }, render: function () { var = this; var template = _.template($('#featuredarticles').html(), {}); that.$el.html(template); homecoming that; } }); homecoming featuredarticlesview; });

i have been reading partials, need guidance on best practice , if / how inline html should broken out.

i found while little snippet of template manager (can't remember author, sorry):

templatemanager = { templates: {}, // holds templates cache get: function(id, callback){ var template = this.templates[id]; if (template) { // homecoming cached version if exists callback(template); } else { var = this; // fetch, cache , homecoming template $.get(id + ".html", function(template) { that.templates[id] = template; callback(that.templates[id]); }); } } };

it fetches template file, caches , calls callback function after loaded, this:

templatemanager.get('path/to/your/template', function(resp) { // resp template markup homecoming this; });

hope helps.

update

here working fiddle:

http://jsfiddle.net/411jgf78/1/

javascript html backbone.js underscore.js

java - Is scringo still working? -



java - Is scringo still working? -

anyone knows if scringo officially down? have read comments it. trying utilize scringo in project , after merging manifests , adding library, error:

10-11 22:29:58.125: e/scringo(12075): error fetching 10-11 22:29:58.125: e/scringo(12075): java.io.filenotfoundexception:https://srv1.scringo.com/scringoserver2/api?command=getappdata&clienttype=2&build=2.5.4&appid=afzeixqfsh3pgscgbq878cu3xjfxcdth&changenumber=0&v=15 10-11 22:29:58.125: e/scringo(12075): @ org.apache.harmony.luni.internal.net.www.protocol.http.httpurlconnectionimpl.getinputstream(httpurlconnectionimpl.java:521) 10-11 22:29:58.125: e/scringo(12075): @ org.apache.harmony.luni.internal.net.www.protocol.https.httpsurlconnectionimpl.getinputstream(httpsurlconnectionimpl.java:258) 10-11 22:29:58.125: e/scringo(12075): @ com.scringo.utils.scringohttpfetcher.getresponsestr(scringohttpfetcher.java:132) 10-11 22:29:58.125: e/scringo(12075): @ com.scringo.utils.scringojsonfetcher.handleresponse(scringojsonfetcher.java:59) 10-11 22:29:58.125: e/scringo(12075): @ com.scringo.utils.scringojsonfetcher.run(scringojsonfetcher.java:40)

in project , in sampleapp available in github, so, working? if is, suggestion problem? lot!

the resource specified uri not exist.

get request : https://srv1.scringo.com/scringoserver2/api?build=2.5.4&appid=afzeixqfsh3pgscgbq878cu3xjfxcdth&v=15&clienttype=2&command=getappdata&changenumber=0

503 service unavailable: back-end server @ capacity 0 bytes 48 ms

java android eclipse chat scringo

visual studio 2012 - how to queue in vb.net using phpmyadmin database records ORDERING PROCESS -



visual studio 2012 - how to queue in vb.net using phpmyadmin database records ORDERING PROCESS -

im using vb.net platform , localhost database. how can queue orders database? process client order in android app order details saved in localhost server sick utilize vb.net platform perform queue of orders. hoping replies. , day all.

i utilize timestamp record database , utilize reference queueing orders vb.net application. answering! godbless

vb.net visual-studio-2012

c# - Checking if a string contains words in a specific order -



c# - Checking if a string contains words in a specific order -

here's interesting question, have list contains 3 sentences such as:

bill cat had

bill had cat

cat had bill

how utilize .contains() or other method check if sentences in list contains words in specific order, algorithm shown below:

1) run sentence list through foreach loop

2) check if sentence contains words in order => bill + had + cat

3) homecoming sentence

so every other sentence returned false since order of words different. ideas on implementing this, folks? :)

try below solution works.

class programme { static void main(string[] args) { list<string> list = new list<string>(); list.add("bill cat had"); list.add("bill had cat"); list.add("bill had cat"); list.add("cat had bill"); regex rex = new regex(@"((bill)).*((had)).*((cat))"); foreach (string str in list) { if (rex.ismatch(str)) { console.writeline(str); } } console.readline(); } }

c# string foreach order condition

Advise on renaming a Android project in Android studio(Gradle based) -



Advise on renaming a Android project in Android studio(Gradle based) -

in nowadays project , wish rename android project in android studio (0.8.9) , wish utilize hereafter. know 2 solutions discussed in forum. 1 please confirm best approach , hassle free. advice tried/tested on android studio 0.8.9 best.

solutions know (but not sure) a.- close project under consideration.copy , rename new name , open android studio. in case - project .iml file still shows old name , .name file under ".idea" folder. error:

unsupported modules detected: compilation not supported next modules: . unfortunately can't have non-gradle java modules , android-gradle modules in 1 project.

b. using f6 alternative ,but not copy. think moves entire project, not solution.

the next works me when renaming project:

close android studio delete *.iml file(s) in project's root directory delete in .idea directory except workspace.xml , tasks.xml. rename project's root directory new project name restart android studio , import project renamed directory.

note: if don't care losing workspace settings (window sizes, etc.) , don't have tasks can delete .idea directory entirely.

android android-studio

java - Cannot add Spring Cache advice to method - internalCacheAdvisor is created in same batch as cachable annotated bean -



java - Cannot add Spring Cache advice to method - internalCacheAdvisor is created in same batch as cachable annotated bean -

we have refactored parts of our application, , after that, methods annotated spring cachable stopped beingness cached although class containing cached method not touched.

after debugging, can see after refactoring , adding new spring beans, bean cachable method created in same batch internalcacheadvisor itself. advice can not applied , spring cache aspect never invoked. method result not cached, @cachable annotation not work.

what mechanism deciding beans can created simultaneously, , how can debug , impact mechanism?

i have looked in spring method beanfactoryadvisorretrievalhelper::findadvisorbeans, , when running old , worikng code, looks this:

after refactoring looks this:

our annotated class couchbasetranslationprovider created @ same batch internalcacheadvisor, not possible. when trying apply advice proxy, debug message "skipping created advisor ...". (i think should have been error message!)

our pom-file enabling cache looks this:

@configuration @enablewebmvc @componentscan({"[package]", "[package].connectors"}) @import({eventsconfig.class, cmsconfig.class}) @enablecaching public class apiconfig { public static class caches{ public static final string sports = "sports"; [...] public static final string pipedtranslations = "translations"; } @value("${[package].document}") private string someurl; @bean public couchbaseclient getcouchbaseclient() throws ioexception { [code] } @bean public cachemanager cachemanager() { simplecachemanager cachemanager = new simplecachemanager(); cachemanager.setcaches(arrays.aslist(new concurrentmapcache(caches.sports), [...], new concurrentmapcache(caches.pipedtranslations))); homecoming cachemanager; } @autowired private eventupdategate eventupdategate; @bean @conditionalonproperty("adaptergate.events.active") public adaptergatereceiver eventadaptergatereceiver(@value("${adaptergate.events.gatechannel}") string channel, @value("${adaptergate.events.apiversion}") string version) { homecoming new adaptergatereceiver(channel, version, eventupdategate); } }

java spring spring-annotations spring-cache

python - numpy.gradient() seems to produce erroneous boundary values (using first differences) -



python - numpy.gradient() seems to produce erroneous boundary values (using first differences) -

there seems problem function numpy.gradient() (numpy 1.9.0) regarding how computes boundary (start , end) values (which know using first differences, while central values computed using central differences). consider instance next example:

import numpy np arr = np.array([1, 2, 4]) arrgrad = np.gradient(arr)

i here expect arrgrad obtain values

[ 1. 1.5 2. ]

i.e.

arrgrad[0] = (2-1)/1 = 1 arrgrad[1] = (4-1)/2 = 1.5 arrgrad[2] = (4-2)/1 = 2

but result

[ 0.5 1.5 2.5]

the behaviour of numpy.gradient() version 1.8.1 (obtained https://github.com/numpy/numpy/blob/v1.8.1/numpy/lib/function_base.py) seems produce right result, however.

is erroneous behaviour described above result of bug? (i'm using python 3.4.2, 64 bit.)

apparently way gradients calculated changed between 1.8.1 , 1.9.0 332d628, boundary elements calculated using second-order accurate approximation well, whereas first-order accurate.

however, documentation on numpy website not include 1.9.0 docs, 1.8.1, see proper documentation can utilize np.source(np.gradient) or print(np.gradient.__doc__).

python numpy

ZMQ python socket from context catch exception -



ZMQ python socket from context catch exception -

i have nginx server uwsgi , python pyzmq (installed sudo pip install pyzmq).

i'm trying create socket zmq context, grab exception.

import zmq import os import sys cgi import parse_qs, escape sys.path.append('/usr/share/nginx/www/application') os.environ['python_egg_cache'] = '/usr/share/nginx/www/.python-egg' def application(environ, start_response): ctx = zmq.context() try: message = 'everything ok' s = ctx.socket(zmq.req) except exception e: message = "exception({0}): {1}".format(e.errno, e.strerror) pass response_headers = [('content-type', 'text/plain'), ('content-length', str(len(message)))] start_response('200 ok', response_headers); homecoming [message]

it raised exception

exception(14): bad address

if commented line

s = ctx.socket(zmq.req)

then ok.

i searched on internet, nobody has same problem.

please, have idea, doing wrong?

edit:

i wrote simple python script, working , response recv:

import zmq import os import sys print 'create zeromq instance...' ctx = zmq.context() print 'create socket ...' try: s = ctx.socket(zmq.req) except exception e: print "exception({0}): {1}".format(e.errno, e.strerror) sys.exit() s.connect('tcp://localhost:5555') s.send('fttt;') message = s.recv() print message

i seems problem uwsgi run python zmq, why?

presumably intend utilize socket somewhere below http response? because @ moment you're not connecting or binding on anything, makes "bad address" exception strange. seek creating minimal illustration without cgi, nginx, cache, response stuff, zmq context creation , socket creation , see if raise same exception. if so, appears there's wonky in binding or library. create sure installed correctly , versions compatible.

python sockets nginx zeromq uwsgi

java - Z-buffering algorithm not drawing 100% correctly -



java - Z-buffering algorithm not drawing 100% correctly -

i'm programming software renderer in java, , trying utilize z-buffering depth calculation of each pixel. however, appears work inconsistently. example, utah teapot illustration model, handle draw perhaps half depending on how rotate it.

my z-buffer algorithm:

for(int = 0; < m_triangles.size(); i++) { if(triangleisbackfacing(m_triangles.get(i))) continue; //backface culling for(int y = miny(m_triangles.get(i)); y < maxy(m_triangles.get(i)); y++) { if((y + getheight()/2 < 0) || (y + getheight()/2 >= getheight())) continue; //getheight/2 , getwidth/2 moving model centre of screen for(int x = minx(m_triangles.get(i)); x < maxx(m_triangles.get(i)); x++) { if((x + getwidth()/2 < 0) || (x + getwidth()/2 >= getwidth())) continue; rayorigin = new point2d(x, y); if(pointwithintriangle(m_triangles.get(i), rayorigin)) { zdepth = zvalueofpoint(m_triangles.get(i), rayorigin); if(zdepth > zbuffer[x + getwidth()/2][y + getheight()/2]) { zbuffer[x + getwidth()/2][y + getheight()/2] = zdepth; colour[x + getwidth()/2][y + getheight()/2] = m_triangles.get(i).getcolour(); g2.setcolor(m_triangles.get(i).getcolour()); drawdot(g2, rayorigin); } } } } }

method calculating z value of point, given triangle , ray origin:

private double zvalueofpoint(triangle triangle, point2d rayorigin) { vector3d surfacenormal = getnormal(triangle); double = surfacenormal.x; double b = surfacenormal.y; double c = surfacenormal.z; double d = -(a * triangle.getv1().x + b * triangle.getv1().y + c * triangle.getv1().z); double rayz = -(a * rayorigin.x + b * rayorigin.y + d) / c; homecoming rayz; }

method calculating if ray origin within projected triangle:

private boolean pointwithintriangle(triangle triangle, point2d rayorigin) { vector2d v0 = new vector2d(triangle.getv3().projectpoint(modelviewer), triangle.getv1().projectpoint(modelviewer)); vector2d v1 = new vector2d(triangle.getv2().projectpoint(modelviewer), triangle.getv1().projectpoint(modelviewer)); vector2d v2 = new vector2d(rayorigin, triangle.getv1().projectpoint(modelviewer)); double d00 = v0.dotproduct(v0); double d01 = v0.dotproduct(v1); double d02 = v0.dotproduct(v2); double d11 = v1.dotproduct(v1); double d12 = v1.dotproduct(v2); double invdenom = 1.0 / (d00 * d11 - d01 * d01); double u = (d11 * d02 - d01 * d12) * invdenom; double v = (d00 * d12 - d01 * d02) * invdenom; // check if point in triangle if((u >= 0) && (v >= 0) && ((u + v) <= 1)) { homecoming true; } homecoming false; }

method calculating surface normal of triangle:

private vector3d getnormal(triangle triangle) { vector3d v1 = new vector3d(triangle.getv1(), triangle.getv2()); vector3d v2 = new vector3d(triangle.getv3(), triangle.getv2()); homecoming v1.crossproduct(v2); }

example of incorrectly drawn teapot:

what doing wrong? sense must little thing. given triangles draw @ all, uncertainty it's pointwithintriangle method. backface culling appears work correctly, uncertainty it's that. culprit me zvalueofpoint method, don't know plenty know what's wrong it.

this must slow

so much redundant computations per iteration/pixel iterate coordinates you should compute 3 projected vertexes , iterate between them instead look here: triangle/convex polygon rasterization

i dislike zvalueofpoint function

can not find utilize of x,y coordinates main loops in it so how can compute z value correctly ? or computes average z value per whole triangle ? or missing something? (not java coder myself) in anyway seems main problem if z-value wrongly computed z-buffer can not work properly to test @ depth buffer image after rendering if not shaded teapot incoherent or constant mess instead clear ...

z buffer implementation

it looks ok

[hints]

you have much times terms x + getwidth()/2 why not compute them 1 time variable? i know modern compilers should anyway code more readable , shorter... at to the lowest degree me

java algorithm graphics 3d zbuffer

Creating new variable in SAS -



Creating new variable in SAS -

i have panel dataset in sas, looks this:

data have; input id time income; cards; 1 2008 1000 1 2009 900 1 2010 1100 2 2008 600 2 2009 500 2 2010 400 3 2008 300 3 2009 350 3 2010 250 ; run;

for each individual, want create new column (named income_id) income of individual in time periods , 0 other individuals. want this:

data want; input id time income income_1 income_2 income_3; cards; 1 2008 1000 1000 0 0 1 2009 900 900 0 0 1 2010 1100 1100 0 0 2 2008 600 0 600 0 2 2009 500 0 500 0 2 2010 400 0 400 0 3 2008 300 0 0 300 3 2009 350 0 0 350 3 2010 250 0 0 250 ; run;

thanks

an intuitive way using macros.

there sugi yunchao tian explaining how perform task here.

i adapted code here you. tested , seems work alright.

proc sort data=have out=unique nodupkey; id; run; /* assign largest value of id macro variable nmax */ info _null_; set unique end=last; if lastly phone call symput('nmax', put(id, 3.)); run; /* create macro variables , assign value 0*/ info _null_; i=1 &nmax; phone call symput('m'||left(put(i,3.)), '0' ); end; run; /* assign value of id corresponding macro variable */ info _null_; set have; phone call symput('m'||left(put(id,3.)), put(id,3.)); run; /* macro create code set col income or 0 */ %macro getid; %do = 1 %to &nmax; %if &&m&i = 0 %then %goto out; if id = &&m&i income_&i = income; else income_&i = 0; %out: %end; %mend getid; /* execute macro */ info want; set have; %getid run; proc print data=want; run;

sas

PHP/JavaScript Cross pages music player -



PHP/JavaScript Cross pages music player -

i had thought before , thought won't executed without iframe or ajax calls.

i couldn't maintain mp3 file or radio channel working after changing url in website, example,

website.com/profile

to

website.com/news

the whole page alter of course, , mp3 or radio have load again.

but, realized soundcloud has feature - after playing music, when exploring site, music keeps working, , when comeback music page, never left page.

also, facebook uses in chat on right. when alter pages, of time, chat won't wound change, meaning chat keeps working if you're on same page , never changed it.

i hope guys help me , tell me technology they're using in this?

iframe , ajax phone call way it. ajax phone call favorite:

$.ajax({ url: "my url", async: true }).done(function(result) { $("#mydiv").html(result); });

javascript php cookies player

c# - using reflection to compare object in list -



c# - using reflection to compare object in list -

i have 'invoice' winform c# contains usual textboxes , unbound datagridview. used 'invoice' class object store form fields' values. datagridview rows stored list < subinvoice> properties in 'invoice'.

public static bool compareobjects(object original, object altered) { type o = original.gettype(); type = altered.gettype(); foreach (propertyinfo p in o.getproperties(bindingflags.public | bindingflags.instance)) { console.writeline("original: {0} = {1}", p.name, p.getvalue(original, null)); console.writeline("altered: {0} = {1}", p.name, p.getvalue(altered, null)); if (p.getvalue(original, null).tostring() != p.getvalue(altered, null).tostring()) { //console.writeline("not equal"); homecoming false; } } homecoming true; }

i using global class method uses reflection loop through original 'invoice' object , compared altered 'invoice'. if there difference, user notified save invoice.

the above method works fine properties of 'invoice' class not know how check list in stores value of each datagridrow 'subinvoice' class object stored object in list.

can please give me help here? have checked similar thread in stackoverflow , other forums in vain.

update: need create global generic method check type of classes. can 'invoice', 'customer'. purpose track changes made form @ particular instance , prompt user save.

if whant inform user save pending changes should implement inotifypropertychanged instead of doing black magic.

c# winforms reflection

SQL Server: Two table join show all rows where there's no data per day -



SQL Server: Two table join show all rows where there's no data per day -

i'm trying create study query shows given date range, names, dates, , if there's data. i'm close i'm @ loss on how these final 0 values in data. here's want:

name id mth day count auburn 7261 10 14 0 auburn 7261 10 15 0 auburn 7261 10 16 0 auburn 7261 10 17 0 auburn 7261 10 18 0 concord 7262 10 14 2 concord 7262 10 15 0 concord 7262 10 15 0 concord 7262 10 17 1 katey 7263 10 14 0 katey 7263 10 15 0 katey 7263 10 16 0 katey 7263 10 17 0 katey 7263 10 18 0

instead i'm getting:

name id mth day count auburn 7261 10 14 0 auburn 7261 10 15 0 auburn 7261 10 16 0 auburn 7261 10 17 0 auburn 7261 10 18 0 concord 7262 10 14 2 concord 7262 10 17 1 katey 7263 10 14 0 katey 7263 10 15 0 katey 7263 10 16 0 katey 7263 10 17 0 katey 7263 10 18 0

here's query:

select pue.name [name], pue.eventid, month(dates.date) month, day(dates.date) day, puc.idcount picturestaken ( select name, eventid events tourid = 444 , eventid > 7256 , eventid < 7323 ) pue outer apply ( select date = dateadd( day, n1.number * 10 + n0.number, '2014-10-14' ) (select 1 number union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) n0 cross bring together (select 1 number union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9 union select 0) n1 dateadd( day, n1.number * 10 + n0.number, '2014-10-14' ) between '2014-10-14' , '2014-10-18' ) dates left outer bring together ( select eventid, convert(date,picturetakendate) picdate, count(consumerdataid) idcount consumerdata eventid > 7256 , eventid < 7323 grouping eventid, convert(date,picturetakendate) ) puc on pue.eventid = puc.eventid puc.picdate = dates.date or puc.idcount null order pue.eventid, month(dates.date), day(dates.date)

i why zeros not showing names, here's outer joined table results:

7262 2014-10-14 2 7262 2014-10-17 1 7265 2014-10-14 2 7266 2014-10-14 2

so makes sense in clause not null or matching date. if take out clause row every count every date i.e.:

concord 7262 10 14 2 concord 7262 10 14 1 concord 7262 10 15 1 concord 7262 10 15 2 concord 7262 10 16 2 concord 7262 10 16 1 concord 7262 10 17 1 concord 7262 10 17 2 concord 7262 10 18 2 concord 7262 10 18 1

i'm close, know there just simple i'm missing each effort create prepare makes results worse, i'm here help. figure need wither prepare query in outer bring together somehow show every date , if reference dates apply easier or alter where. i've been unable figure out how.

add isnull status in select clause

select pue.name [name], pue.eventid, month(dates.date) month, day(dates.date) day, isnull(puc.idcount,0) picturestaken

convert clause on

on pue.eventid = puc.eventid , puc.picdate = dates.date

instead of

where puc.picdate = dates.date or puc.idcount null

sql sql-server join report outer-join

bash - saving output of nettop to file ( mac ) -



bash - saving output of nettop to file ( mac ) -

i'm trying save output of nettop terminal text file ( maybe .csv ) want able isolate different values, want track bytes coming in particular application ( can reference file in application ) i'm not familiar bash scripting imagine right script accomplish sort of thing, or there improve way?

bash shell scripting terminal

angularjs - Nessted Ng-Repeat breaking the inner loop -



angularjs - Nessted Ng-Repeat breaking the inner loop -

i trying render construction nested ng-repeat.

my object construction follows

outercollection: [ { .... .... innercollection: [ // number of objects here variable. can 0 well. {}, {} ] .... }, { .... .... innercollection: [ {}, {} ] .... } ]

now need render inner collection , limit 2.

i need thing similar nested inner loop should execute couple of entries.

foreach(collection in outercollection) { foreach(entry in collection.innercollection) { if(count ==2) break; // , increment count } }

<div ng-repeat="o in outercollection"> <div ng-repeat="innercollection in o|limitto:2"></div> </div>

angularjs angularjs-ng-repeat

controller - tuning pid in systems with delay -



controller - tuning pid in systems with delay -

i need tune pi(d) gains in scheme has quite big delay. it's mutual temperature controller, temperature probe far away heater. farther info:

the response of probe delayed 10 seconds alter on heater

the temperature sampled @ 1 hz, resolution of 0.01 °c

the heater controller in pwm period of 1 hz, 10-bit pwm

the goal maintain oscillation below ±0.05 °c

currently i'm using controller pi. can't avoid oscillations. higher gain, smaller , faster oscillations. still high (about ±0.15 °c). reducing p , gains leads long , deep oscillations.

i think due delay. settling time not problem, may take time needs.

i'm puzzling on how scheme work. let's think utilize i. when probe reaches target value , output starts decrease, temperature rising other time. cannot utilize derivative term because variations slow , derror close 0 (if set dgain huge value there much noise).

any idea?

normally big delays have 2 options: lower gains of scheme or, if have model of plant controlling, utilize smith predictior.

i start modelling scheme (using open-loop steps in input) quantify delay , time constant of plant, check if sampling of temperature , pwm rate ok.

notice if pwm frequency little in comparing plant dynamics, will have sustained oscillations because of slow pwm. can check using constant input pwm (with no controllers, open loop).

edit: didn't see problem solved, i'll leave here reference.

controller delay pid temperature

mysql - How to search for substring in one of two fields of a table -



mysql - How to search for substring in one of two fields of a table -

i have table 3 columns: id, first, , last.

i'd find records 'sam' in either first or lastly field.

i'm not expert mysql, seems me 1 field queried using like operator.

how can utilize like in query info both columns @ same time?

i've tried this:

select id `employees` 'first' 'sam' or 'last' 'sam'

but message "you have error in sql syntax; check manual corresponds mysql server version right syntax."

i can't seem figure out why getting syntax error, 1 problem query putting single quotes around column name causes treated string literal instead of column name.

what mean instead of comparing value in first column string 'sam', it's comparing 2 strings, 'first' , 'sam' different. query homecoming no results.

in addition, work if first or lastly name equal sam. check characters substring @ point, add together wildcards @ front end , of strings.

try this:

select id employees first '%sam%' or lastly '%sam%'

here sql fiddle show how works.

mysql sql