Tuesday, 15 April 2014

html - Is an image within a noscript tag only downloaded if Javascript is disabled? -



html - Is an image within a noscript tag only downloaded if Javascript is disabled? -

consider next example:

<noscript> <img class="photo" src="example.png"> </noscript>

does client download image file if have javascript disabled? (i'm aware client can see image if javascript disabled in example)

the reason i'm asking because i've been using base64 info uris several background-image properties in external css (avoiding http requests). utilize base64 info uris src value of img tags updating values via external javascript (to retain benefits of caching).

essentially, whole point of avoid/limit http requests , wondering if can degrade gracefully , fetch image files if javascript disabled? or image downloaded regardless?

the html 4.01 specification says content of noscript not rendered in situations. however, suggests browsers should not perform operations on basis of content in such situations, since such operations pointless , cut down efficiency.

the html5 draft more explicit , reflects actual browser behavior. says noscript element, in emphatic note: “it works ‘turning off’ parser when scripts enabled, contents of element treated pure text , not real elements”. (the note relates why noscript not work when using xhtml syntax, reveals principle works, when works.)

so can expect when scripting enabled, content of noscript won’t parsed (except recognize end tag). blender’s reply seems confirm this, , little experiment firefox:

<img src=foo style="foo: 1"> <noscript> <img src=bar style="bla: 1"> </noscript>

firefox makes failing request foo no request bar, when scripting enabled. in addition, shows warning erroneous css code foo: 1, in error console, no warning bla: 1. apparently img tag not parsed.

however, don’t see how question relates scenario presented reason asking it. think utilize img element outside noscript , set there, using data: url, desired initial content (which remain, fallback, final content when scripting disabled).

html http background-image image noscript

database - How much slow are the cursors in Sybase -



database - How much slow are the cursors in Sybase -

i have heard cursors slow in sybase, said should avoid cursors. can tell how slow cursors in sybase. read cursors fine, or slow, , acceptable utilize cursors altogether

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.dc20020_1251/html/databases/databases537.htm

here reply example.... sample execution times against 5000-row table

procedure | access method | time --------------------------------------------------------------------- increase_price | uses 3 table scans | 28 seconds increase_price_cursor | uses cursor, single table scan |125 seconds

database stored-procedures cursor sybase

python - How do I call a model method in django ModelAdmin fieldsets? -



python - How do I call a model method in django ModelAdmin fieldsets? -

i want display embedded map on admin form when info exists in db. have next code:

models.py

class address(models.model): address = models.charfield() def address_2_html(self): if self.address: # homecoming html embedded map using entered address. homecoming embedded_map_html else: homecoming '' address_2_html.allow_tags = true

admin.py

class addressadmin(admin.modeladmin): fieldsets = [(label, {'fields': ['address','address_2_html']}),]

this doesn't work. error:

'addressadmin.fieldsets[1][1]['fields']' refers field 'address_2_html' missing form.

another thing tried using 'description' alternative 'fieldsets', however, 'address_2_html' not accessible within scope of addressadmin. did succeed @ embedding static map using 'description' cool not cool enough.

like (from memory):

class addressadmin(admin.modeladmin): fieldsets = [(label, {'fields': ['address','address_2_html']}),] readonly_fields = ['address_2_html'] def address_2_html(self, obj): homecoming obj.address_2_html() address_2_html.allow_tags = true address_2_html.short_description = 'address display'

python django django-models django-admin

python - IO error for saunter.ini while setting up py.Saunter -



python - IO error for saunter.ini while setting up py.Saunter -

while setting py.saunter on system, getting io error saunter.ini file.

directory construction shown in illustration - https://github.com/element-34/py.saunter-examples

below error message -

ioerror: [errno 2] no such file or directory: '/src/conf/saunter.ini' error: module: tests not imported (file:/users/.../pythonworkspace/pysaunter/src/scripts/tests.py)

i know there lot of import related questions. of them suggest add together init.py if not there. have added init.py in every folder.

the code snippet reads saunter.ini below -

def configure(self, config = "saunter.ini"): self.config = configparser.safeconfigparser() self.config.readfp(open(os.path.join("conf", config)))

any help appreciated...

there isn't plenty here diagnose problem. but, in examples directory there 2 different projects (ebay , sauce) -- have in 1 of them, not top.

also, py.saunter won't create saunter.ini you. need create (most renaming saunter.ini.default).

oh, , don't seek , run checkout github -- need egg. if there bits missing http://element34.ca/products/saunter/pysaunter prevent getting started, allow me know , i'll modify page.

(now if remembered credentials...)

python selenium webdriver

subdomain - app.facebook.com/mygame didn't work -



subdomain - app.facebook.com/mygame didn't work -

i have app on facebook, i'm hosting app on subdomain (mygame.mydomain.com). when click game on app center or direct link (www.facebook.com/appcenter/mygame) there no problem, if want redirect on link "app.facebook.com/mygame" didn't work.

i couldn't understand what's problem, please help

isn't "apps.facebook.com"?

and also, think "apps.facebook.com doesn't work anymore. because whenever tried opening app using url, redirected me "facebook.com/appcenter/"

subdomain facebook-apps

xml - How to use or in Xquery -



xml - How to use or in Xquery -

how can utilize use or in query?

i want homecoming if name ="michael" or age =21. have

$d[contains((name,"michael") or (age,"21"))]

if want check if = :

$d[name = "michael" or age = "21"]

or if want utilize contains:

$d[contains(name,"michael") or contains(age,"21")]

when write contains((,) or (,) ) seemingly using or on syntactical level, giving 2 different xquery parser. not possible in xquery, or programming languages, since functions , operands operate on values of expressions, not on syntax. (name,"michael") has no value (well, has value of 2 element sequence, not value interested in), contains(name,"michael") has actual value, of test, if name contains "michael". or has between 2 calls contains.

xml xquery

c# - Serializing and Deserializing with Polymorphism and Protobuf-net -



c# - Serializing and Deserializing with Polymorphism and Protobuf-net -

i'm trying utilize protobuf-net serialize objects. i'm not sure if i'm trying inheritance supported, thought i'd check , see if or if i'm doing wrong.

essentially, i'm trying serialize kid class , deserialize back, doing base of operations class reference. demonstrate:

using unityengine; using system.collections; using protobuf; public class main : monobehaviour { // if don't set "skipconstructor = true" // protoexception: no parameterless constructor found parent // ideally, wouldn't have set "skipconstructor = true" can if necessary [protocontract(skipconstructor = true)] [protoinclude(1, typeof(child))] abstract class parent { [protomember(2)] public float floatvalue { get; set; } public virtual void print() { unityengine.debug.log("parent: " + floatvalue); } } [protocontract] class kid : parent { public child() { floatvalue = 2.5f; intvalue = 13; } [protomember(3)] public int intvalue { get; set; } public override void print() { unityengine.debug.log("child: " + floatvalue + ", " + intvalue); } } void start() { kid child = new child(); child.floatvalue = 3.14f; child.intvalue = 42; system.io.memorystream ms = new system.io.memorystream(); // don't *have* this, can, if needed, utilize kid directly. // cool if abstract reference parent abstractreference = child; protobuf.serializer.serialize(ms, abstractreference); protobuf.serializer.deserialize<parent>(ms).print(); } }

this outputs:

parent: 0

what i'd output is:

child: 3.14 42

is possible? , if so, doing wrong? i've read various questions on inheritance , protobuf-net, , they're bit different illustration (as far i've understood them).

you'll kick yourself. code fine except 1 thing - forgot rewind stream:

protobuf.serializer.serialize(ms, abstractreference); ms.position = 0; // <========= add together protobuf.serializer.deserialize<parent>(ms).print();

as was, deserialize reading 0 bytes (because @ end), trying create parent type. empty stream valid in terms of protobuf specification - means object without interesting values.

c# unity3d protocol-buffers protobuf-net

Decrypt AES - C# .NET from OpenSSL -



Decrypt AES - C# .NET from OpenSSL -

i need know how encrypt message in aes-openssl , decrypt in .net (c# or vb) or know difference between aes-openssl , aes-.net

thank you!

code:

code in vb.net

public function aes_decrypt(byval prm_key string, byval prm_iv string, byval prm_text_to_decrypt string)

dim sencryptedstring string = prm_text_to_decrypt dim myrijndael new rijndaelmanaged myrijndael.padding = paddingmode.zeros myrijndael.mode = ciphermode.cbc myrijndael.keysize = 256 myrijndael.blocksize = 256 dim key() byte dim iv() byte key = system.text.encoding.ascii.getbytes(prm_key) iv = system.text.encoding.ascii.getbytes(prm_iv) dim decryptor icryptotransform = myrijndael.createdecryptor(key, iv) dim sencrypted byte() = convert.frombase64string(sencryptedstring) dim fromencrypt() byte = new byte(sencrypted.length) {} dim msdecrypt new memorystream(sencrypted) dim csdecrypt new cryptostream(msdecrypt, decryptor, cryptostreammode.read) csdecrypt.read(fromencrypt, 0, fromencrypt.length) homecoming (system.text.encoding.ascii.getstring(fromencrypt)) end function

in comment, inquire way encrypt in c# , decrypt in openssl. here's a implementation of evp_bytestokey in c#.

now have generate random byte array in c#, utilize these functions (evp on openssl side , sec 1 in c#) on both sides mutual random byte array.

beware tough, you have utilize same hash algorithm: in given link, md5 used. might have alter sha1 depending on 1 evp_bytestokey using (or other way round). same way, have adapt key , iv size in derive algorithm given in post depending on needs, here 32 , 32.

hope helped.

edit: forgot. owlstead said in comment, rijndael allows utilize block size of 256 bits. however, aes block size fixed 128 bits, block size must 128 bits , iv 16 bytes.

there grab when wish utilize salt. openssl prepends encrypted byte array base64 encryption of "salt__" , actual salt array. can find illustration in this post.

c# openssl aes

validation - Travis-ci: Watch and build a single branch from a Git remote repository -



validation - Travis-ci: Watch and build a single branch from a Git remote repository -

i envountering issues travis-ci. let's have repository on github, multiple branches. need validate , build master branch, , ignore other branches. looking @ travis docs, seems have force single .travis.yml file in every single branch of repository. should these yml files have same contents ? in other words, do have have this @ top of each single travis.yml file in every branches:

in every single yml file branches: only: - master

in yml file, wish run script runs specs tests, in master branch, validates build travis. specification tests written in files exist in master branch, not others, don't need them there. so, guess i'll have skip script part in yml file pushed in every branch different master ? follows:

#yaml file (master branch) branches: only: - master # run script script: "tsc -f specs/*"

in other branch:

#yaml file (any other branch) branches: only: - master

thanks reading.

yes, have specify build-branches in .travis.yml every branch.

no, script line not have included in every branch's file.

edit: might interested in observing this feature request travis-ci.

update: since march 2014, can disable building branches/commits without .travis.yml file in repository settings on travis-ci.org. alternative (currently) called "build commits .travis.yml file", see this blog post

git validation git-branch travis-ci

Disappearing logout button with html, jquery, and php -



Disappearing logout button with html, jquery, and php -

i'm greenish programmer , can't find reply anywhere on web problem. help send way! i'm trying create basic login page users allows upload , allows user logout. during login, start session. works. both upload , logout, i'm using jquery.form.js library take advantage of form functionality. upload portion of code, works fine. user can upload images of type, button deactivated during upload, reactivated after success new uploads. however, logout portion, after clicking logout button , destroying session, logout button disappears. thought may have session destroy, without in php, button gone. copied logout portion of code below, in order, html, js, , php. ideas? thanks!

<html> <head> <title>sample</title> <meta http-equiv= "content-type" content="text/html; charset=utf-8"> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script type = "text/javascript" src = "js/jquery.form.js"></script> <script type = "text/javascript" src = "js/xmlrequest.js"></script> <script>xmlrequest = new xmlrequest();</script> <script type = "text/javascript" src = "js/fileupload.js"></script> <script>fileupload = new fileupload();</script> </head> <body> <div id = 'userlogout'> <form action="php/logout.php" id = "logoutsection" enctype = "multipart/form-data" method = "post" > <button type="submit" id="logoutbutton">close!</button> </form> </div> <div id = 'logoutoutput'> </div> </body> </html> function fileupload() { $(document).ready(function() { $('#logoutsection').on('submit',function(a){ //prevent default action of going new page. a.preventdefault(); $('#logoutbutton').attr('disabled',''); $(this).ajaxsubmit({ target: '#userlogout', success: afterlogout//output give thanks message }); $('#loginform').show(); $('#logoutoutput').append("<br>thanks checking out!<br>"); }); }); function afterlogout() { $('#logoutsection').resetform(); $('#logoutbutton').removeattr('disabled'); } } <?php echo "<br>goner<br>"; session_start();//always required sessions session_destroy();//logs out ?>

i believe although i'm not sure reason why button gone after login out because using ajaxsubmit alternative target set #userlogout points parent div of form.

after ajaxsubmit success replace content of <div id='userlogout'> ... </div> result of of ajax operation.

i way: <div id='output'></div> <div id = 'userlogout'> <form action="php/logout.php" id = "logoutsection" enctype = "multipart/form-data" method = "post" > <button type="submit" id="logoutbutton">close!</button> </form> </div>

and alter ajaxsubmit target target: 'output'

read http://www.justwebdevelopment.com/blog/ajaxform-and-ajaxsubmit-options/ target identifies element(s) in page updated server response. value may specified jquery selection string, jquery object, or dom element. default value: null

php jquery logout

jquery - Redefine border of image no longer selected -



jquery - Redefine border of image no longer selected -

i've dived javascript , jquery please bare me!

i creating form elements images. when hovered over, there css rule creates thick border around selected image. true when image selected; leaves thick border.

the problem faced though when image clicked, whilst leaves thick border around right image, doesn't redefine borders around other previous selected images. (by redefine mean create translucent stop image moving about).

here's jsfiddle: http://jsfiddle.net/bewwf/ or may see code below.

html

<div class="grid_12 alpha" id="selection"> <input type="hidden" id="selsunlight" name="selsunlight" value=""/> <div class="grid_2 omega" style="margin-left: 8px"> <div align="center"><img src="images/details/any.png"/ id="anysun" name="anysun" onclick="selectsunlight('anysun')"/></div> <p id="image-text">any</p> </div> <div class="grid_2 alpha omega"> <div align="center"><img src="images/details/sunlight/full_light.png" id="fullsun" name="fullsun" onclick="selectsunlight('fullsun')"/></div> <p id="image-text">full sun</p> </div> <div class="grid_2 alpha omega"> <div align="center"><img src="images/details/sunlight/part_shade.png" id="partshade" name="partshade" onclick="selectsunlight('partshade')"/></div> <p id="image-text">part shade</p> </div> <div class="grid_2 alpha"> <div align="center"><img src="images/details/sunlight/full_shade.png" id="fullshade" name="fullshade" onclick="selectsunlight('fullshade')"/></div> <p id="image-text">full shade</p> </div> </div>

javascript

function selectsunlight(item) { $.each(['#anysun','#fullsun','#partshade','#fullshade'], function() { $(this).css('border', "3px solid #f5f5f5"); $(this).hover( function() { $(this).addclass('hover'); }, function() { $(this).removeclass('hover'); }); }); $('#'+item).css('border', "3px solid #a6be39"); $('#selsunlight').val(item); }

.hover defined #selection .hover {border: 3px solid #a6be39}

i've resolved problem after problem , after spending lengthy amount of time i've ran out of ideas regards problem. head suggests should work, evidently doesn't!

many thanks!

--

edit - confirm needs done:

1) user selects image 2) 1 time image selected, border image remains thick 3) other images must maintain hover effect, whereby border becomes thick , lean respectively 4) if image selected, border in step 2 reset, , new image takes on thick border

this image may create clearer: http://i48.tinypic.com/ei4f9t.png

i optimized code. since you're using css :hover, don't need utilize jquery hover border. added class="sun" each of images wouldn't need utilize $(".sun") instead of slower .each. utilize jquery's .click replace onclick , .prop name attribute clicked .sun. changed selected img border reddish demo. html:

<div id="selection"> <input type="hidden" id="selsunlight" name="selsunlight" value="" /> <img class="sun" src="http://jonline.me.uk/fbedder/images/details/any.png" id="anysun" name="anysun" /> <p id="image-text">any</p> <img class="sun" src="http://jonline.me.uk/fbedder/images/details/sunlight/full_light.png" id="fullsun" name="fullsun" /> <p id="image-text">full sun</p> <img class="sun" src="http://jonline.me.uk/fbedder/images/details/sunlight/part_shade.png" id="partshade" name="partshade" /> <p id="image-text">part shade</p> <img class="sun" src="http://jonline.me.uk/fbedder/images/details/sunlight/full_shade.png" id="fullshade" name="fullshade" /> <p id="image-text">full shade</p> </div>

css:

.sun {border: 3px solid #f5f5f5} .sun:hover {border: 3px solid #a6be39} .selected {border: 3px solid reddish !important}

jquery:

$(document).ready(function(){ $(".sun").click(function(){ $(".sun").removeclass("selected"); $(this).addclass("selected"); var item = $(this).prop("name"); $('#selsunlight').val(item); }); });

jsfiddle: http://jsfiddle.net/bewwf/2/

jquery html border

assembly - How do i store address in a register on x86 -



assembly - How do i store address in a register on x86 -

i have piece of code below:

.section .data myvar: .long 4,3,2,1 .section .text .globl _start _start: movl $0, %edi movl myvar(,%ed1,4), %eax movl $0, %ebx

i store address of lastly element of array "myvar" in ebx (which 1), how do ?

my mental compiler outputs intel syntax, not at&t's, should idea:

lea eax, myvar + 12

eax has address of '1' value.

assembly x86

android - Send out going call for given number -



android - Send out going call for given number -

please give me illustration or link how send phone call given telephone number using android.

add these line of code u want phone call number, if want dial number can utilize action_dial instead.

intent intent = new intent(intent.action_call); intent.setdata(uri.parse("tel:1231231234")); startactivity(intent);

dont forget add together appropriate permission in manifest file. may below 1

<uses-permission android:name="android.permission.call_phone"></uses-permission>

or

<uses-permission android:name="android.permission.call_privileged"></uses-permission>

android

java - Advantage of >> operator over / operator -



java - Advantage of >> operator over / operator -

what advantage of using >> operator on / operator? extensively used in code maintaining. eg, int width = previouswidth >> 2;

when want shift value number of bits, it's considerably simpler understand. example:

byte[] bits = new byte[4]; bits[0] = (byte) (value >> 24); bits[1] = (byte) (value >> 16); bits[2] = (byte) (value >> 8); bits[3] = (byte) (value >> 0);

that's shifting different numbers of bits. really want express in terms of partition instead?

now of course of study when want division, should utilize partition operator sake of readability. people may utilize bitshifting sake of performance, ever, readability more of import micro-optimization code. in case, if what's actually desired width previouswidth divided 4, code should *absolutely reflect that:

int width = previouswidth / 4;

i'd utilize bitshifting after proving performance difference significant.

java

java - JAXB/MOXy: How to un-/marshall a field containing a scalar or list of scalars -



java - JAXB/MOXy: How to un-/marshall a field containing a scalar or list of scalars -

i have set of properties , each value of single property either scalar (string, integer, ...) or collection of scalars (collection, collection, ...). here xml document serving as example:

<properties xmlns:xs="http://www.w3.org/2001/xmlschema" xmlns:java="http://java.oracle.com" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"> <property name="test#1" xsi:type="xs:int">1</property> <property name="test#2" xsi:type="java:int[]"> <value xsi:type="xs:int">1</value> <value xsi:type="xs:int">2</value> <value xsi:type="xs:int">3</value> <value xsi:type="xs:int">4</value> </property> </properties>

this class use, have no thought how tag value field correctly consume , produce structure. must contain parsed content of property element in form of scalar or list of scalars. datatype nowadays attribute value.

@xmlrootelement(name = "property") public class property { @xmlattribute(name = "name") protected string name; @??? protected object value; }

using 2 fields protected object scalar , protected list<object> list, 1 tagged @xmlvalue, other @xmlelement(name = "value") not working.

has idea?

update 1

i tagged property follows:

@xmlrootelement(name = "property") public class property { @xmlattribute(name = "name") protected string name; @xmljavatypeadapter(test2adapter.class) @xmlpath(".") protected object value; }

i have partly implemented next adapter class

public class test2adapter extends xmladapter<adaptedvalue, object> { @override public object unmarshal(adaptedvalue v) throws exception { if (v instanceof scalar) { homecoming ((scalar) v).value; } if (v instanceof complex) { homecoming ((complex) v).value; } homecoming null; } @override public adaptedvalue marshal(object v) throws exception { if (v instanceof string) { scalar s = new scalar(); s.value = v; homecoming s; } if (v instanceof collection) { complex c = new complex(); c.value = (collection<? extends object>) v; homecoming c; } homecoming null; }

adaptedvalue:

@xmlseealso({ scalar.class, complex.class }) public abstract class adaptedvalue { }

scalar:

public class scalar extends adaptedvalue { @xmlvalue public object value; }

complex :

public class complex extends adaptedvalue { @xmlattribute(name = "xsi:type") public string type; @xmlelement(name = "value") public collection<? extends object> value }

everything marshalled correctly, unmarshalling not work. next exception:

javax.xml.bind.unmarshalexception - linked exception: [exception [eclipselink-43] (eclipse persistence services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.descriptorexception exception description: missing class indicator field value [xs:string] of type[class java.lang.string]. descriptor: xmldescriptor(com.materna.osgi.service.cm.rest.resource.representation.test2adapter$adaptedvalue --> [])] @ org.eclipse.persistence.jaxb.jaxbunmarshaller.unmarshal(jaxbunmarshaller.java:190)

if not wrong, need called xmljavatypeadapter. used long time ago , not have code handy right now, please take @ link , if still stuck give me shout.

http://weblogs.java.net/blog/kohsuke/archive/2005/04/xmladapter_in_j.html

in comments section of above post, "pomcompot" mentions using wrapper list/collection. remember using wrapper class , worked.

http://www.caucho.com/resin-3.1/doc/jaxb-annotations.xtp#xmljavatypeadapter

java jaxb moxy

shell - How to list all files that do not contain two different strings -



shell - How to list all files that do not contain two different strings -

list files not contain 2 different strings

i have dir numerous files named in pattern e.g file1.txt

i can list files not contain 1 string

grep -l "string" file*

how can list files not contain 2 strings tried?

grep -l "string1|string2" file*

you need parameter e grep, or using egrep.

with egrep:

egrep -l "string1|string2" file*

shell scripting grep

xslt - How to use xsl templates and recursion to build a new xml document? -



xslt - How to use xsl templates and recursion to build a new xml document? -

i know how utilize xsl templates transform xml document xml document with original element hierarchy. add together attributes elements in new generated xml.

my original xml file looks this:

<shop> <product> <cookie id="001"> <price>2</price> </cookie> </product> <product> <bread id="002"> <price>5</price> </bread> </product> <product> <milk id="003"> <price>2</price> </milk> </product> </shop>

i transform next xml:

<newxml> <newelement> <newelement id="001"> <newelement price="2"/> </newelement> </newelement> <newelement> <newelement id="002"> <newelement price="5"/> </newelement> </newelement> <newelement> <newelement id="003"> <newelement price="2"/> </newelement> </newelement> </newxml>

what way this? can done using recursion templates or there improve way? i've been trying utilize next logic:

make template creates element read current elements id if exist , set newelement if current element has child, apply template (some kind of recursion)

despite of many attempts haven't been able create work. help appreciated!

to this, build upon xslt identity transform, mutual design pattern in xslt. start have template copies elements , outputs them as-is]

<xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template>

what add together templates match elements, , add together codes rename them, or add together attributes required. example, rename root element add together next template:

you don't have utilize specific element names here either. if wanted rename , element id attribute same name, this

<xsl:template match="product/*[@id]"> <newelement> <xsl:apply-templates select="@*|node()"/> </newelement> </xsl:template>

and in case of price element, if wanted create attribute based on element's text content, add together template so:

<xsl:template match="price"> <newelement price="{.}" /> </xsl:template>

(note, uses attribute value templates create attribute here. preferred using xsl:attribute)

try xml starters:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="shop"> <newxml> <xsl:apply-templates select="@*|node()"/> </newxml> </xsl:template> <xsl:template match="product"> <newelement> <xsl:apply-templates select="@*|node()"/> </newelement> </xsl:template> <xsl:template match="product/*[@id]"> <newelement> <xsl:apply-templates select="@*|node()"/> </newelement> </xsl:template> <xsl:template match="price"> <newelement price="{.}" /> </xsl:template> <xsl:template match="@*|node()"> <xsl:copy> <xsl:apply-templates select="@*|node()"/> </xsl:copy> </xsl:template> </xsl:stylesheet>

this outputs following:

<newxml> <newelement> <newelement id="001"> <newelement price="2"/> </newelement> </newelement> <newelement> <newelement id="002"> <newelement price="5"/> </newelement> </newelement> <newelement> <newelement id="003"> <newelement price="2"/> </newelement> </newelement> </newxml>

xml xslt xpath

regex - Validating and grouping excel formula format -



regex - Validating and grouping excel formula format -

i'm trying validate excel formula style, next regex:

=sum\(((?:\w+\d+)(?::\w+\d+)?)((?:,\w+\d+)(?::\w+\d+)?)*\)

on source:

should pass

=sum(a1,a11:a212,a12:a56,a342:a12,a3) =sum(a11:a12,a12:a12,a34:a3) =sum(a1,a2,a3) =sum(a1)

should fail

=sum(a11:a212:a2,a12:a56,a4,a342:a12)

and have validation part working, can't figure out how grouping each comma sperated values. should be:

how want them grouped:

=sum(a1,a11:a12,a12:a56,a3) // groups: $1 = a1 $2 = a11:a12 $3 = a12:a56 $4 = a3 =sum(a11:a12,a10:a12,a34:a3) // groups: $1 = a11:a12 $2 = a10:a12 $3 = a34:a3 =sum(a1,a2,a3) //groups: $1 = a1 $2 = a2 $3 = a3 =sum(a1) //groups: $1 = a1

how grouped:

=sum(a1,a11:a12,a12:a56,a3) // groups: $1 = a1 $2 = a3 =sum(a11:a12,a10:a12,a34:a3) // groups: $1 = a11:a12 $2 = a34:a3 =sum(a1,a2,a3) //groups: $1 = a1 $2 = a3 =sum(a1) //groups: $1 = a1

notice, grouping first , last. i've pretty new regex if i'm doing awful here, please point me in right direction. give thanks you!

that's not possible: (...)(?:,(...))+ (2 groups) produce 2 matches, no matter how much + matches.

you'll need in (at least) 2 steps:

value := /\w+\d+(?::\w+\d+)?/ value_list := /value(?:,value)*/ look := /=sum\((value_list)\)/

now match grouping 1 expression (the value_list), , find value occurrences in match.

a quick demo in php:

class="lang-php prettyprint-override">$text = 'should pass =sum(a1,a11:a212,a12:a56,a342:a12,a3) =sum(a11:a12,a12:a12,a34:a3) =sum(a1,a2,a3) =sum(a1) should fail =sum(a11:a212:a2,a12:a56,a4,a342:a12)'; $value = "\w+\d+(?::\w+\d+)?"; $value_list = "$value(?:,$value)*"; $expression = "=sum\(($value_list)\)"; preg_match_all("/$expression/", $text, $matches); // iterate on $value_list $expression (group 1) foreach($matches[1] $group1) { preg_match_all("/$value/", $group1, $m); print_r($m); }

prints:

array ( [0] => array ( [0] => a1 [1] => a11:a212 [2] => a12:a56 [3] => a342:a12 [4] => a3 ) ) array ( [0] => array ( [0] => a11:a12 [1] => a12:a12 [2] => a34:a3 ) ) array ( [0] => array ( [0] => a1 [1] => a2 [2] => a3 ) ) array ( [0] => array ( [0] => a1 ) )

regex

image - Need my fully working javascript rewritten in proper javascript -



image - Need my fully working javascript rewritten in proper javascript -

can please help me simplifying - working script @ to the lowest degree wrote swap images?

here it:

<img id="swap_green_img" onmouseover="swapgreen()" onmouseout="swaporiggreen()" onclick="window.open('http://www.stackoverflow.com', '_blank')" style="position:relative; z-index:999; float:left; margin-right:10px; cursor:pointer; height:25px; width:30px" src="facebook_like_icon_orig_50x43.png" width="30" alt="" border="0" /> <img id="swap_red_img" onmouseover="swapred()" onmouseout="swaporigred()" onclick="window.open('http://www.stackoverflow.com', '_blank')" style="position:relative; z-index:999; float:left; margin-right:10px; cursor:pointer; height:25px; width:30px;" src="facebook_like_icon_orig_50x43.png" width="30" alt="" border="0" /> <script type="text/javascript"> function swapgreen() { document.getelementbyid("swap_green_img").src='facebook_like_icon_green_50x43.png'; } function swapred() { document.getelementbyid("swap_red_img").src='facebook_like_icon_red_50x43.png'; } function swaporigred() { document.getelementbyid("swap_red_img").src='facebook_like_icon_orig_50x43.png'; } function swaporiggreen() { document.getelementbyid("swap_green_img").src='facebook_like_icon_orig_50x43.png'; } </script>

thanks much in advance! torsten

function swap(color){ document.getelementbyid("swap_" + color + "_img").src='facebook_like_icon_' + color + '_50x43.png'; }

note: not fits code, should done way

javascript image swap

asp.net - Server Error in '/' Application. The resource cannot be found -



asp.net - Server Error in '/' Application. The resource cannot be found -

i uploaded orchard web-site on hosting. in "wwwroot" created new folder "slider" , uploaded jpg files it. when seek access them url "example.com/slider/1.jpg" maintain getting server error in '/' application. resource cannot found. file there. can see on ftp. tried doing same thing on localhost , gives me same error.

i tried opening image "themes" folder. i've found file "theme.png" , able open in browser. added "1.jpg" same folder i've found theme.png , wasn't able open 1.jpg gave me same error message.

that's web.config file:

<?xml version="1.0"?> <configuration> <configsections> <sectiongroup name="system.web.webpages.razor" type="system.web.webpages.razor.configuration.razorwebsectiongroup, system.web.webpages.razor, version=1.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35"> <remove name="host" /> <remove name="pages" /> <section name="host" type="system.web.webpages.razor.configuration.hostsection, system.web.webpages.razor, version=1.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" requirepermission="false" /> <section name="pages" type="system.web.webpages.razor.configuration.razorpagessection, system.web.webpages.razor, version=1.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" requirepermission="false" /> </sectiongroup> </configsections> <system.web.webpages.razor> <host factorytype="system.web.mvc.mvcwebrazorhostfactory, system.web.mvc, version=3.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" /> <pages pagebasetype="orchard.mvc.viewengines.razor.webviewpage"> <namespaces> <add namespace="system.web.mvc" /> <add namespace="system.web.mvc.ajax" /> <add namespace="system.web.mvc.html" /> <add namespace="system.web.routing" /> <add namespace="system.web.webpages" /> <add namespace="system.linq"/> <add namespace="system.collections.generic"/> <add namespace="orchard.mvc.html"/> </namespaces> </pages> </system.web.webpages.razor> <system.web> <compilation targetframework="4.0"> <assemblies> <add assembly="system.web.abstractions, version=4.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35"/> <add assembly="system.web.routing, version=4.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35"/> <add assembly="system.data.linq, version=4.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089"/> <add assembly="system.web.mvc, version=3.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35" /> <add assembly="system.web.webpages, version=1.0.0.0, culture=neutral, publickeytoken=31bf3856ad364e35"/> </assemblies> </compilation> </system.web> </configuration>

have added web.config file slider folder described in answer 404 javascript file.

asp.net .net http-status-code-404 orchardcms

c# - Custom properties and lambda expressions -



c# - Custom properties and lambda expressions -

i've added custom property linq-to-sql entity:

public partial class user { public bool isactive { { // note startdate , enddate columns of user table homecoming startdate <= datetime.now && enddate >= datetime.now; } } }

and need utilize property lambda expressions:

activeusers = users.where(u => u.isactive);

but when code executed system.notsupportedexception. exception message says "sql conversions fellow member 'user.isactive' not supported".

is there way solve problem?

the isactive show regular c# - compiled il , not available linq-to-sql (etc) inspect , turn tsql execute @ database. 1 alternative here might be:

public static expression<func<user,bool>> getisactivefilter() { homecoming user => user.startdate <= datetime.now && user.enddate >= datetime.now; }

then should able use:

activeusers = users.where(user.getisactivefilter());

or - maybe extension method:

public static iqueryable<user> activeonly(this iqueryable<user> users) { homecoming users.where(user => user.startdate <= datetime.now && user.enddate >= datetime.now); }

then:

activeusers = users.activeonly();

the difference here using iqueryable<t> interface , expression trees throughout, allows linq understand our intent, , create suitable tsql accomplish same.

c# .net linq linq-to-sql lambda

java - HWPFDocument / XWPFDocument New Lines -



java - HWPFDocument / XWPFDocument New Lines -

i trying pull info microsoft-word , translate sql statement , inserting oracle database.

when info in ms-word contains new line created [shift-enter] , not enter,

the text contains icon looks box question mark.

where et standard new line using come in key , st new lines using

shift-enter combination. when generating sql , inserting oracle, oracle counts not text, hex.

my question is, how remove lines created [shift-enter] standard '\n'?

thanks

update how text information

poifsfilesystem fs = new poifsfilesystem(new fileinputstream(file)); hwpfdocument doc = new hwpfdocument(fs); wordextractor = new wordextractor(doc); text = we.gettext();

update answer: bug in poi-3.6. in poi-3.8 shows \r.

what you're seeing "fields" in word document, special blocks of text such links, macros etc

option number 1 go on using wordextractor, phone call stripfields(string) on resulting text before using it. that'll remove of these fields text you.

the other alternative utilize different way of getting text out. wordtotextconverter part of apache poi, , more complex code handles more of format , should skip these (wordextractor pretty simple , low level). other utilize apache tika, provides mutual way of extracting text number of file formats. have proper code deal fields, , added bonus it'll trivial back upwards .docx or .pdf when requirements change!

java apache-poi

ASP.net consuming WCF Soap/Rest Services -



ASP.net consuming WCF Soap/Rest Services -

i have asp.net website consumes wcf service soap protocol hosted azure cloud services.

i have exposed wcf service both rest , soap. (for other clients wanted json)

i have tried configure reference of asp.net site back upwards existing soap endpoint of wcf service maintain getting errors of missing object references, while client calls work fine.

i ve done research still dont have clear view on this.

is possible maintain-stick soap service reference when rest coexists-or improve consume rest endpoint , modify code according rest http requests?

beauty of wcf implement 1 time , deploy (or host) in various protocol (as different endpoint).

in case if have asp.net app consuming wcf service soap, totally possible expose existing wcf service rest service without affecting existing asp.net app.

i have made 1 wcf service consumed 3 app , consumed in different protocol. windowp app consumed in tcp, while asp.net did in rest , php app did in soap. refer post more clarity.

share specific inner exception of issue faced, can help further.

asp.net wcf rest soap

php - loading large images page load time -



php - loading large images page load time -

i've tried couple of ways , have found issues both.

loading image ajax post, , updating img id source it. php function loads images in "li" list class set display:none , jquery hide/show image.

my problem these images 1440px x 960px minimum. if load ajax post takes while show total image, , if load php loop takes veryyyy long time page load.

here illustration of php loop function:

public function loadstreamimages() { $imgs = '<li id="0"><img src="img/om.jpg" class="bgimg" /></li>'; if($db->num_rows($consulta)>0) { while($row = $db->fetch_array($consulta)) { $imgs .= '<li id="' . $row['id'] . '" class="hidden"><img src="img/' . $row['imagefile'] . '" class="bgimg" /></li>'; } } echo $imgs; }

anything can spead up?

i'd guess best solution between methods. send image info thru php load em javascript after page load....

<?php public function loadstreamimages(){ if($db->num_rows($consulta)>0) { $i =0; $imgs = array(); while($row = $db->fetch_array($consulta)) { $imgs[$i]['id'] = $row['id']; $imgs[$i]['imagefile'] = $row['imagefile']; $i++; } } echo "<script>myimages = ".json_encode($imgs).";</script>"; } ?>

and run foreach javascript after page load on myimages inserting <li>s , <img>s tags.

php jquery image loading

types - Switch interface implementation without overhead -



types - Switch interface implementation without overhead -

given interface , 2 (or more) implementations struggle switch implementation when extending functionality.

for illustration assume there interface inumber supports inc , string , 2 implementations numberint32 , numberint64 obvious implementation. assume want implement evencounter on top of inumber. evencounter has inctwice , shall phone call inc twice. struggle types right without using struct surrounding inumber in evencounter.

type inumber interface { inc() string() string } type numberint32 struct { number int32 } func newnumberint32() inumber { ret := new(numberint32) ret.number = 0 homecoming ret } func (this *numberint32) inc() { this.number += 1 } func (this *numberint32) string() string { homecoming fmt.sprintf("%d", this.number) } // type numberint64.... // obvious

here struggle

type evencounter1 inumber // nope, additional methods not possible type evencounter2 numberint32 // nope func (this *evencounter2) inctwice() { i:=0; < 2; i+=1 { // this.inc() // inc not found // inumber(*this).inc() // cannot convert // in, ok := *this.(inumber) // cannot convert // v, ok := this.(inumber) // cannot convert // concrete conversion a) not work , b) won't help // here should generic // v, ok := this.(numberint32) // how phone call inc here on this? } }

just embedding in struct works...

type evencounter3 struct { n inumber } func (this *evencounter3) inctwice() { n := this.n // step want avoid n.inc() // using this.n.inc() twice makes slower n.inc() } func (this *evencounter3) string() string { homecoming this.n.string() }

i live need implement delegation manually each method, want rely on inumber , not specific implementation (that mean changing lots of places seek implementation, however, want avoid indirection , (most likely?) space. there way avoid struct , straight evencounter (specific) inumber additional methods?

btw real illustration set of integers , map of integers integers millions of instances intertwined (and no, map[int]bool won't suffice - slow, bitset interesting depening on utilize case, etc.) , testing different implementations of set , map changing 2-3 lines in code (ideally type , maybe generic creation of instances resp. making copies)

any help appreciated , hope hasn't been asked yet...

your variant using embedding not embed. embedded fields anonymous , go delegates automatically.

this simplifies illustration to:

type evencounter3 struct { inumber } func (this *evencounter3) inctwice() { this.inc() // using this.n.inc() twice makes slower this.inc() }

note string() automatically delegated ("promoted" in go speak).

as calling inc() twice making slower, well, that's limitation of using interfaces. point of interface not expose implementation, cannot access internal number variable.

types interface go implementation

java - eclipse create new .properties file -



java - eclipse create new .properties file -

i need create new .properties file, when create new file alter name have .properties @ end shows question mark next file. advice?

since project controlled svn, question mark appears because it's new file , needs commited, it's alert user hey, don't forget commit new file.

don't worry mark, can edit file long want.

when commit file repository, mark dissappear. then, if modify file, asterisk (*) mark appear in file saying hey, don't forget i've been modified , should commit me.

java eclipse svn

garbage collection - Java Process did not die after OutOfMemoryException -



garbage collection - Java Process did not die after OutOfMemoryException -

i testing application, application threw outofmemory exception, process still alive, can see processexplorer. thought live , not doing after oom, after time still see aplication activity. bit surprised. reason why can happen?

java.lang.outofmemoryerror: java heap space dumping heap java_pid8920.hprof ... heap dump file created [2826469039 bytes in 59.888 secs] exception in thread "activemq transport: tcp://localhost/127.0.0.1:61000@53335" java.lang.outofmemoryerror: java heap space

jvm options used are:

-xx:+useconcmarksweepgc -xx:+useparnewgc -xx:+printgcdetails -verbose:gc -xloggc:c:/temp/gcverbose.log

it 64-bit java 1.7.

edit:::

i thought application still doing saw few more application related log messages after oom exception. after few minutes, see final exception stack below , application activity stopped. process still alive!

exception in thread "pool-3-thread-1" java.lang.outofmemoryerror: java heap space exception in thread "activemq session task-13" java.lang.outofmemoryerror: java heap space feb 17, 2013 4:54:44 pm sun.rmi.transport.tcp.tcptransport$acceptloop executeacceptloop warning: rmi tcp accept-0: take loop serversocket[addr=0.0.0.0/0.0.0.0,port=0,localport=53490] throws java.lang.outofmemoryerror: java heap space @ java.net.networkinterface.getall(native method) @ java.net.networkinterface.getnetworkinterfaces(networkinterface.java:326) @ sun.management.jmxremote.localrmiserversocketfactory$1.accept(localrmiserversocketfactory.java:86) @ sun.rmi.transport.tcp.tcptransport$acceptloop.executeacceptloop(tcptransport.java:387) @ sun.rmi.transport.tcp.tcptransport$acceptloop.run(tcptransport.java:359) @ java.lang.thread.run(thread.java:722) feb 17, 2013 4:57:34 pm servercommunicatoradmin reqincoming warning: server has decided close client connection. exception in thread "activemq inactivitymonitor worker" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.outofmemoryerror: java heap space

try kill -3 <process-pid> print java thread dumps , see app hanging.

java garbage-collection jvm out-of-memory

entity framework - Use EF Code First to work against a schema and not a database -



entity framework - Use EF Code First to work against a schema and not a database -

by default have used working separate database ef creates code first entities , datacontext. @ 1 of projects not allowed allocate separate database app's sole purpose. can create separate schema in existing database. possible, , if so, how configure ef work against separate schema in existent db?

the modelbuilder supports that

modelbuilder.entity<yourentity>.totable("nameoftable",schematouse);

entity-framework

plsql - Problems passing parameters in PL/SQL from php -



plsql - Problems passing parameters in PL/SQL from php -

it's first time i'm developing application pl / sql , have difficulties pass parameters php pl / sql. functions pl / sql created in database , when run next query, returns due parameters:

begin pin_username := 'admin'; pin_passwd := '1'; pout_message := null; retval := pkg_login.login_portal ( pin_username, pin_passwd, pout_message ); dbms_output.put_line('pin_username='||pin_username); dbms_output.put_line('pin_passwd='||pin_passwd); dbms_output.put_line('pout_message='||pout_message); commit; end;

now problem can not same in php. here code in php developed help of google:

include 'define.php'; require_once '../config/connectdb.php'; if(isset($_post['user']) && isset($_post['senha'])) { $utilizador = $_post['user']; $senha = $_post['senha']; $msg; //connection database if(!ligacaodb()) { echo "dont connect"; } $query = "begin :r := pkg_login.login_portal (:1, :2, :3); commit; end;"; $result = oci_parse(ligacaodb(), $query); oci_bind_by_name($result, ":1", $utilizador); oci_bind_by_name($result, ':2', $senha); oci_bind_by_name($result, ':3', $msg); oci_bind_by_name($result, ':r', $r); $xpto = oci_execute($result); if($xpto == false) { $e = oci_error($result); print htmlentities($e['message']); } else { echo $msg . " | " . $r; } oci_free_statement($result); oci_close(ligacaodb()); }

from understand plsql function, parameter receives user , password checks whether database , returns message , boolean represented msg , r.

does can help me , explain me might doing wrong?

have discovered reason. have same problem here answer:

http://docs.oracle.com/cd/e11882_01/appdev.112/e10646/oci03typ.htm#cegieeji

the next 2 types internal pl/sql , cannot returned values oci:

boolean, sqlt_bol

record, sqlt_rec

php plsql

java - How does unmarshalling work in JAXB? -



java - How does unmarshalling work in JAXB? -

i have getter/setter pair element in jaxb:

@xmlelementwrapper(name="requires", required=true) @xmlelement(name="equals", required=true) list<myobject> getmyobjects() { homecoming this.myobject; } void setmyobjects(final myobject... myobjects) { //call regular method setting objects //that not have required signature type }

the thing setter method never getting called. set breakpoint on both getter , setter, , 1 getter hit, not setter's.

i found this question, don't understand answer. myobjects initialized @ construction time, looks fits scenario 2. happens in unmarshalling process after getter called?

your setter doesn't match signature of getter. instead of:

void setmyobjects(final myobject... myobjects)

you need

void setmyobjects(list <myobject> myobjects)

java jaxb

arrays - Google Maps MVCArray With Fusion Tables -



arrays - Google Maps MVCArray With Fusion Tables -

probably rookie question, i've created heatmap-layer html file using hard coded locations within html file. below sample of code. i'm trying replace "heatmapdata" info fusion table. goal map update whenever fusion table updated. help appreciated.

var heatmapdata = [{location: new google.maps.latlng(42.071523,-72.624257), weight:4.2}, {location: new google.maps.latlng(42.37686,-72.46914), weight:1.6} ]; function initialize() { var mapoptions = { zoom: 4, center: new google.maps.latlng(38.82, -99.408660), maptypeid: google.maps.maptypeid.roadmap }; map = new google.maps.map(document.getelementbyid('map_canvas'), mapoptions); pointarray = new google.maps.mvcarray(heatmapdata); heatmap = new google.maps.visualization.heatmaplayer({ data: pointarray }); heatmap.setmap(map); }

using illustration site dr molle posted can't seem render heat map when alter fusion table id reference (it has same column names: lat, long, hits). ideas?

<!doctype html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>test map</title> <script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script> <link rel="stylesheet" type="text/css" href="/css/normalize.css"> <link rel="stylesheet" type="text/css" href="/css/result-light.css"> <script type='text/javascript' src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=visualization&.js"></script> <style type='text/css'> </style> <script type='text/javascript'>//<![cdata[ function initialize() { var mapoptions = { zoom: 4, center: new google.maps.latlng(38.82, -99.408660), maptypeid: google.maps.maptypeid.roadmap }; map = new google.maps.map(document.getelementbyid('map_canvas'), mapoptions); //query fusiontable via ajax $.ajax( { datatype: 'jsonp', url : 'https://www.googleapis.com/fusiontables/v1/query', info : { sql:'select lat,long,hits \ 1jsyexl-bz0dse02llf9cuquxku0mqh6jluynhle', key:'aizasycoif1slcuqpqordbp58zci3yrpx4wvmfg' }, success: function(data){ var heatmapdata=[]; //prepare info $.each(data.rows,function(i,r){ heatmapdata.push({ location:new google.maps.latlng(r[0],r[1]), weight:number(r[2]) }); }); //create weighted heatmap new google.maps.visualization.heatmaplayer({ data: heatmapdata,map:map }); } }); } google.maps.event.adddomlistener(window, 'load', initialize); //]]> </script> </head> <body> <div id="map_canvas" style="height: 800px; width: 1000px;"></div> </body> </html>

you may query fusiontable , create info layer response.

example(using jquery , ajax):

$.ajax( { datatype: 'jsonp', url : 'https://www.googleapis.com/fusiontables/v1/query', info : { sql:'select lat,long,hits \ 1ll0ewi89ngxj17xzdbwkswahpyzqcah8mhoapsk', key:'yourkey' }, success: function(data){ var heatmapdata=[]; //prepare info $.each(data.rows,function(i,r){ heatmapdata.push({ location:new google.maps.latlng(r[0],r[1]), weight:number(r[2]) }); }); //create weighted heatmap new google.maps.visualization.heatmaplayer({ data: heatmapdata,map:map }); } });

demo: http://jsfiddle.net/doktormolle/rxmdf/

note: when utilize ajax must utilize jsonp bypass browsers same-origin-restrictions. of course of study may request info on serverside.

however, if it's usable in application depends on amount of data, because finish data(location , weight) must downloaded client.

arrays google-maps-api-3 google-fusion-tables heatmap

Node.js Jsdom returning [Error: socket hang up] code: 'ECONNRESET' } -



Node.js Jsdom returning [Error: socket hang up] code: 'ECONNRESET' } -

trying utilize jsdom under nodejs , receiving error:

[error: socket hang up] code: 'econnreset' }

using nodejs v0.8.20, ubuntu 12.04

var jsdom = require("jsdom"); jsdom.env({ html: 'http://www.google.com', scripts: ['http://code.jquery.com/jquery.js'], done: function (errors, window) { console.log(errors); } });

http://clock.co.uk/tech-blogs/preventing-http-raise-hangup-error-on-destroyed-socket-write-from-crashing-your-nodejs-server

basically there bug socket hang errors suppressed, in node 0.8.20 no longer suppressed. however, modules don't hear error event yet.

so... downgrade node.js version , wait until jsdom fixes it, or utilize domains. pretty sure issue jsdom using older version of request. or can not utilize http parts of jsdom.

node.js jsdom

(Highcharts) Circle/wedge areas in polar chart -



(Highcharts) Circle/wedge areas in polar chart -

i need draw charts describe area-effect patterns (gaming related stuff) come in 2 varieties:

(1) circular "splash" 3-4 intensity radius values separated color (say 1, 2, 3 in red, orange , yellow).

(2) wedge starting angle, ending angle , radius (say -30, +30 , 5).

i pull info bunch of existing data, examples below. can highcharts polar chart? there way define areas that? can create range series go around polar axis example? , how create proper wedge?

area_effect: { | distance: { | | short: 0f; | | medium: 0.5f; | | long: 1.2f; | | distant: 1.2f; | }; | area_info: { | | angle_left: 0f; | | angle_right: 0f; | | radius: 1.2f; | | area_type: "circle"; | }; | hp_damage: { | | short: 1f; | | medium: 0.4f; | | long: 0.2f; | | distant: 0.2f; | }; }; area_info: { | angle_left: -70f; | angle_right: 70f; | radius: 5f; | area_type: "pie"; | line_length: 0f; | radius_inner: 0f; };

charts highcharts diagram

c# - Must declare the scalar variable "@userid" -



c# - Must declare the scalar variable "@userid" -

i getting:

must declare scalar variable "@userid".

on

if (httpcontext.current.items["albumid"] != null) { page.databind(); ddlalbum.items.findbyvalue(httpcontext.current.items["albumid"].tostring()).selected = true; }

i believe has with:

<asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:sliitcomdbconnectionstring %>" selectcommand="select [albumid], [albumname] [album] (userid=@userid) "> <selectparameters> <asp:querystringparameter defaultvalue="1" name="albumid" querystringfield="albumid" type="int32" /> </selectparameters> </asp:sqldatasource>

in sql query utilize @userid var, not declared!

select [albumid], [albumname] [album] (userid=@userid)

there great info problem http://msdn.microsoft.com/en-us/library/z72eefad%28v=vs.100%29.aspx

c# asp.net sql-server-2008

python - Update list of dictionaries based on another list of dictionaries -



python - Update list of dictionaries based on another list of dictionaries -

i have 2 lists of dictionaries, 1 list of project identifiers , other list of completed project identifiers. i'm looking add together key project identifier list, based on existence in completed list.

current code

>>> projects = [{'id': 1}, {'id': 2}, {'id': 3}] >>> completes = [{'id': 1}, {'id': 2}] >>> finish in completes: ... project in projects: ... if project["id"] == complete["id"]: ... project["complete"] = 1 ... else: ... project["complete"] = 0 ... >>> print projects [{'id': 1, 'complete': 0}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]

expected output

[{'id': 1, 'complete': 1}, {'id': 2, 'complete': 1}, {'id': 3, 'complete': 0}]

how can break out of nested loop 1 time project has been flagged complete? there approach should consider instead of working nested loop?

edit - fixed (thanks @sotapme)

why not like:

cids = [c['id'] c in completes] project in projects: project["complete"] = project["id"] in cids

this set project["complete"] true or false, suggest better. if need 1 , 0, then:

project["complete"] = int(project["id"] in cids)

python python-2.7

iphone - Searching a UITableview -



iphone - Searching a UITableview -

i trying search in uitableview. have implemented uisearchdisplaydelegate, uisearchbardelegate method @ right way. how cellforrowatindexpath looks like.

- (uitableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { static nsstring *cellidentifier = @"cell"; uitableviewcell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier]; if ( cell == nil ) { cell = [[uitableviewcell alloc] initwithstyle:uitableviewcellstyledefault reuseidentifier:cellidentifier]; } if (tableview == self.searchdisplaycontroller.searchresultstableview){ contact *contact = [self.filteredlistcontent objectatindex:indexpath.row]; nsstring *text = [nsstring stringwithformat:@"%@ %@",contact.name,contact.firstname]; nslog(@"cellforrowatindexpath contact text %@",text); cell.textlabel.text = text; [cell setaccessorytype:uitableviewcellaccessorydisclosureindicator]; }else{ nsstring *alphabet = [firstindex objectatindex:[indexpath section]]; //---get states origin letter--- nspredicate *predicate = [nspredicate predicatewithformat:@"self.name beginswith[c] %@",alphabet]; nsarray *contacts = [listcontent filteredarrayusingpredicate:predicate]; contact *contact = [contacts objectatindex:indexpath.row]; nsstring *text = [nsstring stringwithformat:@"%@ %@",contact.name,contact.firstname]; cell.textlabel.text = text; [cell setaccessorytype:uitableviewcellaccessorydisclosureindicator]; } homecoming cell; }

and filtercontentforsearchtext method

- (void)filtercontentforsearchtext:(nsstring*)searchtext scope:(nsstring*)scope { [self.filteredlistcontent removeallobjects]; // first clear filtered array. (contact *contact in listcontent) { nsstring *searchstring = [nsstring stringwithformat:@"%@ %@",contact.name,contact.firstname]; nsrange range = [searchstring rangeofstring:searchtext options:nscaseinsensitivesearch]; if (range.location != nsnotfound) { [self.filteredlistcontent addobject:contact]; [self.searchdisplaycontroller.searchresultstableview reloaddata]; } } }

the unusual thing is. in cellforrowatindexpath returns me right data. tableview itselfs keeps given me no results label.

any help this?

use array show info in table(showdataarray) use array store input values(dataarray) use showdataarray populate table always in searchfield when charecter range changes phone call method filter info using predicate dataarray save value showdataarray call table reloaddata

happy coding :)

iphone ios objective-c uitableview uisearchbar

sql - Select only changes to a value from an audit log table -



sql - Select only changes to a value from an audit log table -

in ms sql server 2008 r2, have table foo, , every insert , update on foo, insert fooauditlog date, user, pk fooid , few of other columns of foo, including 1 numeric value, phone call cxp.

i need retrieve history of changes cxp on time given fooid. possible save foo without changing cxp, , need ignore values.

for example, if audit log entries specific foo (ie select date, user, cxp fooauditlog fooid=17) this:

date user cxp ------------------------- 10/26 fred 42 10/28 george 38 11/7 tom 38 11/9 fred 38 11/12 joe 33 11/14 tom 33 11/18 george 38

then need modify query homecoming only:

date user cxp ----------------------------- 10/26 fred 42 10/28 george 38 11/12 joe 33 11/18 george 38

and ignore entries on 11/7, 11/9, , 11/14. had considered select distinct (cpx) ... grouping date need capture entry value changes previous value.

you need previous value. version uses mysql syntax correlated subquery result:

select t.* (select t.*, (select cxp t t2 t2.date < t.date order date desc limit1 ) prevcxp t ) t prevcxp null or prevcxp <> cxp

in other databases, might utilize lag() instead of subquery, limit might replaced top or fetch first 1 row.

sql sql-server-2008 audit-tables

sql - conditional select using multiple if conditions -



sql - conditional select using multiple if conditions -

i have rows in table players this.

+-----------+----+----+----+----+----+----+----+----+ | username | | b | c | d | e | f | g | h | +-----------+----+----+----+----+----+----+----+----+ | mike | 45 | 34 | 56 | 58 | 29 | 74 | 39 | 48 | +-----------+----+----+----+----+----+----+----+----+

now query should like..

select username players if (difference between & b <20) if (difference between c & d <20) if (difference between e & f <20) if (difference between g & h <20)

now .. have select username if 2 out of 4 conditions true.. please help

assumed sql server

select username from( select username, case when abs(a-b)<20 1 else 0 end case when abs(c-d)<20 1 else 0 end b case when abs(e-f)<20 1 else 0 end c case when abs(g-h)<20 1 else 0 end d players )tmp tmp.a+tmp.b+tmp.c+tmp.d>=2

sql

Trigger email if cell changed in Google Sheet -



Trigger email if cell changed in Google Sheet -

i have sheet track section metrics in google sheets. trying email when metric changes. using counta (in range p2) monitor if new metric came in , want trigger email if value in range changes.

function onedit() { var ss = spreadsheetapp.getactivespreadsheet(); var value = ss.getsheetbyname("emailservices").getrange("p2").getvalue().tostring(); var lastly = scriptproperties.getproperty("last"); if(value != last) { scriptproperties.setproperty("last",value); mailapp.sendemail("dave@mydomain.com", "cell p2 changed", "new value: " + value + "\n\n" + ss.geturl()) } }

i have trending charts , i'd email actual trending chart changed (a new monthly value entered) thought i'd walk before ran. :)

cells alter because of formula not qualify 'edit' trigger onedit function. should either monitor source cell(s) (if edited manually) or sec alternative have function running under trigger runs every min (or whatever frequency like) , send out email. function you've written looks run under trigger.

google-apps-script

linux - Where is TIOCMGET supposed to be implemented? -



linux - Where is TIOCMGET supposed to be implemented? -

this satisfy curiosity after this question. although i'm using alternative solution, original problem appears come downwards fact tiocmget not implemented, , i'd know bit why is.

sadly, haven't found much useful info googling, , i'm finding tty_ioctl man page (the first result) pretty impenetrable.

so, tocmget, implemented, , might mono looking , failing find it?

it's implemented in drivers/tty/tty_io.c has next implementation:

/** * tty_tiocmget - modem status * @tty: tty device * @file: user file pointer * @p: pointer result * * obtain modem status bits tty driver if feature * supported. homecoming -einval if not available. * * locking: none (up driver) */ static int tty_tiocmget(struct tty_struct *tty, int __user *p) { int retval = -einval; if (tty->ops->tiocmget) { retval = tty->ops->tiocmget(tty); if (retval >= 0) retval = put_user(retval, p); } homecoming retval; }

as note comment, , code, works if underlying terminal driver supports , otherwise homecoming einval.

there number of drivers back upwards it, such isdn4linux , various gsm modem drivers, ordinary terminals won't not modems.

linux mono ioctl

entity framework 5 - EF Code First, Unique Contraints, and Testing -



entity framework 5 - EF Code First, Unique Contraints, and Testing -

we implementing our unique constraint executing sql straight in seed method

context.database.executesqlcommand( "begin seek alter table mytable add together constraint uc_code unique (col1, col2, col3) end seek begin grab end catch");

however, can't write tests this.

i mock repository, , insert same record twice, but...of course, no error thrown, because database isn't called (and shouldn't be), how write test ensures error thrown when duplicate record inserted?

unit test needs tun code want test. want test ef+db reaction constraint violations. so, need run tests on real (test) database, can create in origin of test.

unit-testing entity-framework-5 code-first unique-constraint

java - Spring MVC RequestMapping is being forwarded -



java - Spring MVC RequestMapping is being forwarded -

i have rest service based on spring mvc.

this code:

public class sitescontroller { @requestmapping(value="/rest/sites/{id}", method=requestmethod.get) @responsebody public sitedto getsite(@pathvariable string id) { integer siteid = integer.parseint(id); site site = cms.getsite(siteid); sitedto siteresult = new sitedto(site); homecoming siteresult; } @requestmapping(value="/rest/sites", method=requestmethod.get) public sitesresult getsites(@requestparam integer companyid) { collection<site> sites = cms.getsites(cms.getcompany(companyid)); sitesresult sitesresult = new sitesresult(sites); homecoming sitesresult; } }

(i skipped code doesn't apply problem)

when go url /rest/sites/1 returning info expect, when go /rest/sites?companyid=1 404 page: http status 404 - /rest/rest/sites.

the log showing code in getsitesfunction run, after log showing following: org.springframework.web.servlet.view.jstlview forwarding resource [rest/sites] in internalresourceview 'rest/sites'

why redirected instead of executed?

update

found problem. because didn't have @responsebody above method, dispatcher forwarded request. more info here, key thing if method annotated @responsebody, homecoming type written response http body. homecoming value converted declared method argument type using httpmessageconverters.

because method homecoming type sitesresult not 1 of supported homecoming types, spring add together returned object model using class name , seek render view named value of request mapping, why trying render /rest/sites. it's not doing http forward, dispatcher forwards servlets render view (eg. jsp).

if want homecoming specific view, homecoming string containing name.

instead

@requestmapping(value="/rest/sites", method=requestmethod.get) public sitesresult getsites(@requestparam integer companyid) { collection<site> sites = cms.getsites(cms.getcompany(companyid)); sitesresult sitesresult = new sitesresult(sites); homecoming sitesresult; }

do this

@requestmapping(value="/rest/sites", method=requestmethod.get) public string getsites(@requestparam integer companyid, model model) { collection<site> sites = cms.getsites(cms.getcompany(companyid)); sitesresult sitesresult = new sitesresult(sites); model.addattribute("sitesresult", sitesresult); string myview = "myview"; homecoming myview; }

java spring rest spring-mvc

php - Problems accessing two different types of array -



php - Problems accessing two different types of array -

as relative newbie php i'm having problem accessing various elements in array. have access 2 different types of array. first illustration works fine although sec throws error.

any pointers appreciated.

ps. come javascript, vbscript background understand concept of array. cheers!

the next code sample works

// below dump of $dataarray array (size=4) 0 => object(simplexmlelement)[13] public '@attributes' => array (size=15) 'campaignid' => string '215999956' (length=9) // below writes out $dataarray foreach($dataarray $val) { print $val['campaignid']; }

the next code sample doesn't work

// below dump of $dataarray array (size=4) 0 => object(adgroup)[73] public 'campaignid' => string '112520126' (length=9) // below writes out $dataarray foreach($dataarray $val) { print $val['campaignid']; }

the first array , sec object. access campaignid in sec version want to

print $val->campaignid

php arrays

sql server - How to Acess Remote Computer Folders in PS SQLSERVER:\> -



sql server - How to Acess Remote Computer Folders in PS SQLSERVER:\> -

recently came know how utilize powersehll commands executing sql queries mentioned below:

import-module “sqlps” -disablenamechecking $ds=invoke-sqlcmd -query $query -database $database -serverinstance $server -connectiontimeout $connectiontimeout -querytimeout $querytimeout

at time powershell ise output console in

ps sqlserver:\>

i able perform select , update queries without error. problem faced when wanted access 1 of file in remote computer. tried access file below:

ps sqlserver:\> get-content -path \\server\d$\log\app.log

even tried, list files/folders as

ps sqlserver:\> ls \\server\d$\log\

iam getting below errors:

get-content : cannot find path '\server\d$\log\app.log' because not exist. ls : cannot find path '\server\d$\log\' because not exist.

need not say- folder , file exists on server able access same when powershell running without sql module. mean console showing ps c:\user\abc\

sorry long story-- now, simple question! how access remote files/folders when shell in sqlserver console?

thanks in advance!

-raj

you should able utilize filesystem provider explicitly this:

ls filesystem::\\server\d$\log

sql-server powershell remote-access

url - Nginx rewrite but Facebook doesn't like it -



url - Nginx rewrite but Facebook doesn't like it -

before using nginx, apache when rewriting url, share page on facebook , puts right url in sharer.

now, nginx, when share https://www.facebook.com/sharer/sharer.php?u=http://beautifulurl.com/page25 facebook catchs http://beautifulurl.com lose total page url.

also adsense i've problems(in pages doesn't show ads) , google+ sharer.

how prepare it?

the display link of share show top level domain, when click shared link follow uri you've given sharer.php

facebook url nginx rewrite adsense

passwords - How does brute-forcing cryptography work? -



passwords - How does brute-forcing cryptography work? -

i have question regarding info decryption using brute force.

let's alice sending message encrypted message bob. chuck wants know content starts brute forcefulness password cracker it. how chuck's cracker know has right password (except looking whether content "makes sense")?

this educational question. no concrete algorithms etc. or other utils crack passwords. can't find useful on google (a lot of cracking software less on general functionality).

thats essentially. if think it, have know info supposed or functionality supposed provide. take logging os, if password incorrect, wont log in. in message case, lets english language language beingness sent encrypted, 1 have know english language before password cracker effective.

passwords cryptography cracking

maven - Compiling Apache Hadoop Source in Eclipse -



maven - Compiling Apache Hadoop Source in Eclipse -

after 4 tries i've managed utilize git checkout apache's hadoop source code, issue

mvn eclipse:eclipse

command , import of projects eclipse. far has been successful have been. there. attempted build , clean projects , going well. have 3 errors rid of. extremely appreciate if help me this. have been trying work 2 days or so. anyway, in eclipse have 20 hadoop projects. there 2 have errors. 1 called "hadoop-streaming" , other "hadoop-tools-dist."

the error says following:

project 'hadoop-streaming' missing required source folder: 'c:/users/user/hadoop/hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/conf'

the other errors related one. that's eclipse says anyway. tried re-create folder needed didn't clear error. know how prepare this? if need me ask.

i don't know how hadoop project looks like, suppose using maven. instead of using

mvn eclipse:eclipse

i suggest using import functionality of eclipse -> import maven projects (even though works harder 1 might expect). related issue, kind of error occurred me whenever there kind of folder not added source folder in eclipse (generated folders source etc.). so, advise checking folder mentioned there , if added source folder. if not, mark accordingly (source folder). clean project (project > clean...) , if need update maven project(right click on parent project > maven > update project ...)

good luck!

maven hadoop hadoop-streaming

Rails: admin routes to manage non-admin models -



Rails: admin routes to manage non-admin models -

i having problem trying configure rails managing non-admin models using 'admin' namespaced routes. example, widget model have restful route @ /widgets controller called widgetscontroller, have routes file namespaces routes , controller:

namespace :admin resources :widgets end class admin::widgetscontroller < applicationcontroller def index @widgets = ::widget.all respond_to |format| format.html end end ...etc... end

in views getting error when seek utilize route method create:

<% @widgets.each |widget| %> <%= link_to 'show', admin_widget(widget) %> <% end %>

error:

undefined method `admin_widget'

what doing wrong?

i missing path @ end of method name. should have been:

admin_widget_path(widget)

instead of admin_widget

ruby-on-rails

.net - What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean? -



.net - What does "A severe error occurred on the current command. The results, if any, should be discarded." SQL Azure error mean? -

once in while code encounters

system.data.sqlclient.sqlexception service has encountered error processing request. please seek again. error code 40540. severe error occurred on current command. results, if any, should discarded. class 20 number 40197

that happens rarely, goes away in min or 2 , can't reliably reproduce it. error code can number other 40540.

i've googled bit , looks it's triggered bugs in sql server , reproducible.

i have 2 options - retry query or treat fatal , break hard. i'd prefer have improve understanding problem , whether i'm safe retrying query.

do retry query when error occurs?

a quick google search gave me this.

the service has encountered error processing request. please seek again. error code %d. receive error, when service downwards due software or hardware upgrades, hardware failures, or other failover problems. reconnecting sql database server automatically connect healthy re-create of database. may see error codes 40143 , 40166 embedded within message of error 40540. error codes 40143 , 40166 provide additional info kind of failover occurred. not modify application grab error codes 40143 , 40166. application should grab 40540 , seek reconnecting sql database until resources available , connection established again.

you can visit here more information. says your application should grab 40540 , seek reconnecting sql database until resources available , connection established again.

though on personal note suggest not utilize sql azure throttles , can't command resources allocated you. did install sql server on azure vm , utilize in application.

hope helps you.

.net sql-server-2008 azure sql-azure

element present but hidden selenium check -



element present but hidden selenium check -

how can check if html element hidden (display:none:) selenium ide?

in case html button , want selenium announce me if element hidden.

if utilize verifyelementpresent, selenium find element although hidden.

thanks!

you can utilize derivation of storevisible command.

most notably, assertvisible , waitforvisible have been useful me in past.

selenium selenium-ide

c# - Remove Box collider of object in unity 3d -



c# - Remove Box collider of object in unity 3d -

here code in update function. object has box collider.

if (input.getmousebuttondown(0)) { ray ray = camera.screenpointtoray(input.mouseposition); if (physics.raycast (ray, out hit3, 400.0f)) { wname = hit3.collider.gameobject.name; destroy(hit3.collider.gameobject); } }

but box collider not getting destroyed.

how can destroy it?

its working code

destroy(hit3.collider);

c# object scripting unity3d raycasting

What's wrong with this Java Applet code? -



What's wrong with this Java Applet code? -

i'm trying run code in java applet via appletviewer in fedora 18. error

java.lang.nullpointerexception @ main.init(main.java:42) @ sun.applet.appletpanel.run(appletpanel.java:436) @ java.lang.thread.run(thread.java:722)

as per code 42nd line in code bmul.setbounds(100, 280, 50, 50); isn't wrong as-far-as know. after searching on google, found

nullpointerexception runtime exception thrown jvm when application code, other referenced api(s) or middleware (weblogic, was, jboss...) encounters next conditions:

attempting invoke instance method of null object attempting access or modify particular field of null object attempting obtain length of such null object array

i've tried hard failed in making work. please help me. here provide main.java file's code.

import java.awt.*; import java.applet.*; import java.awt.event.*; public class main extends applet implements actionlistener { button b0, b1, b2, b3, b4, b5, b6, b7, b8, b9; button badd, bsub, bmul, bdiv, bequ, bcls, bdec, bsqrt, bsin, bcos, btan; textfield tf1; int add, sub, mul, div, temp = 0; double sqr, s, c, ta; string t = ""; public void init() { setlayout(null); setfont(new font("cantarell", font.bold, 12)); b0 = new button("0"); b1 = new button("1"); b2 = new button("2"); b3 = new button("3"); b4 = new button("4"); b5 = new button("5"); b6 = new button("6"); b7 = new button("7"); b8 = new button("8"); b9 = new button("9"); badd = new button("+"); bsub = new button("-"); bsub = new button("*"); bdiv = new button("/"); bequ = new button("="); bsqrt = new button("sqrt"); bsin = new button("sin"); bcos = new button("cos"); btan = new button("tan"); bcls = new button("cls"); tf1 = new textfield("0"); tf1.seteditable(false); tf1.setcolumns(8); tf1.setbounds(100, 100, 250, 50); b0.setbounds(100, 130, 50, 50); b1.setbounds(150, 130, 50, 50); b2.setbounds(200, 130, 50, 50); b3.setbounds(250, 130, 50, 50); b4.setbounds(100, 180, 50, 50); b5.setbounds(150, 180, 50, 50); b6.setbounds(200, 180, 50, 50); b7.setbounds(250, 180, 50, 50); b8.setbounds(100, 230, 50, 50); b3.setbounds(150, 230, 50, 50); badd.setbounds(200, 230, 50, 50); bsub.setbounds(250, 230, 50, 50); bmul.setbounds(100, 280, 50, 50); bdiv.setbounds(150, 280, 50, 50); bequ.setbounds(200, 280, 50, 50); bsin.setbounds(300, 130, 50, 50); bcos.setbounds(300, 180, 50, 50); btan.setbounds(300, 230, 50, 50); bsqrt.setbounds(250, 280, 50, 50); bcls.setbounds(300, 280, 50, 50); add(b0); add(b1); add(b2); add(b3); add(b4); add(b5); add(b6); add(b7); add(b8); add(b9); add(badd); add(bsub); add(bmul); add(bdiv); add(bequ); add(bsin); add(bcos); add(btan); add(bsqrt); add(bcls); add(tf1); b0.addactionlistener(this); b1.addactionlistener(this); b2.addactionlistener(this); b3.addactionlistener(this); b4.addactionlistener(this); b5.addactionlistener(this); b6.addactionlistener(this); b7.addactionlistener(this); b8.addactionlistener(this); b9.addactionlistener(this); badd.addactionlistener(this); bsub.addactionlistener(this); bmul.addactionlistener(this); bdiv.addactionlistener(this); bequ.addactionlistener(this); bsqrt.addactionlistener(this); bsin.addactionlistener(this); bcos.addactionlistener(this); btan.addactionlistener(this); bcls.addactionlistener(this); } public void actionperformed(actionevent ae) { if(ae.getsource() == b0) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b0.getlabel()); else tf1.settext(tf1.gettext()+b0.getlabel()); temp = 0; } if(ae.getsource() == b1) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b1.getlabel()); else tf1.settext(tf1.gettext()+b1.getlabel()); temp = 0; } if(ae.getsource() == b2) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b2.getlabel()); else tf1.settext(tf1.gettext()+b2.getlabel()); temp = 0; } if(ae.getsource() == b3) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b3.getlabel()); else tf1.settext(tf1.gettext()+b3.getlabel()); temp = 0; } if(ae.getsource() == b4) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b4.getlabel()); else tf1.settext(tf1.gettext()+b4.getlabel()); temp = 0; } if(ae.getsource() == b5) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b5.getlabel()); else tf1.settext(tf1.gettext()+b5.getlabel()); temp = 0; } if(ae.getsource() == b6) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b6.getlabel()); else tf1.settext(tf1.gettext()+b6.getlabel()); temp = 0; } if(ae.getsource() == b7) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b7.getlabel()); else tf1.settext(tf1.gettext()+b7.getlabel()); temp = 0; } if(ae.getsource() == b8) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b8.getlabel()); else tf1.settext(tf1.gettext()+b8.getlabel()); temp = 0; } if(ae.getsource() == b9) { zero(); if(tf1.gettext().equals("0")) tf1.settext(b9.getlabel()); else tf1.settext(tf1.gettext()+b9.getlabel()); temp = 0; } if(ae.getsource() == bsqrt) { sqr = double.parsedouble(tf1.gettext()); tf1.settext(double.tostring(math.sqrt(sqr))); } if(ae.getsource() == bsin) { s = double.parsedouble(tf1.gettext()); tf1.settext(double.tostring(math.sin(s))); } if(ae.getsource() == bcos) { c = double.parsedouble(tf1.gettext()); tf1.settext(double.tostring(math.cos(c))); } if(ae.getsource() == btan) { ta = double.parsedouble(tf1.gettext()); tf1.settext(double.tostring(math.tan(ta))); } if(ae.getsource() == badd) { add together = integer.parseint(tf1.gettext()); tf1.settext(""); t = "+"; } if(ae.getsource() == bsub) { sub = integer.parseint(tf1.gettext()); tf1.settext(""); t = "-"; } if(ae.getsource() == bmul) { mul = integer.parseint(tf1.gettext()); tf1.settext(""); t = "*"; } if(ae.getsource() == bdiv) { div = integer.parseint(tf1.gettext()); tf1.settext(""); t = "/"; } if(ae.getsource() == bequ) { if(t == "+") { int add1 = integer.parseint(tf1.gettext()); int add2 = add together + add1; tf1.settext(string.valueof(add2)); } else if(t == "-") { int sub1 = integer.parseint(tf1.gettext()); int sub2 = sub - sub1; tf1.settext(string.valueof(sub2)); } else if(t == "*") { int mul1 = integer.parseint(tf1.gettext()); int mul2 = mul * mul1; tf1.settext(string.valueof(mul2)); } else if(t == "/") { int div1 = integer.parseint(tf1.gettext()); int div2 = div / div1; tf1.settext(string.valueof(div2)); } if(temp == 0) temp = 1; } if(ae.getsource() == bcls) tf1.settext("0"); if(ae.getsource() == bdec) { string s = tf1.gettext(); for(int = 0; < s.length(); i++) { if((s.charat(i)) == '.') break; else tf1.settext(tf1.gettext()+bdec.getlabel()); } } } void zero() { if(temp == 1) tf1.settext("0"); } }

look @ these lines:

badd = new button("+"); bsub = new button("-"); bsub = new button("*"); bdiv = new button("/");

you're assigning value bsub twice, not assigning value bmul, it's still null.

when dereference bmul @ line 42:

bmul.setbounds(100, 280, 50, 50);

... that's throwing nullpointerexception. suspect start of sec line above should be:

bmul = new button("*");

i strongly advise stick 1 statement per line. i'd advise break code smaller chunks - example, 1 method initialize digits, operators etc.

java applet

ajax - Does php's include option do a partial page refresh? -



ajax - Does php's include option do a partial page refresh? -

i've started using php locally , notice if utilize include files within main index.php file, whole page not refresh when click button/link include new/updated include file. question is, php's include alternative ajax , partial page refresh? if so, improve off using plain php or should stick ajax?

php code interpreted server-side doesn't utilize ajax client-side javascript. clicking link request new page, , php interpret requested files , homecoming output. you're not experiencing refresh times because you're working locally. if take @ network tab of chrome developer tools you'll see refresh take place.

php ajax include

java - ObjectInputStream.read() returning -1, but readObject returns the object -



java - ObjectInputStream.read() returning -1, but readObject returns the object -

am serialize object , deserialize object get:

0 available() -1 read()

eofexception readbyte()

public static element getcacheobject(string key, string cachename, string server) throws ioexception, classnotfoundexception, connectexception { string url = stringutils.join(new string[] { server, cachename, key}, "/"); getmethod getmethod = new getmethod(url); objectinputstream oin = null; inputstream in = null; int status = -1; element element = null; seek { status = httpclient.executemethod(getmethod); if (status == httpstatus.sc_not_found) { // if content deleted homecoming null; } in = getmethod.getresponsebodyasstream(); oin = new objectinputstream(in); system.out.println("oin.available():" + oin.available()); // returns 0 system.out.println("oin.read():" + oin.read()); // returns -1 element = (element) oin.readobject(); // returns object } grab (exception except) { except.printstacktrace(); throw except; } { seek { oin.close(); in.close(); } grab (exception except) { except.printstacktrace(); } } homecoming element; }

what missing here?

i think see behaviour because first create objectinputstream inputstream , check available on inputstream. if check constructor of objectinputstream can see following:

public objectinputstream(inputstream in) throws ioexception { verifysubclass(); bin = new blockdatainputstream(in); handles = new handletable(10); vlist = new validationlist(); enableoverride = false; readstreamheader(); bin.setblockdatamode(true); }

there method readstreamheader reads header input stream. possible info read inputstream during construction of objectinputstream.

java serialization deserialization ehcache objectinputstream