Saturday, 15 June 2013

Why does Lucene (Hibernate Search) ignore my own operator? -



Why does Lucene (Hibernate Search) ignore my own operator? -

i updated hibernate search 5.0.0.alpha4, uses lucene 4.8.1.

i still utilize same codes create search query before (i used lucene 3.3 before updating, old version:)). noticed problem, new version ignores operator , uses default operator time, codes worked fine in older version:

for example: set "and" default operator. typed "java or php" in search field. , made breakpoint @ line of queryparser.parse(searchstring). tells me searchstring "java or php", correct. created searchquery after queryparser.parse() is:

+(title:java) +(title:php)

which means lucene deals searchstring "and" logic!

i don't know if bug of newer lucene or did wrong.

here codes:

standardanalyzer analyzer = new standardanalyzer( version.lucene_47); multifieldqueryparser queryparser = new multifieldqueryparser( version.lucene_47, mysearchfields, analyzer); queryparser.setallowleadingwildcard(true); queryparser.setdefaultoperator(mydefaultoperator); queryparser.setautogeneratephrasequeries(true); query searchquery = queryparser.parse(searchstring); fulltextquery jpaquery = getfulltextentitymanager() .createfulltextquery(searchquery, entities); jpaquery.setmaxresults(oracle_maximum_elements_in_expression);

boolean operators must in caps. is: java or php correct, java or php not.

to explain going on, without or beingness in caps, it's treated term. and beingness default operator, makes it:

java , or , php

or, like

+(title:java) +(title:or) +(title:php)

however, or standard stop word, , eliminated during analysis of query, , left simply:

+(title:java) +(title:php)

lucene hibernate-search

combining ranges for pandas (NumPy? core python?) indexing -



combining ranges for pandas (NumPy? core python?) indexing -

i loading info of size comparable memory limits, conscious efficient indexing , not making copies. need work on columns 3:8 , 9: (also labeled), combining ranges not seem work. rearranging columns in underlying info needlessly costly (an io operation). referencing 2 dataframes , combining them sounds create copies. efficient way this?

import numpy np import pandas pd info = pd.read_stata('s:/data/controls/lasso.dta') x = pd.concat([data.iloc[:,3:8],data.iloc[:,9:888]])

by way, if read in half of info (a random half, even), help, 1 time again not open original info , save another, smaller re-create this.

import numpy np import pandas pd info = pd.read_stata('s:/data/controls/lasso.dta') cols = np.zeros(len(data.columns), np.dtype=bool) cols[3:8] = true cols[9:888] = true x = data.iloc[:, cols] del info

this still makes re-create (but one...). not seem possible homecoming view instead of re-create sort of shape (source).

another suggestion converting .dta file .csv file (howto). pandas read_csv much more flexible: can specify columns interested in (usecols), , how many rows read (nrows). unfortunately requires file copy.

python numpy pandas indexing

c# - does parallel foreach creates different copies of functions in it -



c# - does parallel foreach creates different copies of functions in it -

i have next scenario ,

parallel.foreach(al , sentence => { function abc { double x; } y = add(ref y, x) } public static double add(ref double location1, double value) { double newcurrentvalue = 0; while (true) { double currentvalue = newcurrentvalue; double newvalue = currentvalue + value; newcurrentvalue = interlocked.compareexchange(ref location1, newvalue, currentvalue); if (newcurrentvalue == currentvalue) homecoming newvalue; } }

for each sentence in array of sentence al there value of x calculated. , want sum these values of sentences in variable y. when run code each time different value of y. , guess because x getting overwritten before writing y. each sentence parallel foreach creating different or same re-create of function abc? how can prepare this.

since multiple threads access y writing @ same time

for ex, below code may not result in 4950

int y=0; parallel.foreach(enumerable.range(0, 100), x => y += x);

but 1 ensures it

int z = 0; parallel.foreach(enumerable.range(0, 100), x => interlocked.add(ref z, x));

c#

jdbc - java.sql.SQLException: - ORA-01000: maximum open cursors exceeded -



jdbc - java.sql.SQLException: - ORA-01000: maximum open cursors exceeded -

i getting above ora-01000 sql exception. have queries related it.

maximum open cursors related no of jdbc connections, or related statement objects , resultset objects have created single connections? since using pool of connections. is there in database can specify no of statement/resultset objects connections? is advisable utilize instance variable statement/resultset object instead of method local statement/resultset object in single threaded environment?

does executing prepare stmt on loop cause issue? (of course of study should have used sqlbatch) note: pstmt closed 1 time loop over.

{ //method seek starts string sql = "insert tblname (col1, col2) values(?, ?)"; pstmt = obj.getconnection().preparestatement(sql); pstmt.setlong(1, subscriberid); (string language : additionallangs) { pstmt.setint(2, integer.parseint(language)); pstmt.execute(); } } //method/try ends { //finally starts pstmt.close() } //finally ends

what happen if conn.createstatement() , conn.preparestatement(sql) called multiple times on single connection object?

edit1: 6. utilize of weak/soft reference statement object reference help anymore on leakage?

edit2: 7. there best way; can find in project , statement.close() not happened properly? understand not memory leak. need find statement reference(close() not performed) eligible garbage collection? tool available? or have manually analyze it?

please create me aware more it.

solution to find opened cursor in oracle db username -velu

go oralce machine , start sqlplus sysdba.

[oracle@db01 ~]$ sqlplus / sysdba

then run

select a.value, s.username, s.sid, s.serial# v$sesstat a, v$statname b, v$session s a.statistic# = b.statistic# , s.sid=a.sid , b.name = 'opened cursors current' , username = 'velu';

if possible please read reply @ end..

ora-01000, maximum-open-cursors error, extremely mutual error in oracle database development. in context of java, happens when application attempts open more resultsets there configured cursors on database instance.

common causes are:

configuration mistake

you have more threads in application querying database cursors on db. 1 case have connection , thread pool larger number of cursors on database. you have many developers or applications connected same db instance (which include many schemas) , using many connections.

solution:

increasing number of cursors on database (if resources allow) or decreasing number of threads in application.

cursor leak

the applications not closing resultsets (in jdbc) or cursors (in stored procedures on database) solution: cursor leaks bugs; increasing number of cursors on db delays inevitable failure. leaks can found using static code analysis, jdbc or application-level logging, , database monitoring. background

this section describes of theory behind cursors , how jdbc should used. if don't need know background, can skip , go straight 'eliminating leaks'.

what cursor?

a cursor resource on database holds state of query, position reader in resultset. each select statement has cursor, , pl/sql stored procedures can open , utilize many cursors require. can find out more cursors on orafaq.

a database instance typically serves several different schemas, many different users each multiple sessions. this, has fixed number of cursors available schemas, users , sessions. when cursors open (in use) , request comes in requires new cursor, request fails ora-010000 error.

finding , setting number of cursors

the number configured dba on installation. number of cursors in use, maximum number , configuration can accessed in administrator functions in oracle sql developer. sql can set with:

alter scheme set open_cursors=1337 sid='*' scope=both; relating jdbc in jvm cursors on db

the jdbc objects below tightly coupled next database concepts:

jdbc connection client representation of database session , provides database transactions. connection can have single transaction open @ 1 time (but transactions can nested) a jdbc resultset supported single cursor on database. when close() called on resultset, cursor released. a jdbc callablestatement invokes stored procedure on database, written in pl/sql. stored procedure can create 0 or more cursors, , can homecoming cursor jdbc resultset.

jdbc thread safe: quite ok pass various jdbc objects between threads.

for example, can create connection in 1 thread; thread can utilize connection create preparedstatement , 3rd thread can process result set. single major restriction cannot have more 1 resultset open on single preparedstatement @ time. see does oracle db back upwards multiple (parallel) operations per connection?

note database commit occurs on connection, , dml (insert, update , delete's) on connection commit together. therefore, if want back upwards multiple transactions @ same time, must have @ to the lowest degree 1 connection each concurrent transaction.

closing jdbc objects

a typical illustration of executing resultset is:

statement stmt = conn.createstatement(); seek { resultset rs = stmt.executequery( "select full_name emp" ); seek { while ( rs.next() ) { system.out.println( "name: " + rs.getstring("full_name") ); } } { seek { rs.close(); } grab (exception ignore) { } } } { seek { stmt.close(); } grab (exception ignore) { } }

note how clause ignores exception raised close():

if close resultset without seek {} grab {}, might fail , prevent statement beingness closed we want allow exception raised in body of seek propagate caller. if have loop over, example, creating , executing statements, remember close each statement within loop.

in java 7, oracle has introduced autocloseable interface replaces of java 6 boilerplate nice syntactic sugar.

holding jdbc objects

jdbc objects can safely held in local variables, object instance , class members. improve practice to:

use object instance or class members hold jdbc objects reused multiple times on longer period, such connections , preparedstatements use local variables resultsets since these obtained, looped on , closed typically within scope of single function.

there is, however, 1 exception: if using ejbs, or servlet/jsp container, have follow strict threading model:

only application server creates threads (with handles incoming requests) only application server creates connections (which obtain connection pool) when saving values (state) between calls, have careful. never store values in own caches or static members - not safe across clusters , other weird conditions, , application server may terrible things data. instead utilize stateful beans or database. in particular, never hold jdbc objects (connections, resultsets, preparedstatements, etc) on different remote invocations - allow application server manage this. application server not provides connection pool, caches preparedstatements. eliminating leaks

there number of processes , tools available helping observe , eliminating jdbc leaks:

during development - catching bugs far best approach:

development practices: development practices should cut down number of bugs in software before leaves developer's desk. specific practices include:

pair programming, educate without sufficient experience code reviews because many eyes improve one unit testing means can exercise , of code base of operations test tool makes reproducing leaks trivial use existing libraries connection pooling rather building own

static code analysis: utilize tool first-class findbugs perform static code analysis. picks many places close() has not been correctly handled. findbugs has plugin eclipse, runs standalone one-offs, has integrations jenkins ci , other build tools

at runtime:

holdability , commit

if resultset holdability resultset.close_cursors_over_commit, resultset closed when connection.commit() method called. can set using connection.setholdability() or using overloaded connection.createstatement() method.

logging @ runtime.

put log statements in code. these should clear , understandable customer, back upwards staff , teammates can understand without training. should terse , include printing state/internal values of key variables , attributes can trace processing logic. logging fundamental debugging applications, have been deployed.

you can add together debugging jdbc driver project (for debugging - don't deploy it). 1 illustration (i have not used it) log4jdbc. need simple analysis on file see executes don't have corresponding close. counting open , closes should highlight if there potential problem

monitoring database. monitor running application using tools such sql developer 'monitor sql' function or quest's toad. monitoring described in this article. during monitoring, query open cursors (eg table v$sesstat) , review sql. if number of cursors increasing, , (most importantly) becoming dominated 1 identical sql statement, know have leak sql. search code , review. other thoughts can utilize weakreferences handle closing connections?

weak , soft references ways of allowing reference object in way allows jvm garbage collect referent @ time deems fit (assuming there no strong reference chains object).

if pass referencequeue in constructor soft or weak reference, object placed in referencequeue when object gc'ed when occurs (if occurs @ all). approach, can interact object's finalization , close or finalize object @ moment.

phantom references bit weirder; purpose command finalization, can never reference original object, it's going hard phone call close() method on it.

however, thought effort command when gc run (weak, soft , phantomreferences allow know after fact object enqueued gc). in fact, if amount of memory in jvm big (eg -xmx2000m) might never gc object, , still experience ora-01000. if jvm memory little relative program's requirements, may find resultset , preparedstatement objects gced after creation (before can read them), fail program.

tl;dr: weak reference mechanism not way manage , close statement , resultset objects.

java jdbc

linux - Unknown users rights (-????????? ? ? ? ? ? myFile.php) -



linux - Unknown users rights (-????????? ? ? ? ? ? myFile.php) -

i have weirds user rights on files.

log user1, have set user2 owner of files. did worked.

-rw-r-xr-x 1 user2 user2 21090 jun 18 16:28 myfile.php drw-r-xr-x 2 user2 user2 4096 jun 18 16:30 font

but then, when log user2 have weirds unknown rights.

-????????? ? ? ? ? ? myfile.php d????????? ? ? ? ? ? font/

top directory contains these files has no "x" bit set.

chmod u=rwx test2/; ls -l test2 total 4 drwxr-xr-x 2 user grouping 4096 jun 19 14:43 dir -rw-r--r-- 1 user grouping 0 jun 19 14:43 file chmod u=rw test2/; ls -l test2 ls: cannot access test2/file: permission denied ls: cannot access test2/dir: permission denied total 0 d????????? ? ? ? ? ? dir -????????? ? ? ? ? ? file

to prepare this, please add together "x" bit next section of root directory. "group" part relevant might "others" or "user" depending on situation.

chmod g+x /path/to/directory

for farther reading please consult http://www.linux.com/learn/tutorials/309527-understanding-linux-file-permissions

linux admin chmod rights

parsing - How do you parse and process HTML/XML in PHP? -



parsing - How do you parse and process HTML/XML in PHP? -

how can 1 parse html/xml , extract info it?

this general reference question php tag

native xml extensions

i prefer using 1 of native xml extensions since come bundled php, faster 3rd party libs , give me command need on markup.

dom

the dom extension allows operate on xml documents through dom api php 5. implementation of w3c's document object model core level 3, platform- , language-neutral interface allows programs , scripts dynamically access , update content, construction , style of documents.

dom capable of parsing , modifying real world (broken) html , can xpath queries. based on libxml.

it takes time productive dom, time worth imo. since dom language-agnostic interface, you'll find implementations in many languages, if need alter programming language, chances know how utilize language's dom api then.

a basic usage illustration can found in grabbing href attribute of element , general conceptual overview can found @ domdocument in php

how utilize dom extension has been covered extensively on stackoverflow, if take utilize it, can sure of issues run can solved searching/browsing stack overflow.

xmlreader

the xmlreader extension xml pull parser. reader acts cursor going forwards on document stream , stopping @ each node on way.

xmlreader, dom, based on libxml. not aware of how trigger html parser module, chances using xmlreader parsing broken html might less robust using dom can explicitly tell utilize libxml's html parser module.

a basic usage illustration can found @ getting values h1 tags using php

xml parser

this extension lets create xml parsers , define handlers different xml events. each xml parser has few parameters can adjust.

the xml parser library based on libxml, , implements sax style xml force parser. may improve selection memory management dom or simplexml, more hard work pull parser implemented xmlreader.

simplexml

the simplexml extension provides simple , usable toolset convert xml object can processed normal property selectors , array iterators.

simplexml alternative when know html valid xhtml. if need parse broken html, don't consider simplexml because choke.

a basic usage illustration can found @ a simple programme crud node , node values of xml file , there lots of additional examples in php manual.

3rd party libraries (libxml based)

if prefer utilize 3rd-party lib, i'd suggest using lib uses dom/libxml underneath instead of string parsing.

phpquery (not updated years)

phpquery server-side, chainable, css3 selector driven document object model (dom) api based on jquery javascript library written in php5 , provides additional command line interface (cli).

also see: https://github.com/electrolinux/phpquery

zend_dom

zend_dom provides tools working dom documents , structures. currently, offer zend_dom_query, provides unified interface querying dom documents utilizing both xpath , css selectors.

querypath

querypath php library manipulating xml , html. designed work not local files, web services , database resources. implements much of jquery interface (including css-style selectors), heavily tuned server-side use. can installed via composer.

fluentdom

fluentdom provides jquery-like fluent xml interface domdocument in php. selectors written in xpath or css (using css xpath converter). current versions extend dom implementing standard interfaces , add together features dom living standard. fluentdom can load formats json, csv, jsonml, rabbitfish , others. can installed via composer.

fdomdocument

fdomdocument extends standard dom utilize exceptions @ occasions of errors instead of php warnings or notices. add together various custom methods , shortcuts convenience , simplify usage of dom.

sabre/xml

sabre/xml library wraps , extends xmlreader , xmlwriter classes create simple "xml object/array" mapping scheme , design pattern. writing , reading xml single-pass , can hence fast , require low memory on big xml files.

fluidxml

fluidxml php library manipulating xml concise , fluent api. leverages xpath , fluent programming pattern fun , effective.

3rd-party (not libxml-based)

the benefit of building upon dom/libxml performance out of box because based on native extension. however, not 3rd-party libs go downwards route. of them listed below

simplehtmldom an html dom parser written in php5+ lets manipulate html in easy way! require php 5+. supports invalid html. find tags on html page selectors jquery. extract contents html in single line.

i not recommend parser. codebase horrible , parser rather slow , memory hungry. of libxml based libraries should outperform easily.

ganon a universal tokenizer , html/xml/rss dom parser ability manipulate elements , attributes supports invalid html , utf8 can perform advanced css3-like queries on elements (like jquery -- namespaces supported) a html beautifier (like html tidy) minify css , javascript sort attributes, alter character case, right indentation, etc. extensible parsing documents using callbacks based on current character/token operations separated in smaller functions easy overriding fast , easy

never used it. can't tell if it's good.

html 5

you can utilize above parsing html5, there can quirks due markup html5 allows. html5 want consider using dedicated parser, like

html5lib

a python , php implementations of html parser based on whatwg html5 specification maximum compatibility major desktop web browsers.

we might see more dedicated parsers 1 time html5 finalized. there blogpost w3's titled how-to html 5 parsing worth checking out.

webservices

if don't sense programming php, can utilize web services. in general, found little utility these, that's me , utilize cases.

yql

the yql web service enables applications query, filter, , combine info different sources across internet. yql statements have sql-like syntax, familiar developer database experience.

scraperwiki.

scraperwiki's external interface allows extract info in form want utilize on web or in own applications. can extract info state of scraper.

regular expressions

last , least recommended, can extract info html regular expressions. in general using regular expressions on html discouraged.

most of snippets find on web match markup brittle. in cases working particular piece of html. tiny markup changes, adding whitespace somewhere, or adding or changing attributes in tag, can create regex fails when it's not written. should know doing before using regex on html.

html parsers know syntactical rules of html. regular expressions have taught each new regex write. regex fine in cases, depends on use-case.

you can write more reliable parsers, writing complete , reliable custom parser regular expressions waste of time when aforementioned libraries exist , much improve job on this.

also see parsing html cthulhu way

books

if want spend money, have at

php architect's guide webscraping php

i not affiliated php architect or authors.

php parsing xml-parsing html-parsing

Equinox OSGi bash script execution and bundle permission -



Equinox OSGi bash script execution and bundle permission -

i searched around , haven't found appropriate reply 2 questions:

is possbile execute bash script within (exuinox) osgi bundle?

is possible add together specific permission 1 bundle within (equinox) osgi container?

description example: running (equinox) osgi special user (usera) , user have special permission on os. , want grant these special permissions specific bundle, , other bundles shouldn't have permissions.

thank you!

best!

osgi bundles hold java code. java can do, can do. can runtime.exec bash.

bash osgi bundle containers equinox

Buggy canvas animation on click with JavaScript -



Buggy canvas animation on click with JavaScript -

i'm trying run simple animation each time when user clicks on canvas. i'm sure did wrong animation doesn't fire @ times. have never used canvas animation before , have difficulty understanding how should constructed within for loop.

fgcanvas.on('mousedown', function(e) { var cx = math.round((e.offsetx - m) / gs), cy = math.round((e.offsety - m) / gs); clickdot({x:cx,y:cy}); }); function clickdot(data) { (var = 1; < 100; i++) { fctx.clearrect(0, 0, pw, ph); fctx.beginpath(); fctx.arc(data.x * gs + m, data.y * gs + m, i/10, 0, math.pi * 2); fctx.strokestyle = 'rgba(255,255,255,' + i/10 + ')'; fctx.stroke(); } requestanimationframe(clickdot); }

full code here: http://jsfiddle.net/3nk4a/

the other question how can slow downwards animation or add together easing, rings drawn slower towards end when disappear?

you can utilize requestanimationframe plus easing functions create desired effect:

a demo: http://jsfiddle.net/m1erickson/cevgf/

requestanimationframe creates animation loop itself--so there's no need utilize for-loop within requestanimationframe's animation loop.

in simplest form, requestanimationframe loop animate circle:

var counter=1; animate(); function animate(){ // stop animation after has run 100 times if(counter>100){return;} // there's more animating do, request loop requestanimationframe(animate); // calc circle radius var radius=counter/10; // draw circle }

to animation speed-up or slow-down, can utilize easings. easings alter value (like radius) on time, alter value unevenly. easings speed-up , slow-down on duration of animation.

robert penner made great set of easing algorithms. dan rogers coded them in javascript:

https://github.com/danro/jquery-easing/blob/master/jquery.easing.js

you can see working examples of easing functions here:

http://easings.net/

here's annotated code using requestanimationframe plus easings animate circles.

<!doctype html> <html> <head> <link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css --> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <style> #canvas{border:1px solid red;} </style> <script> $(function(){ // canvas related variables var canvas=document.getelementbyid("canvas"); var ctx=canvas.getcontext("2d"); var $canvas=$("#canvas"); var canvasoffset=$canvas.offset(); var offsetx=canvasoffset.left; var offsety=canvasoffset.top; var scrollx=$canvas.scrollleft(); var scrolly=$canvas.scrolltop(); // set context styles ctx.linewidth=1; ctx.strokestyle="gold"; ctx.fillstyle="#888"; // variables used draw & animate ring var pi2=math.pi*2; var ringx,ringy,ringradius,ingcounter,ringcountervelocity; // fill canvas background color ctx.fillrect(0,0,canvas.width,canvas.height); // tell handlemousedown handle mousedown events $("#canvas").mousedown(function(e){handlemousedown(e);}); // set ring variables , start animation function ring(x,y){ ringx=x; ringy=y; ringradius=0; ringcounter=0; ringcountervelocity=4; requestanimationframe(animate); } // animation loop function animate(){ // homecoming if animation finish if(ringcounter>200){return;} // otherwise request animation loop requestanimationframe(animate); // ringcounter<100 means ring expanding // ringcounter>=100 means ring shrinking if(ringcounter<100){ // expand ring using easeincubic easing ringradius=easeincubic(ringcounter,0,15,100); }else{ // shrink ring using easeoutcubic easing ringradius=easeoutcubic(ringcounter-100,15,-15,100); } // draw ring @ radius set using easing functions ctx.fillrect(0,0,canvas.width,canvas.height); ctx.beginpath(); ctx.arc(ringx,ringy,ringradius,0,pi2); ctx.closepath(); ctx.stroke(); // increment ringcounter next loop ringcounter+=ringcountervelocity; } // robert penner's easing functions coded dan rogers // // https://github.com/danro/jquery-easing/blob/master/jquery.easing.js // // now=elapsed time, // startvalue=value @ start of easing, // deltavalue=amount value alter during easing, // duration=total time easing function easeincubic(now, startvalue, deltavalue, duration) { homecoming deltavalue*(now/=duration)*now*now + startvalue; } function easeoutcubic(now, startvalue, deltavalue, duration) { homecoming deltavalue*((now=now/duration-1)*now*now + 1) + startvalue; } // handle mousedown events function handlemousedown(e){ // tell browser we'll handle event e.preventdefault(); e.stoppropagation(); // calc mouse position mousex=parseint(e.clientx-offsetx); mousey=parseint(e.clienty-offsety); // animate ring @ mouse position ring(mousex,mousey); } }); // end $(function(){}); </script> </head> <body> <h4>click in canvas draw animated circle easings.</h4> <canvas id="canvas" width=300 height=300></canvas> </body> </html>

javascript animation html5-canvas

SOAPUI cannot import updated java file in Groovy script -



SOAPUI cannot import updated java file in Groovy script -

i have testcase in soapui, , in 1 of groovy scripts imports java file , uses 1 of methods in it. (this .java file, not .jar file)

my groovy script

import com.aaa.bbb.ccc.myjavafile myjavafile.method('anystring')

i updated javafile method take in 2 inputs method(string,int)

but when reran testcase, error:

groovy.lang.missingmethodexception: no signature of method: static com.aaa.bbb.ccc.myjavafile.method() apoplicable argument types: (java.lang.string,java.lang.integer).

it looks changes made in java file not beingness imported in script. ideas?

when start soapui, in log tab need see message "info:adding [c:\program files\smartbear\soapui-...\bin\ext\myjavafile.jar] extensions classpath" or soapui did not see it!

make sure had placed .jar in $soapui_home/bin/ext directory.

java groovy soapui

Need help understanding pointers in given code -



Need help understanding pointers in given code -

fbyte *d = (fbyte*) dst; const fbyte *s = (const fbyte*) src; while(cnt >= sizeof(int)) { *(int*) d = *(int*) s; d += sizeof(int); s += sizeof(int); cnt -= sizeof(int); }

i new c programming , unable understand how 4th line of code working

*(int*) d = *(int*) s;

any help appreciated.

this whole piece of code copying buffer in src dst. while loop iterates on src, , in each iteration copies single int.

let's examine right hand side of 4th line:

s pointer area of source memory want copy. the first cast ((int *)s) means treating pointer int the deference before (* (int *)s) means take value point pointing to.

the same applies left hand side of expression.

so, basically, you're iterating on src buffer, , in each iteration copying value of current int dst.

pointers

copy paste - Windows, Watching a folder in C# -



copy paste - Windows, Watching a folder in C# -

i have folder contains read-only files. found out so-called watchservice [1][2] can monitor create, delete or modified events in folder. need notification when user opens, copies and/or moves 1 of files within folder new location.

is possible? can point me right direction?

thanks in advance!

[1] ... http://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx

[2] ... http://docs.oracle.com/javase/tutorial/essential/io/notification.html

c# copy-paste filesystemwatcher

zebra printers - ZPL Center text vertically -



zebra printers - ZPL Center text vertically -

is there way in zpl center text vertically?

i know can utilize ^fo0,0^asn,50^fb200,3,0,c,0^fd text ^fs. how can create print on 2nd line if it's short enough?

there isn't vertical centering feature, can false it, if know in advance string short plenty fit on middle line.

your ^fb defines field block 3 lines. best alternative determine if string fits on 1 line... , if does, insert "\&" before string.

^fo0,0^asn,50^fb200,3,0,c,0^fd\&text^fs

zebra-printers zpl

javascript - passing event trigger as function arguement with jquery .on() -



javascript - passing event trigger as function arguement with jquery .on() -

i have line of code trigger function when of <td>s clicked:

$("#grid .square").on( "click", move(e) );

it triggers function, says e undefined. how can pass on element triggers event argument?

is there way other utilize if .on()?

something like:

$( document ).on( "click", "#grid .square", move(e) );

you can bind anonymous function , pass eventdata parameter click function. you sure don't know anonymous?

eventdata type: object object containing info passed event handler.

$("#grid").on('click',{anon:'people power\nknowledge power'}, function(event){ move(event.data); }); jsfiddle

javascript jquery variables arguments

curl php grep to a variable for printing -



curl php grep to a variable for printing -

i have tried few different things in dom, nil quite working yet. i've got lot larn still. give thanks in advance help.

this question different 1 posted. previous shell script come in info database. need go in different direction. question parsing info in php , assign variable can show pertinent info -- no database or shell scripting, php. can utilize regular expressions in someway in php.... like: grep -po '[0-9]+(?=[^0-9]+(c5:2<|c5:6<|c5:13))'

i have device on network provides table of info piece of equipment. need able curl site , parse values table variables. below device provides. can help me in how parse info table variables? in particular i'm looking numbers @ end of c5:1 , c5:5, have values of 191 , 1506 in example.

<html><head><title>data table monitor</title></head> <body bgcolor="#ffffff"><center> <h2><font face="helvetica">ethernet processor</font></h2> <h2><i>data table monitor</i></h2> <hr width=25% align=center> <meta http-equiv="refresh" content="15"><body bgcolor="#ffffff"><center><table border=1><tr><th>address</th><th>cu</th><th>cd</th><th>dn</th><th>ov</th><th>un</th> <th>ua</th><th>pre</th><th>acc</th><th>address</th><th>cu</th><th>cd</th><th>dn</th><th>ov</th><th>un</th><th>pre</th><th>acc</th></tr><tr><td>c5:0</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>10</td><td align=right>0</td><td>c5:1</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td> <td align=right>191</td></tr><tr><td>c5:2</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td> <td align=right>2</td><td>c5:3</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td></tr><tr><td>c5:4</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td><td>c5:5</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td> <td align=right>1506</td></tr><tr><td>c5:6</td> <td align=center>1</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>0</td><td>c5:7</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td></tr><tr><td>c5:8</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td><td>c5:9</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td></tr><tr><td>c5:10</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>717</td><td>c5:11</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>70</td></tr><tr><td>c5:12</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>187</td><td>c5:13</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>1506</td></tr><tr><td>c5:14</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>0</td><td>c5:15</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>0</td></tr><tr><td>c5:16</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>0</td><td>c5:17</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>32000</td><td align=right>1506</td></tr><tr><td>c5:18</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td><td>c5:19</td> <td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=center>0</td><td align=right>0</td><td align=right>0</td></tr></table></center><hr width=25% align=center>

now haven't tried code, it's function preg_match_all() gets matches regex.

//gets site $ch = curl_init(); curl_setopt($ch, curlopt_url, 'http://site.org'); curl_setopt($ch, curlopt_returntransfer, 1); $response = curl_exec($ch); //parse info preg_match_all('/[0-9]+(?=[^0-9]+(c5:2<|c5:6<|c5:13))/', $response, $matches); //prints parsed info print_r($matches[0]);

http://php.net/preg_match_all

php curl

hadoop - Should HBase be installed on the client side? Is sqoop an API? Is Drill an API? -



hadoop - Should HBase be installed on the client side? Is sqoop an API? Is Drill an API? -

i have done research hadoop, still need know reply next questions:

i think hbase not core component of hadoop, hence client, should do? is sqoop api? if yes, implemented in java? should install in client side? is drill api? if yes, implemented in java? should install in client side? is spark high-level language? should install in client side?

thank you.

i think hbase not core component of hadoop, hence client, should do?

hbase not core component of hadoop. utilize it, need install hbase on top of hadoop cluster. dependent on hdfs/zookeeper. not dependent on mapreduce services.

to utilize client side, depends on utilize case. have java api/ rest api or shell access. shell access need have hbase library on local machine.

is sqoop api? if yes, implemented in java? should install in client side

sqoop api/tool implemented in java. have install on client side.

is drill api? if yes, implemented in java? should install in client side?

drill not api. more bundle has installed on nodes. provides api based access client side installation may not required.

is spark high-level language? should install in client side?

spark not high level language , 1 time again depends on client is. web application can utilize spark api whereas through shell need client library.

hadoop hbase sqoop apache-spark

java - Do While Loop doesn't want to work for app -



java - Do While Loop doesn't want to work for app -

assignment 6 object array salon needs have menu loop user can utilize sorts till take '0' exit app.errors posted below code. know tried way without using 3 methods , got work need able utilize methods , while have advice or input can create work . thanks

import java.util.*; public class salonreport { public static void main(string[]args) { int x =0; service s1 = new service(); service s2 = new service(); service s3 = new service(); service s4 = new service(); service s5 = new service(); service s6 = new service(); s1.setservice("cut"); s1.setprice(5.00); s1.settime(15); s2.setservice("shampoo"); s2.setprice(5.00); s2.settime(10); s3.setservice("manicure"); s3.setprice(20.00); s3.settime(30); s4.setservice("style"); s4.setprice(60.00); s4.settime(55); s5.setservice("permanent"); s5.setprice(28.00); s5.settime(35); s6.setservice("trim"); s6.setprice(8.00); s6.settime(5); service[] services = {s1, s2, s3, s4, s5,s6}; //menu system.out.println("choose sort"); system.out.println("1: service"); system.out.println("2: price"); system.out.println("3: time"); system.out.println("0: exit"); scanner input = new scanner(system.in); do{ x = integer.parseint(input.next()); switch(x) { case 1: sortbyservice(services); break; case 2: sortbyprice(services); break; case 3: sortbytime(services); break; case 0: break; default: system.out.println("invalid entry"); }while(x!=0); } } public static void sortbytime(service[] array) { service temp; int highsubscript = array.length - 1; for(int = 0; < highsubscript; ++a) { for(int b = 0; b < highsubscript; ++b) { if(array[b].gettime() > array[b+1].gettime()) { temp = array[b]; array[b] = array[b + 1]; array[b + 1] = temp; } } } for(int = 0; < array.length; ++i) { system.out.println("service: "+array[i].getservice()+", "+"price: " +array[i].getprice()+", "+"time: "+ array[i].gettime()); } } public static void sortbyservice(service[] array) { service temp; int highsubscript = array.length - 1; for(int = 0; < highsubscript; ++a) { for(int b = 0; b < highsubscript; ++b) { if((array[b].getservice().comparetoignorecase(array[b+1].getservice())) >= 0) { temp = array[b]; array[b] = array[b + 1]; array[b + 1] = temp; } } } for(int = 0; < array.length; ++i) { system.out.println("service: "+array[i].getservice()+", "+"price: " +array[i].getprice()+", "+"time: "+ array[i].gettime()); } } public static void sortbyprice(service[] array) { service temp; int highsubscript = array.length - 1; for(int = 0; < highsubscript; ++a) { for(int b = 0; b < highsubscript; ++b) { if(array[b].getprice() > array[b+1].getprice()) { temp = array[b]; array[b] = array[b + 1]; array[b + 1] = temp; } } } for(int = 0; < array.length; ++i) { system.out.println("service: "+array[i].getservice()+", "+"price: "+array[i].getprice()+", "+"time: "+ array[i].gettime()); } } } salonreport.java:87: error: while expected } ^ salonreport.java:91: error: illegal start of look public static void sortbytime(service[] array) ^ salonreport.java:91: error: ')' expected public static void sortbytime(service[] array) ^ salonreport.java:91: error: ';' expected public static void sortbytime(service[] array) ^ salonreport.java:91: error: '.class' expected public static void sortbytime(service[] array) ^ salonreport.java:91: error: ';' expected public static void sortbytime(service[] array) ^ salonreport.java:116: error: illegal start of look public static void sortbyservice(service[] array) ^ salonreport.java:116: error: illegal start of look public static void sortbyservice(service[] array) ^ salonreport.java:116: error: ';' expected public static void sortbyservice(service[] array) ^ salonreport.java:116: error: '.class' expected public static void sortbyservice(service[] array) ^ salonreport.java:116: error: ';' expected public static void sortbyservice(service[] array) ^ salonreport.java:141: error: illegal start of look public static void sortbyprice(service[] array) ^ salonreport.java:141: error: illegal start of look public static void sortbyprice(service[] array) ^ salonreport.java:141: error: ';' expected public static void sortbyprice(service[] array) ^ salonreport.java:141: error: '.class' expected public static void sortbyprice(service[] array) ^ salonreport.java:141: error: ';' expected public static void sortbyprice(service[] array) ^ salonreport.java:166: error: reached end of file while parsing } ^ 17 errors ----jgrasp wedge2: exit code process 1. ----jgrasp: operation complete.

you missed }

it should

do{ x = integer.parseint(input.next()); switch(x) { case 1: sortbyservice(services); break; case 2: sortbyprice(services); break; case 3: sortbytime(services); break; case 0: break; default: system.out.println("invalid entry"); } }while(x!=0);

java arrays methods do-while

Android - Unable to figure out memory leak in a lockscreen type application -



Android - Unable to figure out memory leak in a lockscreen type application -

i have feeling problem quite similar this, not same.

i have application activity loads image upon receiving event. user swipes on image, , activity finishes. next time user switches off screen , switches on, same event triggers, , activity loads again.

this works fine, every time activity loads, increases memory (4mb 8mb 11mb 14mb etc.). goes around 30mb , either application crashes & restarts or phone starts getting sluggish etc.

i have tried number of things: - clearing & setting image related variables & view after utilize - using reusebitmap

but hasn't helped.

can suggests missing?

also, finish() doesn't seem finishing activity. keeping in background. if long press home, can see activity there, don't want happen. there way prepare that? cause of problem?

my start-up activity (which runs once), kicks off service:

protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_settings); startservice(new intent(this.getapplicationcontext(),myservice.class)); }

my service kicks off event broadcaster:

public void oncreate() { keyguardmanager.keyguardlock k1; keyguardmanager km =(keyguardmanager)getsystemservice(keyguard_service); k1= km.newkeyguardlock("in"); k1.disablekeyguard(); log.i("event", "servicestarted"); intentfilter filter = new intentfilter(intent.action_screen_on); filter.addaction(intent.action_screen_off); mreceiver = new eventsreciever(); registerreceiver (mreceiver, filter); super.oncreate(); }

when event occurs, kicks off main activity:

public void onreceive(context context, intent recievedintent) { log.i("check","[broadcastreciever] onrecieve()"); if (recievedintent.getaction().equals(intent.action_screen_off)) { wasscreenon = false; log.i("check","[broadcastreciever] screen went off"); intent intent11 = new intent(context,mainactivity.class); intent11.addflags(intent.flag_activity_new_task); context.startactivity(intent11); } else if (recievedintent.getaction().equals(intent.action_screen_on)) { wasscreenon = true; log.i("check","[broadcastreciever] screen went on"); intent intent11 = new intent(context, mainactivity.class); intent11.addflags(intent.flag_activity_new_task); } else if(recievedintent.getaction().equals(intent.action_boot_completed)) { intent intent11 = new intent(context, mainactivity.class); intent11.addflags(intent.flag_activity_new_task); context.startactivity(intent11); } } }

and here little more complex activity code. sense issue might somewhere here, unable figure out:

public class mainactivity extends activity { private static bitmap reusedbitmap; @override protected void oncreate(bundle savedinstancestate) { log.i("event", "activity oncreate"); requestwindowfeature(window.feature_no_title); this.getwindow().settype(windowmanager.layoutparams.type_keyguard_dialog); super.oncreate(savedinstancestate); getwindow().addflags(windowmanager.layoutparams.flag_keep_screen_on|windowmanager.layoutparams.flag_show_when_locked|windowmanager.layoutparams.flag_fullscreen); setcontentview(r.layout.activity_main); if (getintent()!=null&&getintent().hasextra("kill")&&getintent().getextras().getint("kill")==1){ // toast.maketext(this, "" + "kill activity", toast.length_short).show(); finish(); } try{ settime(); imageview img2 = (imageview)findviewbyid(r.id.imageview); changeimage(false); img2.setontouchlistener(new onswipetouchlistener(this) { @override public void onswipeleft() { changeimage(true); log.i("event","onswipeleft"); } @override public void onswiperight() { textview tvdisplaydate = (textview)findviewbyid(r.id.date1); customdigitalclock cdc = (customdigitalclock)findviewbyid(r.id.dc1); if (tvdisplaydate.getvisibility()==view.visible) { tvdisplaydate.setvisibility(view.gone); cdc.setvisibility(view.gone); } else { tvdisplaydate.setvisibility(view.visible); cdc.setvisibility(view.visible); } } @override public void onswipeup() { // mainactivity.this.movetasktoback(true); vcounter = 0; reusedbitmap = null; finish(); } @override public void onswipedown() { } }); img2.destroydrawingcache(); img2 = null; } grab (exception e) { } } public void settime() { textview tvdisplaydate = (textview)findviewbyid(r.id.date1); final calendar c = calendar.getinstance(); int yy = c.get(calendar.year); int mm = c.get(calendar.month); int dd = c.get(calendar.day_of_month); simpledateformat dayformat = new simpledateformat("e", locale.getdefault()); string weekday = dayformat.format(c.gettime());; // set current date textview tvdisplaydate.settext(new stringbuilder() // month 0 based, add together 1 .append(yy).append(" ").append("-").append(" ").append(mm + 1).append(" ") .append("-").append(dd).append(" ").append(weekday)); } @override public void onbackpressed() { // don't allow dismiss. return; } //only used in lockdown mode @override protected void onpause() { super.onpause(); log.i("event","onpause"); } @override protected void onresume() { super.onresume(); log.i("event", "onresume"); } @override protected void onstart() { log.i("event", "activity onstart"); super.onstart(); } @override protected void onstop() { log.i("event","onstop"); reusedbitmap = null; } @override public boolean onkeydown(int keycode, keyevent event) { log.i("event", "key pressed " + keycode); if ((keycode == keyevent.keycode_volume_down)||(keycode == keyevent.keycode_power)||(keycode == keyevent.keycode_volume_up)||(keycode == keyevent.keycode_camera)) { homecoming true; //because handled event } if((keycode == keyevent.keycode_home)){ toast.maketext(this, "you pressed home button", toast.length_long).show(); homecoming true; } if ( keycode == keyevent.keycode_menu ) { // nil homecoming true; } homecoming false; } public void ondestroy(){ super.ondestroy(); } public boolean dispatchkeyevent(keyevent event) { if (event.getkeycode() == keyevent.keycode_power ||(event.getkeycode() == keyevent.keycode_volume_down)||(event.getkeycode() == keyevent.keycode_power)) { homecoming false; } if((event.getkeycode() == keyevent.keycode_home)){ system.out.println("home key press event sent"); homecoming true; } homecoming false; } public void changeimage(boolean vforce) { string pathv = null; sharedpreferences pref = getapplicationcontext().getsharedpreferences("mypref", 0); // 0 - private mode boolean vpicchosen; vpicchosen = pref.getboolean("picchosen", false); if (vpicchosen == true) { pathv = pref.getstring("picurl", "nopic"); } else pathv = "nopic"; if (pathv == "nopic" || vforce == true) { pathv = randompic(); } file imgfile = new file(pathv); if(imgfile.exists()) { imageview img1 = (imageview)findviewbyid(r.id.imageview); display display = getwindowmanager().getdefaultdisplay(); int width = display.getwidth(); int height = display.getheight(); bitmap bmp2 = decodesampledbitmapfrompath(pathv, width, height); img1.destroydrawingcache(); img1.setimagebitmap(bmp2); img1.destroydrawingcache(); bmp2 = null; img1 = null; imgfile = null; } else toast.maketext(this, "no image present", toast.length_short).show(); } public static bitmap decodesampledbitmapfrompath(string path, int reqwidth, int reqheight) { // first decode injustdecodebounds=true check dimensions final bitmapfactory.options options = new bitmapfactory.options(); options.injustdecodebounds = true; options.inbitmap = reusedbitmap; bitmapfactory.decodefile(path, options); // calculate insamplesize options.insamplesize = calculateinsamplesize(options, reqwidth, reqheight); // decode bitmap insamplesize set options.injustdecodebounds = false; homecoming bitmapfactory.decodefile(path, options); } public class onswipetouchlistener implements ontouchlistener { private final gesturedetector gesturedetector; public onswipetouchlistener(context context) { gesturedetector = new gesturedetector(context, new gesturelistener()); } public void onswipeleft() { } public void onswiperight() { } public void onswipeup() { } public void onswipedown() { } public boolean ontouch(view v, motionevent event) { homecoming gesturedetector.ontouchevent(event); } private final class gesturelistener extends simpleongesturelistener { private static final int swipe_distance_threshold = 100; private static final int swipe_velocity_threshold = 100; @override public boolean ondown(motionevent e) { homecoming true; } @override public boolean onfling(motionevent e1, motionevent e2, float velocityx, float velocityy) { float distancex = e2.getx() - e1.getx(); float distancey = e2.gety() - e1.gety(); if (math.abs(distancex) > math.abs(distancey) && math.abs(distancex) > swipe_distance_threshold && math.abs(velocityx) > swipe_velocity_threshold) { if (distancex > 0) onswiperight(); else onswipeleft(); homecoming true; } if (math.abs(distancey) > math.abs(distancex) && math.abs(distancey) > swipe_distance_threshold && math.abs(velocityy) > swipe_velocity_threshold) { if (distancey < 0) onswipeup(); else onswipedown(); homecoming true; } homecoming false; } } } public string randompic(){ file dir = new file(path4); file childfile[] = dir.listfiles(); integer numfiles = childfile.length; random r1=new random(); integer selfile = r1.nextint(numfiles); sharedpreferences pref = getapplicationcontext().getsharedpreferences("mypref", 0); // 0 - private mode editor editor = pref.edit(); editor.putboolean("picchosen", true); editor.putstring("picurl", childfile[selfile].getpath()); editor.commit(); dir = null; homecoming childfile[selfile].getpath(); } }

any clues on might missing please?

edit 1:

this line seems causing problem:

bitmap bmp2 = decodesampledbitmapfrompath(pathv, width, height);

i changed below, reuse static bitmap variable:

// reusedbitmap.recycle(); reusedbitmap = decodesampledbitmapfrompath(pathv, width, height);

if recycle variable before reusing (as suggested gabe), image not loading @ all, stranger.

edit 2:

if seek recycle reusedbitmap within changeimage method, imageview isn't loading image @ all. , if recycle reusedbitmap within onswipeup (just before finish), not creating positive effect. memory consumption remaining same in case.

android android-intent memory-leaks android-event android-bitmap

ios - Change RootViewcontroller with the Push Transition effect -



ios - Change RootViewcontroller with the Push Transition effect -

in ios app need alter rootviewcontroller of window in between of app .so when alter rootviewcontroller dyncamically flicking view before change.but want give smooth transition when rootviewcontroller changed.

i had tried next not transition want.

[uiview transitionwithview:self.window duration:.8 options:uiviewanimationoptiontransitioncurlup animations:^{ self.window.rootviewcontroller = tabbarcontrollermain; [self.window makekeyandvisible]; } completion:null];

i want specific transition navigationcontroller pushview transition.

can body give me thought how accomplish that?

based on apple's documentation

uiviewcontroller *viewcontrollertobeshown=[[uiviewcontroller alloc]init]; //viewcontrollertobeshown.view.frame = self.view.frame; viewcontrollertobeshown.view.backgroundcolor = [uicolor orangecolor]; appdelegateclass *yourappdelegate =(appdelegateclass*)[uiapplication sharedapplication].delegate; uiview *myview1 = yourappdelegate.window.rootviewcontroller.view; uiview *myview2 = viewcontrollertobeshown.view; myview2.frame = yourappdelegate.window.bounds; [yourappdelegate.window addsubview:myview2]; catransition* transition = [catransition animation]; transition.startprogress = 0; transition.endprogress = 1.0; transition.type = kcatransitionpush; transition.subtype = kcatransitionfromright; transition.duration = 5.0; // add together transition animation both layers [myview1.layer addanimation:transition forkey:@"transition"]; [myview2.layer addanimation:transition forkey:@"transition"]; myview1.hidden = yes; myview2.hidden = no; yourappdelegate.window.rootviewcontroller = viewcontrollertobeshown;

ios iphone objective-c uiviewanimationtransition

android - zxing scanner view shows wierd background in Glass -



android - zxing scanner view shows wierd background in Glass -

i have created simple app integrates zxing scanner. when app runs on tablet, scanner view displayed properly. however, when run same code on glass, background scanner view displayed different color bars:

i wondering if missed something. regards.

google glass still has problems photographic camera driver. in particular not back upwards high frame rates , high preview resolution @ same time. if set high see unusual artifacts this.

i have used 1280x720 preview , modest frame rate. see

https://github.com/zxing/zxing/blob/master/glass/src/com/google/zxing/client/glass/cameraconfigurationmanager.java

android google-glass

java - Error while executing Google Prediction API Command line Sample -



java - Error while executing Google Prediction API Command line Sample -

i have downloaded sample command line programme prediction api , imported in eclipse mention here .

i have imported sample programme , replaced content of client_secrets.json values of file downloaded api console mentioned in above link .

i have built model using standalone explorer .

but prediction want through java code . below have mentioned code .

package com.google.api.services.samples.prediction.cmdline; import com.google.api.client.auth.oauth2.credential; import com.google.api.client.extensions.java6.auth.oauth2.authorizationcodeinstalledapp; import com.google.api.client.extensions.jetty.auth.oauth2.localserverreceiver; import com.google.api.client.googleapis.auth.oauth2.googleauthorizationcodeflow; import com.google.api.client.googleapis.auth.oauth2.googleclientsecrets; import com.google.api.client.googleapis.javanet.googlenethttptransport; import com.google.api.client.http.httpresponse; import com.google.api.client.http.httpresponseexception; import com.google.api.client.http.httptransport; import com.google.api.client.json.jsonfactory; import com.google.api.client.json.jackson2.jacksonfactory; import com.google.api.client.util.store.datastorefactory; import com.google.api.client.util.store.filedatastorefactory; import com.google.api.services.prediction.prediction; import com.google.api.services.prediction.predictionscopes; import com.google.api.services.prediction.model.input; import com.google.api.services.prediction.model.input.inputinput; import com.google.api.services.prediction.model.output; import com.google.api.services.prediction.model.training; import java.io.ioexception; import java.io.inputstreamreader; import java.util.collections; /** * @author yaniv inbar */ public class predictionsample { /** * sure specify name of application. if application name {@code null} or * blank, application log warning. suggested format "mycompany-productname/1.0". */ private static final string application_name = "senti-model/1.0"; static final string model_id = "senti-model"; //static final string storage_data_location = "enter_bucket/language_id.txt"; /** directory store user credentials. */ private static final java.io.file data_store_dir = new java.io.file(system.getproperty("user.home"), ".store/prediction_sample"); /** * global instance of {@link datastorefactory}. best practice create single * globally shared instance across application. */ private static filedatastorefactory datastorefactory; /** global instance of http transport. */ private static httptransport httptransport; /** global instance of json factory. */ private static final jsonfactory json_factory = jacksonfactory.getdefaultinstance(); /** authorizes installed application access user's protected data. */ private static credential authorize() throws exception { // load client secrets googleclientsecrets clientsecrets = googleclientsecrets.load(json_factory, new inputstreamreader(predictionsample.class.getresourceasstream("/client_secrets.json"))); if (clientsecrets.getdetails().getclientid().startswith("enter") || clientsecrets.getdetails().getclientsecret().startswith("enter ")) { system.out.println( "enter client id , secret https://code.google.com/apis/console/?api=prediction " + "into prediction-cmdline-sample/src/main/resources/client_secrets.json"); system.exit(1); } // set authorization code flow googleauthorizationcodeflow flow = new googleauthorizationcodeflow.builder( httptransport, json_factory, clientsecrets, collections.singleton(predictionscopes.prediction)).setdatastorefactory( datastorefactory).build(); // authorize homecoming new authorizationcodeinstalledapp(flow, new localserverreceiver()).authorize("user"); } private static void run() throws exception { httptransport = googlenethttptransport.newtrustedtransport(); datastorefactory = new filedatastorefactory(data_store_dir); // authorization credential credential = authorize(); prediction prediction = new prediction.builder( httptransport, json_factory, credential).setapplicationname(application_name).build(); //train(prediction); predict(prediction, "is sentence in english?"); predict(prediction, "¿es esta frase en español?"); predict(prediction, "est-ce cette phrase en français?"); } private static void error(string errormessage) { system.err.println(); system.err.println(errormessage); system.exit(1); } private static void predict(prediction prediction, string text) throws ioexception { input input = new input(); inputinput inputinput = new inputinput(); inputinput.setcsvinstance(collections.<object>singletonlist(text)); input.setinput(inputinput); output output = prediction.trainedmodels().predict(model_id, input).execute(); system.out.println("text: " + text); system.out.println("predicted language: " + output.getoutputlabel()); } public static void main(string[] args) { seek { run(); // success! return; } grab (ioexception e) { system.err.println(e.getmessage()); } grab (throwable t) { t.printstacktrace(); } system.exit(1); } }

this error getting while executing code:

jun 24, 2014 2:11:09 pm com.google.api.client.util.store.filedatastorefactory setpermissionstoowneronly warning: unable alter permissions everybody: c:\users\deepesh.shetty\.store\prediction_sample jun 24, 2014 2:11:09 pm com.google.api.client.util.store.filedatastorefactory setpermissionstoowneronly warning: unable alter permissions owner: c:\users\deepesh.shetty\.store\prediction_sample java.lang.nullpointerexception @ com.google.api.client.repackaged.com.google.common.base.preconditions.checknotnull(preconditions.java:191) @ com.google.api.client.util.preconditions.checknotnull(preconditions.java:127) @ com.google.api.client.json.jackson2.jacksonfactory.createjsonparser(jacksonfactory.java:96) @ com.google.api.client.json.jsonobjectparser.parseandclose(jsonobjectparser.java:85) @ com.google.api.client.json.jsonobjectparser.parseandclose(jsonobjectparser.java:81) @ com.google.api.client.auth.oauth2.tokenresponseexception.from(tokenresponseexception.java:88) @ com.google.api.client.auth.oauth2.tokenrequest.executeunparsed(tokenrequest.java:287) @ com.google.api.client.auth.oauth2.tokenrequest.execute(tokenrequest.java:307) @ com.google.api.client.auth.oauth2.credential.executerefreshtoken(credential.java:570) @ com.google.api.client.auth.oauth2.credential.refreshtoken(credential.java:489) @ com.google.api.client.auth.oauth2.credential.intercept(credential.java:217) @ com.google.api.client.http.httprequest.execute(httprequest.java:859) @ com.google.api.client.googleapis.services.abstractgoogleclientrequest.executeunparsed(abstractgoogleclientrequest.java:410) @ com.google.api.client.googleapis.services.abstractgoogleclientrequest.executeunparsed(abstractgoogleclientrequest.java:343) @ com.google.api.client.googleapis.services.abstractgoogleclientrequest.execute(abstractgoogleclientrequest.java:460) @ com.google.api.services.samples.prediction.cmdline.predictionsample.predict(predictionsample.java:157) @ com.google.api.services.samples.prediction.cmdline.predictionsample.run(predictionsample.java:100) @ com.google.api.services.samples.prediction.cmdline.predictionsample.main(predictionsample.java:164)

help me in issue . give thanks .

.../jre/lib/security/java.policy

can seek giving permission below ?

grant{ permission java.security.allpermission; };

java eclipse nullpointerexception google-api google-prediction

c# - What providerName and connectionStrings should be used for MS SQL Compact Edition in MVC 4 in Visual Studio 2013 in ASP.NET MVC 4? -



c# - What providerName and connectionStrings should be used for MS SQL Compact Edition in MVC 4 in Visual Studio 2013 in ASP.NET MVC 4? -

what providername should used in web.config file ms sql compact edition in mvc 4 in visual studio 2013?

introduction when use:

<connectionstrings> <add name="musicstoreentities" connectionstring="data source=|datadirectory|mvcmusicstore.sdf" providername="system.data.sqlserverce.4.0"/> </connectionstrings>

my website database works , genre objects retrieved database , displayed

after alter of providername providername="system.data.sqlclient this:

<connectionstrings> <add name="musicstoreentities" connectionstring="data source=|datadirectory|mvcmusicstore.sdf" providername=providername="system.data.sqlclient"/> </connectionstrings>

i get:

so why want alter anything?

actual problem: if leave providername="system.data.sqlserverce.4.0" when want add together new controller menu:

i get:

but if set providername="system.data.sqlclient storemanagercontroller generated database not work @ all.

question: should generate storemanagercontroller? follow tutorial: http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-5 , link working project before step it: http://www.speedyshare.com/rgdqh/mvcmusicstore.zip

so bare in mind "mvc music store" mvc 101 since origin of mvc. given there have been lot of changes, chances of documentation/walk-throughts beingness little off unfavorable. said:

the t4 template data-driven controller failing due connection string. because sql express (in of itself) has gone through lot of cycles , next localdb. given you're using mvc4, it's time upgrade, , means can have benefits of sql express (including system.data.sqlclient provider) without possible headaches previous revisions.

with said, alter connection string utilize new format:

<connectionstrings> <add name="musicstoreentities" connectionstring="data source=(localdb)\v11.0;integrated security=true;attachdbfilename=|datadirectory|mvcmusicstore.mdf" providername="system.data.sqlclient" /> </connectionstrings>

and (probably) re-run databaseinitializer (if recall correctly, should happen automatically since it's using ef. if not, can go bundle manager console , run update-database).

this gives provider controller template wants while still keeping local (dev) database.

c# sql asp.net-mvc asp.net-mvc-4 visual-studio-2013

ios - .plist access array of dictionaries? -



ios - .plist access array of dictionaries? -

my .plist starts array root , has multiple keys of dictionaries containing 6 items each.

- (void)viewdidload { nsstring *path = [[nsbundle mainbundle] pathforresource:@"questions" oftype:@"plist"]; self.questions = [nsarray arraywithcontentsoffile:path]; nsdictionary *firstquestion = [self.questions objectatindex:0]; self.questionlabel.text = [firstquestion objectforkey:@"questiontitle"]; [self.ansone settitle:[firstquestion objectforkey:@"a"] forstate:uicontrolstatenormal]; [self.anstwo settitle:[firstquestion objectforkey:@"b"] forstate:uicontrolstatenormal]; [self.ansthree settitle:[firstquestion objectforkey:@"c"] forstate:uicontrolstatenormal]; [self.ansfour settitle:[firstquestion objectforkey:@"d"] forstate:uicontrolstatenormal];

but load blank labels, here's xml of .plist

<?xml version="1.0" encoding="utf-8"?> <!doctype plist public "-//apple//dtd plist 1.0//en" "http://www.apple.com/dtds/propertylist-1.0.dtd"> <plist version="1.0"> <array> <dict> <key>questiontitle</key> <string>which of next probes accomplish highest penetration?</string> <key>a</key> <string>5.0 mhz</string> <key>b</key> <string>4.0 mhz</string> <key>c</key> <string>3.4 mhz</string> <key>d</key> <string>1.0 mhz</string> <key>questionanswer</key> <string>d</string> </dict> <dict> <key>questiontitle</key> <string></string> <key>a</key> <string></string> <key>b</key> <string></string> <key>c</key> <string></string> <key>d</key> <string></string> <key>questionanswer</key> <string></string> </dict> <dict> <key>questiontitle</key> <string></string> <key>a</key> <string></string> <key>b</key> <string></string> <key>c</key> <string></string> <key>d</key> <string></string> <key>questionanswer</key> <string></string> </dict> </array> </plist>

i next tutorial , many other people facing issue, can point me in right direction, or prepare code me please?

thanks in advance.

my app same thing yours trying except plist root dictionary instead of array.

instead of:

self.questions = [nsarray arraywithcontentsoffile:path];

use:

nsdictionary* questions = [nsdictionary dictionarywithcontentsoffile:path];

and question want to, use:

nsdictionary *firstquestion = [nsdictionary dictionarywithdictionary:[questions objectforkey:[nsstring stringwithformat:@"0"]]];

ios objective-c

go - Golang ssh - how to run multiple commands on the same session? -



go - Golang ssh - how to run multiple commands on the same session? -

i'm trying run multiple commands through ssh seems session.run allows 1 command per session ( unless i'm wrong). i'm wondering how can bypass limitation , reuse session or send sequence of commands. reason need run sudo su within same session next command ( sh /usr/bin/myscript.sh )

you can utilize little trick: sh -c 'cmd1&&cmd2&&cmd3&&cmd4&&etc..'

this single command, actual commands passed argument shell execute them. how docker handles multiple commands.

ssh go

Recovering variables from try/catch in Powershell -



Recovering variables from try/catch in Powershell -

i having problem restart script. trying sent out restart-computer command series of servers , capture failures can retry them in manner (in case through vic).

here code snippet

try { restart-computer -computername $_.servername -credential $cred -force -erroraction stop } grab [system.exception] { #create output object $output = [pscustomobject] @{ servername = $_.servername domain = $_.domain environment = $_.environment vic = $_.vic } export-csv -inputobject $output -path c:\temp\vicredo.csv -force -notypeinformation } }

the issue here $_ variables don't create downwards grab block, have no way of writing them "retry list". can think of way works?

when encounters terminating error, original pipeline stopped. pipeline started, , what's in pipeline error.

you can around switching using foreach loop.

powershell

Eclipse has no Java facet version 1.8 -



Eclipse has no Java facet version 1.8 -

i using eclipse kepler (enterprise edition), java 8, , m2eclipse , trying create web application. have gone help -> eclipse marketplace , installed these 2 patches:

java 8 back upwards eclipse kepler sr2 java 8 back upwards m2e eclipse kepler sr2

those patches cleared lot of problems, 1 remains. did maven -> update within eclipse, went , updated projects except web app in workspace. gives me pop message says "version 1.8 of project facet java not exist"

i opened project properties , clicked project facets. sure enough, java facet maximum version 1.7. wondering why don't have same problem on other projects. viewed properties on other projects , discovered none of them using project facets @ all. think might because made of previous projects using standard edition of eclipse, not enterprise edition.

so guess have couple questions. how can eclipse recognize java facet 1.8? there way can have web app not utilize project facets? should add together project facets other projects?

just ran issue. problem tomcat server looking in wrong place jre. prepare that:

double click on server in servers tab open "runtime environment" change jre selector.

hope saves someones time

eclipse java-8 m2eclipse

html - Why are bullets not appearing on posts? -



html - Why are bullets not appearing on posts? -

in post http://technopcarea.blogspot.com/2014/06/how-to-make-your-websites-design.html,the bullets not appearing inspite of addng right html,why ?

list type none added ul . add list-style-type css property ul:

<ul style="list-style-type:circle !important"> <li><span style="font-size: large;"><b>go template tab of blog's html</b></span></li> <li><span style="font-size: large;"><b>click on edit html button</b></span></li> <li><span style="font-size: large;"><b>search for&nbsp;&nbsp;]]&gt;&lt;/b:skin&gt;</b></span></li> <li><span style="font-size: large;"><b>add next piece of codes before it</b></span></li> </ul>

you can add together desired value list can read in next link:

http://www.w3schools.com/cssref/pr_list-style-type.asp

i have checked link have provided , in link have given css has made padding:0 on list items li tag

html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { border: 0; padding: 0; font-size: 100%; font: inherit; vertical-align: baseline; }

remove padding , list style come requires padding on content , have made padding 0 on li

html css xml

ubuntu 12.04 - Glusterfs Not Replicating data -



ubuntu 12.04 - Glusterfs Not Replicating data -

i have glusterfs setup 2 nodes (node1 , node2). see connection has made between 2 connection. problem when create folders on node1 not replicate on node2. please suggest me overcome if 1 had fixed it?

if mount on other server glusterfs client , create files , folders replicating glusterfs nodes. behavior normal?

volume name: testvol type: replicate status: started number of bricks: 2 transport-type: tcp bricks: brick1: gluster1.example.com:/var/www/drupal7/sites/default/files brick2: gluster2.example.com:/var/www/drupal7/sites/default/files

gluster volumes supposed access , update via clients. saw similar post on same. below links suggested if don't want install client in node , install in same server itself.

http://gopukrish.wordpress.com/glusterfs/ http://gopukrish.wordpress.com/high-availability-load-balanced-wordpress-site/

ubuntu-12.04 replication glusterfs

sql - How to select from unknown number of databases? -



sql - How to select from unknown number of databases? -

i want show client history of total orders across multiple 'vendors'. each vendor has separate database in sql server store own orders.

in database know vendors user signed with. sequence needs go this:

get vendorids user signed with. go vendor table , server + database name perform select statement gets orders each order table in each of vendor databases user signed to. declare @userid int = 999 select count(ordernumber) 'orders' --- need kind of loop here? [vendorserver].[vendordb].[ordertable] o1 o1.userid = @userid

how aggregate of total number of orders client made when orders spread across multiple databases?

the user may signed on 100 vendors. has query across 100 databases. extreme illustration possible.

this can solved using dynamic query: query generated dynamically , executed.

without table schema it's impossible write work in environment thought be

declare @query nvarchar(max) = '' select @query += 'union select whatever ' + vendorserver + '.' + vendordb + '.ordetable condition' vendor vendorid in (all vendorids user signed with) set @query = substring(@query, 10, len(@query)) exec sp_executesql(@query)

the op in comment described schema

create table user_vendor ( userid int , vendorid int ) create table vendors ( vendorid int , name varchar(50) , databasename varchar(50) , servername varchar(50) )

in case query/stored procedure body be

declare @userid int = '999' declare @query nvarchar(max) = '' declare @vuserid nvarchar(10) = cast(userid nvarchar(10)) select @query += 'union select count(ordernumber) [orders] ' + v.servername + '.' + v.databasename + '.ordetable o1.userid = ' + @userid + ' ' user_vendor uv inner bring together vendors v on uv.vendorid = v.vendorid uv.userid = @userid set @query = substring(@query, 10, len(@query)) exec sp_executesql(@query)

sqlfiddle demo select @query instead of exec sp_executesql(@query)

the added variable @vuserid avoid multiple cast in query, user table not needed in query.

to total figure of orders, instead of count every vendor, line

set @query = substring(@query, 10, len(@query))

should changed to

set @query = 'select sum([orders]) [orders] (' + substring(@query, 10, len(@query)) + ') a'

sql sql-server

java - How would I implement my present threads into an AsyncTask to make the UI respond better? -



java - How would I implement my present threads into an AsyncTask to make the UI respond better? -

for activities work, have info internet.

i implemented threads, not java or threads yet, kinda rushed through hoping work. works, ui feels slow because takes awhile until activity appears.

here code

an activity, lets phone call mainactivity calls:

jsonobject info = webapi.getdata(id);

the class webapi pieces url together:

public static jsonobject getdata(string id) { string url = url; url += data_url; url += value_data_id + id; homecoming webinterface.executeweb(url); }

and hands on webinterface, in webinterface whole thing gets executed:

public static string geturl(final string url) { final stringbuilder sb = new stringbuilder(); thread thread = new thread(new runnable() { public void run() { seek { inputstream = (inputstream) new url(url).getcontent(); bufferedreader reader = new bufferedreader(new inputstreamreader(is)); string result, line = reader.readline(); result = line; while((line=reader.readline())!=null){ result+=line; } sb.append(result); } grab (exception e) { // todo: handle exception e.printstacktrace(); } } }); thread.start(); seek { thread.join(); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } string result = sb.tostring(); log.d(app.tag, result); homecoming result; } public static jsonobject executeweb(final string url) { string result = webinterface.geturl(url); jsonobject json = null; seek { json = new jsonobject(result.trim()); } grab (jsonexception e) { seek { json = new jsonobject("{}"); } grab (jsonexception e1) { // todo auto-generated grab block e1.printstacktrace(); } } homecoming json; }

well works sense work better, if implement asynctask. activity show cached info until "real" info appears. possible asynctask? , need redo lot of code that?

thanks in advance help!

edit:

thanks whoever suggested asynctaskloader (i think 1 deleted answer) did asynctaskloader, handy , easy!

in effect code single threaded because of thread.join(). current thread waits newly spawned thread finish. have in effect not removed network main thread, hence ui "locks up" or feels slow.

you have callback runs on main thread when thread finished, asynctask you, , allows update progress bar if desired. read documentation on how implement asynctask.

java android multithreading android-asynctask

How to redirect with nginx to an url with file extensions -



How to redirect with nginx to an url with file extensions -

what have written far in config looks following:

server { hear 80; server_name www.thissouldberedirected.com; rewrite ^ http://www.example.de/nice/stillnice/nice.html permanent; }

the result http://www.example.de/nice/stillnice/nice.html/ causes page not found...

what need http://www.example.de/nice/stillnice/nice.html

here code i'm using create php file convert directory

rewrite ^/test/$ /test.php last;

before : example.com/test.php

after example.com/test/

what u looking 301 redirect

if ( $request_filename ~ old-page/ ) { rewrite ^ http://newdomain/next-best-page/? permanent; }

source: https://jeffsebring.com/2012/nginx-301-redirects/

nginx

javascript - using tr:nth-child(n) selector in a jQuery function -



javascript - using tr:nth-child(n) selector in a jQuery function -

i know little jquery, i'm not @ 'real' javascript. create next lines lot simpler:

$('.product tr:nth-child(2) .knop',window.parent.document).bind("click", function(){ $('#edit-submitted-data-cursus').val($('.product tr:nth-child(2) .cursus a',window.parent.document).html()) $('#edit-submitted-data-cursusdatum').val($('.product tr:nth-child(2) .datum',window.parent.document).html()) $('#edit-submitted-data-opleidingscode').val($('.product tr:nth-child(2) .code',window.parent.document).html()) $('#edit-submitted-data-cursuslocatie').val($('.product tr:nth-child(2) .loc',window.parent.document).html()) $('#edit-submitted-data-cursustarief').val($('.product tr:nth-child(2) .tarief',window.parent.document).html()) }); $('.product tr:nth-child(3) .knop',window.parent.document).bind("click", function(){ $('#edit-submitted-data-cursus').val($('.product tr:nth-child(3) .cursus a',window.parent.document).html()) $('#edit-submitted-data-cursusdatum').val($('.product tr:nth-child(3) .datum',window.parent.document).html()) $('#edit-submitted-data-opleidingscode').val($('.product tr:nth-child(3) .code',window.parent.document).html()) $('#edit-submitted-data-cursuslocatie').val($('.product tr:nth-child(3) .loc',window.parent.document).html()) $('#edit-submitted-data-cursustarief').val($('.product tr:nth-child(3) .tarief',window.parent.document).html()) }); $('.product tr:nth-child(4) .knop',window.parent.document).bind("click", function(){ $('#edit-submitted-data-cursus').val($('.product tr:nth-child(4) .cursus a',window.parent.document).html()) $('#edit-submitted-data-cursusdatum').val($('.product tr:nth-child(4) .datum',window.parent.document).html()) $('#edit-submitted-data-opleidingscode').val($('.product tr:nth-child(4) .code',window.parent.document).html()) $('#edit-submitted-data-cursuslocatie').val($('.product tr:nth-child(4) .loc',window.parent.document).html()) $('#edit-submitted-data-cursustarief').val($('.product tr:nth-child(4) .tarief',window.parent.document).html()) });

,etc,etc (i have 30 of these blocks of code. sure there way rid of redundant code, did not succeed yet. using code populate fields in form. help much appreciated!

you can utilize loop.

var i; (i = 1; < 41; i++) { $('.product tr:nth-child(" + + ") .knop', window.parent.document).bind("click", function () { $('#edit-submitted-data-cursus').val($('.product tr:nth-child(" + + ") .cursus a', window.parent.document).html()) $('#edit-submitted-data-cursusdatum').val($('.product tr:nth-child(" + + ") .datum', window.parent.document).html()) $('#edit-submitted-data-opleidingscode').val($('.product tr:nth-child(" + + ") .code', window.parent.document).html()) $('#edit-submitted-data-cursuslocatie').val($('.product tr:nth-child(" + + ") .loc', window.parent.document).html()) $('#edit-submitted-data-cursustarief').val($('.product tr:nth-child(" + + ") .tarief', window.parent.document).html()) }); }

javascript jquery css

c++ - Change key in unordered multimap -



c++ - Change key in unordered multimap -

is there efficient way alter key in unordered multimap? example, want alter key key_val1 key_val2. looks can done much efficiently iterating on equal_range(...) , readding pairs new key subsequent erasing old one.

no. if want alter keys, have little selection delete existing item, create new item new key, , insert new item set.

an unordered_multi(set|map) (at to the lowest degree normally) implemented hash table. alter in key requires computing hash new key (which may entirely different hash old key, though key modified).

thinking things, can if you're ambitious enough. i'm not @ sure it's worthwhile, possible. in particular, unordered associative containers back upwards called local iterators. local iterator can iterate through items in specific bucket in table. definition, items equal keys must in same bucket.

so, you'd start getting local iterator bucket containing items. you'd iterate through using key_equal find items contains have same key. you'd utilize hasher find new bucket of those, , straight move them new bucket.

i've never done this, i'm not certain local_iterator gives plenty access it--but seem @ to the lowest degree might possible--likely plenty worth farther investigation, anyway.

my own take on things if you're plenty bother optimizing task, worth considering using unordered_map<key, std::vector<whatever>>, you'd have 1 stored key, arbitrary number of items associated it. if need modify key, moving associated info trivial (happens pretty much automatically).

c++ c++11 multimap

Expect - how to set output from $expect_out(0,string) as variable and use it further -



Expect - how to set output from $expect_out(0,string) as variable and use it further -

i totally new expect ... need write script telnet ms server, displays current sessions there , logoff specific user. script attached.

#!/bin/bash # execute expect part /usr/bin/expect <<eof # # telnet pc # spawn telnet 9.9.9.9; expect "login:"; send "admin\r"; expect "password:"; send "admin\r"; expect "*>"; send "query session test\r"; expect -re " \[0-9] "; set val [\$expect_out(0,string)]; send "logoff $val\r"; send "\r"; expect "*>"; send "\x1d"; expect "*>"; send "q\r"; exit 1; eof;

i can't working. seems i'm doing wrong defining variable. when run script i'm getting next result:

c:\users\admin>query session test sessionname username id state type device rdp-tcp#0 test 3 active rdpwd c:\users\admin>invalid command name " 3 " while executing "$expect_out(0,string)" invoked within "set val [$expect_out(0,string)]"

btw when used send_user in script instead, got right input in telnet session, reason not accepting command @ all.

any help appreciated. give thanks you.

expect treat things between matching brackets command.

set val [\$expect_out(0,string)] means executing command named $expect_out(0,string) (in case, it's 3.) , assigning command output val. that's why output shows invalid command name " 3 " because there no such command.

change line set val $expect_out(0,string) , believe things better.

btw, send_user puts. prints message standard output, not spawned process.

expect