Wednesday, 15 June 2011

htmlpurifier add missing url protocol -



htmlpurifier add missing url protocol -

using autoformat.linkify htmlpurifier converts text such http://www.example.com into links. many people write links without protocol, such www.example.com or example.com. there anyway utilize htmlpurifier convert these links?

i know no way htmlpurifier this. should work adding http:// every link, not containing it. can utilize regular look this.

preg_replace( '#\s((https?|ftp)\:\/\/)?([a-z0-9-.]*)\.([a-z]{2,4})\s#', ' http://${3}.${4} ', $html );

test regex here.

example:

test example.com test<br> test www.example.com test<br> test http://example.com test

becomes

test http://example.com test test http://www.example.com test test http://example.com test

now htmlpurifier should right things.

htmlpurifier

sql - Why are the two queries different (left join on ... and ... as opposed to using where clause) -



sql - Why are the two queries different (left join on ... and ... as opposed to using where clause) -

i'm wondering why next 2 queries produce different results (the first query has more rows second).

select * bring together ... bring together ... bring together c on ... left bring together b on b.id = a.id , b.otherid = c.otherid

as opposed to:

select * bring together ... bring together ... bring together c on ... left bring together b on b.id = a.id b.otherid = c.otherid

please help me understand. in sec query, left bring together has 1 status shouldn't include results first query , more (where rows have unmatched otherid). where clause should ensure otherid matches, in first query. why different?

the where performed first query engine before performing join. reasoning beingness why expensive join, if going filter rows later. query engines pretty @ optimizing query write.

also see effect in outer joins. in inner joins both where , join conditions behave same.

sql oracle

ajax - method not allowed, when using onlyajax in controller action -



ajax - method not allowed, when using onlyajax in controller action -

background:

i'm attempting create restful apis in cakephp, , delegate front end end work front end end templating language handlebars. elicited here (http://www.dereuromark.de/2014/01/09/ajax-and-cakephp/) , using jsonview , making extensionful api approach.

problem:

allowing ajax using $this->request->onlyallow('ajax'); returning method not allowed. want enforce apis not straight called browser. could (the community) validate approach building such apis.

code:

//at controller public function joinwithcode() { //$this->request->onlyallow('ajax'); //returns 405 method not allowed //$this->request->onlyallow('post'); //works , not allow access browser $this->response->type('json'); $data = array( 'content' => 'something', 'error' => 'something else', ); $this->set(compact('data')); $this->set('_serialize', 'data'); } //routes.php router::parseextensions('json'); router::connect('/classrooms/join', array('controller' => 'classrooms', 'action' => 'joinwithcode'));

the post effort postman extension:

ajax cakephp

java - ShapeRenderer produces pixelated shapes using LibGDX -



java - ShapeRenderer produces pixelated shapes using LibGDX -

when utilize shaperenderer, comes out pixelated. if draw shape in photoshop same dimensions, it's smooth , clean-looking.

my method follows:

package com.me.actors; import com.badlogic.gdx.gdx; import com.badlogic.gdx.graphics.color; import com.badlogic.gdx.graphics.texture; import com.badlogic.gdx.graphics.g2d.sprite; import com.badlogic.gdx.graphics.g2d.spritebatch; import com.badlogic.gdx.graphics.glutils.shaperenderer; import com.badlogic.gdx.graphics.glutils.shaperenderer.shapetype; import com.badlogic.gdx.scenes.scene2d.actor; public class bub_actors extends actor { private shaperenderer shapes; private texture text; private sprite sprite; public bub_actors(){ shapes = new shaperenderer(); text = new texture(gdx.files.internal("data/circle.png")); sprite = new sprite(); sprite.setregion(text); } @override public void draw(spritebatch batch, float parentalpha) { batch.draw(sprite, 200, 200, 64, 64); shapes.begin(shapetype.filledcircle); shapes.filledcircle(50, 50, 32); shapes.setcolor(color.black); shapes.end(); } }

here's image of output:

any ideas why happens? possible create shaperenderer image (so don't have create spritebatch of different-colored circles...).

the difference anti-aliasing photoshop applies image generates. if zoom in on edges of 2 circles, you'll see anti-aliased 1 has semi-black pixels around edge, shaperenderer generated circle shows pixels exclusively on or off.

the libgdx shaperenderer designed beingness quick , simple way debugging shapes on screen, not back upwards anti-aliasing. easiest way consistent anti-aliased rendering utilize texture. (its possible opengl shader.)

that said, not have create different sprites render different colored circles. utilize white circle transparent background, , render color. (assuming want variety of solid-colored circles).

java libgdx

java - jmf mp3 plugin not play some categories of mp3 files -



java - jmf mp3 plugin not play some categories of mp3 files -

i tried play mp3 file using jmf jmfmp3plugin works format of mp3 files not all. mp3 file mpeglayer means plays mpeg-audio means shows error below,

java.lang.arrayindexoutofboundsexception: 15 @ codeclib.mpa.k.a(unknown source) @ codeclib.mpa.k.do(unknown source) @ codeclib.mpa.decoder.decode(unknown source) @ com.sun.media.codec.audio.mpa.javadecoder.process(javadecoder.java:327) @ com.sun.media.basicfiltermodule.process(basicfiltermodule.java:322) @ com.sun.media.basicmodule.connectorpushed(basicmodule.java:69) @ com.sun.media.basicoutputconnector.writereport(basicoutputconnector.java:120) @ com.sun.media.sourcethread.process(basicsourcemodule.java:729) @ com.sun.media.util.loopthread.run(loopthread.java:135)

the player has been displayed file not play. i'm using jmf code play , createplayer etc,...

thanks in advance..,

java swing mp3 jmf

android - How to get current location at once and after it -load map? -



android - How to get current location at once and after it -load map? -

i have next issue: want current location after want draw markers around it. have used locationlistener current location, when run app saw empty map , after few seconds current location , draw markers. want create next: want load map when after current location.i don't want see map without markers. code is:

public class whereamifragment extends basecontainerfragment implements locationlistener { private supportmapfragment mmapfragment; private locationmanager locationmanager; public static whereamifragment newinstance() { homecoming new whereamifragment(); } private googlemap.onmapclicklistener monmapclicklistener = new googlemap.onmapclicklistener() { @override public void onmapclick(latlng latlng) { } }; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view root = inflater.inflate(r.layout.fragment_where_am_i, container, false); mmapfragment = supportmapfragment.newinstance(); getchildfragmentmanager().begintransaction().replace(r.id.map_container, mmapfragment).commit(); homecoming root; } @override public void onstart() { super.onstart(); mmapfragment.getmap().setmylocationenabled(true); mmapfragment.getmap().setonmapclicklistener(monmapclicklistener); locationmanager = (locationmanager) getactivity().getsystemservice(getactivity().location_service); locationmanager.requestlocationupdates(locationmanager.network_provider, 0, 0, this); } @override public void onlocationchanged(location location) { locationmanager.removeupdates(whereamifragment.this); locationmanager = null; drawstops(new latlng(location.getlatitude(), location.getlongitude())); } private void drawstops(latlng latlng) { defaultcallback<arraylist<stop>> callback = new defaultcallback<arraylist<stop>>(getactivity()) { @override public void success(arraylist<stop> stops, response response) { log.d("mylogs", "array list size= " + stops.size()); (int = 0; < stops.size(); i++) { log.d("mylogs", + ". " + stops.get(i).getlng()); drawmarkers(stops); } } }; mmapfragment.getmap().movecamera(cameraupdatefactory.newlatlngzoom(latlng, 14.0f)); requestdatabuilder builder = new requestdatabuilder(getactivity()).preparewhereamidata( latlng, 500); ewayapi api = restadaptersprovider.getapi(new stopsconverter()); api.sendrequest(builder, callback); } private void drawmarkers(arraylist<stop> arraylist) { (int = 0; < arraylist.size(); i++) { mmapfragment.getmap().addmarker(new markeroptions() .position(arraylist.get(i).getlng()) .title(arraylist.get(i).gettitle())); } } @override public void onstatuschanged(string s, int i, bundle bundle) { } @override public void onproviderenabled(string s) { } @override public void onproviderdisabled(string s) { }

}

the map can init as,

supportmapfragment fm = (supportmapfragment) getsupportfragmentmanager().findfragmentbyid(r.id.map); map = fm.getmap(); map.setmylocationenabled(true); map.settrafficenabled(true); map.setmaptype(googlemap.map_type_normal);

you can add together markers like,

latlng toposition = new latlng(promolat, promolon); map.addmarker(new markeroptions() .position(toposition) .title(promotions.getpromotionheading().tostring()) .snippet(merchants.getmerchantaddress().tostring()) .icon(bitmapdescriptorfactory.defaultmarker(bitmapdescriptorfactory.hue_azure))); map.movecamera(cameraupdatefactory.newlatlngzoom(toposition, 15));

android google-maps location google-maps-android-api-2

graph - Find node with element in array -



graph - Find node with element in array -

i can't find anywhere on net cypher query allow me find nodes contain specific element in array.

to give example, have

0 {name:"john", email:["j@example.com", "j@test.com"]}

what query find john email?

i realised easier expected, might have improve answer.

match (n) "j@example.com" in n.emails homecoming collect(n)

graph neo4j nosql cypher

visual studio 2013 - HOw can i bing an image in dropdown list in mvc 5 asp.net -



visual studio 2013 - HOw can i bing an image in dropdown list in mvc 5 asp.net -

i have drop downwards list listingfew data. along texts displaying, need display image along text.

my code

@html.dropdownlistfor( x => x.id, new selectlist(model.coursecollection, "id", "title"), "create new course", new { @class = "form-control" })

i tried create variable , binding image path , calling along "title" homecoming errors.

any help highly appreciated....plss

visual-studio-2013 asp.net-mvc-5

json - Python: Why is every character of string on newline -



json - Python: Why is every character of string on newline -

i have been trying prepare problem cannot. have next code:

import json def jsonblock(filename): my_array = [] open(filename) f: line in f: my_array.append(line) p = " ".join(str(x) x in my_array) homecoming p; in jsonblock('p5.json'): print(i)

and p5.json

{ "signalpassed" : true, "location" : { "longitude" : 113.3910083760899, "latitude" : 22.57224988908558 }, "phoneosversion" : "7.0.3", "signalstddev" : 4.139107, "phonemodel" : "ipad", }

i want normal output in str format when it, next output:

" 7 . 0 . 3 " , " s g n l s t d d e v " : 4 . 1 3 9 1 0 7 , }

where problem? how can prepare this?

your function jsonblock returns string, result of ''.join(...). iterating on string produces individual characters, print out 1 1 in loop @ end.

to "solve" immediate problem, print jsonblock('p5.json') instead of using loop.

however, want parse json correctly. in case, utilize json library imported @ top.

filename = 'p5.json' open(filename, 'rb') f: info = json.load(filename) print info # info dictionary in case

python json

date - Regex - "captured group equals" in a condition -



date - Regex - "captured group equals" in a condition -

i writing regex capture various date formats. maintain short , flexible, wanted pack possible combinations of months, days , years separate groups. let`s assume have 2 dates this:

01.01. - 31.12.2013

jan - dec 2013

now, want accomplish write regex capture both dates above ones. that's easy. want exclude dates e.g. those:

01.01. - 31 dec 2013

in other words, whenever months mixed, don't want dates. also, if first date doesn't have day, don't want day captured in sec 1 either.

i wanted build conditional captures sec date's appropriate fields, based on found in first 1 (so, e.g. if first date has alpha month, alpha month in sec one, ignore numeric). regex looks this:

(?<firstday>0[1-9]|[12][0-9]|3[01]|[1-9])[-/\s\.](?<firstmonth>0[1-9]|1[012]|[\p{l}]{3,}|[1-9])\s*[-\s/\.]*\s*(?<secondday>0[1-9]|[12][0-9]|3[01]|[1-9])[-\s/.]*(?<secondmonth>((?<firstmonth>)(?<=0[1-9]|1[012]|[1-9]))(0[1-9]|1[012]|[1-9])|[\p{l}]{3,})[-\s/\.]*(?<year>(19|20)\d\d|[012][0-9]$)

this background, question is, is possible check captured grouping equal , build capturing status based on that? found similar topic on stack overflow (can't find referenec, unfortunately), when implement it, stops capturing proper dates (e.g. 01.01. - 31.12.2013). part:

(?<secondmonth>((?<firstmonth>)(?<=0[1-9]|1[012]|[1-9]))(0[1-9]|1[012]|[1-9])|[\p{l}]{3,})

regex date

c# - Entity Framework 5 DB-first association on a non-primary key field error -



c# - Entity Framework 5 DB-first association on a non-primary key field error -

suppose have next 3 tables in oracle db:

table1:

table1id field1 field2 field3

with table1id primary key, field1 beingness unique , made primary key, though isn't defined such in db.

table2:

table2id field1 field4 field5

with table2id primary key , field1 matching values field1 table1.

table3:

table3id table1id field6

with table3id primary key , table1id matching value table1id table1.

so, create entity framework 5 db-first model (can't ef 6 because seems oracle model isn't supported yet in version) , able create association between table3 , table1, want create association between table2 , table1.

i found if add together field1 primary key in table1 (had editing xml edmx file since otherwise error using gui), issue setting association since there 2 primary keys, wants me map both fields in table2. if leave association table1 > table1id blank , fill in association table1 > field1 table2 > field1, 111 error.

i still new entity framework... hope explained question well, have no clue how overcome this... i've seen answers can't done in ef4, there way in later version?

any help @ (please remember i'm ef newbie!!) appreciated!!

c# oracle entity-framework

javascript - render template into application fail to open any further route on Ember -



javascript - render template into application fail to open any further route on Ember -

i followed answer render error , 404 page, thought working fine, realised can't go other route (by clicking #link-to link), kind of error every time, , doesn't load template:

typeerror: cannot read property 'connectoutlet' of undefined @ appendview (http://localhost:8000/assets/js/libs/ember.js:38926:19) @ emberobject.extend.render (http://localhost:8000/assets/js/libs/ember.js:38742:9) @ emberobject.extend.rendertemplate (http://localhost:8000/assets/js/libs/ember.js:38643:14) @ emberobject.extend.setup (http://localhost:8000/assets/js/libs/ember.js:38083:16) @ handlerenteredorupdated (http://localhost:8000/assets/js/libs/ember.js:41076:36) @ http://localhost:8000/assets/js/libs/ember.js:41045:18 @ foreach (http://localhost:8000/assets/js/libs/ember.js:42113:54) @ setupcontexts (http://localhost:8000/assets/js/libs/ember.js:41044:9) @ object.router.transitionbyintent (http://localhost:8000/assets/js/libs/ember.js:40747:13) @ dotransition (http://localhost:8000/assets/js/libs/ember.js:41300:21) ember.js:3910 uncaught error: assertion failed: typeerror: cannot read property 'connectoutlet' of undefined

just reference, i'm doing in applicationroute:

this.render(template, { into: 'application' });

oh, there no need that. automatically goes error route when error thrown. http://emberjs.com/guides/routing/loading-and-error-substates/#toc_code-error-code-substates-with-dynamic-segments

remove this, automatically render error route in resource above resource failed this.render(template, { into: 'application' });

http://emberjs.jsbin.com/jaxufiqu/1/edit

javascript ember.js handlebars.js

How to add a application pool in iis by command line? -



How to add a application pool in iis by command line? -

i want create application pool in iis using command line. don't know command line create it. please help me if did.thanks much!

even easier if utilize new-webapppool web server (iis) administration cmdlets.

iis command-line

php - Order wp_query by numeric custom field -



php - Order wp_query by numeric custom field -

i'm trying allow users sort list of results wp_query numeric custom field value. users can click button alter sort values, when cost selected, wp_query looks like:

'meta_key' => 'adult', 'orderby' => 'meta_value_num', 'order' => 'asc',

the field numeric field acf (acf 5 beta beingness used) step size of 0.01 allow prices 9.99.

however, if run query returns no results every time, when there results should matching.

any ideas i'm going wrong?

edit - total query

$keywordstring = $_session['search']['keyword']; $keywords = explode(', ', $keywordstring); $taxquery = array( 'relation' => 'and', array ( 'taxonomy' => 'main-cat', 'field' => 'slug', 'terms' => $_session['search']['cat'] ) ); if( $_session['search']['keyword'] != '' ) { $taxquery[] = array( 'taxonomy' => 'sub-cat', 'field' => 'name', 'terms' => $keywords ); } $args = array( // general 'post__in' => $postids, 'post_type' => 'event', 'posts_per_page' => 10, 'paged' => $paged, 'cache_results' => false, 'meta_key' => $_session['search']['sort-key'], // becomes 'adult' 'orderby' => $_session['search']['sort-by'], // becomes 'meta_value_num' 'order' => 'asc', // category filter 'tax_query' => $taxquery, // date filter meta_query' => array( 'relation' => 'and', array( 'key' => 'date_%_start-date', 'value' => $when, 'compare' => '>=', 'type' => 'numeric' ), array ( 'key' => 'date_%_end-date', 'value' => $when2, 'compare' => '<=', 'type' => 'numeric' ) ) ); $temp = $wp_query; $wp_query = null; $wp_query = new wp_query( $args );

php sql wordpress acf

php - Wordpress - Retrieving specific posts from the current user -



php - Wordpress - Retrieving specific posts from the current user -

i have custom post 2 fields, first field beingness user, , sec 1 beingness table, , whenever user logged in, must display of posts have user in 1st field, found:

in wp_user id of user i'll using test have: user_id = 3

in wp_postmeta, have row these values:

-post_id=92 -meta_value=3

and in wp_posts, in id = 92, have specific post name looking for.

i'm pretty confused on how create code dynamically, user able see own posts. and btw, post_author admin, can't utilize field

basiclly, must retrieve post_id wp_postmeta using the meta_value i've seen couple of guides can't understand how it. know must utilize wp_get_current_user(). please explain me detail how accomplish this.

thanks

in functions.php need place hook , hook fired whenever post added or updated need utilize saving post id in post meta table.

function enter_post_id( $post_id ) { wp_get_current_user() // current user id update_post_meta()($post_id, $meta_key, $meta_value, $unique) // add together meta key 'user_id' , place value of user_id meta value } add_action( 'save_post', 'enter_post_id' );

now have match completed , need query through post meta table , post id user , , wp_posts show post's matched id.

hope helps . sense free inquire if have confusion.

php wordpress user

xml - double sort in xslt on two different fields -



xml - double sort in xslt on two different fields -

i sort xml file on 2 fieds: identifier , impact. order elements identifier, except elements have xx product must appear last.

my xml file

<evolutionlist> <date> <object> <identifier>id5</identifier> <impact> <product>aa</produit> </impact> </objet> <object> <identifier>id2</identifier> <impact> <product>xx</produit> </impact> </objet> <object> <identifier>id4</identifier> <impact> <product>bb</produit> </impact> </objet> <object> <identifier>id3</identifier> <impact> <product>xx</produit> </impact> </objet> <object> <identifier>id1</identifier> <impact> <product>cc</produit> </impact> </objet> </date> </evolutionlist>

the expceted result be:

<evolutionlist> <date> <object> <identifier>id1</identifier> <impact> <product>cc</produit> </impact> </objet> <object> <identifier>id4</identifier> <impact> <product>bb</produit> </impact> </objet> <object> <identifier>id5</identifier> <impact> <product>aa</produit> </impact> </objet> <object> <identifier>id2</identifier> <impact> <product>xx</produit> </impact> </objet> <object> <identifier>id3</identifier> <impact> <product>xx</produit> </impact> </objet> </date> </evolutionlist>

my xslt code (does not work though)

<xsl:for-each select="//date"> <tr> <td> <xsl:value-of select="./@id"/> </td> </tr> <xsl:for-each select="./object"> <xsl:choose> <xsl:when test="impact/produit = 'xx'"> <xsl:sort select="impact/produit" order="descending"/> </xsl:when> <xsl:otherwise> <xsl:sort select="identifiant"/> </xsl:otherwise> </xsl:choose> ... </xsl:for-each>

you can place <xsl:sort> in origin of <xsl:for-each> or <xsl:apply-templates/>, not in <choose> block.

you using sort order xx, i assume that's ok in scenario (e.g.: don't have product named zz, placed after xx). if that's not case, shouldn't utilize sort rule, template matches xx contents , places them @ end.

this stylesheet produces results expect using sort rules have in original stylesheet (ordering id , product strings). moved selection rules xpath predicate, , used templates instead of nested for-each nodes.

<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0"> <xsl:template match="date"> <xsl:apply-templates select="object"> <xsl:sort select="impact/product[. = 'xx']" order="ascending"/> <xsl:sort select="identifier"/> </xsl:apply-templates> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

you can seek out in xslt fiddle

update in case don't want order xx products, place them @ end, always, can filter elements , apply templates after processing other elements. other stylesheet that:

<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/xsl/transform" version="1.0"> <xsl:template match="date"> <xsl:apply-templates select="object[not(impact[product = 'xx'])]"> <xsl:sort select="identifier"/> </xsl:apply-templates> <xsl:apply-templates select="object[impact[product = 'xx']]"/> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

here's xslt fiddle example.

xml xslt

java - log4j.properties - remove classname from output -



java - log4j.properties - remove classname from output -

i'd remove timestamp , classname output logging message info using log4j logging. right now, appears programme not using conversionpattern layout line, because line doesn't refer c java class owning logger object.

log4j.properties loaded this:

url logconfigurl = classloader.getsystemresource("log4j.properties"); propertyconfigurator.configure(logconfigurl);

here log4j.properties file contents:

log4j.rootlogger=info, stdout log4j.rootlogger=error, stdout log4j.appender.stdout=org.apache.log4j.consoleappender log4j.appender.stdout.target=system.out log4j.appender.stdout.layout=org.apache.log4j.patternlayout log4j.appender.stdout.layout.conversionpattern=%d{yyyy-mm-dd hh:mm:ss} %-5p %c{1}:%l - %m%n

right now, output looks this:

14:24:17.387 [main] info com.nim.tools.recontool.recontool

i want this:

[main] info

i believe wrong "log4j.properties" file has been loaded, output not match configuration.

url logconfigurl = classloader.getsystemresource("log4j.properties");

loads first "log4j.properties" found on class search paths. jars/dirs contains "log4j.properties" have been loaded ahead of class. verify log4j.properties loaded, can print out url.

to configure desirable output, need:

log4j.appender.stdout.layout.conversionpattern=[%t] %-5p: %m%n

java log4j

list - Copying Specific Lines To a .txt File -



list - Copying Specific Lines To a .txt File -

ok, using 'ipconfig /displaydns' display websites visited (since lastly 'ipconfig /flushdns') , re-create just website's url websites.txt. typical layout of output is:

ocsp.digicert.com ---------------------------------------- record name . . . . . : ocsp.digicert.com record type . . . . . : 5 time live . . . . : 17913 info length . . . . . : 4 section . . . . . . . : reply cname record . . . . : cs9.wac.edgecastcdn.net badge.stumbleupon.com ---------------------------------------- record name . . . . . : badge.stumbleupon.com record type . . . . . : 1 time live . . . . : 39560 info length . . . . . : 4 section . . . . . . . : reply (host) record . . . : 199.30.80.32 0.gravatar.com ---------------------------------------- record name . . . . . : 0.gravatar.com record type . . . . . : 5 time live . . . . : 2047 info length . . . . . : 4 section . . . . . . . : reply cname record . . . . : cs91.wac.edgecastcdn.net

but, wish have

ocsp.digicert.com badge.stumbleupon.com 0.gravatar.com

as output. ideas on how that, using windows rt device, external applications not alternative , output 10 times longer that, , not records same.

use powershell:

ipconfig /displaydns | select-string 'record name' | foreach-object {$_ -replace "record name . . . . . :", ""}

list batch-file

mapreduce - Best separator character for Hadoop files -



mapreduce - Best separator character for Hadoop files -

if i'm writing csv style files out of scheme consumed hadoop. best column separator utilize within file? have tried ctrl-a it's pain imo because other programs don't show it, eg might view file using vi, notepad, web browser, excel. comma pain because info might contains commas. thinking of standardising on tab. there best practice in regards hadoop or doesn't matter. have done fair bit of searching , can't find much on basic question.

there tradeoffs each. depends care about.

commas- if care interoperability. every tool works csv. commas in info pain if writing scheme doesn't escape properly, or reading scheme doesn't respect escaping. hive handles escaping correctly, far know.

tabs- if care interoperability , expect commas in info no tabs. you're less have tabs in data, less given tool supports tsv.

ctrl+a- if care hadoop-ecosystem functionality. has become de-facto hadoop standard, hadoop supports commas , tabs. upside don't have care escaping.

in end, think it's toss-up, assuming you're escaping correctly (and should be!). there's no best practice. if find worrying lot kind of thing, might want step more serious serialization format, avro, well-supported in hadoop-world.

hadoop mapreduce hive

ruby - saving documents in rails controller -



ruby - saving documents in rails controller -

i have model, "grievance". grievance can have many documents attached it. documents can associated kinds of things polymorphic.

here grievance model

class grievance < activerecord::base belongs_to :account belongs_to :employee has_many :documents, :class_name => "employeedocument", :as => 'documentable' accepts_nested_attributes_for :documents, :allow_destroy => true end

the show page of grievance allows user upload multiple documents associated grievance. works well.

i refactoring code of developer, , looking @ update action in controller. code looks this...

def update @grievance = @employee.grievances.find(params[:id]) update! { flash[:notice] = 'updated successfully' redirect_to edit_employee_grievance_path(:employee_id => @employee.id, :id => @grievance, :tab_to_return_to => params[:tab_to_return_to]) , homecoming } render :form end

whilst works fine, wanted refactor it, create more readable learn. changed this.

def update @grievance = @employee.grievances.find(params[:id]) if @grievance.save flash[:notice] = "#{@grievance.grievance_type} record updated" redirect_to employee_grievance_path(@employee, @grievance) , homecoming else flash[:alert] = "there problem editing record" render :edit end

now appreciate code more advanced more, , more concise, trying understand why code save documents, , mine not. can see in log form passing details of document controller, must update code?

in version, there nil beingness done @greivance between beingness loaded, , saved.

you missing this:

@grievance.update_attributes(params[:grievance])

inside params attributes form set values of @grievance, it's nested attributes save attached documents.

the other developer's version using inherited resources, automatically. overriding functionality different inheritedresources default.

ruby-on-rails ruby

sql - Optimizing self join on all columns in an ms access table - without any conditions/clauses -



sql - Optimizing self join on all columns in an ms access table - without any conditions/clauses -

i coding in ms access using vba.

i trying self bring together table in ms access . has 8 columns , need cartesian product all.

the problem query have written takes long execute (more 30 mins!) . need help on how optimise it.

the query written follows:

insert table1 select t1.col1, t2.col2, t3.col3, t4.col4, t5.col5, t6.col6,t7.col7,t8.col8 table1 t1, table1 t2, table1 t3, table1 t4, table1 t5, table1 t6, table1 t7, table1 t8;

i checked other threads found none reply query.

thanks in advance!

sql vba ms-access self-join

ios - Xcode Server: error with -destination flag -



ios - Xcode Server: error with -destination flag -

yesterday installed xcode server 4.0. ran commit on git repository created on server , ok. problem when create bot of project. seek run error occurred:

no destinations specified -destination flag valid specified scheme 'xxx' -> imagelink

do know why happens , how can prepare it?

ios objective-c xcode bots xcode-server

command line - How do I run a gawk file with spaces in the path name? -



command line - How do I run a gawk file with spaces in the path name? -

i trying run next line in awk script , getting error. think error because filename has spaces in it. how phone call file without changing path name (i.e. rename file/path)? code contain within begin{} block.

installation_location_gawk = "l:/cpu_analysis/sanity/cpuanalysisapp/cpu_analysis_application/" data_summary_location_gawk = "c:/program files/cpu analysis/data/data_summary.csv" .... command = ("gawk -v version=" dataarray[1] " -v date=" dataarray[2] " -v platform=" dataarray[3] " -f ") (installation_location_gawk "generatesanity_scripts/removedata.awk ") data_summary_location_gawk system(command)

update: ran issue cannot copy/save/edit files in c:\program files due windows restrictions. solved problem moving project c:\my programs.

i think case of providing quotes in command string:

command = "gawk" command = command " -v version=\"" dataarray[1] "\"" command = command " -v date=\"" dataarray[2] "\"" command = command " -v platform=\"" dataarray[3] "\"" command = command " -f \"" installation_location_gawk "generatesanity_scripts/removedata.awk\"" command = command " \"" data_summary_location_gawk "\""

file command-line awk space gawk

java - Guice constructor injection of String dependency (or other unbound primitive)? -



java - Guice constructor injection of String dependency (or other unbound primitive)? -

here code:

public class injectedclass{ private final dependency dependency; private final string string; @inject public injectedclass(dependency dependency, string string){ this.dependency=dependency; this.string=string; } }

let's have bound dependency in module, not have binding string there. how/what guice take default string argument? in (more complicated) test case, seems setting "", logic how not apparent me , not know if deterministic behavior.

by default guice instantiate object has either

an @inject-marked non-private constructor a non-private no-args constructor a default constructor (no constructor)

because string has no-args public constructor, new string() create string equivalent ""

this deterministic behavior, , happen type has above conditions. if concerned it, can do

binder().requireatinjectonconstructors()

then guice study missing binding. additionally there future enhancement beingness planned prevent java.lang.* types beingness bound without qualifier/bindingannotation. prevent core types string or integer beingness automatically bound "" or 0 because injected them.

java constructor dependency-injection guice

Reading OleDb records into TextBox using ComboBox VB.NET -



Reading OleDb records into TextBox using ComboBox VB.NET -

i'm new programming. i'm trying accomplish fill in 9 textboxes in vb.net, reading access table tblklanten, using combobox (cbbnaamfirma). cannot work life of me; i've been searching 6 hours simple thing. can of help me out? i've read numerous threads on so.com , won't work me. code have now:

private sub cbbnaamfirma_selectedindexchanged(sender system.object, e system.eventargs) handles cbbnaamfirma.selectedindexchanged dim connection new oledb.oledbconnection connection.connectionstring = "provider=microsoft.ace.oledb.12.0;data source='" & application.startuppath & "\database.accdb.'" seek connection.open() dim query string query = "select adres tblklanten [naam firma] = ' " & cbbnaamfirma.text & " ' " dim cmd new oledbcommand(query, connection) dim reader oledbdatareader = cmd.executereader reader = cmd.executereader while reader.read txtadresprev.text = reader.getstring("adres") end while connection.close() grab ex oledbexception messagebox.show(ex.message) connection.dispose() end seek end sub

thank in advance. hope code block turned out alright?

the first thing alter reading database using parameterized query. notice code cannot find because add together space before , after value of combobox.

then need start employing using statement around disposable objects ensure proper closing , disposing

finally getstring method oledbdatareader wants numeric index within returned list of fields, not name of field

private sub cbbnaamfirma_selectedindexchanged(sender system.object, e system.eventargs) handles cbbnaamfirma.selectedindexchanged dim cnstring = "provider=microsoft.ace.oledb.12.0;data source=" & _ application.startuppath & "\database.accdb" dim query = "select adres tblklanten [naam firma] = ?" using connection = new oledb.oledbconnection(cnstring) using cmd = new oledbcommand(query, connection) seek connection.open() cmd.parameters.addwithvalue("@p1", cbbnaamfirma.text) using reader = cmd.executereader while reader.read dim posadres = reader.getordinal("adres") txtadresprev.text = reader.getstring(posadres) .... other text boxes other fields here..... end while end using grab ex oledbexception messagebox.show(ex.message) end seek end using end using end sub

also connection string seems wrong. no need of quotation , stray point after fielname wrong

vb.net combobox textbox oledb

javascript - Message is not getting masked automatically in Chrome and IE in Extjs -



javascript - Message is not getting masked automatically in Chrome and IE in Extjs -

i having problem iframe in extjs. below code snippet works fine in firefox not work in ie , in chrome. "msg" should hidden automatically 1 time download started. please suggest wrong below code.

items: [{ xtype: 'button', icon: 'images/interface-icons/page_white_magnify.gif', text: t['generatereport'], width: 100, handler: function(me) { // loding mask mymask = new ext.loadmask(ext.getbody(), {msg: "please wait...preparing dowload csv file."}); window.mymask.show(); var url = getbaseurl() + 'index.php?r=admin/administrativereport'; downloadurl = url; var downloadframe = document.createelement("iframe"); downloadframe.setattribute('src', downloadurl); downloadframe.setattribute('id', "i_frame"); downloadframe.setattribute('class', "screenreadertext"); downloadframe.setattribute('onload', "setframeloaded()"); document.body.appendchild(downloadframe); settimeout(function() { mymask.hide(); }, 600000); } }] function setframeloaded() { window.mymask.hide(); }

javascript google-chrome iframe extjs onload

php - Caching large arrays -



php - Caching large arrays -

i have next function:

function f($idx, $arr) { static $a; if ($a == null) { foreach ($arr $v) { $key = $v['key']; if (!isset($a[$key])) { $a[$key] = array(); } $a[$key][] = $v; } } homecoming $a[$idx]; }

and initial conditions are:

function f() called many-many times in 1 request $arr large $arr may differ in different function calls (low cardinality) $idx differs in every function phone call (high cardinality)

and need know, if $arr cached , if not, create "cached version", maintain previous arrays.

according 2. i'm not able utilize md5(serialize($arr)) utilize identifier, need way determine that. have thought how accomplish such hight-performance caching functionality (let's i'm not able changes outside function)?

if it's not imperative $arr not modified, i'd add together optimized key access straight it:

// note argument has been changed &$arr - we're passing reference function f($idx, &$arr) { if (empty($arr['___cached'])) { $arr['___cached'] = array(); foreach ($arr $k => $v) { if ($k === '___cached') continue; if (!isset($arr['___cached'][$v['key']])) { $arr['___cached'][$v['key']] = array(); } $arr['___cached'][$v['key']][] = $v; } } homecoming $arr['___cached'][$idx]; }

php arrays performance caching

ruby on rails - Check_box_tag not displaying labels properly -



ruby on rails - Check_box_tag not displaying labels properly -

everything posting correctly, not see labels in checkboxes, blanks. form looks this:

<%= form_for @itemrecord |f| %> <div class="col-xs-12"> <p><b>items people asking for</b></p> </div> <% @wishlist.each |category, list| %> <div class="col-xs-2"> <div class="form-group box"> <h5> <%="#{category}"%> </h5> <% list.each |thing| %> <%= check_box_tag ":item_name[]", "#{thing}" %> </br> <% end %> </div> </div> <% end %> <%= f.submit "go!", class: "btn btn-primary btn-large btn-block" %> </div> <% end %>

what's happening wishlist hash of categories , items within categories set in controller, , called multiple form builders build checkboxes. challenge right in current implementation, checkboxes params passed through (fyi controller code @ bottom), beside each checkbox, there no text shows thing (i.e., no label people know they're checking.

here's html generated 1 checkbox (it's same checkboxes)

basically, need create value label.

fyi what's happening every item checked, record beingness created. here's controller code:

def create items_to_be_saved = [] inventory_params.each |i| items_to_be_saved << ({ :signup_id => signup.find_by_email(session[:signup_email]).id, :item_name => }) end if inventory.create items_to_be_saved flash[:success] = "thanks!" redirect_to root_path else render new_inventory_path end end def inventory_params params.require(":item_name") end

in code:

<%= check_box_tag ":item_name[]", "#{thing}" %>

second parameter check_box_tag not label value, value goes controller in parameters. if wan't display label within checkbox need phone call label_tag in view:

= label_tag ':item_name[]', thing = check_box_tag ':item_name[]'

but should check simple_form gem allows render checkboxes in much cleaner way:

f.input :field, as: :boolean, inline_label: 'label'

ruby-on-rails forms checkbox form-helpers

javascript - Issue on Quering Database Using jQuery Ajax and PHP -



javascript - Issue on Quering Database Using jQuery Ajax and PHP -

can please take @ this demo , allow me know why getting empty array? have jquery ajac request as:

$( "#appinfo" ).on( "submit", function( e ) { var etraget = $(".opacity").html().replace(/\d/g,''); var senario = current; if(qtype =="econo"){ var col = senario +"_"+etraget; var data='column='+col; $.ajax({ type:"post", url:"assets/econo.php", data:data, datatype : 'json', success:function(html) { coords = html; console.log(data); st = map.set(); (var = 0; < coords.length; i++) { var circle = map.circle(coords[i][0], coords[i][1], 6); st.push(circle); } e.preventdefault(); });

and econo.php as:

<?php include 'conconfig.php'; $con = new mysqli(db_host,db_user,db_pass,db_name); $collm = $_post['column']; $query = "select x, y econo where".$collm."=1"; $results = $con->query($query); $return = array(); if($results) { while($row = $results->fetch_assoc()) { $return[] = array((float)$row['x'],(float)$row['y']); } } $con->close(); echo json_encode($return); ?>

as can see console.log(data); , console display result column=ce_3000 $collm = $_post['column']; empty because whrn tried dump got empty []. can please allow me know why happening?

javascript php jquery ajax

Java Varargs edge case confusion -



Java Varargs edge case confusion -

i little bit puzzled this:

void a(){ log.d(tag, "noargs"); } void a(int... s){ log.d(tag, "varargs"); }

my first question logged if phone call a();? please seek guess because trying illustrate confusion this. tested , reply in end of question.

the real question how varargs work, how jvm know method calling since way phone call them same?

also there in java (or planned) allow this

as3 code: function sayhello(somebody:string = “world”):void{} //this allows specify default values of arguments , have them optional

answer noargs ecipse references method.

the behaviour you're observing because java always chooses most specific version of overloaded method based on arguments pass (further reading).

given scenario:

void a() { log.d(tag, "noargs"); } void a(int... s) { log.d(tag, "varargs"); }

a phone call a() matches void a() { ... } method - it's most specific version of method given arguments. when remove void a() { ... } varargs method becomes specific version , called instead.

you can take step further:

public class varargstest { public static void a(int... s) { system.out.println("int varargs invoked."); } public static void a(short... s) { system.out.println("short varargs invoked."); } public static void a(long... s) { system.out.println("long varargs invoked."); } public static void a(byte... s) { system.out.println("byte varargs invoked."); } public static void main(string... args) { a(); } }

this invokes byte... overload of a. if remove that, short... version gets called, int... , long....

if instead add together overload char... argument, becomes compilation error because char , byte have same specificity - compiler unable determine version right 1 phone call unless explicitly provide argument method call.

java varargs

Why is GnuRadio companion not allowing me to add blocks? -



Why is GnuRadio companion not allowing me to add blocks? -

i have installed gnu radio , grc 3.7.2.2 on 32bit xp machine next instructions from ettus. starts without messages, can open existing flowgraph, delete blocks, edit block properties, cannot add together new blocks. double click on block has no effect. nor dragging it, right clicking or other gesture think of. can think of problem might causing this?

update: turns out homecoming works, not double-click

it sounds having issues installed graphics libraries. did install whole list of dependencies in instructions?

you should e-mail gnu radio mailing list what's going on: https://lists.gnu.org/mailman/listinfo/discuss-gnuradio

gnuradio

javascript - Fire ul tag click event not li with jquery -



javascript - Fire ul tag click event not li with jquery -

how can impact click event ul tag not li jquery?

<!-- html --> <ul class="wrap"> <li>test1</li> <li>test2</li> <li>test3</li> </ul>

i tried jquery this.but doesnt work.

//javascript jquery("ul.wrap").not(jquery("ul > li")).click(function(){ //fire ul });

how can this?

events 'bubble' dom parent elements. need attach event ul, , event on kid li elements uses stoppropagation():

jquery("ul.wrap") .on('click', function(){ // something... }) .on('click', 'li', function(e) { e.stoppropagation(); });

javascript jquery html

c# - How to convert JSON Array to List? -



c# - How to convert JSON Array to List<>? -

this json , need access values under each object in attendance array:

{"name":" ","course":"","attendance":[{"name":"international finance","type":"theory","conducted":"55","present":"50"},{"name":"indian constitution","type":"theory","conducted":"6","present":"6"}]}

here code:

public class att { public class attendance { public string name { get; set; } public string type { get; set; } public string conducted { get; set; } public string nowadays { get; set; } } public att(string json) { jobject jobject = jobject.parse(json); jtoken juser = jobject; name = (string)juser["name"]; course of study = (string)juser["course"]; attender = juser["attendance"].tolist<attendance>; } public string name { get; set; } public string course of study { get; set; } public string email { get; set; } //public array attend { get; set; } public list<attendance> attender { get; set; } }

it attender = juser["attendance"].tolist<attendance>; line have problem with. says,

cannot convert method grouping tolist non-delegate type. did intend invoke method?

how access values?

you have typo!

attendance vs attendence

and should work

attender = juser["attendance"].toobject<list<attendance>>();

you may find running result @ dotnetfiddle

c# json windows-phone

c# - Why EF is pluralizing just one table? -



c# - Why EF is pluralizing just one table? -

im using entity framework database first approach create mapping of objects database. utilize ef wizard select tables , generates domain, context , , etc classes. in wizard didnt select alternative pluralize names. have table wich name error, , when seek records of particular table error message : invalid object name 'dbo.errors'.

public iqueryable<error> getallerrors() { homecoming _context.error.asqueryable(); } public actionresult index() { var aux = new messagerepository(); var errors = aux.getallerrors().tolist(); // exception here homecoming view(); }

why im getting error?

c# .net entity-framework

java - How to filter a request that has an invalid parameter in JAX-RS? -



java - How to filter a request that has an invalid parameter in JAX-RS? -

by "invalid" mean parameter not expected.

for example:

@path("/") public interface exampleinterface { @get @path("/example") public response test( @queryparam("param1") string param1, @queryparam("param2") string param2 ); }

and phone call ".../example?param3=foo"

you can check utilize containerrequestfilter , compare passed parameters defined parameters:

@provider public class requestparamfilter implements containerrequestfilter { @context private resourceinfo resourceinfo; @context private httpservletrequest servletrequest; @override public void filter(containerrequestcontext requestcontext) throws ioexception { set<string> validparams = new hashset<string>(); method method = resourceinfo.getresourcemethod(); (annotation[] annos : method.getparameterannotations()) { (annotation anno : annos) { if (anno instanceof queryparam) { validparams.add(((queryparam) anno).value()); } } } (string param : servletrequest.getparametermap().keyset()) { if (!validparams.contains(param)) { requestcontext.abortwith(response.status(status.bad_request).build()); } } } }

don't forget servletrequest#getparametermap returns map contains both - query string parameters , parameters passed in body of request. maybe need parse query string yourself.

note: won't speed application.

java filter jax-rs resteasy query-parameters

Authentication with my android code for Twitter -



Authentication with my android code for Twitter -

i trying user tweets through code:

public void displaytweets() throws twitterexception{ /*logintotwitter(); uri uri = getintent().getdata(); string verifier = uri.getqueryparameter(url_twitter_oauth_verifier); accesstoken accesstoken = twitter.getoauthaccesstoken(requesttoken, verifier); */ // access token string access_token = msharedpreferences.getstring(pref_key_oauth_token, ""); // access token secret string access_token_secret = msharedpreferences.getstring(pref_key_oauth_secret, ""); accesstoken accesstoken = new accesstoken(access_token, access_token_secret); long userid = accesstoken.getuserid(); system.out.println("==> "+userid); seek { twitter twitter = new twitterfactory().getinstance(); //list<status > statuses = twitter.getretweets(long.parselong(args[0])); list<status> statuses = twitter.getretweets(userid); (status status : statuses) { system.out.println("@" + status.getuser().getscreenname() + " - " + status.gettext()); } system.out.println("done."); system.exit(0); } grab (twitterexception te) { te.printstacktrace(); system.out.println("failed retweets: " + te.getmessage()); system.exit(-1); } }

the problem got user id (for system.out.println ("==>"+userid)), got fatal error

06-26 15:31:35.983: e/androidruntime(9874): fatal exception: main 06-26 15:31:35.983: e/androidruntime(9874): java.lang.illegalstateexception: authentication credentials missing. see http://twitter4j.org/en/configuration.html details 06-26 15:31:35.983: e/androidruntime(9874): @ twitter4j.twitterbaseimpl.ensureauthorizationenabled(twitterbaseimpl.java:201) 06-26 15:31:35.983: e/androidruntime(9874): @ twitter4j.twitterimpl.get(twitterimpl.java:1941) 06-26 15:31:35.983: e/androidruntime(9874): @ twitter4j.twitterimpl.getretweets(twitterimpl.java:209) 06-26 15:31:35.983: e/androidruntime(9874): @ com.androidhive.twitterconnect.mainactivity.affichertweets(mainactivity.java:287) 06-26 15:31:35.983: e/androidruntime(9874): @ com.androidhive.twitterconnect.mainactivity.onclick(mainactivity.java:418) 06-26 15:31:35.983: e/androidruntime(9874): @ android.view.view.performclick(view.java:3620) 06-26 15:31:35.983: e/androidruntime(9874): @ android.view.view$performclick.run(view.java:14292) 06-26 15:31:35.983: e/androidruntime(9874): @ android.os.handler.handlecallback(handler.java:605) 06-26 15:31:35.983: e/androidruntime(9874): @ android.os.handler.dispatchmessage(handler.java:92) 06-26 15:31:35.983: e/androidruntime(9874): @ android.os.looper.loop(looper.java:137) 06-26 15:31:35.983: e/androidruntime(9874): @ android.app.activitythread.main(activitythread.java:4507) 06-26 15:31:35.983: e/androidruntime(9874): @ java.lang.reflect.method.invokenative(native method) 06-26 15:31:35.983: e/androidruntime(9874): @ java.lang.reflect.method.invoke(method.java:511) 06-26 15:31:35.983: e/androidruntime(9874): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:980) 06-26 15:31:35.983: e/androidruntime(9874): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:747) 06-26 15:31:35.983: e/androidruntime(9874): @ dalvik.system.nativestart.main(native method) 06-26 15:32:02.513: i/process(9874): sending signal. pid: 9874 sig: 9

what's wrong?

android twitter

Android - Intent Acitivity to a Fragment of a FragmentActivity -



Android - Intent Acitivity to a Fragment of a FragmentActivity -

i have activity , want 1 of fragment of fragmentactivity

im trying

startactivity(new intent(secondactivity.this, (mainactivity)secondfragment.class));

it because can't phone call fragments via intent? iknow fragment part of fragmentactivity.

you have seek below code alter fragment within activity.

getsupportfragmentmanager() .begintransaction() .replace(r.id.content_frame, new homefragment(), "" + _homefragment).commit();

android android-layout android-intent android-activity android-fragments

email - Emailing with Mailboxer gem in Rails 4 -



email - Emailing with Mailboxer gem in Rails 4 -

i've setup site mailboxer create in-site messaging system. i'd implement email functions of mailboxer when message sent in site, user receive email notifiying them.

i've searched documentation, though there doesn't seem setting email side of things. far, i've taken mailer classess gem's app/mailer/ directory, , set them in app/mailer/ directory, within of mailboxer folder. (app/mailer/mailboxer/). i'm not sure how create utilize of methods in these mailers.

here controllers i've setup insite messaging, working fine:

messages controller:

class messagescontroller < applicationcontroller # /message/new def new @request = request.find(params[:request]) @message = current_user.messages.new @user = @request.user end def reply @conversation ||= current_user.mailbox.conversations.find(params[:id]) end # post /message/create def create @user = user.find(params[:user]) @body = params[:body] @subject = params[:subject] current_user.send_message(@user, params[:body], params[:subject]) flash[:notice] = "message has been sent!" redirect_to :conversations end end

conversations controller:

class conversationscontroller < applicationcontroller before_filter :authenticate_user! helper_method :mailbox, :conversation def index @conversations ||= current_user.mailbox.inbox.all end def reply current_user.reply_to_conversation(conversation, *message_params(:body, :subject)) redirect_to conversation_path(conversation) end def trashbin @trash ||= current_user.mailbox.trash.all end def trash conversation.move_to_trash(current_user) redirect_to :conversations end def untrash conversation.untrash(current_user) redirect_to :back end def empty_trash current_user.mailbox.trash.each |conversation| conversation.receipts_for(current_user).update_all(:deleted => true) end redirect_to :conversations end private def mailbox @mailbox ||= current_user.mailbox end def conversation @conversation ||= mailbox.conversations.find(params[:id]) end def conversation_params(*keys) fetch_params(:conversation, *keys) end def message_params(*keys) fetch_params(:message, *keys) end def fetch_params(key, *subkeys) # debugger params[key].instance_eval # debugger case subkeys.size when 0 self when 1 self[subkeys.first] else subkeys.map { |k| self[k] } end end end end

i tried using new_message_email message_mailer function in messages_controller's create method, this:

def create @user = user.find(params[:user]) @body = params[:body] @subject = params[:subject] current_user.send_message(@user, params[:body], params[:subject]) new_message_mailer(@subject, @user) flash[:notice] = "message has been sent!" redirect_to :conversations end

but it's giving me error undefined method 'new_message_email' #<messagescontroller:...>, apparently don't know i'm doing. please give me of need set up? advice appreciated.

ruby-on-rails email mailboxer

java - Running a client/server through a fragment in android -



java - Running a client/server through a fragment in android -

i'm trying connect java server android client (which i've achieved 1 simple activity). want add together list/details fragment , able pass info , server , list , details. i'm using illustration list/details view fragment:

android fragments example

i have 3 questions:

is possible run server fragment , pass info , server? would have connection start in main activity or of fragments? if in main activity, how pass info 4th fragments main activity?

i quite new android , still learning why inquire unusual questions.

many thanks!

1) cannot run server communication on fragment. mean is, has run on different thread on ui thread. fragment runs on ui thread.

you can technically write "server" code on same class fragment long runs on different thread know - fragments have lifecycles means 1 time user moves fragment/activity or goes launcher - server , communication killed!

you should create android service communication stuff , keeps running in background when application hidden/not running (as see fit).

2) start connection once, no need start every fragment/activity.

3) there lots of ways passing around data. happens intents, read it.

implementation may differ, of import thing remember not run long duration tasks on main thread since create application freeze , hence killed android.

java android android-fragments

uicollectionview - Android like view pager with tabs on iOS -



uicollectionview - Android like view pager with tabs on iOS -

i know best way implement android view pager tabs on ios 1 found on fifa world cup app

the various approaches think of were:

customised uitabbarcontroller swipe , pan gesture- tried , swipe experience not fluid fifa app. sluggish new skype app (think using approach). page view controller- tried ran unusual issues. did not seek much after that. collection view controller horizontal paging- seemed best approach me, not sure memory management.

my current implementation- have 3 tab bar entries of now. have separate view controllers each of them. here way implemented using horizontal paging collection view:

- (uicollectionviewcell *)collectionview:(uicollectionview *)collectionview cellforitematindexpath:(nsindexpath *)indexpath { nsinteger indexnumber = indexpath.row; uicollectionviewcell *cell; switch (indexnumber) { case 0: cell = [collectionview dequeuereusablecellwithreuseidentifier:@"collectionviewcell1" forindexpath:indexpath]; [cell.contentview addsubview:self.firstviewcontrollerobject.view]; break; case 1: cell = [collectionview dequeuereusablecellwithreuseidentifier:@"collectionviewcell2" forindexpath:indexpath]; [cell.contentview addsubview:self.secondviewcontrollerobject.view]; break; case 2: cell = [collectionview dequeuereusablecellwithreuseidentifier:@"collectionviewcell3" forindexpath:indexpath]; [cell.contentview addsubview:self.thirdviewcontrollerobject.view]; break; default: break; } homecoming cell; }

i not figure out way manage cells improve made different entities. how can improve approach or if approach not should use?

ios uicollectionview uitabbar

windows phone 8 - multiple instances of view and view model in memory -



windows phone 8 - multiple instances of view and view model in memory -

we have windows phone 8 application in using mvvm lite having 4 , 5 views , , same number of view models. 1 day observed size of application increasing usage , reaches more 100 mb , crashes.after lot of testing able understand every time navigate view , instance created , stored in memory.it observed instances of view , view model living in memory , increasing space on ram. confirmed same defining finializer on view class , view model , on closing application finializer called same number of times page navigated to. binding datacontext of view respective view model in xaml. 1 of main view has advertisement command , size increases fast if user navigates view multiple times. how resolve issue. unable understand view should destroyed 1 time user presses button, not happening . help much appreciated.

we found solution adding below line of code code behind.

protected override void onnavigatedfrom(navigationeventargs e) { base.onnavigatedfrom(e); messenger.default.unregister(this); if (e.navigationmode == navigationmode.back) { datacontext = null; } }

what doing above unregisterring message handlers page , assigning datacontext null. in our case datacontext assigned in xaml , messenge handlers registered in onnavigatedto event of page. still unclear on navigating page , page object should have died automatically . , should line of code added mvvm lite project pages , if why not mutual practice.

windows-phone-8 mvvm memory-leaks mvvm-light

Jquery Search Plugin, show no results -



Jquery Search Plugin, show no results -

i'm using jquery plugin search on page: http://rmm5t.github.io/jquery-sieve/

it works great, i'm trying figure out how go updating display "no results" if search doesn't come anything. know need hidden, that's how far have gotten...

http://jsfiddle.net/mzsu2/1/

(function() { var $; $ = jquery; $.fn.sieve = function(options) { var compact; compact = function(array) { var item, _i, _len, _results; _results = []; (_i = 0, _len = array.length; _i < _len; _i++) { item = array[_i]; if (item) { _results.push(item); } } homecoming _results; }; homecoming this.each(function() { var container, searchbar, settings; container = $(this); settings = $.extend({ searchinput: null, searchtemplate: "<div><label>search: <input type='text'></label></div>", itemselector: "tbody tr", textselector: null, toggle: function(item, match) { homecoming item.toggle(match); }, complete: function() {} }, options); if (!settings.searchinput) { searchbar = $(settings.searchtemplate); settings.searchinput = searchbar.find("input"); container.before(searchbar); } homecoming settings.searchinput.on("keyup.sieve change.sieve", function() { var items, query; query = compact($(this).val().tolowercase().split(/\s+/)); items = container.find(settings.itemselector); items.each(function() { var cells, item, match, q, text, _i, _len; item = $(this); if (settings.textselector) { cells = item.find(settings.textselector); text = cells.text().tolowercase(); } else { text = item.text().tolowercase(); } match = true; (_i = 0, _len = query.length; _i < _len; _i++) { q = query[_i]; match && (match = text.indexof(q) >= 0); } homecoming settings.toggle(item, match); }); homecoming settings.complete(); }); }); }; }).call(this);

demo fiddle

the thought count visible element on search finish event , , if there no visible divs show "no results", otherwise hide it.

i have chaged html,css,js somewhat, check demo more

javascript

$(function () { var searchtemplate = "<label style='width:100%;'>search: <input type='text' class='form-control' placeholder='search' style='width:80%;'></label>" $(".div-sieve").sieve({ searchtemplate: searchtemplate, itemselector: "div", complete: function () { var visible = $('.div-sieve>div:visible').size(); if(visible){ $(".noresults").hide(); } else{$(".noresults").show();} } }); });

css

.div-sieve { margin-top:10px; } .div-sieve div { background-color:#eeeeee; margin-bottom:10px; padding:10px; } div.noresults { background-color:#eeeeee; margin-bottom:10px; padding:10px; display:none; }

html

<div class="div-sieve"> <div> <a href="#">question 1?</a> <br />the lysine contingency - it's intended prevent spread of animals case ever got off island. dr. wu inserted gene makes single faulty enzyme in protein metabolism. animals can't manufacture amino acid lysine. unless they're continually supplied lysine us, they'll slip coma , die.</div> <div> <a href="#">question 2?</a> <br />now know are, know am. i'm not mistake! makes sense! in comic, know how can tell arch-villain's going be? he's exact opposite of hero. , times they're friends, , me! should've known way when... know why, david? because of kids. called me mr glass.</div> </div> <div class="noresults">sorry, not find looking for.</div>

jquery search

jquery - Display notification message onsave data to DB in MVC4 VB.NET using razor -



jquery - Display notification message onsave data to DB in MVC4 VB.NET using razor -

i need display notification messge user when click save button on page. save button phone call click event in jquery , calling ajax function within event. in ajax phone call calling action method in controller httppost method. when info posted info returning integer value( 1 success, 0 failure). based on need display message user.how ?

$("#btnsave").click(function (e) { var vcomments = $("#ddlcomments :selected").text(); $.ajax({ url: "/acc/save", type: "post", data: vcomments, success: function (data) { }, error: function (ex) { alert(ex.responsetext); } }); });

controller:

<httppost> function save(byval comments string) actionresult dim result int32 = save(comments) if result = 1 'i need display notification saying posted else ' need display notification "unable post" end if end function

after thinking (and varying original comment) suggest taking advantage of httpstatuscoderesult in action:

class="lang-vb prettyprint-override"><httppost> function save(byval comments string) actionresult dim result int32 = save(comments) if result = 1 homecoming new httpstatuscoderesult(204) ' 204 successful, no content else homecoming new httpstatuscoderesult(500) ' error, internal server end if end function

now can rely on error , success callbacks display appropriate message.

jquery vb.net asp.net-mvc-4

json - Passing dictionary from python server to vb.net client -



json - Passing dictionary from python server to vb.net client -

i'm starting out json. have working illustration of passing dictionary python server python client using json. trying pass dictionary python server (which know works) vb.net client. have less experience of network programming in vb.net python. here's client vb.net code:

imports system.text imports newtonsoft.json module module1 private clientsocket new tcpclient private serverstream networkstream private _host string = "raspberrypi" private _port integer = 2001 private my_dict new dictionary sub main() dim received_data string dim instream(100000) byte clientsocket.connect(_host, _port) serverstream = clientsocket.getstream() serverstream.read(instream, 0, cint(clientsocket.receivebuffersize)) received_data = encoding.ascii.getstring(instream) dim output json_result = jsonconvert.deserializeobject(of json_result)(received_data) console.writeline(output.name) console.writeline(output.extension) console.readline() serverstream.close() end sub public class json_result public property name() string public property extension() integer end class end module

i don't error - don't anything. able point me in right direction? want end dictionary object.

python json vb.net dictionary network-programming

c# - How to get and handle form changes in a different form that is accessible from Application.OpenForms? -



c# - How to get and handle form changes in a different form that is accessible from Application.OpenForms? -

i'm using delegate poll current active command focused external form every few milliseconds, works badly.

the title of question confusing, not have application.openforms. property exposes collection of open forms. if new form opened had not been opened, added collection. operating scheme allows 1 active window @ time on desktop, want notified when active window changes. polling work this, isn't solution.

you either need install a global hook (wh_cbt 1 want), or take advantage of winevents infrastructure (via setwineventhook function) intended accessibility tools. both of these provide notification when active window changes. of course, scope won't limited application testing. you'll notification when active window on desktop changes other window. filter downwards application care about.

i don't have time @ moment translate of required code c#/.net, can find somewhere online, 1 time know search for. additionally, winevents wrapped in system.windows.automation namespace.

c# .net winforms

java - does tibco ems scale with more connections -



java - does tibco ems scale with more connections -

i have java server (jdk 1.6) pulls in info tibco ems topic through 1 connection. starting see log on beingness able pull message tibco. how tibco scale if break info multiple topics , each topic gets separate connection (same jms server) server.

also can't break server multiple servers.

tibco principle made used in enterprise massive amounts of info transiting message server. instead of pulling messages using server, can seek utilize tibco other way around: publishing messages , using server subscribe publisher. can utilize observer/observable design pattern analogy. wouldn't worry scaling.

java jms tibco tibco-ems

c# - Working with large data sets and memory limitations -



c# - Working with large data sets and memory limitations -

i working code comparing big collections of objects , storing matches.

unsurprisingly, have encountered system.outofmemoryexception

how can go solving this?

during comparing should writing memory, have else write results disk/rdbms. i.e. create buffer.

in fact depend on environment, particularly on operation scheme either x86 or x64. check more details here: memory in depth

1.you have advanced scenario streaming need. exact solution depends on pulling data. in case of pulling info sql database can utilize streaming sqldatareader tightly coupled async in case, sample code:

using (sqldatareader reader = await command.executereaderasync(commandbehavior.sequentialaccess)) { if (await reader.readasync()) { if (!(await reader.isdbnullasync(0))) { using (var datastream = reader.getstream(0)) { //process info } } } }

this link reveal bit more details: retrieving big info set. however, maintain in mind such approach forces utilize async in connection string deal async code, additional complexity, when want cover specs/tests.

2.yet approach batching, i.e. buffering info acceptable limit , exposing batch consuming code, after go on fetching new batch of info unless loaded, sample code:

while(true) { int count = 0; bool canread = reader.read(); while(canread) { canread = reader.read(); count++; if (count >= batchsize) break; } if (!canread) break; }

the size of batch can calculate estimating size of 1 row of info (based on table schema, msdn article) or create configurable , play around suitable value. main advantage of approach need minimal changes in code , code remains synchronous. disadvantage have maintain either active connection or open new connection every time , instead maintain records have read , still need fetch.

finally both options forcefulness take care more advanced questions, such should if part of info fetched , after connection lost (need fail-over mechanism), ability cancel long-running retrieving operation after timeout, etc.

to conclude, if not want handle additional complexity big info introduces, delegate task whatever there available on market, i.e. database or 3rd party framework. if sense team have plenty skills this, go ahead , implement - maintain result of comparing in disk file, utilize in-memory cache or force info database

c# out-of-memory large-data

php - Implementing code into smarty -



php - Implementing code into smarty -

i new frameworks. , made simple script in php. don't know how can implement code in smarty .tpl file.

// yesterday $hour = 12; $today = strtotime("$hour:00:00"); $yd = strtotime("-1 day", $today); $yesterday = date('d/m/y', $yd); $query = "select date, amount yesterday_deposit"; $fetch_query = mysql_query($query); $total_amount = 0; while($row = mysql_fetch_array($fetch_query)){ $day = $row['date']; if(($dt = date('d/m/y', $day)) === $yesterday){ $total_amount += $row['amount']; } } echo $total_amount;

smarty template engine separate displaying info , other operations.

what should in case is:

// yesterday $hour = 12; $today = strtotime("$hour:00:00"); $yd = strtotime("-1 day", $today); $yesterday = date('d/m/y', $yd); $query = "select date, amount yesterday_deposit"; $fetch_query = mysql_query($query); $total_amount = 0; while($row = mysql_fetch_array($fetch_query)){ $day = $row['date']; if(($dt = date('d/m/y', $day)) === $yesterday){ $total_amount += $row['amount']; } } $smarty->assign('total_amount', $total_amount);

and in smarty template file should simple do:

{$total_amount}

that's way should work. create calculations, info database in pure php files , display info in template files (for illustration in smarty).

in above illustration assume have created smarty object , variable name $smarty , display somewhere else in code template file.

php smarty

vb.net - Compression ZipArchive won't compile -



vb.net - Compression ZipArchive won't compile -

i have class, i've converted c# vb.net (framework 4.5)

i'm trying utilize new compression features. think i've followed instructions msdn it's still not compiling.

zipfile, ziparchive , ziparchiveentry coming "type not defined"

i've imported namespace "system", "system.io" , "system.io.compression" in references

what else have work?

imports scheme imports system.io imports system.io.compression imports system.collections.generic imports system.linq public class clszip1 ' used specify our overwrite policy files extracting. public enum overwrite = 0 ifnewer = 1 never = -1 end enum ' used identify if trying create zip file , exists. public enum archiveaction emerge = 0 ereplace = 1 eerror = 2 eignore = 3 end enum ' unzips specified file given folder in safe manner. ' plans missing paths , existing files , handles them gracefully. public sub extracttodirectory(byval sourcearchivefilename string, byval destinationdirectoryname string, optional byval overwritemethod overwrite = overwrite.ifnewer) 'opens zip file read using archive ziparchive = zipfile.openread(sourcearchivefilename) 'loops through each file in zip file each file ziparchiveentry in archive.entries improvedextracttofile(file, destinationdirectoryname, overwritemethod) next end using end sub ' safely extracts single file zip file public sub extracttofile(byval file ziparchiveentry, byval destinationpath string, optional byval overwritemethod overwrite = overwrite.ifnewer) 'gets finish path destination file, including 'relative paths in zip file dim destinationfilename string = path.combine(destinationpath, file.fullname) 'gets new path, minus file name can create 'directory if not exist dim destinationfilepath string = path.getdirectoryname(destinationfilename) 'creates directory (if doesn't exist) new path directory.createdirectory(destinationfilepath) 'determines file based upon 'method of overwriting chosen select case overwritemethod case overwrite.always 'just set file in , overwrite found file.extracttofile(destinationfilename, true) case overwrite.ifnewer 'checks see if file exists, , if so, if should 'be overwritten if (not file.exists(destinationfilename) or file.getlastwritetime(destinationfilename) < file.lastwritetime) 'either file didn't exist or file newer, 'we extract , overwrite existing file file.extracttofile(destinationfilename, true) end if case overwrite.never 'put file in if new ignores 'file if exists if (not file.exists(destinationfilename)) file.extracttofile(destinationfilename) end if end select end sub ' allows add together files archive, whether archive exists or not public sub addtoarchive(byval archivefullname string, byval files list(of string), optional byval action archiveaction = archiveaction.ereplace, optional byval fileoverwrite overwrite = overwrite.ifnewer, optional byval compression compressionlevel = compressionlevel.optimal) 'identifies mode using - default create dim mode ziparchivemode = ziparchivemode.create 'determines if zip file exists dim archiveexists boolean = file.exists(archivefullname) 'figures out based upon our specified overwrite method select case action case archiveaction.emerge 'sets mode update if file exists, otherwise 'the default of create fine if (archiveexists) mode = ziparchivemode.update case archiveaction.ereplace 'deletes file if exists. either way, default 'mode of create fine if (archiveexists) file.delete(archivefullname) case archiveaction.eerror 'throws error if file exists if (archiveexists) throw new ioexception(string.format("the zip file {0} exists.", archivefullname)) case archiveaction.eignore 'closes method silently , nil if (archiveexists) homecoming case else end select 'opens zip file in mode specified using zipfile ziparchive = zipfile.open(archivefullname, mode) 'this bit of hack , should refactored - 'doing similar foreach loop both modes, create 'i doing little work while update gets lot of 'code. not handle other mode (of 'which there wouldn't 1 since don't 'use read here). if (mode = ziparchivemode.create) each file string in files 'adds file archive zipfile.createentryfromfile(file, path.getfilename(file), compression) next else each file string in files dim fileinzip = (from f in zipfile.entries f.name = path.getfilename(file) select f).firstordefault() select case fileoverwrite case overwrite.always 'deletes file if found if (fileinzip isnot nothing) fileinzip.delete() end if 'adds file archive zipfile.createentryfromfile(file, path.getfilename(file), compression) case overwrite.ifnewer 'this bit trickier - delete file if 'newer, if newer or if file isn't in 'the zip file, write zip file if (fileinzip isnot nothing) 'deletes file if older our file. 'note file ignored if existing file 'in archive newer. if (fileinzip.lastwritetime < file.getlastwritetime(file)) fileinzip.delete() 'adds file archive zipfile.createentryfromfile(file, path.getfilename(file), compression) else 'the file wasn't in zip file add together archive zipfile.createentryfromfile(file, path.getfilename(file), compression) end if end if case overwrite.never 'don't - decision need 'consider, however, since mean no file 'be writte. write sec re-create zip 'the same name (not sure wise, however). case else end select next end if end using end sub end class

you need add together reference system.io.compression.dll. have vs2010 @ work, can't test this, i'm guessing it's available framework 4.5, since it's not on pc.

open 'my project', go references tab, click 'add...' drop-down , select 'reference'. in add together reference dialog, utilize .net tag, sort list component name , find system.io.compression.

if it's not there, seek searching hard drive dll , utilize same reference dialog add together manually. who's got experience particular library can clarify abnormalities in using it.

vb.net compression .net-4.5 ziparchive

java - Android - Error while reading data from Bluetooth -



java - Android - Error while reading data from Bluetooth -

i have android application sends , retreives info to/from arduino device.

package com.arduino.arduinoled1; import java.io.ioexception; import java.io.inputstream; import java.io.outputstream; import java.util.uuid; import android.app.activity; import android.bluetooth.bluetoothadapter; import android.bluetooth.bluetoothdevice; import android.bluetooth.bluetoothsocket; import android.content.intent; import android.os.bundle; import android.os.handler; import android.util.log; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.textview; import android.widget.toast; public class mainactivity extends activity { private static final string tag = "abdel-domotic"; button ledon, ledoff; button gateon, gateoff; button curton, curtoff; button gettemp; textview temp; outputstream mmoutputstream; inputstream mminputstream; thread workerthread; byte[] readbuffer; int readbufferposition; int counter; volatile boolean stopworker; private static final int request_enable_bt = 1; private bluetoothadapter btadapter = null; private bluetoothsocket btsocket = null; private outputstream outstream = null; // known spp uuid private static final uuid my_uuid = uuid.fromstring("00001101-0000-1000-8000-00805f9b34fb"); // insert server's mac address private static string address = "20:13:12:05:10:24"; /** called when activity first created. */ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); log.d(tag, "in oncreate()"); setcontentview(r.layout.activity_main); ledon = (button) findviewbyid(r.id.ledon); ledoff = (button) findviewbyid(r.id.ledoff); gateon = (button) findviewbyid(r.id.gateon); gateoff = (button) findviewbyid(r.id.gateoff); curton = (button) findviewbyid(r.id.curton); curtoff = (button) findviewbyid(r.id.curtoff); gettemp = (button) findviewbyid(r.id.gettemp); btadapter = bluetoothadapter.getdefaultadapter(); checkbtstate(); ledon.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("1"); toast msg = toast.maketext(getbasecontext(), "you have clicked led on", toast.length_short); msg.show(); } }); ledoff.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("0"); toast msg = toast.maketext(getbasecontext(), "you have clicked led off", toast.length_short); msg.show(); } }); gateon.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("3"); toast msg = toast.maketext(getbasecontext(), "you have clicked gate on", toast.length_short); msg.show(); } }); gateoff.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("2"); toast msg = toast.maketext(getbasecontext(), "you have clicked gate off", toast.length_short); msg.show(); } }); curton.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("5"); toast msg = toast.maketext(getbasecontext(), "you have clicked curton on", toast.length_short); msg.show(); } }); curtoff.setonclicklistener(new onclicklistener() { public void onclick(view v) { senddata("4"); toast msg = toast.maketext(getbasecontext(), "you have clicked curton off", toast.length_short); msg.show(); } }); gettemp.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { senddata("6"); toast msg = toast.maketext(getbasecontext(), "you have clicked temperature", toast.length_short); msg.show(); beginlistenfordata(); } }); } @override public void onresume() { super.onresume(); log.d(tag, "...in onresume - attempting client connect..."); // set pointer remote node using it's address. bluetoothdevice device = btadapter.getremotedevice(address); // 2 things needed create connection: // mac address, got above. // service id or uuid. in case using // uuid spp. seek { btsocket = device.createrfcommsockettoservicerecord(my_uuid); } grab (ioexception e) { errorexit("fatal error", "in onresume() , socket create failed: " + e.getmessage() + "."); } // discovery resource intensive. create sure isn't going on // when effort connect , pass message. btadapter.canceldiscovery(); // found connection. block until connects. log.d(tag, "...connecting remote..."); seek { btsocket.connect(); log.d(tag, "...connection established , info link opened..."); } grab (ioexception e) { seek { btsocket.close(); } grab (ioexception e2) { errorexit("fatal error", "in onresume() , unable close socket during connection failure" + e2.getmessage() + "."); } } // create info stream can talk server. log.d(tag, "...creating socket..."); seek { outstream = btsocket.getoutputstream(); } grab (ioexception e) { errorexit("fatal error", "in onresume() , output stream creation failed:" + e.getmessage() + "."); } } @override public void onpause() { super.onpause(); log.d(tag, "...in onpause()..."); if (outstream != null) { seek { outstream.flush(); } grab (ioexception e) { errorexit("fatal error", "in onpause() , failed flush output stream: " + e.getmessage() + "."); } } seek { btsocket.close(); } grab (ioexception e2) { errorexit("fatal error", "in onpause() , failed close socket." + e2.getmessage() + "."); } } private void checkbtstate() { // check bluetooth back upwards , check create sure turned on // emulator doesn't back upwards bluetooth , homecoming null if(btadapter==null) { errorexit("fatal error", "bluetooth not supported. aborting."); } else { if (btadapter.isenabled()) { log.d(tag, "...bluetooth enabled..."); } else { //prompt user turn on bluetooth intent enablebtintent = new intent(btadapter.action_request_enable); startactivityforresult(enablebtintent, request_enable_bt); } } } private void errorexit(string title, string message){ toast msg = toast.maketext(getbasecontext(), title + " - " + message, toast.length_short); msg.show(); finish(); } private void senddata(string message) { byte[] msgbuffer = message.getbytes(); log.d(tag, "...sending data: " + message + "..."); seek { outstream.write(msgbuffer); } grab (ioexception e) { string msg = "in onresume() , exception occurred during write: " + e.getmessage(); if (address.equals("00:00:00:00:00:00")) msg = msg + ".\n\nupdate server address 00:00:00:00:00:00 right address on line 37 in java code"; msg = msg + ".\n\ncheck spp uuid: " + my_uuid.tostring() + " exists on server.\n\n"; errorexit("fatal error", msg); } } void beginlistenfordata() { final handler handler = new handler(); final byte delimiter = 10; // ascii code newline // character stopworker = false; readbufferposition = 0; readbuffer = new byte[1024]; workerthread = new thread(new runnable() { public void run() { while (!thread.currentthread().isinterrupted() && !stopworker) { seek { int bytesavailable = mminputstream.available(); if (bytesavailable > 0) { byte[] packetbytes = new byte[bytesavailable]; mminputstream.read(packetbytes); (int = 0; < bytesavailable; i++) { byte b = packetbytes[i]; if (b == delimiter) { byte[] encodedbytes = new byte[readbufferposition]; system.arraycopy(readbuffer, 0, encodedbytes, 0, encodedbytes.length); final string info = new string( encodedbytes, "us-ascii"); readbufferposition = 0; handler.post(new runnable() { public void run() { temp.settext(data); } }); } else { readbuffer[readbufferposition++] = b; } } } } grab (ioexception ex) { stopworker = true; } } } }); workerthread.start(); } }

the sending part works fine, when seek retrieve info gives me next error message

06-20 17:28:12.440: d/abdel-domotic(6718): ...connection established , info link opened... 06-20 17:28:12.440: d/abdel-domotic(6718): ...creating socket... 06-20 17:28:15.470: d/abdel-domotic(6718): ...sending data: 6... 06-20 17:28:15.470: d/blz20_asockwrp(6718): asocket_write 06-20 17:28:15.470: i/blz20_wrapper(6718): blz20_wrp_poll: nfds 2, timeout -1 ms 06-20 17:28:15.470: d/blz20_wrapper(6718): blz20_wrp_poll: transp poll : (fd 43) returned r_ev [pollout ] (0x4) 06-20 17:28:15.470: d/blz20_wrapper(6718): blz20_wrp_poll: homecoming 1 06-20 17:28:15.470: d/blz20_wrapper(6718): blz20_wrp_write: wrote 1 bytes out of 1 on fd 43 06-20 17:28:15.490: w/dalvikvm(6718): threadid=9: thread exiting uncaught exception (group=0x4001e578) 06-20 17:28:15.500: e/androidruntime(6718): fatal exception: thread-10 06-20 17:28:15.500: e/androidruntime(6718): java.lang.nullpointerexception 06-20 17:28:15.500: e/androidruntime(6718): @ com.arduino.arduinoled1.mainactivity$8.run(mainactivity.java:260) 06-20 17:28:15.500: e/androidruntime(6718): @ java.lang.thread.run(thread.java:1019) 06-20 17:28:15.530: d/abdel-domotic(6718): ...in onpause()... 06-20 17:28:15.530: d/blz20_asockwrp(6718): asocket_abort [43,44,45] 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_shutdown: s 43, how 2 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_shutdown: fd (-1:43), bta 2, rc 1, wflags 0x800, cflags 0x0, port 9050 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_shutdown: shutdown socket 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_write: wrote 1 bytes out of 1 on fd 45 06-20 17:28:15.530: d/blz20_asockwrp(6718): asocket_destroy 06-20 17:28:15.530: d/blz20_asockwrp(6718): asocket_abort [43,44,45] 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_shutdown: s 43, how 2 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_shutdown: fd (-1:43), bta 2, rc 1, wflags 0x800, cflags 0x0, port 9050 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_shutdown: shutdown socket 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_write: wrote 1 bytes out of 1 on fd 45 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_close: s 45 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_close: std close (45) 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_close: s 44 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_close: std close (44) 06-20 17:28:15.530: i/blz20_wrapper(6718): blz20_wrp_close: s 43 06-20 17:28:15.530: d/blz20_wrapper(6718): blz20_wrp_close: fd (-1:43), bta 2, rc 1, wflags 0x800, cflags 0x0, port 9050 06-20 17:28:15.530: i/blz20_wrapper(6718): __close_prot_rfcomm: fd 43 06-20 17:28:15.530: i/btl_ifc(6718): send_ctrl_msg: [btl_ifc ctrl] send btlif_bts_rfc_close (bts) 8 pbytes (hdl 40) 06-20 17:28:15.530: d/btl_ifc_wrp(6718): wrp_close_s_only: wrp_close_s_only [43] (43:-1) [brcm.bt.btlif] 06-20 17:28:15.530: d/btl_ifc_wrp(6718): wrp_close_s_only: info socket closed 06-20 17:28:15.530: d/btl_ifc_wrp(6718): wsactive_del: delete wsock 43 active list [ad42cbd0] 06-20 17:28:15.530: d/btl_ifc_wrp(6718): wrp_close_s_only: wsock closed, homecoming pool 06-20 17:28:15.530: d/blz20_wrapper(6718): btsk_free: success

my first guess error in line 260 says int bytesavailable = mminputstream.available();

am correct?

what problem? , how can prepare it?

your mminputstream object null. forgot create object before using it.

java android bluetooth arduino