Thursday, 15 August 2013

jsf - How to get Trinidad tr:inputText to echo its changed value instantly? -



jsf - How to get Trinidad tr:inputText to echo its changed value instantly? -

i have next trinidad tr:inputtext field in xhtml file bound "value1" in managed bean class; inputtext field of type:

org.apache.myfaces.trinidad.component.core.input.coreinputtext

<tr:inputtext value="#{mybean.value1}" autosubmit="true" immediate="true" valuechangelistener="#{mybean.textchangelistener}" styleclass="stylepagetextsmallcolored"> </tr:inputtext> <tr:commandbutton id="btncommit" inlinestyle="width:20" immediate="true" text="commit" action="#{mybean.docommit()}" styleclass="stylebutton"> </tr:commandbutton> public void textchangelistener(valuechangeevent e) { log.debug(">> textchangelistener: value=["+(string)e.getnewvalue()+"]"); } public string docommit() throws throwable { log.debug("in docommit: value1="+value1); value1 = "("+value1+")"; // update database modified value1 string here; database has right // updated value1 string (with parentheses). // how modified value1 (above) echo screen instantly // within docommit() method changes? }

when type field , alter value press "commit" button, can see value obtained screen in docommit() method , textchangelistener() method indicates has been called. create changes "value1" variable , echo value instantly screen without doing screen submit; can done part of docommit() method or through other mechanism/tag in xhtml file?

please note using trinidad , input text class listed above.

update...

thank reference jasper; want same inputtext field update after setter method called , input text changed (by setter method). reference page pointed to; tried next , works using partialtriggers attribute:

<tr:inputtext id="myvalue" value="#{mybean.value1}" autosubmit="true" immediate="true" partialtriggers="myvalue" valuechangelistener="#{mybean.textchangelistener}" styleclass="stylepagetextsmallcolored"> </tr:inputtext>

you can using trinidad's partial page rendering.

in short: need add together id attribute input, , have , tr:outputtext component partialtriggers attribute refer input component.

minimal implementation in case be:

<tr:inputtext id="value1input" value="#{mybean.value1}" autosubmit="true" immediate="true"/> <tr:outputtext value="value1: #{mybean.value1}" partialtriggers="value1input"/>

jsf jsf-2 trinidad

linux - Is there a way to identify the instruction that caused the most recent Last Level Cache miss on modern Intel processors? -



linux - Is there a way to identify the instruction that caused the most recent Last Level Cache miss on modern Intel processors? -

i able read hardware counters on lastly level cache misses , references user space using wrmsr select them , rdpmc read them.

however, while of misses obvious references not nail cache, others much more subtle , move around when same code path executed multiple times (order 100,000 times).

i suspect of misses due hardware prefetching, disabled hardware prefetcher through bios, still getting sliding cache misses causes hard pin down.

is there capability in either linux kernel or intel's registers determine address of instruction caused recent lastly level cache miss?

if useful, running 2.6.32-279.el6.x86_64 on intel xeon x3470.

linux performance caching intel msr

Android - how to detect touch listener if view has click listener -



Android - how to detect touch listener if view has click listener -

i have basic layout linear layout, scrollview , imageview.

scrollview has registered ontouchlistener , imageview onclicklistener. if tap on imageview , pulling out of imageview, not see log "onclick".

if tap out of imageview (on scrollview) , pulling somewhere, see log "on touch". how can grab ontouch event on imageview, when pulling out of it?

here code:

imageview testbutton = (imageview) myview.findviewbyid(r.id.imageview1); testbutton.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { log.d(tag, "onclick"); } }); scrollview scrollview = (scrollview) myview.findviewbyid(r.id.scrollview1); scrollview.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { log.d(tag, "ontouch"); homecoming false; } });

and here xml:

<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical" > <scrollview android:id="@+id/scrollview1" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/com_facebook_blue" android:scrollbaralwaysdrawverticaltrack="false" > <linearlayout android:id="@+id/linearlayout1" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <imageview android:id="@+id/imageview1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/com_facebook_profile_picture_blank_square" /> </linearlayout> </scrollview> </linearlayout>

set ontouchlistener imageview well. when pull away touch view's touchable part fire touch event. onclick wont fired when ontouch cancelled(motionevent.action_cancel).you should not consume ontouch() hence homecoming false in ontouch()

android android-layout ontouchlistener

Displaying homepage on localhost REST+ JAVA -



Displaying homepage on localhost REST+ JAVA -

i have written rest+tomcat+jersey java application , rest oft paths homepage working fine. however, localhost:8080 returns 404 because there's no function points it. in:

@path("/") @produces({mediatype.text_plain}) public string homepage(){ homecoming "homepage"; }

i have tried using "/" path doesnt seem work. how proceed? thanks!

if deploy war named foo tomcat listening @ http://localhost:8080/, root of war available @ http://localhost:8080/foo/.

if jax-rs application configured utilize additional path segment bar, homepage resource available @ http://localhost:8080/foo/bar.

check bailiwick of jersey configuration in application value of bar, if there any.

java rest

javascript - Parse.com fetch collection -



javascript - Parse.com fetch collection -

i'm new parse.com, , want ask, how display items collection. code:

var user = parse.object.extend("user"); var testcollection = parse.collection.extend({ model: user }); var collection = new testcollection(); collection.fetch({ reset: false, success: function(collection) { document.write('<h1>' + "users:<br>" + '</h1>'); document.write('<table><tr>'); document.write('<td>user name</td>'); document.write('<td>email</td></tr>'); collection.each(function(user) { document.write('<tr><td>'+user.get('username')+'</td>'); document.write('<td>'+user.get('email')+'</td>'); document.write('</tr></table>'); }); }, error: function(collection, error) { alert("error: " + error.code + " " + error.message); } });

in way, got items, webpage reload without stop. help please. in advance!

once you've fixed document.write() issues, you'll need aware user (and role , installation) classes special in parse.

to query them, can't way have. delete line you're extending "user" won't work.

change collection following:

var testcollection = parse.collection.extend({ model: parse.user });

the way have done right classes create, have utilize inbuilt definitions inbuilt parse classes.

javascript backbone.js parse.com

javascript - How do I echo a a base64 string as an image to the browser using php? -



javascript - How do I echo a a base64 string as an image to the browser using php? -

i've got database base64 strings of images. i've built api phone call display these images uuid (example.com/image/5e7edbe0-a765-4863-9d75-9f89ccc532e0). value database, decode base64 binary, , echo browser follows:

$document = documentmodel::getfromdatabase($uuid); $type = $document->gettype(); // image/png $valuebase64 = $document->getvalue(); // data:image/png;base64,ivborw0kggoaaaansuheugaaaaiaaaaccaaaaabx3vl4aaaacxbiwxmaaastaaaleweampwyaaaab3rjtuuh3gysdcugsze0aaaaaa5jrefucndjrgjgymaaaaj0ah4sdhviaaaaaelftksuqmcc $value = base64_decode($valuebase64); header('content-type: ' . $type); echo $value;

unfortunately, 1 of these broken images icons saying image can't load. if take raw base64 value database , seek render in browser using javascript console below indeed shows image (a 2x2 pixel gray image).

var img = new image(); img.src = "data:image/png;base64,ivborw0kggoaaaansuheugaaaaiaaaaccaaaaabx3vl4aaaacxbiwxmaaastaaaleweampwyaaaab3rjtuuh3gysdcugsze0aaaaaa5jrefucndjrgjgymaaaaj0ah4sdhviaaaaaelftksuqmcc"; document.body.appendchild(img);

so don't understand why echo'ing binary value doesn't work. know i'm doing wrong here? tips welcome!

the string in $valuebase64 contains data uri, unacceptable php's base64_decode() function, since accepts pure base64 encoded data.

in order programme work, you'll have strip header (the data:image/png;base64, part - including comma) input data.

javascript php html image base64

lua - Table value doesn't change -



lua - Table value doesn't change -

i have 2 dim array , it's cells filled zeros.

what i'm trying take randomly chosen cells , fill 4 or 5

but either empty gird value equal 0 or 1 value has changed 4 or 5 , that's code below:

local grid = {} i=1,10 grid[i] = {} j=1,10 grid[i][j] = 0 end end local empty={} i=1,10 j=1,10 if grid[i][j]==0 table.insert(empty,i ..'-'.. j) end end end local fp=math.floor(table.maxn(empty)/3) local fx,fy i=1,fp math.randomseed(os.time()) math.random(0,1) local fo=math.random(0,1) math.random(table.maxn(empty)) local temp= empty[math.random(table.maxn(empty))] local dashindex=string.find(temp,'-') fx=tonumber(string.sub(temp,1,dashindex-1)) fy=tonumber(string.sub(temp,dashindex+1,string.len(temp))) if fo==0 grid[fx][fy]=4 elseif fo==1 grid[fx][fy]=5 end end i=1,10 j=1,10 print(grid[i][j]) end print('\n') end

i'm not sure for i=1,fp loop doing temp , fo, illustration seed should set once, , also, homecoming value on line after local fo ignored, seems messy. based on post, if want randomly select n cells 2d array , set either 4 or 5 (randomly), should work:

-- maybe n = fp local n = 5 math.randomseed(os.time()) local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] == 0 grid[fx][fy] = math.random(4,5) = + 1 end until > n

note closer n number of items in array (100 in example), longer take loop complete. if concern, big n values, opposite: initialize each cell 4 or 5 randomly, , randomly set size - n of them 0.

math.randomseed(os.time()) local rows = 10 local columns = 10 local grid = {} if n > rows*columns/2 i=1,rows grid[i] = {} j=1,columns grid[i][j] = math.random(4,5) end end local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] ~= 0 grid[fx][fy] = 0 = + 1 end until > n else i=1,rows grid[i] = {} j=1,columns grid[i][j] = 0 end end local = 1 repeat fx = math.random(1, 10) fy = math.random(1, 10) if grid[fx][fy] == 0 grid[fx][fy] = math.random(4,5) = + 1 end until > n end

lua lua-table

c# - Script manager popup doesn't appear -



c# - Script manager popup doesn't appear -

i have asp.net page. want throw pop upon clicking button on page. syntax used this:

scriptmanager.registerstartupscript(this, this.gettype(), "popup", "alert('invalid address!!');", true);

the popup did not appear.

however, when trying same syntax on different page in same project, worked.

any ideas?

try changing below line

scriptmanager.registerstartupscript(this, this.gettype(), "popup", "alert('invalid address!!');", true);

to

scriptmanager.registerstartupscript(this.page, this.gettype(), "popup", "alert('invalid address!!');", true);

if whatever reason above code doesn't work, seek below if works

scriptmanager.registerstartupscript(this.page, this.gettype(), "alert", "javascript:displayalert('invalid address!!');", true);

and js function

function displayalert(msg) { alert(msg); homecoming false; }

c# asp.net popup

php mail() to multiple recipients - dont share email adresses -



php mail() to multiple recipients - dont share email adresses -

im sending batch email multiple recipients using:

mail(implode(',', $emails), $subject, $content, $headers);

however, each person can see list of email sent to. want maintain private, , email appears more personal.

is there way without sending mail() each email, i'm guessing take long time run?

you looking simple bcc address. in same mail service not able see each others email address.

look here: http://php.net/manual/en/function.mail.php , find bcc.

this piece need:

$headers = array(); $headers[] = "mime-version: 1.0"; $headers[] = "content-type: text/plain; charset=iso-8859-1"; $headers[] = "from: sender name <sender@domain.com>"; $headers[] = "bcc: jj chong <bcc@domain2.com>"; $headers[] = "reply-to: recipient name <receiver@domain3.com>"; $headers[] = "subject: {$subject}"; $headers[] = "x-mailer: php/".phpversion(); mail($to, $subject, $email, implode("\r\n", $headers));

php email

Auto Import With Eclipse Snippets -



Auto Import With Eclipse Snippets -

i started using snippets recently. mutual 1 utilize inserts @ cursor:

private logger log = loggerfactory.getlogger(getclass());

however, still have ctrl-shift-o import logger , loggerfactory.

out of pure laziness inquire this: there way automatic import when insert snippet?

i don't think snippet can automatically insert import statement (or anything other insert text @ current cursor location). can set automatic save action organize imports whenever save. open project properties , navigate java editor > save actions.

i set few different things in additional actions including organize imports, removed trailing whitespace, insert missing annotations, etc.

eclipse

php - Mysql_query insert into -



php - Mysql_query insert into -

i have problem insert mysql query. if perform on localhost, works fine. however, on webserver doesn't want work, , don't know why. tried alter syntax in many ways though.

<? if( $_post ) { $dbhost ='ip address'; $dbuser = 'username'; $dbpassword = 'password'; $database = 'db1214492_davidmszabo'; $con = mysql_connect($dbhost, $dbuser, $dbpassword); if (!$con) { die('could not connect: ' . mysql_error()); } mysql_select_db($database, $con); $users_name = $_post['name']; $users_email = $_post['email']; $users_website = $_post['website']; $users_comment = $_post['comment']; $users_name = mysql_real_escape_string($users_name); $users_email = mysql_real_escape_string($users_email); $users_website = mysql_real_escape_string($users_website); $users_comment = mysql_real_escape_string($users_comment); $articleid = $_get['id']; if( !is_numeric($articleid) ) die('invalid article id'); $query = " insert `db1214492_davidmszabo`.`comments` (`id`, `name`, `email`, `website`, `comment`, `timestamp`, `articleid`) values (null, '$users_name', '$users_email', '$users_website', '$users_comment', current_timestamp, '$articleid');"; /* insert `inmoti6_mysite`.`comments` (`id`, `name`, `email`, `website`, `comment`, `timestamp`, `articleid`) values (null, '$users_name', '$users_email', '$users_website', '$users_comment', current_timestamp, '$articleid');";*/ $sql = "insert `db1214492_davidmszabo`.`comments` (`id`, `name`, `email`, `website`, `comment`, `timestamp`, `articleid`) values (null , '$users_name', '$users_email', '$users_website', '$users_comment', current_timestamp, '$articleid')"; /* $sqltwo = 'insert `db1214492_davidmszabo`.`comments` (`id`, `name`, `email`, `website`, `comment`, `timestamp`, `articleid`) values (\'\', \'cd\', \'ddsa@enauk.com\', \'dda.com\', \'dsaf\', current_timestamp, \'1\');'; - code copied phpmyadmin when insert in database */ mysql_query($query); echo "<h2>thank comment!</h2>"; mysql_close($con); } ?>

// edited post - , don't seek connecting localhost. got ip address @ $dbhost = "" - error got adding 2 more: lines error_reporting(e_all); , ini_set('display_errors', 1); - , changed connection mysqli_connect();

warning: mysql_real_escape_string(): can't connect local mysql server through socket '/var/lib/mysql/mysql.sock' (2) in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 105 warning: mysql_real_escape_string(): link server not established in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 105 warning: mysql_real_escape_string(): can't connect local mysql server through socket '/var/lib/mysql/mysql.sock' (2) in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 106 warning: mysql_real_escape_string(): link server not established in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 106 warning: mysql_real_escape_string(): can't connect local mysql server through socket '/var/lib/mysql/mysql.sock' (2) in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 107 warning: mysql_real_escape_string(): link server not established in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 107 warning: mysql_real_escape_string(): can't connect local mysql server through socket '/var/lib/mysql/mysql.sock' (2) in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 108 warning: mysql_real_escape_string(): link server not established in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 108 warning: mysql_query(): can't connect local mysql server through socket '/var/lib/mysql/mysql.sock' (2) in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 155 warning: mysql_query(): link server not established in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 155

and after comment: give thanks comment error this:

warning: mysql_close() expects parameter 1 resource, object given in /usr/local/pem/vhosts/479307/webspace/httpdocs/davidmszabo.com/articles/manage_comments.php on line 165

what construction of table inserting into? if id column auto_increment - should not trying insert it.

also, i'm not sure if current_timestamp valid value (especially if column datetime type). perhaps more experienced mysql guru can right me. utilize now() instead

try this:

$sql = "insert `$database`.`comments` (`name`, `email`, `website`, `comment`, `timestamp`, `articleid`) values ('$users_name', '$users_email', '$users_website', '$users_comment', now(), '$articleid')";

php mysql

java - SecretKeyFactory generateSecret error when passing PBEKeySpec -



java - SecretKeyFactory generateSecret error when passing PBEKeySpec -

i'm trying encrypt , decrypt java string. purpose wrote 2 methods below :

public static string aesencryptstring(string clearstr) throws exception { string cipherstr = null; //génération de la clé de cryptage aes secretkeyfactory mill = secretkeyfactory.getinstance("pbkdf2withhmacsha1"); pbekeyspec spec = new pbekeyspec(key.tochararray()); log.d("test", ""+ spec); secretkey tmp = factory.generatesecret(spec); secretkey key = new secretkeyspec(tmp.getencoded(), "aes"); //cryptage du mot de passe cipher cipher = cipher.getinstance("aes/cbc/pkcs5padding"); cipher.init(cipher.encrypt_mode, key); byte[] cipherbytearray = cipher.dofinal(clearstr.getbytes("utf-8")); //convertion du mot de passe en string pour l'enregistrement en base of operations cipherstr = new string(base64.encode(cipherbytearray, 0)); homecoming cipherstr; } public static string aesdecryptstring(string cipherstr) throws exception { string clearstr = null; //génération de la clé de cryptage aes secretkeyfactory mill = secretkeyfactory.getinstance("pbkdf2withhmacsha1"); keyspec spec = new pbekeyspec(key.tochararray()); secretkey tmp = factory.generatesecret(spec); secretkey key = new secretkeyspec(tmp.getencoded(), "aes"); //décryptage du mot de passe cipher decipher = cipher.getinstance("aes/cbc/pkcs5padding"); decipher.init(cipher.decrypt_mode, key); byte[] clearbytearray = decipher.dofinal(cipherstr.getbytes()); //convertion du mot de passe en string pour l'enregistrement en base of operations clearstr = new string(base64.encode(clearbytearray, 0)); homecoming clearstr; }

the thrown error "invalidkeyspec" during execution of factory.generatesecret -> know error due lack of salt but, if can create pbekeyspec password, should have way utilize it, can help find ?

i tried salt, testing and... doesn't work either error not same. in case error thrown on "cipher.init" , can't figure out error because debugger tells me ""

please help me because i'll going crazy !

when creating pbekeyspec have utilize constructor 4 arguments:

pbekeyspec(char[] password, byte[] salt, int iterationcount, int keylength)

note: can store unencrypted salt right before encrypted text. iterationcount can hard-coded within application.

byte[] salt = new byte[8]; new securerandom().nextbytes(salt); pbekeyspec spec = new pbekeyspec(key.tochararray(), salt, 10000, 128);

the illustration uses 128 aes128 sufficient.

java android aes

node.js - Import and process SASS file only in dev mode with grunt -



node.js - Import and process SASS file only in dev mode with grunt -

i'm wanting add together directory of files sass processing in "dev" task, or alternatively exclude in "build" task. tips doing well?

in nutshell there css don't want include in build.

you can seek utilize grunt-copy task in dev task.

for illustration have next construction of styles:

/styles /dev-scss /scss /main /dev

the thought re-create content of "dev-scss" folder "dev" folder dev grunt task. there problem, have clear dev folder every other task.

node.js build sass gruntjs

c# - Access Files in Phone memory on WP 8.1 -



c# - Access Files in Phone memory on WP 8.1 -

i developing in windows phone 8.1. can utilize knownfolders.removabledevices access sd card , can farther retrieve files & folders. since wp devices don't have sd cards, how can access phone memory retrieve files files app microsoft made?

the microsoft-built file explorer app has broader set of capabilities available windows phone store apps. in particular, has total access documents library , unfiltered access sd card.

c# api windows-phone-8.1

logging - The best way to show important information in Gradle? -



logging - The best way to show important information in Gradle? -

after execution of custom task, want show user generated study is. wrote:

println "the generated study in ${report.getabsolutepath()}"

but wondering best practice that. in way or using logger

logger.quiet "${report.getabsolutepath()}"

or other. , in real environment how done? write log file or when running on ci server(jenkins) specify want log level?

logging jenkins gradle

Linq to object - ranking items out of 100 in descending order -



Linq to object - ranking items out of 100 in descending order -

i have next array of numbers:

dim lst() integer = {4, 3, 200, 250, 670, 1, 450, 3, 10, 15, 900, 450}

i need list them series of objects number , corresponding rank out of 100, results below:

number rank 900 100 670 90 450 80 450 80 250 60 200 50 15 40 10 30 4 20 3 10 3 10 1 0

i'm stumped - i've got this:

dim t = l in lst order l descending select new { .number = l, .rank = ((from o in lst o > l select o).distinct.count + 1)}

this technique used on series of lists of approximately 3000+ objects, , suspect performance of approach dire , improved when utilize total dataset.

any suggestions appreciated...

fixed it... pretty close already:

dim lst() integer = {4, 3, 200, 250, 670, 1, 450, 15, 15, 15, 900, 450} dim t = (from l in lst order l descending).select( function(l, index) new { .number = l, .rank = 100 - (((from o in lst o > l select o).count + 1) - 1) * 100 / lst.count})

linq

javascript - ajax revealing sql field names -



javascript - ajax revealing sql field names -

i have been working has used ajax phone call results database refresh results table oppose reloading html page.

the info beingness sent json php script exposing field names used in sql database.

is worry in terms of security? not sense comfortable filed names beingness visible on client side.

maybe way things done now, or there can done in php cut down potential risk?

you can hide things that. can illustration phone call getdata.php?type=employees , retrieve info reacting on type value.

of course of study have utilize aliases in query hide real fields name.

example:

select employee__name name employees

i never reveal fields names in client script.

javascript php ajax

functional programming - How does term-rewriting based evaluation work? -



functional programming - How does term-rewriting based evaluation work? -

the pure programming language apparently based on term rewriting, instead of lambda-calculus traditionally underlies similar-looking languages.

...what qualitative, practical difference make? in fact, is difference in way evaluates expressions?

the linked page provides lot of examples of term rewriting being useful, doesn't describe what differently function application, except has rather flexible pattern matching (and pattern matching appears in haskell , ml nice, not fundamental evaluation strategy). values matched against left side of definition , substituted right side - isn't beta reduction?

the matching of patterns, , substitution output expressions, superficially looks bit syntax-rules me (or humble #define), main feature of happens before rather during evaluation, whereas pure dynamic , there no obvious phase separation in evaluation scheme (and in fact otherwise lisp macro systems have made big noise how not different function application). beingness able manipulate symbolic look values cool'n'all, seems artifact of dynamic type scheme rather core evaluation strategy (pretty sure overload operators in scheme work on symbolic values; in fact you can in c++ look templates).

so mechanical/operational difference between term rewriting (as used pure) , traditional function application, underlying model of evaluation, when substitution happens in both?

term rewriting doesn't have function application, languages pure emphasise style because a) beta-reduction simple define rewrite rule , b) functional programming well-understood paradigm.

a counter-example blackboard or tuple-space paradigm, term-rewriting well-suited for.

one practical difference between beta-reduction , total term-rewriting rewrite rules can operate on definition of expression, rather value. includes pattern-matching on reducible expressions:

-- functional style map f nil = nil map f (cons x xs) = cons (f x) (map f xs) -- compose f , g before mapping, prevent traversing xs twice result = map (compose f g) xs -- term-rewriting style: spot double-maps before they're reduced map f (map g xs) = map (compose f g) xs map f nil = nil map f (cons x xs) = cons (f x) (map f xs) -- double maps automatically fused result = map f (map g xs)

notice can lisp macros (or c++ templates), since term-rewriting system, style blurs lisp's crisp distinction between macros , functions.

cpp's #define isn't equivalent, since it's not safe or hygenic (sytactically-valid programs can become invalid after pre-processing).

we can define ad-hoc clauses existing functions need them, eg.

plus (times x y) (times x z) = times x (plus y z)

another practical consideration rewrite rules must confluent if want deterministic results, ie. same result regardless of order apply rules in. no algorithm can check (it's undecidable in general) , search space far big individual tests tell much. instead must convince ourselves our scheme confluent formal or informal proof; 1 way follow systems known confluent.

for example, beta-reduction known confluent (via church-rosser theorem), if write of our rules in style of beta-reductions can confident our rules confluent. of course, that's functional programming languages do!

functional-programming evaluation rewriting

angularjs - Why does Bower say Angular depends on random things? -



angularjs - Why does Bower say Angular depends on random things? -

i trying install package, instance bower install restangular --save

then bower asks me take angular version:

> unable find suitable version angular, please take one: > 1) angular#1.2.6 resolved 1.2.6 , has ang-changeorg, angular-cookies#1.2.6, angular-mocks#1.2.6, angular-resource#1.2.6, > angular-sanitize#1.2.6, angular-scenario#1.2.6 dependants > 2) angular#1.2.17-build.226+sha.b6388b3 resolved 1.2.17-build.226+sha.b6388b3 , has angular-animate#1.2.17-build.226+sha.b6388b3 dependants > 3) angular#* resolved 1.2.18 , has restangular#1.4.0 dependants > 4) angular#~1.2.0 resolved 1.2.19-build.258+sha.ea653e4 , has angularfire#0.7.1 dependants > 5) angular#>= 1.0.8 resolved 1.3.0-build.2845+sha.e57ad6a , has angular-ui-router#0.2.10 dependants > > prefix selection ! persist bower.json

in these options ang-changeorg project i've worked on locally, has no relation current working directory.

my bower.json current project looks so:

{ "name": "ang-changeorg", "version": "0.0.0", "apppath": "public", "dependencies": { "angular": "1.2.6", "json3": "~3.2.6", "es5-shim": "~2.1.0", "jquery": "~1.10.2", "bootstrap": "~3.0.3", "angular-resource": "1.2.6", "angular-cookies": "1.2.6", "angular-sanitize": "1.2.6", "firebase": "~1.0.11", "angularfire": "~0.7.1", "spin.js": "~2.0.0", "angular-ui-router": "~0.2.10", "angular-animate": "~1.2.16", "ng-file-upload": "~1.4.0" }, "devdependencies": { "angular-mocks": "1.2.6", "angular-scenario": "1.2.6" }, "resolutions": { "angular": "1.2.6" } }

bower cache clean did not resolve this.

why bower list ang-changeorg dependent? clarity on how these angularjs version dependents work awesome.

it's because in bower.json, name of project ang-changeorg { "name": "ang-changeorg", "version":

and dependencies in file

"dependencies": { "angular": "1.2.6", "json3": "~3.2.6", "es5-shim": "~2.1.0", "jquery": "~1.10.2", ...

are ones "name": "ang-changeorg" dependent to. hence ang-changeorg dependent angular#1.2.6 because version 1.2.6 of angular specified in bower file: "dependencies": { "angular": "1.2.6",

angularjs bower

sql server 2008 - Tsql: Search multiple fields per row for a given set of string values -



sql server 2008 - Tsql: Search multiple fields per row for a given set of string values -

i having problem wrapping head around next problem, having reporting total sales promotions in generic plenty way can handle routine user requests via subscription. (or allow users info on demand)

i trying write query ssrs study take input text parameter allows multipule values. illustration (‘code1,code2,code3’)… , searches 4 sale “id” fields in illustration table below – returning each [documentno], [lineno_] combination 1 of provided codes appears in 1 of id fields. 4 fields cannot null, can empty string. possible more 1 code apply order line, 1 in each field. each [documentno], [lineno_] combination should appear 1 time in output, can sum [qty] , right total.

[documentno] [varchar](20) not null [lineno_] [int] not null [salesdiscountreasonid] [varchar](20) not null [couponid] [varchar](30) not null [campaignid] [varchar](20) not null [promotioncodeid] [varchar](20) not null [qty] [int] not null

i cannot alter sturcture of info in info warehouse, , cannot expect users routinely inquire study maintain track of type of promotion coupon, campaign, salesdiscount, promocode used implement sale since don’t setup sales or info entry of orders.

i think can want like:

where (','+@codes+',' '%,'+salesdiscountreasonid+',%' or ','+@codes+',' '%,'+couponid+',%' or ','+@codes+',' '%,'+campaignid+',%' or ','+@codes+',' '%,'+promotioncodeid+',%' )

the additional comma used avoid confusion between, say, 10 , 100.

if constructing sql, much, much, much improve do:

where salesdiscountreasonid in (''' + replace(@codes, ',', ''',''') + ''') or couponid in (''' + replace(@codes, ',', ''',''') + ''') or campaignid in (''' + replace(@codes, ',', ''',''') + ''') or promotioncodeid in (''' + replace(@codes, ',', ''',''') + ''')'

one reason in can create utilize of indexes , perform much better.

sql-server-2008 tsql ssrs-2008

Adding a Back button to a iOS app in Titanium Appcelerator without TabGroup or NavBar -



Adding a Back button to a iOS app in Titanium Appcelerator without TabGroup or NavBar -

i'm developing titanium appcelerator ios. manage manually 'back' button using properties of window, can set left , right buttons.

i'm trying code:

var win = titanium.ui.currentwindow; win.backgroundcolor = '#fff'; var b = titanium.ui.createbutton({title:'back'}); win.setleftnavbutton(b); b.addeventlistener('click', function() { win.close(); });

but no button showed.

swanand right want add together more thing if utilize modal property of window open can utilize setleftnavbutton method set button in navigation bar if not want utilize tab grouping or navigation grouping or modal property need add together button in window left,top,width , height property.

you can utilize below example....

var win = titanium.ui.currentwindow; win.backgroundcolor = '#fff'; var b = titanium.ui.createbutton({ title:'back', width : ti.ui.size, height : ti.ui.size, top : 10, left : 10 }); win.add(b);

titanium appcelerator

c# - connect object to listViewItem -



c# - connect object to listViewItem -

i have overview of objects, displayed in listview. when object selected want show form containing more details selected item.

public lessonform(lesson foo) [get , display data]

[...]

lessonlistview.itemactivate += lessonselected; void lessonselected(object sender, eventargs e) { lesson ??? = //requestion magic here. new lessonform(???).show(); }

since listviewitems acutally texts , not programmatically connected lesson-object used create them, have not found proper way find respective lesson-object each listviewitem. sure

lesson ??? = program.listofalllessons.find((candidate) => { homecoming candidate.plaintextname == selecteditem.text //abbrev. on purpose });

however think undisputed that horrible code, on more 1 level. basically: wish listviewitem have an

obj underlyingobject;

field allows easy access object represented listviewitem. there functionality allows this?

you utilize tag property store associated object when creating listviewitem. tag of type object you'd need cast appropriately when read it.

c# winforms listview user-interface control

c# - How can I open AutoCAD 2015 through the .NET API -



c# - How can I open AutoCAD 2015 through the .NET API -

i've been browsing hr , have yet find help this. i'm working on opening autocad .net api in vs2013 using c#, reason, can never autocad launch. i'm using next code:

using system; using system.runtime.interopservices; using autodesk.autocad.interop; using autodesk.autocad.runtime; using autodesk.autocad.applicationservices; namespace ioautocadhandler { public static class acaddocumentmanagement { [commandmethod("connecttoacad")] public static void connecttoacad() { acadapplication acappcomobj = null; // no version number run version const string strprogid = "autocad.application"; // running instance of autocad seek { acappcomobj = (acadapplication)marshal.getactiveobject(strprogid); } grab // error occurs if no instance running { seek { // create new instance of autocad acappcomobj = (acadapplication)activator.createinstance(type.gettypefromprogid(strprogid), true); } grab //// stops here { // if instance of autocad not created message , exit // note: shows box , never opens autocad system.windows.forms.messagebox.show("instance of 'autocad.application'" + " not created."); return; } } // display application , homecoming name , version acappcomobj.visible = true; system.windows.forms.messagebox.show("now running " + acappcomobj.name + " version " + acappcomobj.version); // active document acaddocument acdoccomobj; acdoccomobj = acappcomobj.activedocument; // optionally, load assembly , start command or if assembly // demandloaded, start command of in-process assembly. acdoccomobj.sendcommand("(command " + (char)34 + "netload" + (char)34 + " " + (char)34 + @"c:\users\administrator\documents\all code\main-libraries\ioautocadhandler\bin\debug\ioautocadhandler.dll" + (char)34 + ") "); acdoccomobj.sendcommand("drawcomponent"); } }

unfortunately, stops @ nested catch statement , displays popup box without opening autocad. suggestions on how @ to the lowest degree create autocad open me?

edit: error message

the issue you're coding (correctly) autocad interop interface. recommend against (due potential version changes).

the other issue documentation autocad plugins using newer .net api plugins when autocad running.

final issue programme id of autcad mystery. have resorted making configurable setting, default "autocad.application", take registered autocad.application on production machine. if there multiple versions installed on machine , want specific, append version number (which you'll need research) progid like: "autocad.application.19", or "autocad.application.20" 2015.

for first issue, 1 technique utilize dynamics autocad objects, particularly creating instances. have used objectarx api creating application in dummy project, , switching dynamics when i'm happy properties , method names.

in standalone .net application starts autocad utilize like:

// comment these out in production //using autodesk.autocad.interop; //using autodesk.autocad.interop.common; //... //private static acadapplication _application; private static dynamic _application; static string _autocadclassid = "autocad.application"; private static void getautocad() { _application = marshal.getactiveobject(_autocadclassid); } private static void startautocad() { var t = type.gettypefromprogid(_autocadclassid, true); // create new instance autocad. var obj = activator.createinstance(t, true); // no need casting dynamics _application = obj; } public static void ensureautocadisrunning(string classid) { if (!string.isnullorempty(classid) && classid != _autocadclassid) _autocadclassid = classid; log.activity("loading autocad: {0}", _autocadclassid); if (_application == null) { seek { getautocad(); } grab (comexception ex) { seek { startautocad(); } grab (exception e2x) { log.error(e2x); throwcomexception(ex); } } grab (exception ex) { throwcomexception(ex); } } }

c# .net visual-studio-2013 autocad

worklight calling service using adapter fails -



worklight calling service using adapter fails -

i using ibm worklight depoly on iphone , when seek phone call soap service using adapter error can't understand cause of it. this log got:

2014-06-24 20:57:26.375 myapp[842:60b] user name xxxxx 2014-06-24 20:57:26.376 myapp[842:60b] [debug] [none] establishsslclientauth 2014-06-24 20:57:26.378 myapp[842:60b] wluserauthmanager.getcertificateidentifierfromentity: com.worklight.userenrollment.certificate:com.myapp.dev 2014-06-24 20:57:26.381 myapp[842:60b] [debug] [none] establishsslclientauth iscertificateexists: false 2014-06-24 20:57:26.383 myapp[842:60b] [debug] [none] request[http://192.168.23.1:10080/myapp/apps/services/api/myapp/iphone/query] 2014-06-24 20:57:26.416 myapp[842:60b] [error] [none] [http://192.168.23.1:10080/myapp/apps/services/api/myapp/iphone/query] failure. state: 500, response: application 'myapp' version=1.0 not back upwards iphone environment 2014-06-24 20:57:26.417 myapp[842:60b] loading stop 2014-06-24 20:57:26.418 myapp[842:60b] mymodel::error::{"status":500,"invocationcontext":null,"errorcode":"unexpected_error","errormsg":"the application 'myapp' version=1.0 not back upwards iphone environment"}

note: the app deployed on android no problem.

edit:

i forgot deployed iphone app no problem. message shown when seek phone call adapter calling web service.

as idan stated above error due fact not have version 1.0 of application "myapp" deployed worklight server. accomplish in wl studio right click iphone enviornment in below location , run as-> run on worklight development server:

/"project name"/apps/myapp/iphone

also create sure have right version listed within of application descriptor specific environment. can verify application has been deployed seeing next messages within of console:

deploying application 'myapp' environment 'iphone' worklight server... application 'myapp' deployed environment 'iphone'

just quick tip, can test adapters within of wl studio right-clicking specific adapter , choosing run -> invoke worklight procedure. here can take procedure want test , include parameters requests

worklight worklight-adapters worklight-security

sql - Update not working properly with derived table -



sql - Update not working properly with derived table -

please see query below:

update dbusns set thisdate = created (select max(created) created, dbcustody.reference dbusns inner bring together [server].custody.dbo.dbcustody on dbusns.urns = dbcustody.reference dbusns.datasetname = 'custody' grouping dbcustody.reference) custodydatetable dbusns.urns = custodydatetable.reference , dbusns.urns = '1'

the next query returns 01/01/2011:

select max(created) created, dbcustody.reference dbusns inner bring together server.database.dbo.dbcustody on dbusns.urns = dbcustody.reference dbusns.datasetname = 'custody' , dbcustody.reference = '1'

however, next query homecoming 31/10/2011 (after query 1 run):

select thisdate dbusns datasetname = 'custody' , urns = '1' --query 3

the query below returns 2 rows (31/10/2011 , 01/11/2011):

select created [server].custody.dbo.dbcustody reference = '1'

why query 3 homecoming 31/10/2011? should homecoming 01/11/2011? execution plan/linked server?

your update syntax seems wrong want. in case, best way utilize inner join:

update d set thisdate = t.created dbusns d inner bring together (select max(created) created, c.reference dbusns inner bring together [server].custody.dbo.dbcustody c on dbusns.urns = dbcustody.reference dbusns.datasetname = 'custody' grouping dbcustody.reference) t on d.urns = t.reference d.urns = 1

sql sql-server-2008

ssms - Removing all templates from SQL Server Management Studio -



ssms - Removing all templates from SQL Server Management Studio -

so in ssms, template browser has of these preloaded templates never use. i'd rather clear out can start own structure, however, everytime delete them from:

c:\users[user]\appdata\roaming\microsoft\sql server management studio\11.0\templates

and reboot ssms, magically reappear. templates in there more or less worthless me, out of saving query projects or quick templates folder , set them in here organization , ease. there's no settings can find causes behavior wondering if had thought how disable feature.

any help appreciated!

if want remove default templates completely, need delete files , folders under both of next folders:

64-bit sql server:

%programfiles(x86)%\microsoft sql server\110\tools\binn\managementstudio\sqlworkbenchprojectitems\sql c:\users\<user>\appdata\roaming\microsoft\sql server management studio\11.0\templates\sql\

32-bit sql server:

%programfiles%\microsoft sql server\110\tools\binn\managementstudio\sqlworkbenchprojectitems\sql c:\users\<user>\appdata\roaming\microsoft\sql server management studio\11.0\templates\sql\

sql-server-2012 ssms

hibernate - java quivalent of linq + lambda expression -



hibernate - java quivalent of linq + lambda expression -

say in c# have next code:

int = 1; listofints.where(li=>li > i).tolist();

i wondering when using hibernate, there possible way of doing similar stuff above, instead of using hql?

java hibernate hql

many to many - Postgresql 9.3 - array_agg challenge -



many to many - Postgresql 9.3 - array_agg challenge -

i'm trying understand array_agg function in postgresql 9.3. i've set fun illustration may interested in participating.

any fan of american films 1980's may familiar "brat pack" appeared in many nail films together. using info brat pack films on wikipedia, i've created tables when joined together, can tell worked each other -- if have right query!

/* see: http://en.wikipedia.org/wiki/brat_pack_(actors) */ create table actor( id serial primary key, name varchar(50) ); insert actor(name) values ('emilio estevez'),('anthony michael hall'),('rob lowe'),('andrew mccarthy'),('demi moore'),('judd nelson'),('molly ringwald'),('ally sheedy') create table movie( id serial primary key, title varchar(200) ); insert movie(title) values ('the outsiders'),('class'),('sixteen candles'),('oxford blues'),('the breakfast club'),('st. elmos fire'), ('pretty in pink'),('blue city'),('about lastly night'),('wisdom'), ('fresh horses'),('betsys wedding'),('hail caesar'); create table movie_brats( id serial primary key, movie_id int references movie(id), actor_id int references actor(id) ); insert movie_brats(movie_id, actor_id) values (1,1),(1,3),(2,3),(2,4),(3,2),(3,7),(4,3),(4,8),(5,1),(5,2),(5,6), (5,7),(5,8),(6,1),(6,3),(6,4),(6,5),(6,6),(6,8),(7,4),(7,7),(8,6),(8,8),(9,3),(9,5),(10,1),(10,5),(11,4),(11,7), (12,7),(12,8),(13,2),(13,6);

query: show distinct list of each fellow member of brat pack worked with, ordered name in both columns

name worked ---------------------------------------------------------------------------------------------------------------- emelio estevez | emilio estevez, anthony michael hall, rob lowe, andrew mccarthy, demi moore, judd nelson, molly ringwald, ally sheedy */

my broken query:

select a1.name, array_to_string(array_agg(a2.name),', ') co_stars actor a1, actor a2, film m, movie_brats mb m.id = mb.movie_id , a1.id = mb.actor_id , a2.id = mb.actor_id grouping a1.id

sql fiddle

with v ( select a.id actor_id, a.name actor_name, m.id m_id actor inner bring together movie_brats mb on a.id = mb.actor_id inner bring together film m on m.id = mb.movie_id ) select v1.actor_name "name", string_agg( distinct v2.actor_name, ', ' order v2.actor_name ) "worked with" v v1 left bring together v v2 on v1.m_id = v2.m_id , v1.actor_id != v2.actor_id grouping 1 order 1

the distinct aggregation above necessary not show repeated names in case worked in more 1 movie.

the left join necessary not suppress actor did not work of others in list happen inner join.

if want show in film worked together: sql fiddle

with v ( select a.id actor_id, a.name actor_name, m.id m_id, m.title title actor inner bring together movie_brats mb on a.id = mb.actor_id inner bring together film m on m.id = mb.movie_id ) select a1 "name", string_agg( format('%s (in %s)', a2, title), ', ' order format('%s (in %s)', a2, title) ) "worked with" ( select v1.actor_name a1, v2.actor_name a2, string_agg(v1.title, ', ' order v1.title) title v v1 left bring together v v2 on v1.m_id = v2.m_id , v1.actor_id != v2.actor_id grouping 1, 2 ) s grouping 1 order 1

postgresql many-to-many aggregate-functions

python - Virtual environment in R? -



python - Virtual environment in R? -

i've found several posts best practice, reproducibility , workflow in r, example:

how increment longer term reproducibility of research (particularly using r , sweave) complete substantive examples of reproducible research using r

one of major preoccupations ensuring portability of code, in sense moving new machine (possibly running different os) relatively straightforward , gives same results.

coming python background, i'm used concept of virtual environment. when coupled simple list of required packages, goes way ensuring installed packages , libraries available on machine without much fuss. sure, it's no guarantee - different oses have own foibles , peculiarities - gets 95% of way there.

does such thing exist within r? if it's not sophisticated. illustration maintaining plain text list of required packages , script install missing?

i'm start using r in earnest first time, in conjunction sweave, , ideally start in best way possible! thoughts.

i'm going utilize comment posted @cboettig in order resolve question.

packrat

packrat dependency management scheme r. gives 3 of import advantages (all of them focused in portability needs)

isolated : installing new or updated bundle 1 project won’t break other projects, , vice versa. that’s because packrat gives each project own private bundle library.

portable: transport projects 1 computer another, across different platforms. packrat makes easy install packages project depends on.

reproducible: packrat records exact bundle versions depend on, , ensures exact versions ones installed wherever go.

what's next?

walkthrough guide: http://rstudio.github.io/packrat/walkthrough.html

most mutual commands: http://rstudio.github.io/packrat/commands.html

using packrat rstudio: http://rstudio.github.io/packrat/rstudio.html

limitations , caveats: http://rstudio.github.io/packrat/limitations.html

r python

ember.js - How to destroy the view between sibling routes? ie: /posts/1 to /posts/2 -



ember.js - How to destroy the view between sibling routes? ie: /posts/1 to /posts/2 -

is there ember way destroy view when navigating between sibling routes?

i've had problem in several ember.js applications. user goes /posts/1 , starts doing something, goes /posts/2 , whatever loaded in view still shown sibling route. i've worked around doing transition logic reset view manually (form validation messages, comment boxes, etc), feels kind of hacky.

i think should seek calling distroy element http://emberjs.com/api/classes/ember.view.html#method_destroy on willdestroyelement hook of view ,if calling within view can phone call this.distroy(this).

ember.js

c++ - Why am I getting heap corrpution when I'm not using new or delete? -



c++ - Why am I getting heap corrpution when I'm not using new or delete? -

tl;dr: remember std::vector needs move info around when grows, invalidates pointers still have floating around.

i've googled around problem bit, , seems every case came across question of calling delete on same pointer twice. i'm writing little programme , i'm getting heap corruption, thing doing heap allocation c++ standard library. have hunch i'm leaking reference local variable or done wrong polymorphism, can't figure out.

#include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> using namespace std; struct project; struct solution; struct line { string command; vector<string> params; void print(ostream &os) { os << command << ": "; (string s : params) os << s << ' '; os << endl; } }; struct properties { vector<string> includes; vector<string> libpaths; vector<string> libs; vector<string> sources; vector<string> headers; vector<project *> depends; string folder; string name; string type; }; struct project : properties { project() { built = false; } bool built; void build() { if (built) return; built = true; (project *p : depends) p->build(); cout << "building project: " << name << endl; } }; struct solution : properties { public: project *getproject(const string &name) { (project &p : projects) { if (p.name == name) homecoming &p; } // no project such name -- create project p; cout << &p << endl; p.name = name; projects.push_back(p); cout << "created project: " << name << endl; homecoming getproject(name); } private: vector<project> projects; }; line parseline(const string &strline) { istringstream stream(strline); line line; stream >> line.command; while (stream.good()) { string tok; stream >> tok; if (tok.length() > 0) line.params.push_back(tok); } homecoming line; } template <typename t> vector<t> concat(const vector<t> &a, const vector<t> &b) { vector<t> vec; (t obj : a) vec.push_back(obj); (t obj : b) vec.push_back(obj); homecoming vec; } template <typename t> void printvector(ostream os, vector<t> v) { (t obj : v) os << obj; os << endl; } int main(int argc, char *argv[]) { solution solution; properties *properties = &solution; ifstream stream("testproj.txt"); project p[100]; // no error here.... string linestr; (int linenum = 1; getline(stream, linestr); linenum++) { line line = parseline(linestr); if (line.command == "solution") { // create future commands impact solution properties = &solution; } else if (line.command == "exe" || line.command == "lib") { if (line.params.size() != 1) { cerr << "error @ line " << linenum << endl; homecoming 1; } // create future commands impact project properties = solution.getproject(line.params[0]); properties->type = line.command; properties->name = line.params[0]; } else if (line.command == "includes") { properties->includes = concat(properties->includes, line.params); } else if (line.command == "libpath") { properties->libpaths = concat(properties->libpaths, line.params); } else if (line.command == "libs") { properties->libs = concat(properties->libs, line.params); } else if (line.command == "folder") { if (line.params.size() != 1) { cerr << "error @ line " << linenum << endl; homecoming 1; } properties->folder = line.params[0]; } else if (line.command == "source") { properties->sources = concat(properties->sources, line.params); } else if (line.command == "header") { properties->headers = concat(properties->headers, line.params); } else if (line.command == "depends") { project *proj; (string projname : line.params) { proj = solution.getproject(projname); properties->depends.push_back(proj); } } } }

the error:

heap: free heap block 00395b68 modified @ 00395bac after freed

here stack trace (sorry no line numbers in source above):

crashes in malloc & ntdll somewhere here libstdc++ ---- incomprehensible name mangling main.cpp, line 24 (inside properties::properties()): (compiler-generated constructor) main.cpp, line 37 (inside project::project()): project() { built = false; } main.cpp, line 62 (inside solution::getproject()): project p; main.cpp, line 150 (inside main()): proj = solution.getproject(projname);

it seems crashing in default constructor properties? perhaps while constructing vector?

edit: input file, if help:

solution includes deps/include deps/include/sdl2 libpath deps/lib libs opengl32 glu32 sdl2main sdl2 libpng16 glew exe game folder game source main.cpp depends render mutual lib render folder render source shader.cpp header todo depends mutual lib mutual folder mutual source util.cpp header todo

this lot of code, 1 strong possibility de-referencing 1 of pointers returned getproject, has been invalidated because vector projects, holds objects pointed to, has performed re-allocation. invalidates pointers, references , iterators.

when this:

projects.push_back(p);

projects may need grow, results in re-allocation , invalidation of pointers mentioned above.

without looking code in depth, looks can implement solution quite trivially using std::map:

struct solution : properties { public: // check project name "name" // add together 1 if doesn't exist // homecoming project& getproject(const std::string& name) { if (!projects.count(name)) { projects[name].name = name; } homecoming projects[name]; } // homecoming project name "name" or raise exception // if doesn't exist const project& getproject(const string &name) const { homecoming projects.at(name); } private: std::map<std::string, project> projects; };

c++

twitter - post a tweet to multiple accounts php -



twitter - post a tweet to multiple accounts php -

am trying create php script post tweets users

i utilize php class https://github.com/abraham/twitteroauth

but how can post tweet multiple accounts in same time

i utilize code sand 1 business relationship only

<?php session_start(); require_once('library/twitteroauth.php'); $consumerkey = "xxx"; $consumersecret = "xxx"; $oauth_token = "xxx"; $oauth_token_secret = "xxx"; $connection = new twitteroauth($consumerkey, $consumersecret ,$oauth_token , $oauth_token_secret); //$twit_body = $_post['twit_body']; $twit_body = 'تجربة للجميع022222222'; $status = $connection->post('statuses/update', array('status' => $twit_body) ); //$status = $connection->send($twit_body); print_r($status); ?>

you need different oauth tokens accomplish this. unique each user.

please go through link: post multiple twitter accounts php

php twitter twitter-oauth

javascript - Data not showing until I start to filter? -



javascript - Data not showing until I start to filter? -

i trying utilize info binding feature of angularjs show list of info send ajax request for. new angularjs know i'm missing here. info beingness populated shows if include text box ng-model directive , begin typing in it.

i know code isn't best practice i'm trying in sharepoint , i'm having problem using modules , factories i'm trying simple demo setup first. help much appreciated.

code

class="lang-html prettyprint-override"><!-- info not show until start typing in text box other not need it. --> <input ng-model="foo" /> <ul ng-controller="simplecontroller"> <li ng-repeat="item in discussions"> {{item.title}} </li> </ul> class="lang-js prettyprint-override">function simplecontroller($scope) { $.ajax({ url: requesturi, type: "get", headers: { "accept": "application/json;odata=verbose", }, success: function (data) { $scope.discussions = data.d.results; console.log("simplecontroller success callback"); }, error: function (err) { alert(err); } }); }

i believe what's happening angular not know when $.ajax phone call complete, technically utilize if ( $scope.$$phase ) $scope.$apply(), i'd recommend rebuilding $.ajax "the angular way":

function simplecontroller($scope, $http) { $http.get( requesturi ) .then(function( json ) { console.log( json ); $scope.discussions = json.data; }); }

more reading:

$scope.$apply: manually tell angular recalculate scope upon changing info outside of angular data, e.g. jquery. $http: angular version of $.ajax , automatically handles $scope.$apply (recommended)

javascript angularjs data-binding

javascript - mouseover event propagation issue - Manually propagate -



javascript - mouseover event propagation issue - Manually propagate -

i implementing user interface project i'm working on , can found here : toobrok

each time mouse of user enters div, class added div highlight it, utilize stoppropagation() method restrict highlighting div z-index higher (the top div in z axis). however, sometimes, user needs select element hidden one, when dimensions of 2 elements different, , if bottom div larger, can find points of bottom div not hidden top one, when dimensions same, user able press key alter depth (on z-axis) of selection.

the relevant code given below (in coffeescript), javascript solution help me:

ui.bind = (elements, index) -> ids = ui.getidselector(elements) $(ids).attr("centroid", index) $(ids).mouseover (event) -> event.stoppropagation() ui.highlight $(ids) $(ids).mouseout (event) -> event.stoppropagation() ui.resethighlight $(ids)

i hope question clear , looking forwards answer.

this illustration of html consider :

<!doctype html> <html> <head> <title> sample page </title> </head> <body> <div id="container"> <div id="child1">some text...</div> </div> </body </html>

and related css :

#container { height: 200px; width: 500px; } #child1 { height: 90%; width: 90%; }

when mouse enters child1 element, element highlighted, want container element highlight when user press specific key.

i utilize jquery parent() function select element on example, not sure solution, sometimes, parent can have size of 0px , and mouseover on element not consistent. want select element selected javascript if not utilize stoppropagation() event.

i found might help : how undo event.stoppropagation in jquery?

but cannot utilize in case... because status user action, , cannot synchronously wait user something.

i started writing code decided leave implementation you. here text explanation:

at point of time (probably when user press button cycle through hovered elements) have find candidates highlighting. there no other way rather manually loop through elements , check if mouse position within bound rect. can mouse coordinates argument in mouseover callback. save these hovered elements in array.

next, have manually take element highlight. highlight first element in saved array , move element end of array. may want increment element z-index , add together callback mouseout element.

hope helps, sense free inquire if need more details.

javascript jquery css arrays coffeescript

ios - Updating NSArray in Singleton -



ios - Updating NSArray in Singleton -

i have block, result contains nsarray called message. need access array in several uiviewcontrollers. utilize singletons, array not static, client can receive new message anytime, don't know possible update array within singleton? or reload in every view imported..

overall, i'm not sure how it. here's code, shows variable need utilize in other views. suggestions welcomed, easier solution without singletons best.

sampleviewcontroller.m:

pnchannel *my_channel = [pnchannel channelwithname:currentchannel.user shouldobservepresence:yes]; [pubnub requesthistoryforchannel:my_channel from:nil to:nil limit:100 reversehistory:no withcompletionblock:^(nsarray *message, pnchannel *channel, pndate *fromdate, pndate *todate, pnerror *error) { //i wanna access message array in other view controllers }];

i think singleton nice way this. other can utilize appdelegate property store value , can called in class [[[uiapplication sharedapplication] delegate] yoursharedproperty].in case using singleton appdelegate itself

ios objective-c objective-c-blocks

php / ftp upload_max_filesize .htaccess for a specific root? -



php / ftp upload_max_filesize .htaccess for a specific root? -

is there can set upload_max_filesize in .htaccess ( or way ) 1 root directory?

example:

home/admin/uploader.php

home/pdf <- directory file should uploaded

i want set filesize 10m for home/pdf wont allow other php script within home/admin max_filesize of 10m

whats best way that, or there way that? hope can help me ;) thx far

you're looking @ wrong way. php couldn't care less file going end up. it's script file upload going needs have memory_limit/upload_max_size settings applied it.

all need is

<files uploader.php> php_value upload_max_size 10m </files>

php .htaccess upload ftp

c++ - MAPIInitialize fails -



c++ - MAPIInitialize fails -

under windows 7(64bit) & outlook 2010(64bit), phone call mapiinitialize initialize mapi, there popup message saying:

"either there no default mail service client or current mail service client cannot fulfill messaging request.please run microsoft outlook , set default mail service client."

then mapiinitialize homecoming 0x80004005, indicating fail initialize mapi.

the same programme works under windows vista(32bit) & outlook 2007(32bit).

what problem? thanks.

c++

angularjs - Passing string to ng-click -



angularjs - Passing string to ng-click -

i've trying working out no success far.

the view:

<div class="col-md-4 col-xs-4 col-sm-4"> <div ng-click="action()" class="nav-link">click me action in scope </div> </div>

what trying replace "action()" variable send service modifies rootscope.

in service:

$scope.myaction = function() { $scope.$broadcast("actionevent"); }

what achieve:

<div class="col-md-4 col-xs-4 col-sm-4"> <div ng-click="myaction()" class="nav-link">click me action in scope </div> </div>

but when seek replace it, ng-click not recognize action. text displayed fine, action not execute.

any thought how possible add together action rootscope executes in ng-click?

looking forwards answers, give thanks !

btw, i've tried these options:

1) angular.js parsing value in ng-click 2) angular js ng-click action function string

if function needs access rootscope, don't need scope function within service. inject rootscope controller utilize it.

module.controller("myctrl", function($scope, $rootscope){ $scope.myaction = function() { $rootscope.$broadcast("actionevent"); }; });

if function service, create function fellow member of service, utilize service in ng-click.

module.service("myservice", function($rootscope){ this.myaction = function() { $rootscope.$broadcast("actionevent"); // other stuff }; });

in controller

module.controller("myctrl", function($scope, myservice){ $scope.ms = myservice; });

in markup

<div ng-click="ms.myaction()" class="nav-link">click me action in scope </div>

note doesn't create sense inject $scope service, doesn't have scope. $rootscope different since service, service can depend on. note shouldn't $scope.myaction = myservice.myaction might cause unexpected behavior.

angularjs rootscope

c# - VarChar conversion to Decimal -



c# - VarChar conversion to Decimal -

i have records in database next format, eg: 04567.123 datatype varchar. when access them c# app need sum number lastly three, "04567.124" having troubles this. utilize next code seek convert value , +1

using (sqldatareader read1 = cmd1.executereader()) { while (read1.read()) { string num1 = (read1["numerodossier"].tostring()); decimal ndos = convert.todecimal(num1 + 1); textbox10.text = ndos.tostring(); } }

but gives me error, format error , can't figure out :\ can helo me? many thanks!

edit1:

string num1 = (read1["numerodossier"].tostring()); decimal ndos = convert.todecimal(num1, cultureinfo.invariantculture); decimal total = ndos += (0.001); textbox10.text = total.tostring();

solution (many habib):

using (sqldatareader read1 = cmd1.executereader()) { while (read1.read()) { string num1 = (read1["numerodossier"].tostring()); decimal ndos = convert.todecimal(num1, cultureinfo.invariantculture); decimal total = ndos += 0.001m; textbox10.text = total.tostring(); } }

the problem line:

decimal ndos = convert.todecimal(num1 + 1);

assuming num1 set "04567.123" adding 1 homecoming string "04567.1231", not increment lastly digit assumed.

still shouldn't cause conversion error due format. i believe on civilization uses different decimal separator .. should do:

decimal ndos = convert.todecimal(num1, cultureinfo.invariantculture);

and don't need 1 added number need 0.001m

ndos += 0.001m; //m decimal

you may consider decimal.tryparse method.

c# sql winforms

unix - tail -f command and null copy doesn't work well -



unix - tail -f command and null copy doesn't work well -

why tail command -f alternative not work well. when target file null clear, tail command not write out anymote.

tail -f hoge& cp /dev/null hoge

tail has tail -f alternative checks see if file has been changed.

from man page:

the -f alternative implies -f option, tail check see if file beingness followed has been renamed or rotated. file closed , reopened when tail detects filename beingness read has new inode number. -f alternative ignored if reading standard input rather file.

unix

python - Return list of active bits -



python - Return list of active bits -

how can list of active bits (active bit when equal 1)?

example: number 220 in decimal 11011100 in binary should homecoming ['2', '3', '4', '6', '7'] because bits 0, 1 , 5 off .

alternative dirty 1 liner (no strings attached):

input_number = 220 print [i in xrange(input_number.bit_length()) if ((1 << i) & input_number)]

python bits

javascript - Getting form data from both dependent drop down lists to php -



javascript - Getting form data from both dependent drop down lists to php -

i have form on page includes 2 dependent drop downwards lists. when user selects value 1st list, populates sec list , user selects value 2nd list.

i want submit form info php page insert table in mysql, when submits, info passed except value 2nd list. value 1st list , other input fields passed ok. i've tried know , can't create work. ideas how implement this?

this form index2.php (edit: simplified form element):

<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add"> <label for="parts">choose part</label> <select name="part_cat" id="part_cat"> <?php while($row = mysqli_fetch_array($query_parts)):?> <option value="<?php echo $row['part_id'];?>"> <?php echo $row['part_name'];?> </option> <?php endwhile;?> </select> <br/> <label>p/n</label> <select name="pn_cat" id="pn_cat"></select> <br/> <input type="text" id="manufactured" name="manufactured" value="" placeholder="manufactured" /> <input id="submit_data" type="submit" name="submit_data" value="submit" /> </form>

and javascript:

$(document).ready(function() { $("#part_cat").change(function() { $(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>'); $.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) { $("#pn_cat").html(data); $('#loader').slideup(200, function() { $(this).remove(); }); }); }); });

and php load 2nd list:

<?php include('db_connect.php'); // connects db $con=mysqli_connect(db_host,db_user,db_pass,db_name); $part_cat = $_get['part_cat']; $query = mysqli_query($con, "select * pn pn_categoryid = {$part_cat}"); while($row = mysqli_fetch_array($query)) { echo "<option value='$row[part_id]'>$row[pn_name]</option>"; } ?>

i getting $part_cat 1st list insertpart.php, $pn_cat.

edit: insertpart.php (simplified , echos resuls)

<?php //start session session_start(); //include database connection details require_once('../includes/db_details.php'); //db connect $con=mysqli_connect(db_host,db_user,db_pass,db_name); // check connection if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } // escape variables security // find part name based on id $part_typeid = mysqli_real_escape_string($con, $_post['part_cat']); $part_name_result = mysqli_query($con, "select part_name parts part_id = $part_typeid"); $part_row = mysqli_fetch_array($part_name_result, mysql_num); $part_type = $part_row[0]; echo"part_type='$part_type'"; //find pn value based on id $pn_typeid = mysqli_real_escape_string($con, $_get['pn_cat']); $pn_name_result = mysqli_query($con, "select pn_name pn pn_id = $pn_typeid"); $pn_row = mysqli_fetch_array($pn_name_result, mysql_num); $pn = $pn_row[0]; echo"pn='$pn'"; mysqli_close($con); ?>

it's still work in progress, code ugly, , know i'm mixing post , beingness rectified. if echo $pn_cat on page there no output, $part_type ok.

can seek swapping $_get in

$pn_typeid = mysqli_real_escape_string($con, $_get['pn_cat']);

with $_post?

$pn_typeid = mysqli_real_escape_string($con, $_post['pn_cat']);

edit: based on asker's feedback , thought work-around

note: edit based on suggested, though tested original code , received satisfactory results (after removed php , mysql code , replaced them suitable alternatives).

the work-around

here's html hidden field:

<input type="hidden" id="test" name="test" value="" placeholder="test" />

here's simple javascript function:

function sethiddentextfieldvalue(initiator, target){ $(initiator).change(function() { $(target).val($(this).val()); }); }

you can phone call above function within function(data) { of original code like:

sethiddentextfieldvalue('#pn_cat', '#test'); // note hashes (#)

i recommend hard-code next html html , php files, right before looping of <option>s begin:

<option value="" disabled selected="selected">select</option>

the above line improve user experience, depending on how want code work. note however, exclusively optional.

javascript php jquery mysql

sql server - SQLServer + PHP.ini -



sql server - SQLServer + PHP.ini -

i'm trying create php connecting sql server 2008 server returns next error:

fatal error: phone call undefined function mssql_connect ()

looked in many places , go in php.ini , uncomment line:

extension = php_mysql.dll

but php.ini file doesn't have line.

this current code, i've tried several others:

<? php mssql_connect ("192.168.2.7", "sa", "5c n9r1n7 @ # @ dm") or die ("could not connect server"); mssql_select_db ("fd_585b0f87") or die ("unable select database"); mssql_close (); print "connection ok"; >

i've tried also:

<? php $ server = "192.168.2.7"; $ database = "fd_585b0f87"; $ user = "sa"; $ password = "5c n9r1n7 @ # @ dm"; $ conn = mssql_connect ($ server, $ user, $ password); $ conn = mssql_select_db ("$ database", $ connection); if ($ conn) { echo "one connection"; } >

anyone know way prepare error? give thanks you

you want uncomment line:

;php_mssql.dll

not

;php_mysql.dll

one microsoft sql server (php_mssql.dll) whilst other mysql (php_mysql.dll).

if fails, don't have mssql drivers installed. this link provides instructions on how install mssql drivers enable interface mssql within php script.

php sql-server

.htaccess - RewriteRule working both online and on a local subfolder -



.htaccess - RewriteRule working both online and on a local subfolder -

i have problem , i'm sure there much solutions here can't find search find it...

i'm working on website, , sometime prefer work on local version. assuming :

http://www.normal-website.com http://127.0.0.1/local-version/

for each version have different rule rewrite css/style.css css/style.css.php (my htaccess in root folder) :

rewriterule ^css/([a-z0-9-/]+).css$ css/$1.css.php [qsa,l] rewriterule ^css/([a-z0-9-/]+).css$ local-version/css/$1.css.php [qsa,l]

how ca write have 1 rule, can have same htaccess online , locally ? possible dir (like if work on version 127.0.0.1/website2/ example) ?

thanks lot help, sorry repost if can find existing reply me.

you can use:

rewriteengine on rewritecond %{request_uri}::$1 ^(.*?/)(.*)::\2$ rewriterule ^(.*)$ - [e=base:%1] rewriterule ^css/([a-z0-9/-]+)\.css$ %{env:base}css/$1.css.php [nc,l]

.htaccess mod-rewrite

python - Can I pass on options from optparse to argparse? -



python - Can I pass on options from optparse to argparse? -

i wrapping class exposes optionparser through property named options_parser. wrapping class in 'runner' i've written utilize argparse. utilize argumentparser's parse_known_args() method parse wrapper's argument, , of remaining arguments pass on instance of wrapped class.

running ./wrapper.py --help not list options wrapped class. there convenient way add together optparse options wrapper's argparse argument?

if it's solely displaying options, 1 way can think of utilize format_help of optparse , set in epilog of argparse, example:

in [303]: foo = optionparser() in [304]: foo.add_option("-f", "--file", dest="filename",help="read info filename") in [305]: foo.add_option("-v", "--verbose",action="store_true", dest="verbose") in [311]: bar = argumentparser(epilog = foo.format_help(), formatter_class = rawtexthelpformatter) in [312]: bar.add_argument('integers', metavar='n', type=int, nargs='+',help='an integer accumulator') in [313]: bar.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum integers (default: find max)') in [314]: bar.print_help() usage: ipython [-h] [--sum] n [n ...] positional arguments: n integer accumulator optional arguments: -h, --help show help message , exit --sum sum integers (default: find max) usage: ipython [options] options: -h, --help show help message , exit -f filename, --file=filename read info filename -v, --verbose

you can of course of study format epilog want, including explanation 2 lists of options. might experiment different formatter, though default 1 doesn't work in case because strips newlines epilog. if desperate layout might seek create own formatter subclassing argparse.helpformatter, though i'd not recommend based on class docs:

"""formatter generating usage messages , argument help strings. name of class considered public api. methods provided class considered implementation detail. """

python argparse optparse

I need to send json request for multiple users using csv file in jmeter -



I need to send json request for multiple users using csv file in jmeter -

i have csv file containing user names , password, need utilize csv file pass json request im getting internal sever error json cant understand csv files.

please help me need passing json request multiple users.

parse csv using user csv reader , set inputs variables, illustration ${username}, ${password}. then, wherever creating json utilize pre-processor assign these values need go - example, if had template json loaded , had field "username: ", set field equal variable ${username}.

json csv

javascript - Remembering last selected href/button through a cookie with jQuery -



javascript - Remembering last selected href/button through a cookie with jQuery -

i have document uses 4 links on top navigation. upon clicking link div right below changes size. want accomplish utilize cookie remember lastly selected link.

here code links:

<li><a href="#" class="desktop">desktop</a></li> <li><a href="#" class="tablet">tablet</a></li> <li><a href="#" class="tabletp">tablet (p)</a></li> <li><a href="#" class="mobile">mobile</a></li>

and after have jquery code controls div.

$(document).ready(function () { $(".desktop").click(function() { $(".iframe").animate({"width" : "100%"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "100%"},{queue: false, duration: 1000 }); }); $(".tablet").click(function() { $(".iframe").animate({"width" : "1040px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); }); $(".tabletp").click(function() { $(".iframe").animate({"width" : "788px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); }); $(".mobile").click(function() { $(".iframe").animate({"width" : "350px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); }); });

for using jquery cookie pluging have created next code create cookie. tweaked above jquery code this:

$(".desktop").click(function() { $(".iframe").animate({"width" : "100%"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "100%"},{queue: false, duration: 1000 }); $.cookie("laststate", "desktop", { expires: 7 }); }); $(".tablet").click(function() { $(".iframe").animate({"width" : "1040px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); $.cookie("laststate", "tablet", { expires: 7 }); }); $(".tabletp").click(function() { $(".iframe").animate({"width" : "788px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); $.cookie("laststate", "tabletp", { expires: 7 }); }); $(".mobile").click(function() { $(".iframe").animate({"width" : "350px"},{queue: false, duration: 1000 }); $(".iframe").animate({"height" : "488px"},{queue: false, duration: 1000 }); $.cookie("laststate", "mobile", { expires: 7 }); });

now need know how read cookie created , give out necessary output, auto select link alter size of above mentioned div.

i had @ other questions. this seemed close looking for. code suggested in question little confusing

below code question:

$(function() { var $activelink, activelinkhref = $.cookie('activelinkhref'), activeclass = 'activelink'; $('.navbar').on('click', 'a', function() { $activelink && $activelink.removeclass(activeclass); $activelink = $(this).addclass(activeclass); $.cookie('activelinkhref', $activelink.attr('href')); }); // if cookie found, activate related link. if (activelinkhref) $('.navbar a[href="' + activelinkhref + '"]').click(); });​

i hope question clear enough.

the code posted shows how value cookie, line sets gets value cookie:

cookieval= $.cookie('laststate')

and line check see if found:

if (cookieval)

so given that, know how value cookie, , how check see if value found. if found value, go onto next step, select specific link using value got cookie.

you're storing class of element in cookie, can utilize in selector simulated click event ex:

$('.' + cookieval).click();

javascript jquery html css cookies

java - Button causing app crash on launch -



java - Button causing app crash on launch -

hi when launch app crashes instantly reading logcat can see cause sendbutton in mainactivity, reading around people has button not beingness initiated far can see is, have declared in fragment_main.xml okay , without button code in mainactivity.java code loads app grand. help appreciate.

logcat

06-20 08:50:18.323: e/androidruntime(30036): fatal exception: main 06-20 08:50:18.323: e/androidruntime(30036): java.lang.runtimeexception: unable start activity componentinfo{com.draco.dragonmessage/com.draco.dragonmessage.mainactivity}: java.lang.nullpointerexception 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread.performlaunchactivity(activitythread.java:2483) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread.handlelaunchactivity(activitythread.java:2535) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread.access$600(activitythread.java:178) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread$h.handlemessage(activitythread.java:1390) 06-20 08:50:18.323: e/androidruntime(30036): @ android.os.handler.dispatchmessage(handler.java:107) 06-20 08:50:18.323: e/androidruntime(30036): @ android.os.looper.loop(looper.java:194) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread.main(activitythread.java:5560) 06-20 08:50:18.323: e/androidruntime(30036): @ java.lang.reflect.method.invokenative(native method) 06-20 08:50:18.323: e/androidruntime(30036): @ java.lang.reflect.method.invoke(method.java:525) 06-20 08:50:18.323: e/androidruntime(30036): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:844) 06-20 08:50:18.323: e/androidruntime(30036): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:611) 06-20 08:50:18.323: e/androidruntime(30036): @ dalvik.system.nativestart.main(native method) 06-20 08:50:18.323: e/androidruntime(30036): caused by: java.lang.nullpointerexception 06-20 08:50:18.323: e/androidruntime(30036): @ com.draco.dragonmessage.mainactivity.oncreate(mainactivity.java:48) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activity.performcreate(activity.java:5135) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.instrumentation.callactivityoncreate(instrumentation.java:1151) 06-20 08:50:18.323: e/androidruntime(30036): @ android.app.activitythread.performlaunchactivity(activitythread.java:2437) 06-20 08:50:18.323: e/androidruntime(30036): ... 11 more

mainactivity.java

package com.draco.dragonmessage; import android.app.activity; import android.app.actionbar; import android.app.dialog; import android.app.fragment; import android.app.fragmentmanager; import android.os.bundle; import android.view.layoutinflater; import android.view.menu; import android.view.menuitem; import android.view.view; import android.view.view.onclicklistener; import android.view.viewgroup; import android.support.v4.widget.drawerlayout; import android.widget.button; import android.widget.textview; import android.widget.edittext; public class mainactivity extends activity implements navigationdrawerfragment.navigationdrawercallbacks { /** * fragment managing behaviors, interactions , presentation of navigation drawer. */ private navigationdrawerfragment mnavigationdrawerfragment; /** * used store lastly screen title. utilize in {@link #restoreactionbar()}. */ private charsequence mtitle; string sendmessagestring = ""; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); mnavigationdrawerfragment = (navigationdrawerfragment) getfragmentmanager().findfragmentbyid(r.id.navigation_drawer); mtitle = gettitle(); // set drawer. mnavigationdrawerfragment.setup(r.id.navigation_drawer, (drawerlayout) findviewbyid(r.id.drawer_layout)); final button sendmessage = (button) findviewbyid(r.id.messagebutton); system.out.println(sendmessage.tostring()); sendmessage.setonclicklistener(new onclicklistener(){ @override public void onclick(view view) { final textview receivedmessage = (textview) findviewbyid(r.id.textreceived); final edittext messagetosend = (edittext) findviewbyid(r.id.edittextsend); sendmessagestring = messagetosend.tostring(); receivedmessage.settext(sendmessagestring); } }); } @override public void onnavigationdraweritemselected(int position) { // update main content replacing fragments fragmentmanager fragmentmanager = getfragmentmanager(); fragmentmanager.begintransaction() .replace(r.id.container, placeholderfragment.newinstance(position + 1)) .commit(); } public void onsectionattached(int number) { switch (number) { case 1: mtitle = getstring(r.string.title_section1); break; case 2: mtitle = getstring(r.string.title_section2); break; case 3: mtitle = getstring(r.string.title_section3); break; } } public void restoreactionbar() { actionbar actionbar = getactionbar(); actionbar.setnavigationmode(actionbar.navigation_mode_standard); actionbar.setdisplayshowtitleenabled(true); actionbar.settitle(mtitle); } @override public boolean oncreateoptionsmenu(menu menu) { if (!mnavigationdrawerfragment.isdraweropen()) { // show items in action bar relevant screen // if drawer not showing. otherwise, allow drawer // decide show in action bar. getmenuinflater().inflate(r.menu.main, menu); restoreactionbar(); homecoming true; } homecoming super.oncreateoptionsmenu(menu); } @override public boolean onoptionsitemselected(menuitem item) { // handle action bar item clicks here. action bar // automatically handle clicks on home/up button, long // specify parent activity in androidmanifest.xml. int id = item.getitemid(); if (id == r.id.action_settings) { homecoming true; } homecoming super.onoptionsitemselected(item); } /** * placeholder fragment containing simple view. */ public static class placeholderfragment extends fragment { /** * fragment argument representing section number * fragment. */ private static final string arg_section_number = "section_number"; /** * returns new instance of fragment given section * number. */ public static placeholderfragment newinstance(int sectionnumber) { placeholderfragment fragment = new placeholderfragment(); bundle args = new bundle(); args.putint(arg_section_number, sectionnumber); fragment.setarguments(args); homecoming fragment; } public placeholderfragment() { } @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.fragment_main, container, false); textview textview = (textview) rootview.findviewbyid(r.id.section_label); textview.settext(integer.tostring(getarguments().getint(arg_section_number))); homecoming rootview; } @override public void onattach(activity activity) { super.onattach(activity); ((mainactivity) activity).onsectionattached( getarguments().getint(arg_section_number)); } } }

fragment_main.xml

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context="com.draco.dragonmessage.mainactivity$placeholderfragment" > <textview android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <edittext android:id="@+id/edittextsend" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/section_label" android:layout_alignparentbottom="true" android:ems="10" android:hint="enter message send..." /> <textview android:id="@+id/textview2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/section_label" android:layout_aligntop="@+id/textreceived" android:text="keith" android:textsize="20sp" android:textstyle="bold" /> <textview android:id="@+id/textreceived" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbottom="@+id/section_label" android:layout_alignright="@+id/edittextsend" android:text="medium text" android:textappearance="?android:attr/textappearancemedium" /> <button android:id="@+id/messagebutton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignbottom="@+id/edittextsend" android:layout_alignparentright="true" android:layout_marginright="31dp" android:text="button" /> </relativelayout>

activity_main.xml

<android.support.v4.widget.drawerlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.draco.dragonmessage.mainactivity" > <!-- main content view, view below consumes entire space available using match_parent in both dimensions. --> <framelayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> <!-- android:layout_gravity="start" tells drawerlayout treat sliding drawer on left side left-to-right languages , on right side right-to-left languages. if you're not building against api 17 or higher, utilize android:layout_gravity="left" instead. --> <!-- drawer given fixed width in dp , extends total height of container. --> <fragment android:id="@+id/navigation_drawer" android:name="com.draco.dragonmessage.navigationdrawerfragment" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent" android:layout_gravity="start" /> </android.support.v4.widget.drawerlayout>

thanks 1 time again help.

the button id messagebutton in fragment_main.xml. findbyviewbyid() accessing activity_main.xml (setcontentview(r.layout.activity_main);.

you can add together attribute button class , link element in oncreateview method of placeholderfragment. can access button anywhere in activity.

java android button android-fragmentactivity