Thursday, 15 August 2013

wordpress - header that becomes fixed on scroll -



wordpress - header that becomes fixed on scroll -

im looking ideas on how accomplish delayed fixed header? similar on site itsnicethat.com header on becomes fixed after scroll farther downwards on page. i’m looking implement client using wordpress?

any pointers appreciated,

thanks

i think straightforward way monitor scrolltop , alter style or toggle class header sets fixed/normal

wordpress header

user defined functions - storing a file in an already occupied location in Pig -



user defined functions - storing a file in an already occupied location in Pig -

it seems pig prevents reusing output directory. in case, want write pig udf take filename parameter, open file within udf , append contents existing file @ location. possible?

thanks in advance

it may possible, don't know it's advisable. why not have new output directory? example, if want results in /path/to/results, store output of first run /path/to/results/001, next run /path/to/results/002, , on. way can identify bad info failed jobs, , if want of together, can hdfs -cat /path/to/results/*/*.

if don't want append instead want replace existing contents, can utilize pig's rmf shell command:

%define output /path/to/results rmf $output store results '$output';

user-defined-functions apache-pig

emacs - why the change is in place for the list with elisp? -



emacs - why the change is in place for the list with elisp? -

i have question elisp. example:

(setq trees '(maple oak pine birch)) -> (maple oak pine birch) (setcdr (nthcdr 2 trees) nil) -> nil trees -> (maple oak pine)

i thought (nthcdr 2 trees) returns new list - (pine birch) , set list setcdr expression, should not alter value of trees. explain me?

if read documentation string nthcdr, you'll see returns pointer "nth" "cdr" - pointer original list. you're modifying original list.

doc string:

take cdr n times on list, homecoming result.

edit wow, "pointer" seems stir confusion. yes, lisp has pointers.

just @ box diagrams used explain list construction in lisp (here's emacs's documentation on thing):

--- --- --- --- --- --- | | |--> | | |--> | | |--> nil --- --- --- --- --- --- | | | | | | --> rose --> violet --> buttercup

look @ arrows, they're .... pointing things. when take cdr of list, 2nd box refers (aka "points" to), atom, string, or cons cell. heck, check out on wikipedia's entry car , cdr.

if feels improve phone call reference, utilize terminology.

cdr not homecoming copy of refers to, confusing rnaer.

list emacs elisp cdr

java - BufferedReader.readLine is not working -



java - BufferedReader.readLine is not working -

this question has reply here:

how compare strings in java? 23 answers

my programme kind of gets stuck after readline call, if statements don't work. doing wrong? #java-first-timer

import java.io.inputstreamreader; import java.io.bufferedreader; import java.io.ioexception; public class nums { public static void main(string[] args) throws ioexception { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println("number mania!!!"); system.out.println("pick favourite number 1 5"); string favnum = br.readline(); if (favnum=="3"){ system.out.println("your favourite number three!"); } else{ system.out.println("hi!"); } } }

use favnum.equals("3") instead of favnum == "3". should never utilize == compare objects; utilize .equals instead. (there few rare exceptions, won't need worry them until larn fair bit more java.)

java

x86 - Interconnect between per-core L2 and L3 in Core i7 -



x86 - Interconnect between per-core L2 and L3 in Core i7 -

the intel core i7 has per-core l1 , l2 caches, , big shared l3 cache. need know kind of interconnect connects multiple l2s single l3. student, , need write rough behavioral model of cache subsystem. crossbar? single bus? ring? references came across mention structural details of caches, none of them mention kind of on-chip interconnect exists.

thanks,

-neha

modern i7's utilize ring. tom's hardware:

earlier year, had chance talk sailesh kottapalli, senior principle engineer @ intel, explained he’d seen sustained bandwidth close 300 gb/s xeon 7500-series’ llc, enabled ring bus. additionally, intel confirmed @ idf every 1 of products in development employs ring bus.

your model rough, may able glean more info public info on i7 performance counters pertaining l3.

x86 computer-architecture cpu-cache

PHP adding to array in while loop -



PHP adding to array in while loop -

i'm having problem adding array during while loop , wondering if of help me. firstly, background. looping through sql results , trying gather results while grouping various ids create easier deal later. seems 1 line of code isn't working. there code below

while($row=mysql_fetch_assoc($res)){ if(!array_key_exists($row['foreign_key_value'],$contacts)){ $contacts[$row['foreign_key_value']]=array(); } if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){ $contacts[$row['foreign_key_value']][$row['uid']]=array(); } $contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value']; }

it lastly line having problem with, adding rating_id , rating_value. info looping through 4 fields - foreign_key_value, uid, rating_id , rating_value. construction want end looks like

array(1) { [73]=> array(2) { [9]=> array(1) { [4]=> string(1) "3" } [1762]=> array(1) { [1]=> string(1) "5" } }

i cannot rating_id , rating_value create more 1 key value pair in lastly array, expecting 5 pairs. thing getting lastly pair selected. have no thought why i'm not getting info need, can help?

abc667 - you're spot on. give thanks much. i've been staring @ long missed , i'm starting sense idiot now

you need declare $contacts array before while() loop - can utilize afterwards

$contacts = array(); while($row=mysql_fetch_assoc($res)){ if(!array_key_exists($row['foreign_key_value'],$contacts)){ $contacts[$row['foreign_key_value']]=array(); } if(!array_key_exists($row['uid'],$contacts['foreign_key_value'])){ $contacts[$row['foreign_key_value']][$row['uid']]=array(); } $contacts[$row['foreign_key_value']][$row['uid']][$row['rating_id']]=$row['rating_value']; }

php arrays

Django ORM version of SQL COUNT(DISTINCT ) -



Django ORM version of SQL COUNT(DISTINCT <column>) -

i need fill in template summary of user activity in simple messaging system. each message sender, want number of messages sent , number of distinct recipients.

here's simplified version of model:

class message(models.model): sender = models.foreignkey(user, related_name='messages_from') recipient = models.foreignkey(user, related_name='messages_to') timestamp = models.datetimefield(auto_now_add=true)

here's how i'd in sql:

select sender_id, count(id), count(distinct recipient_id) myapp_messages grouping sender_id;

i've been reading through documentation on aggregation in orm queries, , although annotate() can handle first count column, don't see way count(distinct) result (even extra(select={}) hasn't been working, although seems should). can translated django orm query or should stick raw sql?

from django.db.models import count messages = message.objects.values('sender').annotate(message_count=count('sender')) m in messages: m['recipient_count'] = len(message.objects.filter(sender=m['sender']).\ values_list('recipient', flat=true).distinct())

sql django orm

jackson deserialization json to java-objects -



jackson deserialization json to java-objects -

here java code used fro de de-serialization, trying convert json string java object. in doing have used next code.

package ex1jackson; import com.fasterxml.jackson.core.jsongenerationexception; import com.fasterxml.jackson.databind.jsonmappingexception; import com.fasterxml.jackson.databind.objectmapper; import java.io.ioexception; public class ex1jackson { public static void main(string[] args) { objectmapper mapper = new objectmapper(); seek { string userdatajson = "[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"}," + "{\"id\": \"value21\",\"name\":\"value22\",\"qty\": \"value23\"}]"; product userfromjson = mapper.readvalue(userdatajson, product.class); system.out.println(userfromjson); } grab (jsongenerationexception e) { system.out.println(e); } grab (jsonmappingexception e) { system.out.println(e); } grab (ioexception e) { system.out.println(e); } } }

and product.java class

package ex1jackson; public class product { private string id; private string name; private string qty; @override public string tostring() { homecoming "product [id=" + id+ ", name= " + name+",qty="+qty+"]"; } }

i getting next error.

com.fasterxml.jackson.databind.exc.unrecognizedpropertyexception: unrecognized field "id" (class ex1jackson.product), not marked ignorable (0 known properties: ]) @ [source: java.io.stringreader@16f76a8; line: 1, column: 8] (through reference chain: ex1jackson.product["id"]) build successful (total time: 0 seconds)

help me slove this,

it looks trying read object json describes array. java objects mapped json objects curly braces {} json starts square brackets [] designating array.

what have list<product> describe generic types, due java's type erasure, must utilize typereference. deserialization read: myproduct = objectmapper.readvalue(productjson, new typereference<list<product>>() {});

a couple of other notes: classes should camelcased. main method can public static void main(string[] args) throws exception saves useless catch blocks.

java json object jackson deserialization

mysql - Yii CDbCriteria -



mysql - Yii CDbCriteria -

hollow have kind of query table select m.voterid, sum(jm.mark) marks m left bring together marks jm on jm.id = m.id jm.voterid in (1,2) grouping m.voterid

and don't understand how wright using cdbcriteria. table structute

`id` int(11) not null auto_increment, `voterid` int(11) not null, `votedid` int(11) not null, `mark` int(11) not null, `creation_date` timestamp not null default current_timestamp on update current_timestamp, primary key (`id`)

$criteria = new cdbcriteria(); $criteria->select = 'm.voterid, sum(jm.mark)'; $criteria->from = 'marks m'; $criteria->join = 'left bring together marks jm on jm.id = m.id'; $criteria->condition = 'jm.voterid in (1,2)'; $criteria->group = 'm.voterid';

mysql activerecord yii

opengl - Pass stream hint to existing texture? -



opengl - Pass stream hint to existing texture? -

i have texture created part of code (with qt5's bindtexture, isn't relevant).

how can set opengl hint texture updated?

glbindtexture(gl_texture_2d, textures[0]); //tell opengl plan on streaming texture glbindtexture(gl_texture_2d, 0);

there no mechanism indicating texture updated repeatedly; related buffers (e.g., vbos, etc.) through usage parameter. however, there 2 possibilities:

attache texture framebuffer object , update way. that's efficient method you're asking. memory associated texture remains resident on gpu, , can update @ rendering speeds. try using pixel buffer object (commonly called pbo, , has opengl buffer type of gl_pixel_unpack_buffer) buffer qt writes generated texture into, , mark buffer gl_dynamic_draw. you'll still need phone call glteximage*d() buffer offset of pbo (i.e., zero) each update, approach may afford efficiency on blasting texels pipe straight through glteximage*d().

opengl textures

ember.js - How can I get My previous route? -



ember.js - How can I get My previous route? -

how can previous router in current controller.

app.mycontroller = em.objectcontroller.extend({ next:function() { // action helper in hbs this.transitionto('nextpage'); }, back:function() { // action helper in hbs // here need dynamically identify previous route. // how can previous route. } });

after having inspected router object again, don't see property in there allow grab lastly route. in pre 4 there property lastly route, hard property work with.

my solution hence same in pre 4: i'd create own mixin handle routes navigate into, , list of routes, can whatever route you're after: current one, lastly one, et cetera...

jsfiddle here: http://jsfiddle.net/smtng/

mixin

the first thing create mixin allow force routes historycontroller. can creating setupcontroller method of course of study gets invoked every time move route.

app.historymixin = ember.mixin.create({ setupcontroller: function() { this.controllerfor('history').pushobject(this.get('routename')); } });

we pushing route historycontroller.

history controller

since we're pushing routename non-existent historycontroller, we'll need go ahead , create that, absolutely nil special.

app.historycontroller = ember.arraycontroller.extend();

index controller

since historycontroller stores list of routes we've navigated into, we'll need accessible on other controllers, such indexcontroller, we'll hence utilize needs specify in controller should accessible.

app.applicationcontroller = ember.controller.extend({ needs: ['history'] });

implement mixin

we have need maintain track of routes, , we'll specify our routes need implement mixin.

app.catroute = ember.route.extend(app.historymixin);

template

last not least, have historycontroller our indexcontroller can access, , mixin pushes each accessed route historycontroller, can utilize our application view output list of routes, , specify lastly route. of course of study in case you'll need lastly route minus one, there's no sense in me doing everything!

<h1>routes history ({{controllers.history.length}})</h1> <ul> <li>last route: {{controllers.history.lastobject}}</li> {{#each controllers.history}} <li>{{this}}</li> {{/each}} </ul>

i hope gets onto straight , narrow.

ember.js ember-router

html - Javascript not working on specific versions of IE -



html - Javascript not working on specific versions of IE -

i've rare issue ie. i'm trying create page launches script when ie version lower or equal ie 8 (just simple alert , location). when seek debug html on ietester alert shows on ie 5.5 , ie 6 neither in 7 nor 8. doing wrong?

<!doctype html> <html> <head> <meta content="text/html; charset=utf-8" http-equiv="content-type"> <!--[if lte ie 8]> <script type="text/javascript"> alert('para poder usar consumedia necesita tener instalada una version de net explorer 9 o superior'); window.location = "http://www.google.com"; </script> <![endif]--> </head> <body> </body> </html>

this showing me alert native ie7.

it seems ietester might have bug regarding conditional comments. see how create ie9 emulate ie7? alternative ietester.

@pekka has commented on matter couple of times:

when multiple instances of net explorer installed (or active) on same system, conditional comments resolved against highest ie version available on system

edit: doesn't add together much, i've got ie7 installed, , shows alert ietester ie <= 7.

javascript html internet-explorer alert ietester

3d - Algorithm for partially filling a polygonal mesh -



3d - Algorithm for partially filling a polygonal mesh -

overview: have simple plastic sandbox represented 3d polygonal mesh. need able determine water level after pouring specific amount of water sandbox.

the water distributed evenly above when poured no fluid simulation, water poured slowly it needs fast

question: kind of techniques/algorithms utilize problem?

i'm not looking programme or similar can this, algorithms - i'll implementation.

just idea:

first compute saddle points. tools discrete morse theory or topological persistence might useful here, know little them sure. next iterate on saddle points, starting @ lowest, , compute point in time after water starts cross point. time @ shallower (in terms of volume versus surface area) of 2 adjacent basins has reached level matches height of saddle point. point onward, water pouring onto surface flow on other basin , contribute water level instead, until 2 basins have reached equal level. after that, treated 1 single basin. along way might have right times when other saddle points reached, area associated basins changes. iterate in order of increasing time, not increasing height (e.g. using heap decrease-key operation). 1 time final pair of basins have equal height, done; afterwards there single basin left.

on whole, gives sequence of “interesting” times, things alter fundamentally. in between these, problem much more local, have consider shape of single basin compute water level. in local problem, know volume of water contained in basin, can e.g. utilize bisection find suitable level that. adjacent “interesting” times might provide useful end points bisection.

to compute volume of triangulated polytope, can utilize 3d version of shoelace formula: every triangle, take 3 vertices , compute determinant. sum them , split 6, , have volume of enclosed space. create sure orientate triangles consistently, i.e. either seen within or seen outside. selection decides overall sign, seek out see 1 which.

note question might need refinement: when level in basin reaches 2 saddle points @ exactly same height, water flow? without fluid simulation not defined, guess. argue should distributed as among adjacent basins. argue such situations unlikely occur in real data, , hence take 1 neighbour arbitrarily, implying saddle point has infinitesimally less height other ones. or come number of other solutions. if case of involvement you, might need clarify expect there.

algorithm 3d geometry simulation theory

javascript - Box2D b2.ContactListener strangeness -



javascript - Box2D b2.ContactListener strangeness -

i've been using jonas wagner's js box2d port , running unusual problem shape userdata. i've setup entity have collision shape secondary 'foot' sensor shape determine when object on solid ground. definition looks little this:

var bodydef = new b2.bodydef(); bodydef.position.set( (this.pos.x + this.size.x / 2) * b2.scale, (this.pos.y + this.size.y / 2) * b2.scale ); this.body = ig.world.createbody(bodydef); var shapedef = new b2.polygondef(); shapedef.setasbox( this.size.x / 2 * b2.scale, this.size.y / 2 * b2.scale ); shapedef.density = 0.85; shapedef.filter.groupindex = -1; this.body.createshape(shapedef); var footshapedef = new b2.polygondef(); footshapedef.setasorientedbox( 3 * b2.scale, 3 * b2.scale, new b2.vec2(0,7*b2.scale), 0 ); footshapedef.issensor = true; footshapedef.density = 0.85; footshapedef.filter.groupindex = -1; var footshape = this.body.createshape(footshapedef); footshape.setuserdata("feet"); this.body.setmassfromshapes();

the thought here beingness can observe when foot sensor stops colliding entities. working expected , b2.contactlistener correctly reporting when objects stop colliding foot sensor. problem userdata i'm assigning foot shape isn't beingness correctly reported.

as can see below, point object returned in b2.contactlistener's remove callback contains shape (shape2) it's m_userdata attribute set 'feet'. however, querying shape2 object straight reports it's m_userdata null.

i've included screenshot of safari's debug console performing console.log shown below. what's going on here?!

var listener = new b2.contactlistener(); listener.remove = function(point) { var p = point; var s1 = p.shape1; var s2 = p.shape2; console.log(p, s1, s2); }

javascript box2d box2dweb

mysql - Why is percona xtrabackup so slow and big -



mysql - Why is percona xtrabackup so slow and big -

when phone call innobackupex no arguments, produces backup of databases. takes 3 minutes, , produces 8gb output. when run mysqldump --all-databases, takes 1 minutes, , produces 1.5gb output. since both of these outputs can used recreate same database, why xtrabackup much slower , larger?

is ibdata1 file 8gb? xtrabackup hot re-create of entire file. hot re-create process doesn't need lock tables (which allows database available during backup process). disadvantage unused space in file backed up.

mysql percona mysql-backup

Unsafe region of code in TypeScript -



Unsafe region of code in TypeScript -

sometimes hard come valid typescript, illustration when reference library has tons of entities each of needs declaration. in situations nice tell typescript skip part of code deals library considering valid. there way in typescript?

there isn't way turn off type checking entire block of code, if access off look of type any, result any, if can access library through any reference of sort, you'll working without type checking.

typescript

javascript - requirejs setup work -



javascript - requirejs setup work -

i'm finding hard utilize info on require.js site in own projects.

one question have based on sample code on require.js site:

define(function () {

//do setup work here homecoming { color: "black", size: "unisize" }

});

can please give me illustration goes in do setup work here section?

your own code. if want homecoming plain object, there's nil else add.

javascript jquery requirejs

Asynchronous call with a static method in C# .NET 2.0 -



Asynchronous call with a static method in C# .NET 2.0 -

i have .net 2.0 application. in application, need pass info server. server exposes rest-based url can post info to. when pass info server, need asynchronously, , other times need blocking call. in scenario of asynchronous call, need know when phone call completed. point understand how do.

where problem is, method working on must static. it's code i've inherited, , i'd rather not have redo of code. currently, have 2 static methods:

public static string senddata (...) { } public static string senddataasync(...) { }

the string returned response code server. static part giving me fits. doesn't cause problem in blocking version. however, in competition of asynchronous call, i'm not sure do.

does have insights can provide?

this general async pattern before c# 5 (iirc).

public static string senddata (...) { } public static iasyncresult beginsenddata(..., asynccallback cb) { var f = new func<..., string>(senddata); homecoming f.begininvoke(..., cb, f); } public static string endsenddata(iasyncresult ar) { homecoming ((func<..., string>) ar.asyncstate).endinvoke(ar); }

usage:

beginsenddata(..., ar => { var result = endsenddata(ar); // result });

full console example:

public static string senddata(int i) { // sample payload thread.sleep(i); homecoming i.tostring(); } public static iasyncresult beginsenddata(int i, asynccallback cb) { var f = new func<int, string>(senddata); homecoming f.begininvoke(i, cb, f); } public static string endsenddata(iasyncresult ar) { homecoming ((func<int, string>)ar.asyncstate).endinvoke(ar); } static void main(string[] args) { beginsenddata(2000, ar => { var result = endsenddata(ar); console.writeline("done: {0}", result); }); console.writeline("waiting"); console.readline(); }

the above print:

waiting done: 2000

c# asynchronous .net-2.0

web services - Can an Android device be a server to response SMS by Http post? -



web services - Can an Android device be a server to response SMS by Http post? -

i going develop android app on mobile phone or tablet gsm, be: step 1: when device receiving gsm sms trigger event of server. step 2: server gets content of sms , sender's phone number. carried out computing decryption. step 3: server post http request web service.

it used sms register server.

is possible? problem meet?

yes, can capture incoming sms in android application. need write broadcastreceiver that.

for more info on how write 1 , around incoming sms - check thread out: android – hear incoming sms messages

android web-services sms

javascript - js conditional: if not false, null or undefined then -



javascript - js conditional: if not false, null or undefined then -

i have !! markup anther object , works, here doesn't (in 1 case, works in other cases).

if (!!slides) { console.log("close view clear slides") clearinterval(slides); }

in firebug error:

referenceerror: slides not defined

what should conditional be?

you can't utilize variable if it's not defined.

typeof(asdf) "undefined" !asdf referenceerror: asdf not defined if (typeof(asdf) != "undefined") { // execute if asfd defined. }

javascript if-statement

python - Multiple django apps using same url pattern -



python - Multiple django apps using same url pattern -

i'd run 2 apps same url patterns. avoid having app-specific slug domain.com/pages/something-here or domain.com/blog/something-there.

i tried this:

# urls.py urlpatterns = patterns('', url(r'^$', 'my.homepage.view'), url(r'^admin/', include(admin.site.urls)), url(r'^', include('pages.urls')), url(r'^', include('blog.urls')), ) # pages/urls.py urlpatterns = patterns('', url(r'^(.+)/$', views.page), ) # blog/urls.py urlpatterns = patterns('', url(r'^(.+)/$', views.post), )

my code doesn't work, whichever include comes first (here, pages.urls) works ok, other urls (for blog) throw 404.

thanks in advance

edit: did this: created glue.py in same directory settings.py. handle homepage , dispatcher view:

def dispatcher(request, slug): try: page = get_object_or_404(page, slug=slug) homecoming render(request, 'pages/page.html', {'page': page}) except: post = get_object_or_404(post, slug=slug) homecoming render(request, 'blog/post.html', {'post': post})

i don't know if it's ok. hope there improve way.

thanks comments.

this doesn't work because django urls sesolved in order, meaning first url matches regexp resolved one. in case, the urls included blogs application never searched, django resolved url on pages includes line.

also, django url module not supposed know if page or blog post exists, believe in application determined database lookup.

the urls module executes view connected first regexp matches.

you should alter logic, e.g. prepending "blog/" blog urls (what's wrong that?)

url(r'^blog/', include('blog.urls')), url(r'^', include('pages.urls')),

notice moved blog url up, generic regxexp should lastly tried django url resolver.

alternatively, code proxy view tries both blog posts , pages. doesn't seem best way me.

python django django-urls

php - Failed inserting more items in database using IPN, Paypal, add to cart -



php - Failed inserting more items in database using IPN, Paypal, add to cart -

i adapted ipn script purchase button , after include add together cart button.

this purchase button: <form action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="return" value="http://www.company.develway.com/company_user?id= <?php echo $id; ?>"> <input type="hidden" name="cmd" value="_s-xclick"> <input type="hidden" name="custom" value="<?php echo $id; ?>"/> <input type="hidden" name="quantity" value="1"> <input type="hidden" name="item_name" value="<?php echo 'premium content ' . $name; ?>"> <input type="hidden" name="hosted_button_id" value="tv4swl86ehyyq"> <input type="image" src="https://www.paypalobjects.com/en_us/i/btn/btn_buynowcc_lg.gif" border="0" name="submit" alt="paypal - safer, easier way pay online!"> <img alt="" border="0" src="https://www.paypalobjects.com/en_us/i/scr/pixel.gif" width="1" height="1"> </form> add together cart button: <form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post"> <input type="image" src="https://www.paypal.com/en_us/i/btn/x-click-but22.gif" border="0" name="submit" alt="make payments paypal - it'sfast, free , secure!"> <input type="hidden" name="add" value="1"> <input type="hidden" name="cmd" value="_cart"> <input type="hidden" name="business" value="finciucsergiu@gmail.com"> <input type="hidden" name="custom" value="<?php echo $id; ?>"/> <input type="hidden" name="item_name" value="<?php echo 'premium content ' . $name; ?>"> <input name="notify_url" value="http://www.company.develway.com/ipn.php" type="hidden"> <input type="hidden" name="item_number" value="wid-001"> <input type="hidden" name="amount" value="0.01"> <input type="hidden" name="no_note" value="1"> <input type="hidden" name="currency_code" value="usd"> <input name="notify_url" value="http://www.company.develway.com/ipn.php" type="hidden"> </form>

and main part of ipn file:

if (strcmp ($res, "verified") == 0) { $item_name = $_post['item_name']; $item_number = $_post['item_number']; $payment_status = $_post['payment_status']; $payment_amount = $_post['mc_gross']; $payment_currency = $_post['mc_currency']; $txn_id = $_post['txn_id']; $receiver_email = $_post['receiver_email']; $payer_email = $_post['payer_email']; $custom = $_post['custom']; $txn_type = $_post['txn_type']; $number_of_items = $_post['num_cart_items']; $connection = mysql_connect("hhh", "fff", "lll"); $db_select = mysql_select_db("company", $connection); mysql_query("insert paid_companies(users_email, companies_id) values('$payer_email', '$custom') ") or die(mysql_error());

}

al works first-class purchase , add together cart if 1 item, if insert more 1 in database included lastly item. doing wrong?

when have more 1 item in cart have loop through items included in ipn of items in database.

check out...

// cart items $num_cart_items = isset($_post['num_cart_items']) ? $_post['num_cart_items'] : ''; $i = 1; $cart_items = array(); while(isset($_post['item_number' . $i])) { $item_number = isset($_post['item_number' . $i]) ? $_post['item_number' . $i] : ''; $item_name = isset($_post['item_name' . $i]) ? $_post['item_name' . $i] : ''; $quantity = isset($_post['quantity' . $i]) ? $_post['quantity' . $i] : ''; $mc_gross = isset($_post['mc_gross_' . $i]) ? $_post['mc_gross_' . $i] : 0; $mc_handling = isset($_post['mc_handling' . $i]) ? $_post['mc_handling' . $i] : 0; $mc_shipping = isset($_post['mc_shipping' . $i]) ? $_post['mc_shipping' . $i] : 0; $custom = isset($_post['custom' . $i]) ? $_post['custom' . $i] : ''; $option_name1 = isset($_post['option_name1_' . $i]) ? $_post['option_name1_' . $i] : ''; $option_selection1 = isset($_post['option_selection1_' . $i]) ? $_post['option_selection1_' . $i] : ''; $option_name2 = isset($_post['option_name2_' . $i]) ? $_post['option_name2_' . $i] : ''; $option_selection2 = isset($_post['option_selection2_' . $i]) ? $_post['option_selection2_' . $i] : ''; $option_name3 = isset($_post['option_name3_' . $i]) ? $_post['option_name3_' . $i] : ''; $option_selection3 = isset($_post['option_selection3_' . $i]) ? $_post['option_selection3_' . $i] : ''; $option_name4 = isset($_post['option_name4_' . $i]) ? $_post['option_name4_' . $i] : ''; $option_selection4 = isset($_post['option_selection4_' . $i]) ? $_post['option_selection4_' . $i] : ''; $option_name5 = isset($_post['option_name5_' . $i]) ? $_post['option_name5_' . $i] : ''; $option_selection5 = isset($_post['option_selection5_' . $i]) ? $_post['option_selection5_' . $i] : ''; $option_name6 = isset($_post['option_name6_' . $i]) ? $_post['option_name6_' . $i] : ''; $option_selection6 = isset($_post['option_selection6_' . $i]) ? $_post['option_selection6_' . $i] : ''; $option_name7 = isset($_post['option_name7_' . $i]) ? $_post['option_name7_' . $i] : ''; $option_selection7 = isset($_post['option_selection7_' . $i]) ? $_post['option_selection7_' . $i] : ''; $option_name8 = isset($_post['option_name8_' . $i]) ? $_post['option_name8_' . $i] : ''; $option_selection8 = isset($_post['option_selection8_' . $i]) ? $_post['option_selection8_' . $i] : ''; $option_name9 = isset($_post['option_name9_' . $i]) ? $_post['option_name9_' . $i] : ''; $option_selection9 = isset($_post['option_selection9_' . $i]) ? $_post['option_selection9_' . $i] : ''; $btn_id = isset($_post['btn_id' . $i]) ? $_post['btn_id' . $i] : ''; $current_item = array( 'item_number' => $item_number, 'item_name' => $item_name, 'quantity' => $quantity, 'mc_gross' => $mc_gross, 'mc_handling' => $mc_handling, 'mc_shipping' => $mc_shipping, 'custom' => $custom, 'option_name1' => $option_name1, 'option_selection1' => $option_selection1, 'option_name2' => $option_name2, 'option_selection2' => $option_selection2, 'option_name3' => $option_name3, 'option_selection3' => $option_selection3, 'option_name4' => $option_name4, 'option_selection4' => $option_selection4, 'option_name5' => $option_name5, 'option_selection5' => $option_selection5, 'option_name6' => $option_name6, 'option_selection6' => $option_selection6, 'option_name7' => $option_name7, 'option_selection7' => $option_selection7, 'option_name8' => $option_name8, 'option_selection8' => $option_selection8, 'option_name9' => $option_name9, 'option_selection9' => $option_selection9, 'btn_id' => $btn_id ); array_push($cart_items, $current_item); $i++; }

that leave array called $cart_items contains of items. add together database inserts loop provided, or utilize gather cart items $cart_items , utilize work from.

either way, need loop through items.

php insert paypal shopping-cart paypal-ipn

css - jQuery addclass and toggle class not setting my class -



css - jQuery addclass and toggle class not setting my class -

good day

for reason browser ignoring addclass , toggleclass jquery calls:

html <div id="menunav" class="row-fluid"> <div id="menunavsub" class="span12"> <ul> <li id="homenav"><a href="index.aspx"><img src="images/homenav2.png" /></a></li> <li id="gallerynav"><a href="galleries.aspx" class="block"><img src="images/homenav2.png" /></a></li> <li id="aboutnav"><a href="about.aspx"><img src="images/homenav2.png" /></a></li> <li id="contactnav"><a href="contact.aspx"><img src="images/homenav2.png" /></a></li> </ul> </div> </div> css: .activenavhome1 { background-position: -200px center; } .activenavhome2{ background: url('/images/homenavsmall.png') no-repeat left center; background-position: -150px center; } jquery: $('#homenav').addclass('activenavhome1'); if ($(window).width() < 1080) { $('#homenav').toggleclass('activenavhome2'); }

notes: using asp.net , jquery code contained in index.aspx file. html contained in master file.

however, when utilize

$('#homenav').css('background-position', '-200px center')

it works. why not assigning classes addclass , toggleclass commands? have made no spelling mistakes in css.

pass 2 classes instead , i think didn't referenced jquery library or may doc ready missing:

<script> $(function(){ // <-----------------------------you missing $('#homenav').addclass('activenavhome1'); if ($(window).width() < 1080) { $('#homenav').toggleclass('activenavhome1 activenavhome2'); } }); </script> note:

make sure have loaded jquery before script:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

jquery css

ruby - Redis won't install with Resque Task -



ruby - Redis won't install with Resque Task -

i'm trying set resque redis , followed documentation:

https://github.com/defunkt/resque#section_installing_redis

but when execute 'rake redis:install dtach:install' get:

rake aborted! don't know how build task 'redis:install' /home/max/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `eval' /home/max/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `<main>'

i tried sudo. don't know how resolve this. suspect there might wrong ruby setup?

when type 'sudo bundle install' following:

/home/max/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:247:in `to_specs': not find bundler (>= 0) amongst [bigdecimal-1.1.0, io-console-0.3, json-1.5.4, minitest-2.5.1, rake-0.9.2.2, rdoc-3.9.4] (gem::loaderror) /home/max/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems/dependency.rb:256:in `to_spec' /home/max/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/site_ruby/1.9.1/rubygems.rb:1231:in `gem' /home/max/.rvm/gems/ruby-1.9.3-p194/bin/bundle:18:in `<main>' /home/max/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `eval' /home/max/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `<main>'

seems there seperate ruby , gemlist within ruby 1.9.3-p194?

you should not utilize sudo rvm, seek plain bundle install, sudo looses environment variables used configure rvm / ruby / rubygems.

also create sure steps successful, git clone command

ruby redis rvm resque

vb.net - Unable to dynamically load a control into a SplitContainer panel -



vb.net - Unable to dynamically load a control into a SplitContainer panel -

i have placed splitcontainer command onto form. have custom command within panel 1. custom command container user-control.

there treeview command within user-control. trying load user-control onto panel 2 upon selection of node in tree view. not getting loaded. missing something?

the code loading command given below:

dim ucimportexcel1 new ucimportexcel() frmmain.splitcontainer1.panel2.controls.add(ucimportexcel1) ucimportexcel1.dock = dockstyle.fill

an add-on above: in same treeview selection event

for code below sets form text:

me.parentform.text = "sample text 1"

whereas if utilize code, nil happens:

frmmain.text = "sample text 2"

when referred directcast, solved problem:

directcast(me.parentform.controls.item("splitcontainer1"), system.windows.forms.splitcontainer).panel2.controls.add(ucimportexcel1)

vb.net winforms custom-controls

java - JFreeChart MultiPiePlot change title font colour -



java - JFreeChart MultiPiePlot change title font colour -

jfreechart 1.0.14 dealing multipieplot. dataset categorydataset category defining sub plot's title text.

i need alter colour of titles each sub plot.

i changing background black , need contrasting title colour. i've found how alter colour of pretty much else.

in below image sub titles "response pending", "resplan pending" , "resolution pending" need changed in colour.

i can't seem access object set paint colour anywhere.

have tried:

chart1.gettitle().setpaint(color.red);

where char1 name of 1 of charts?

java colors jfreechart title

java - Difference between Hibernate and Hibernate JPA -



java - Difference between Hibernate and Hibernate JPA -

i found lot of similar questions

difference between hibernate library , hibernate jpa library what's difference between jpa , hibernate? similarity , difference between jpa , hibernate

but no 1 answers next question. diference between classical hibernate approach using org.hibernate.sessionfactory , jpa javax.persistence.entitymanager implementation? heard, jpa implementation uses org.hibernate.sessionfactory , works wrapper, real?

indeed.

jpa api allows abstract used persistence layer. hibernate provides implementation of entitymanager interface acts adapter - uses same underlying methods hibernate sessionmanager.

the thought could, example, switch implementation eclipse link , not have alter of source code.

java hibernate jpa orm

java - Member method synchronized on whole class -



java - Member method synchronized on whole class -

after quick searching, not able find clear answer.

is there more elegant way synchronize whole fellow member method (bound on instance) on whole class? means method can called on multiple instances multiple threads, 1 thread @ time. can written synchronized block.

(for illustration, method inserts it's instance shared cache.)

class dataobject { public putincache() { synchronized(getclass()) { // ... stuff cache.insert(this); // ... more stuff } } }

it's thought avoid synchronizing on publicly accessible object. can utilize shared monitor object, however:

class dataobject { private static final object cachelock = new object(); public putincache() { synchronized(cachelock) { // ... stuff cache.insert(this); // ... more stuff } } }

note particular implementation dataobject , classes derived share lock.

java synchronized

javascript - anchor download link not working in firefox -



javascript - anchor download link not working in firefox -

i have used this

<a href="/admin/con/image/studentimportfiletemplate_create.csv" download="studentimportfiletemplate_create.csv">download</a>

i have added download attribute chrome not supported firefox

this working fine in ie , chrome file getting downloaded can explain me how work firefox also.

you don't need utilize such attribute start file download.

just use:

<a href="/admin/con/image/studentimportfiletemplate_create.csv">download</a>

if csv beingness opened rather getting downloaded , still want utilize download attribute, here's right way it:

http://davidwalsh.name/download-attribute

javascript html internet-explorer google-chrome firefox

ruby - 2 forms on same page, Sending using Pony in Sinatra, same email address -



ruby - 2 forms on same page, Sending using Pony in Sinatra, same email address -

i using pony.mail send mail service within sinatra, have 2 forms, 1 sends email address subscription newsletter , sec form contact form, both going through same action.

what trying accomplish if subscription field completed send params or if contact form completed , sent send params

heres come far, getting undefined method nil

post '/' require 'pony' pony.mail( :from => params[:name] || params[:subscribe], :to => 'myemailaddress', :subject => params[:name] + " has contacted via website" || params[:subscribe] + " has subscribed newsletter", :body => params[:email] + params[:comment], :via => :smtp, :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => 'myemailaddress', :password => 'mypassword', :authentication => :plain, :domain => "localhost.localdomain" }) redirect '/success' end

is possible or each form have dealt individually?

thanks

there several stages i'd go through refactor code.

1. extract things changing (and create them more rubyish) post '/' require 'pony' = params[:name] || params[:subscribe] subject = "#{params[:name]} has contacted via website" || "#{params[:subscribe]} has subscribed newsletter" body = "#{params[:email]}#{params[:comment]}" pony.mail( :from => from, :to => 'myemailaddress', :subject => subject, :body => body, :via => :smtp, :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => 'myemailaddress', :password => 'mypassword', :authentication => :plain, :domain => "localhost.localdomain" }) redirect '/success' end 2. create clear intentions

in case, there 2 branches through code.

post '/' require 'pony' if params[:name] # contact form = params[:name] subject = "#{params[:name]} has contacted via website" else # subscription form = params[:subscribe] subject = "#{params[:subscribe]} has subscribed newsletter" end body = "#{params[:email]}#{params[:comment]}" pony.mail( :from => from, :to => 'myemailaddress', :subject => subject, :body => body, :via => :smtp, :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => 'myemailaddress', :password => 'mypassword', :authentication => :plain, :domain => "localhost.localdomain" }) redirect '/success' end

(i'm not big fan of setting local vars within conditional branches, we'll ignore clarity. i'd create hash before conditional keys done, , populate in branches ymmv.)

3. extract doesn't alter does.

sinatra has configure block kind of thing.

require 'pony' configure :development set :email_options, { :via => :smtp, :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => 'myemailaddress', :password => 'mypassword', :authentication => :plain, :domain => "localhost.localdomain" } end pony.options = settings.email_options

notice i've added :development may want set differently production.

now route lot cleaner , easier debug:

post '/' if params[:name] # contact form = params[:name] subject = "#{params[:name]} has contacted via website" else # subscription form = params[:subscribe] subject = "#{params[:subscribe]} has subscribed newsletter" end body = "#{params[:email]}#{params[:comment]}" pony.mail :from => from, :to => 'myemailaddress', :subject => subject, :body => body, redirect '/success' end

my lastly tip, set many of pony options env vars, not maintain things passwords out of source command allow alter settings lot easier. perhaps set them in rakefile , load different environments different contexts etc.

to utilize environment variables, following:

# rakefile # in method set env vars def basic_environment # load them in yaml file *not* in source command # specify them here # e.g. env["email_a"] = "me@example.com" end namespace :app desc "set environment locally" task :environment warn "entering :app:environment" basic_environment() end desc "run app locally" task :run_local => "app:environment" exec "bin/rackup config.ru -p 4630" end end # command line, i'd run `bin/rake app:run_local` # in sinatra app file configure :production # these actual settings utilize heroku app using sendgrid set "email_options", { :from => env["email_from"], :via => :smtp, :via_options => { :address => 'smtp.sendgrid.net', :port => '587', :domain => 'heroku.com', :user_name => env['sendgrid_username'], :password => env['sendgrid_password'], :authentication => :plain, :enable_starttls_auto => true }, } end # block different settings development configure :development # local settings… set "email_options", { :via => :smtp, :via_options => { :address => 'smtp.gmail.com', :port => '587', :enable_starttls_auto => true, :user_name => env["email_a"], :password => env["email_p"], :authentication => :plain, :domain => "localhost.localdomain" } } end

i maintain of these setting in yaml file locally development, add together these production server directly. there lots of ways handle this, ymmv.

ruby forms sinatra pony

cookies - Warning: Cannot modify header information - headers already sent by... PHP -



cookies - Warning: Cannot modify header information - headers already sent by... PHP -

this question has reply here:

“warning: cannot modify header info - headers sent by” error [duplicate] 6 answers how prepare “headers sent” error in php 11 answers

i understand said error means sending it's output on http protocol (if understood correctly). lines gives me errors setcookie 1 , header 1 (last one). can help me out please? give thanks you.

<?php $a = 'thisissomestring=='; $b = 'thisissomestring=='; $encrypteddata = base64_decode($a); $iv = base64_decode($b); $appkey ='thisissomestring'; $td = mcrypt_module_open(mcrypt_serpent, '', mcrypt_mode_cbc, ''); $ks = mcrypt_enc_get_key_size($td); $key = substr($appkey, 0, $ks); mcrypt_generic_init($td, $key, $iv); $decrypted = mdecrypt_generic($td, $encrypteddata); $str = $decrypted; mcrypt_generic_deinit($td); mcrypt_module_close($td); $file = file($decrypted); $output = $file[0]; if( !isset( $_cookie['thisismycookie'] ) ) { setcookie('thisismycookie', $output, time() + 600, "/", $_server['http_host']); } else { echo 'action not allowed [3]'; die(); } unset($file[0]); file_put_contents($str, $file); header("location: http://www.mysite.com/something");

?>

setting cookie requires sending info browser. 1 time can't redirect using php or else you'll error you're seeing. seek using session instead.

php cookies header

php - Calculating an Exponent -



php - Calculating an Exponent -

in excel =(b5/2)^2*3.141592654, b5 rod.

this doesn't produce same results.

$rodarea = $rod/2 ^2*3.141592654 ;

what doing wrong? thanks.

my guess error in whatever language (perl?) written in:

$rodarea = $rod/2 ^2*3.141592654 ;

many programming languages don't honor ^ exponent operator, due ambiguity xor ^. typically have function pow or exp exponents. in case do:

$rodarea = (($rod/2)*($rod/2))*3.141592654 ;

(exponent in perl **, not ^, though don't know if that's right language).

php excel exponent

javascript - Matching content within a string with one regex -



javascript - Matching content within a string with one regex -

this question has reply here:

how pass variable regular look javascript? 16 answers simple way utilize variables in regex 3 answers

i looking way regex match string (double quote followed 1 or more letter, digit, or space followed double quote). example, if input var s = "\"this string\"", create regex match string , produce result of [""this string""].

thank you!

use regexp constructor function.

var s = "this string"; var re = new regexp(s);

note may need quote input string.

javascript regex

php - How to secure json -



php - How to secure json -

so have main page gets info json link , populates dropdown based on data. question is, can access url json getting printed , want secure server , pages running on server can access json output.

i thinking of comparing php server vars such remote_addr , server_addr remote_addr clients ip , not server.

what way go doing this?

thanks

the security issue refer known json hijacking, , whilst browsers include features mitigate risk, still issue in other browsers.

fortunately there simple solution. understand it, need understand how attack works in first place. isn't possible third-party site request json file via xmlhttprequest , parse in normal way, prevented same-origin policy. attacker redefine object setter functions in javascript homecoming values of new objects own code, , create new <script> tag referencing json file. when json loaded browser execute it, create new object, , homecoming values attacker's object setter handler. attacker has data.

to prevent this, need create impossible parse json code straight javascript. want create throw error if done. 1 mutual way accomplish (used sites such google , facebook) add together code origin of json file create infinite loop, preventing parser reaching rest of code (and throwing javascript error).

for example, facebook's json responses start string for(;;);, while google utilize various bits of code such while(1);, , throw(1); <don't evil> (the latter throws error directly, rather creating infinite loop).

you need modify own json handling javascript strip cruft out before parsing it. example, might do:

function parsejson(json) { json = json.replace("for(;;);", ""); /* parse json usual */ }

this adds little bit of cruft script , json, effective @ preventing json hijacking.

php json

r - Apply any over rows -



r - Apply any over rows -

in r any-function applied on columns result boolean. best way, apply row row? target in case recode a, if of a, b or c 1 or 6. (if true test$new should 101)

here dataframe:

b c d 1 1 1 "a" 2 1 2 "b" 3 6 3 "c" 5 3 5 "d"

it done in way, there should smarter solution:

test$new <- ifelse(test$a == 1 | test$b == 1 | test$c == 1 | test$a == 6 | test$b == 6 | test$c == 6, 101, na)

test$new <- ifelse(apply(test,1,function(x) any(x==1|x==6)),101,na)

r

java - Graphics wont clear properly -



java - Graphics wont clear properly -

i having problems, want square (fly) drawn , redrawn show movement. fine in code when button pressed fly "move", old squares not delete. have tried enviromentpanel.repaint() updateui() , removeall() , cannot work, if utilize of them none of shapes appear , blank screen.

import java.util.random; public class fly implements runnable{ private int xposition; private int yposition; private boolean eaten; public fly(){ random randomgenerator = new random(); xposition = randomgenerator.nextint(690) + 10; yposition = randomgenerator.nextint(690) + 10; eaten = false; } public int getxposition() { homecoming xposition; } public void setxposition(int xposition) { this.xposition = xposition; } public int getyposition() { homecoming yposition; } public void setyposition(int yposition) { this.yposition = yposition; } public boolean iseaten() { homecoming eaten; } public void seteaten(boolean eaten) { this.eaten = eaten; } public void move(){ random randomgenerator = new random(); int xchange = -10 + randomgenerator.nextint(20); int ychange = -10 + randomgenerator.nextint(20); xposition = xposition + xchange; yposition = yposition + ychange; seek { thread.sleep(1000); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } move(); } @override public string tostring() { homecoming "fly [xposition=" + xposition + ", yposition=" + yposition + ", eaten=" + eaten + "]"; } @override public void run() { move(); } } import java.awt.color; import java.awt.flowlayout; import java.awt.graphics; import java.awt.panel; import java.awt.event.actionevent; import java.awt.event.actionlistener; import java.awt.event.actionevent; import java.awt.image.bufferedimage; import java.io.file; import java.io.ioexception; import java.util.arraylist; import javax.swing.*; import java.awt.*; import javax.imageio.imageio; public class enviroment2 implements runnable,actionlistener{ private jframe frame; private jpanel enviromentpanel,totalgui,enviromentbuttonpanel; private jbutton newfrogbutton, resetbutton, hungrybutton; private jtextfield entername; private jlabel hungrylabel; private arraylist<frog> frogs; private arraylist<fly> flys; public enviroment2(){ totalgui = new jpanel(); flys = new arraylist<fly>(); frogs = new arraylist<frog>(); enviromentpanel = new jpanel(); enviromentbuttonpanel = new jpanel(); newfrogbutton = new jbutton("new frog"); entername = new jtextfield("enter name"); hungrybutton = new jbutton("hungry!"); resetbutton = new jbutton("reset"); frame = new jframe("[=] hungry cyber pet [=]"); jframe.setdefaultlookandfeeldecorated(true); frame.setcontentpane(runenviroment()); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(740, 800); frame.setvisible(true); } public jpanel runenviroment(){ totalgui.setlayout(null); enviromentpanel.setlayout(null); enviromentpanel.setlocation(10, 10); enviromentpanel.setsize(700, 700); enviromentpanel.setbackground(color.white); totalgui.add(enviromentpanel); flowlayout experimentlayout = new flowlayout(); enviromentbuttonpanel.setlayout(experimentlayout); enviromentbuttonpanel.setlocation(10, 710); enviromentbuttonpanel.setsize(700, 50); totalgui.add(enviromentbuttonpanel); newfrogbutton.setlocation(0, 0); newfrogbutton.setsize(120, 30); newfrogbutton.addactionlistener(this); enviromentbuttonpanel.add(newfrogbutton); entername.setlocation(140,0); entername.setsize(120,30); enviromentbuttonpanel.add(entername); hungrybutton.setlocation(280, 0); hungrybutton.setsize(120, 30); hungrybutton.addactionlistener(this); enviromentbuttonpanel.add(hungrybutton); resetbutton.setlocation(420, 0); resetbutton.setsize(120, 30); resetbutton.addactionlistener(this); enviromentbuttonpanel.add(resetbutton); totalgui.setopaque(true); homecoming totalgui; } public void draw(){ graphics paper = enviromentpanel.getgraphics(); (int = 0; <= flys.size()-1; i++){ system.out.println("hi"); paper.setcolor(color.black); paper.fillrect(flys.get(i).getxposition(), flys.get(i).getyposition(), 10, 10); } seek { thread.sleep(1000); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } draw(); } public void actionperformed(actionevent e) { if(e.getsource() == newfrogbutton){ frog frog = new frog(entername.gettext()); frogs.add(frog); fly fly = new fly(); thread t = new thread(fly); t.start(); flys.add(fly); showflys(); } else if(e.getsource() == hungrybutton){ } else if(e.getsource() == resetbutton){ frogs.clear(); flys.clear(); system.out.println(frogs); system.out.println(flys); } } public void showflys(){ (int = 0; <= flys.size()-1; i++){ system.out.println(flys.get(i)); } } @override public void run() { draw(); } }

this graphics paper = enviromentpanel.getgraphics() start of problems, not how custom painting done.

getgraphics returns graphics context used in lastly paint cycle, @ best it's snap shot, @ worst can null.

you should never maintain reference graphics context didn't create. can alter , painting on out of turn can produce unexpected results.

instead, should override paintcomponent method (probably in environmentpanel) , custom painting in it.

your sec problem violating thread rules of swing - should never create or modify ui component in thread other edt

you might take read through

performing custom painting painting in awt , swing concurrency in swing

java swing graphics jpanel

SpineJS handle server-side rails model validations -



SpineJS handle server-side rails model validations -

i have model, let's phone call book. in rails, when book saved, validate uniqueness of it's isbn number. front end end, have simple spinejs app let's me add together new book.

in spinejs:

class app.book extends spine.model @configure 'book', 'name', 'isbn' @extend spine.model.ajax validate: -> "name required" unless @name "isbn required" unless @isbn

and in rails:

class book < activerecord::base attr_accessible :name, :isbn validates :name, :presence => true validates :isbn. :presence => true, :uniqueness => true end

my issue in spinejs app, happily saves new book duplicate isbn number, though rails server returns validation errors.

is there way handle error client-side on save?

spine's manual claims:

if validation fail server-side, it's error in client-side validation logic rather user input.

i don't see how work uniqueness requirement. may workable if can load database info impact validation client side and can somehow avoid multi-user race conditions.

you can grab "ajaxerror" event , tell user retry, although catching "ajaxerror" goes against recommendations in manual. iirc may have juggling object ids convince spine new record in fact not created.

additionally, can fire pre-emptive validation requests user editing data, user's convenience. in theory can still nail race status else creates conflicting record before user hits save.

personally switched backbone since found spine's careless mental attitude error handling scary.

ruby-on-rails ruby-on-rails-3 javascriptmvc spine.js

android - onSingleTapConfirmed -



android - onSingleTapConfirmed -

the proble : "syntax error on token "start", identifier expected after token"------on first start.(loadinganimation.start();

new countdowntimer(30000, 1000) { public void ontick(long millisuntilfinished) { animationdrawable loadinganimaton; loadinganimation = (animationdrawable) imageview.getbackground(); }loadinganimation.start(); public void onfinish() { mtextfield.settext("done!"); } }.start(); homecoming true; }});

android countdowntimer

java - is it possible to detect a parents transformation in the child? -



java - is it possible to detect a parents transformation in the child? -

the javadoc of javafx.scene.group says:

any transform, effect, or state applied grouping applied children of group

but possible tot observe transform applied grouping in children? ie there property on kid can hear if parent grouping gets transformation applied it? tried listening layoutxproperty(), translatexproperty(), gettransforms() couldn't observe alter there.

when add together transformation node, transformation propogated internal scenegraph rendering mechanism on children (if applicable, , if there no bugs), , there no way know in children it. children's transformations lists correspond transformations, should applied node, , children , set user, , list (or according properties) not notify transformations, done parents.

java javafx-2

Error while creating mysql restore cmd in java -



Error while creating mysql restore cmd in java -

i trying restore mysql sql file using java, dont have thought why it's not working. code given below.

/*note: getting path jar file beingness executed*/ codesource codesource = dbmanager.class.getprotectiondomain().getcodesource(); file jarfile = new file(codesource.getlocation().touri().getpath()); string jardir = jarfile.getparentfile().getpath(); /*note: creating database constraints*/ string dbname = "dth"; string dbuser = "root"; string dbpass = "root"; string restorepath ="\""+ jardir + "\\backup" + "\\" + s+"\""; /*note: used create dos command*/ string executecmd = ""; executecmd = "c:\\xampp\\mysql\\bin\\mysql -u" + dbuser + " -p" + dbpass + " --database " + dbname + " < " + restorepath; system.out.println(executecmd); process runtimeprocess = runtime.getruntime().exec(executecmd); int processcomplete = runtimeprocess.waitfor(); if (processcomplete == 0) { joptionpane.showmessagedialog(null, "successfully restored sql : " + s); } else { joptionpane.showmessagedialog(null, "error @ restoring"); }

the code executes java swing stuck on runtime command. line outputted system.out.println this.

c:\xampp\mysql\bin\mysql -uroot -proot --database dth < "f:\final year project\final\build\backup\0_harish_2013-02-17-20-05-12.sql"

this line works if re-create , paste in command line. dunno why java swing interface gets stuck in wait state. (the same query takes 2 seconds on cmd , on java have waited 5minutes).

edit: ran streamgobbler , still no benefit, still gives exit value: 1 problem illegalthreadstateexception how can solve this?

edit2:

the gobbling doesnt help hang still exists , heres output of gobbler

class="lang-none prettyprint-override">output>c:\xampp\mysql\bin\mysql ver 14.14 distrib 5.5.27, win32 (x86) output>copyright (c) 2000, 2011, oracle and/or affiliates. rights reserved. output> output>oracle registered trademark of oracle corporation and/or output>affiliates. other names may trademarks of respective output>owners. output> output>usage: c:\xampp\mysql\bin\mysql [options] [database] output> -?, --help display help , exit. output> -i, --help synonym -? output> --auto-rehash enable automatic rehashing. 1 doesn't need utilize output> 'rehash' table , field completion, startup output> , reconnecting may take longer time. disable output> --disable-auto-rehash. output> (defaults on; utilize --skip-auto-rehash disable.) output> -a, --no-auto-rehash output> no automatic rehashing. 1 has utilize 'rehash' output> table , field completion. gives quicker start of output> mysql , disables rehashing on reconnect. output> --auto-vertical-output output> automatically switch vertical output mode if output> result wider terminal width. output> -b, --batch don't utilize history file. disable interactive behavior. output> (enables --silent.) output> --character-sets-dir=name output> directory character set files. output> --column-type-info display column type information. output> -c, --comments preserve comments. send comments server. output> default --skip-comments (discard comments), enable output>

(rest of usage message omitted)

i able solve problem chanding string command string array command. made utilize of gobbler redundant.

java mysql swing

bash - Is there a way to catch a failure in piped commands? -



bash - Is there a way to catch a failure in piped commands? -

this question has reply here:

catching error codes in shell pipe 3 answers

here's illustration of i'm trying achieve:

#!/bin/bash set -e # abort if error ... command1 2>&1 | command2 ...

and notice command1 fails command2 not , shell script happily continues... if did not have utilize pipe here, set -e have been sufficient not work pipe there...

any thoughts? thanks

since using bash, other set -e can add together set -o pipefail results want...

bash shell pipe

java - Image content of HashMap won't appear -



java - Image content of HashMap won't appear -

so come code

map<integer, integer> images = new hashmap<integer, integer>(); images.put(1,r.drawable.a); images.put(2,r.drawable.b); images.put(3,r.drawable.c); string[] abcd = {"a","b","c"}; integer count = 3; for(int inte = 0; inte==count;inte ++ ){ if(strn.get(inte).equalsignorecase(abcd[inte])){ image.setimagedrawable(getresources().getdrawable(images.get(inte))); } } to set images drawables hashmap integer keys i made array[] compare user input,a loop traverse content of hashmap , to display image if status true.

this insight of want done but... problem image wont appear prior code. think question bit similar loop through hashtable, or can't see contents , notice enumeration, iterator can't manage apply them in code. can guide me or suggestion fine solve problem.

adapted reply here:

change

for(int inte = 0; inte==count; inte++){ // start inte beeing 0, execute while inte 3 (count 3) // never true

to

for(int inte = 0; inte < count; inte++){ // start inte beeing 0, execute while inte smaller 3 // true 3 times

explanation:

a loop has next structure:

for (initialization; condition; update)

initialization executed 1 time before loop starts. condition checked before each iteration of loop , update executed after every iteration.

your initialization int inte = 0; (executed once). condition inte == count, false, because inte 0 , count 3. status false, , loop skipped.

java android

iphone - Why do iOS keychain values not change without leaving the ViewController? -



iphone - Why do iOS keychain values not change without leaving the ViewController? -

i have an abstraction on ios keychain api seems work well. basically, has:

public string getgenericpasswordfield(string account) { var record = seckeychain.queryasrecord(query, out code); if (code == secstatuscode.itemnotfound) homecoming null; homecoming nsstring.fromdata(record.valuedata, nsstringencoding.utf8); } public void setgenericpasswordfield(string account, string value) { if (value == null) { seckeychain.remove(record); return; } var record = new secrecord (seckind.genericpassword) { service = service, label = label, business relationship = account, valuedata = nsdata.fromstring (value), }; secstatuscode code = seckeychain.add (record); if (code == secstatuscode.duplicateitem) { // (remove , re-add item) } }

i have used abstraction on app's settings screen save values while leaving, , load values elsewhere in app.

but i've run issue saving value not appear take effect if don't leave current viewcontroller. i'm doing analogous to:

if (keychain.getgenericpasswordfield("remotelogin") == null) { var remotepassword = getfromdialog(); keychain.setgenericpasswordfield("remotelogin", hash(remotepassword)); // safe assume remotelogin password got saved, right? } // later on... if (keychain.getgenericpasswordfield("remotelogin") == null) { // block beingness executed }

i've stepped through code in debugger confirm things i'm describing them, , abstraction method getting secstatuscode.itemnotfound back, meaning null appropriate value return.

i worked around 1 time moving first half of code previous viewcontroller, , reason seemed wake up, or clear out whatever caching taking place. i've encountered situation that's not practical.

why happening? abstraction leaking?

iphone ios monotouch

c++ - Asymmetry of string::find_first_of and string::find_last_of -



c++ - Asymmetry of string::find_first_of and string::find_last_of -

with fellow member function string::find_first_of in c++ standard library can search in empty substring:

s.find_first_of(c, s.size())

or

s.find_first_of(c, string::npos)

but cannot search in empty substring string::find_last_of; next phone call search in substring containing (only) first character:

s.find_last_of(c, 0)

i think imperfection of c++ standard library, isn't it?

i don't see asymmetry here. in fact quite opposite, appears symmetrical. think of find_first_of search right starting position, while find_last_of search left starting position.

the name find_last_of has misleading quality it: implies natural forward search, except homecoming lastly occurrence instead of first one. however, bidirectional sequences 1 can ignore "forward" nature of name , think of of backward search. backward search returns first occurrence, proceeds to left starting point. point of view, function symmetrical find_first_of.

edit: after reading comments understand point. so, problem current semantics of pos parameter makes impossible specify empty search part find_last_of. yes, makes sense. agree, indeed can seen inconsistency in find_last_of design.

for consistency purposes, expect find_last_of non-inclusive respect pos value. in case specification of target position of xpos returned find_last_of be

xpos < pos , xpos < size();

in case s.find_last_of(c, 0) search empty prefix, while s.find_last_of(c, s.size()) search entire string.

however standard says

xpos <= pos , xpos < size();

i don't know why decided give pos parameter such inclusive meaning. thought create easier understand.

c++

[cocos2dx android]Rendering CCSprite using raw data from Bitmap -



[cocos2dx android]Rendering CCSprite using raw data from Bitmap -

i trying fetch image url bitmap , using raw info bitmap trying create ccsprite. issue here image corrupted when display sprite. created standalone android application(no cocos2dx) , used same code fetch , display bitmap , displayed correctly. reason why image not beingness rendered in cocos2dx?

my code fetch image url is:

string urlstring = "http://www.mathewingram.com/work/wp-content/themes/thesis/rotator/335f69c5de_small.jpg";//http://graph.facebook.com/"+user.getid()+"/picture?type=large"; bitmap pic = null; pic = bitmapfactory.decodestream((inputstream) new url(urlstring).getcontent()); int[] pixels = new int[pic.getwidth() * pic.getheight()]; pic.getpixels(pixels, 0, pic.getwidth(), 0, 0,pic.getwidth(),pic.getheight()); int len = pic.getwidth()* pic.getheight(); nativefbusername(pixels,len,pic.getwidth(), pic.getheight());

the function "nativefbusername" phone call native c++ function :

void java_com_wbs_test0001_test0001_nativefbusername(jnienv *env, jobject thiz,jintarray name, jint len, jint width, jint height) { jint *jarr = env->getintarrayelements(name,null); int username[len]; (int i=0; i<len; i++){ username[i] = (int)jarr[i]; } helloworld::getshared()->piclen = (int)len; helloworld::getshared()->picheight = (int)height; helloworld::getshared()->picwidth = (int)width; helloworld::getshared()->savearray(username); helloworld::getshared()->schedule(sel_schedule(&helloworld::addsprite),0.1); } void helloworld::savearray(int *arraytosave) { arr = new int[piclen]; for(int = 0; < piclen; i++){ arr[i] = arraytosave[i]; } } void helloworld::addsprite(float time) { this->unschedule(sel_schedule(&helloworld::addsprite)); cctexture2d *tex = new cctexture2d(); bool val = tex->initwithdata(arr,(cocos2d::cctexture2dpixelformat)0,picwidth,picheight, ccsizemake(picwidth,picheight)); cclog("flag %d",val); ccsprite *spritetoadd = ccsprite::createwithtexture(tex); spritetoadd->setposition(ccp(500, 300)); this->addchild(spritetoadd); }

edit: found link access raw info in argb_8888 android bitmap states might bug. has found solution this?

edit noticed corruption of images on lower right corner of image.i not sure why happening , how prepare it. ideas?

edit end

answering own question, obtained byte array bitmap using:

byte[] info = null; bytearrayoutputstream baos = new bytearrayoutputstream(); pic.compress(bitmap.compressformat.jpeg, 100, baos); info = baos.tobytearray();

and passed byte array native code.

android bitmap cocos2d-x ccsprite

c# - How do I show status in a progress bar on my winform? -



c# - How do I show status in a progress bar on my winform? -

while transferring info 1 table another, want progress bar show status on form. tried ways it's not working.

if (datagridview1.rowcount - 1 == no_of_rows) { progressbar1.value = 100; datagridview1.visible = true; } else { progressbar1.value = 50; datagridview1.visible = false; }

use progress bar window control

for references : http://www.codeproject.com/articles/449594/progress-bars-threads-windows-forms-and-you

c# winforms c#-4.0 progress-bar

linux - Optparse and sys.argv - Python -



linux - Optparse and sys.argv - Python -

i've written python script, accepts input via optparse module of python. , take input sys.argv well.

when utilize either of them, programme works correctly. example:

python dperf.py -m 1 -c 2 -n 3 python dperf.py foobar

however, not when give input in manner.

python dperf.py foobar -m 1 -c 2 -n 3

is there error in way using sys.argv?

parser = optparse.optionparser() #migration parser.add_option("-m", type="float", dest="migr") #collection parser.add_option("-c", type="float", dest="coll") #num of lines read parser.add_option("-n", type="float", dest="fileread") (options, args) = parser.parse_args() ti = options.migr colle = options.coll linereadfiles = options.fileread apps = sys.argv[1:]

if parse options via parse_args() of optionparser, not utilize sys.argv straight returned args instead should contain parts not parsed optionparser.

for illustration in code replace

apps = sys.argv[1:]

by

apps = args

(or scrap apps , go on args).

python linux

python - ftplib.error_pern 501 No File Name? -



python - ftplib.error_pern 501 No File Name? -

name = raw_input() ftp = ftp("") ftp.login('','') #these work fine ftp.storbinary("stor", "%s.txt" % (name)) # think issue here ftp.quit()

the programme crashes reaches part, googled , unable find answer, have tried typing name of file, same result.

what doing wrong?

if take @ docs, storbinary method takes form of ('stor filename', <file_object>). issue above don't have finish stor command first (command) argument. since need pass open file handler file argument, seek like:

ftp.storbinary("stor %s.txt" % (name), open("%s.txt" % name, 'rb'))

which create open file handler based on name raw_input (as you're accepting input, you'd want wary of malicious input well). assuming handle that, context manager used open file (and ensure closes):

my_file = "%s.txt" % name open(my_file, "rb") f: ftp.storbinary("stor %s" % (my_file), f)

python ftplib

php - Second input based on what was selected in first input -



php - Second input based on what was selected in first input -

i have 2 inputs correspond each other on same page , in same form.

the input's are:

select event: <input type="radio" name="type" value="birthday" id="birthday" checked /> <label for="birthday">birthday</label><br /> <input type="radio" name="type" value="anniversary" id="anniversary" /> <label for="anniversary">anniversary</label><br /> <input type="radio" name="type" value="holiday" id="holiday" /> <label for="holiday">holiday</label><br />

now need have input selected above correspond value img src of input below...

for example, let's say, if birthday radio above selected radio below be:

<input type="radio" name="design" value="birthday_design_1" id="1" checked /> <label for="1"><img src="images/birthday_design_1.jpg" border="0" width="150" height="200" /></label> <input type="radio" name="design" value="birthday_design_2" id="2" /> <label for="1"><img src="images/birthday_design_1.jpg" border="0" width="150" height="200" /></label>

or if anniversary radio above filled above radio below be:

<input type="radio" name="design" value="anniversary_design_1" id="1" checked /> <label for="1"><img src="images/anniversary_design_1.jpg" border="0" width="150" height="200" /></label> <input type="radio" name="design" value="anniversary_design_2" id="2" /> <label for="1"><img src="images/anniversary_design_1.jpg" border="0" width="150" height="200" /></label>

or if holiday radio above filled above radio below be:

<input type="radio" name="design" value="holiday_design_1" id="1" checked /> <label for="1"><img src="images/holiday_design_1.jpg" border="0" width="150" height="200" /></label> <input type="radio" name="design" value="holiday_design_2" id="2" /> <label for="1"><img src="images/holiday_design_1.jpg" border="0" width="150" height="200" /></label>

as may able see out, value of input changes img src of radio.

please help, believe jquery needed this.

thanks, chad.

<input group_class="group-1" class="event_radio" type="radio" name="type" value="birthday" id="birthday" checked /> <label for="birthday">birthday</label><br /> <input group_class="group-2" class="event_radio" type="radio" name="type" value="anniversary" id="anniversary" /> <label for="anniversary">anniversary</label><br /> <input group_class="group-3" class="event_radio" type="radio" name="type" value="holiday" id="holiday" /> <label for="holiday">holiday</label><br /> <input class="group-1" type="radio" name="design" value="birthday_design_1" id="1" checked /> <label class="group-1" for="1"><img src="images/birthday_design_1.jpg" border="0" width="150" height="200" /></label> <input class="group-1" type="radio" name="design" value="birthday_design_2" id="2" /> <label class="group-1" for="2"><img src="images/birthday_design_1.jpg" border="0" width="150" height="200" /></label> <input class="group-2" type="radio" name="design" value="anniversary_design_1" id="3" checked /> <label class="group-2" for="3"><img src="images/anniversary_design_1.jpg" border="0" width="150" height="200" /></label> <input class="group-2" type="radio" name="design" value="anniversary_design_2" id="4" /> <label class="group-2" for="4"><img src="images/anniversary_design_1.jpg" border="0" width="150" height="200" /></label> <input class="group-3" type="radio" name="design" value="holiday_design_1" id="5" checked /> <label class="group-3" for="5"><img src="images/holiday_design_1.jpg" border="0" width="150" height="200" /></label> <input class="group-3" type="radio" name="design" value="holiday_design_2" id="6" /> <label class="group-3" for="6"><img src="images/holiday_design_1.jpg" border="0" width="150" height="200" /></label>

css:

.group-1, .group-2, .group-3 { display: none; }

and javascript:

$(document).ready(function () { $('.event_radio').click(function () { $radio = $(this); $('.group-1, .group-2, .group3').fadeout('fast'); $('.'+$radio.attr('group_class')).fadein('fast'); }); });

php jquery html forms

ssis - Can we have the mapping for OleDB Source to Excel Destination at runtime rather than at design time? -



ssis - Can we have the mapping for OleDB Source to Excel Destination at runtime rather than at design time? -

i trying create ssis bundle export csv info excel file. bundle called c# giving csv file input package. quite new ssis , i've been able produce expected result same headers.

i went next approach -

script task - created scripts csv headers create temp table, mass insert, excel table scripts. execute sql task - created temp table in database execute sql task - mass insert csv info table execute sql task - create excel file data flow task - oledb source excel destination execute sql task - drop temp table created

the challenge facing csv may have different headers (both text , number of headers may different). , want single bundle serve purpose.

with headers beingness different, mapping between oledb souce excel destination in step 5 above not working dynamic headers , giving unexpected results in excel output. there way these mappings can decided @ runtime , not @ design time.

i don't believe can specify columns or column mappings of info flow @ ssis runtime. build ssis bundle on-the-fly, allow c# code create column mappings, mappings have created before bundle can run. see building packages programmatically in msdn details.

on other hand, if you're trying convert csv file excel spreadsheet, seem logical me utilize workbook.saveas method of office object model.

ssis

cannot load info library for opencv android -



cannot load info library for opencv android -

after getting openv android git , compiling , tried run 3rd tutorial , problem getting opencv drror : cannot load info library opencv

02-18 12:04:26.959: w/system.err(9329): java.lang.unsatisfiedlinkerror: couldn't load opencv_java: findlibrary returned null 02-18 12:04:26.959: w/system.err(9329): @ java.lang.runtime.loadlibrary(runtime.java:365) 02-18 12:04:26.959: w/system.err(9329): @ java.lang.system.loadlibrary(system.java:535) 02-18 12:04:26.959: w/system.err(9329): @ org.opencv.android.statichelper.loadlibrary(statichelper.java:54) 02-18 12:04:26.959: w/system.err(9329): @ org.opencv.android.statichelper.initopencvlibs(statichelper.java:85) 02-18 12:04:26.964: w/system.err(9329): @ org.opencv.android.statichelper.initopencv(statichelper.java:29) 02-18 12:04:26.964: w/system.err(9329): @ org.opencv.android.opencvloader.initdebug(opencvloader.java:26) 02-18 12:04:26.964: w/system.err(9329): @ org.opencv.samples.tutorial3.sample3native.<clinit>(sample3native.java:27) 02-18 12:04:26.964: w/system.err(9329): @ java.lang.class.newinstanceimpl(native method) 02-18 12:04:26.964: w/system.err(9329): @ java.lang.class.newinstance(class.java:1319) 02-18 12:04:26.964: w/system.err(9329): @ android.app.instrumentation.newactivity(instrumentation.java:1068) 02-18 12:04:26.964: w/system.err(9329): @ android.app.activitythread.performlaunchactivity(activitythread.java:2015) 02-18 12:04:26.964: w/system.err(9329): @ android.app.activitythread.handlelaunchactivity(activitythread.java:2125) 02-18 12:04:26.964: w/system.err(9329): @ android.app.activitythread.access$600(activitythread.java:140) 02-18 12:04:26.964: w/system.err(9329): @ android.app.activitythread$h.handlemessage(activitythread.java:1227) 02-18 12:04:26.964: w/system.err(9329): @ android.os.handler.dispatchmessage(handler.java:99) 02-18 12:04:26.964: w/system.err(9329): @ android.os.looper.loop(looper.java:137) 02-18 12:04:26.964: w/system.err(9329): @ android.app.activitythread.main(activitythread.java:4898) 02-18 12:04:26.964: w/system.err(9329): @ java.lang.reflect.method.invokenative(native method) 02-18 12:04:26.964: w/system.err(9329): @ java.lang.reflect.method.invoke(method.java:511) 02-18 12:04:26.964: w/system.err(9329): @ com.android.internal.os.zygoteinit$methodandargscaller.run(zygoteinit.java:1008) 02-18 12:04:26.964: w/system.err(9329): @ com.android.internal.os.zygoteinit.main(zygoteinit.java:775) 02-18 12:04:26.964: w/system.err(9329): @ dalvik.system.nativestart.main(native method)

but when seek re-create libopencv_java , libopencv_info lib/arm7v deleted automatically eclipse ! libnative cameras ok thought ?

it turned out enabling static linking prevent shared library management , libopencv_java , libopencv_info libs not added output , solve problem load these 2 libs manually .

android opencv

seo - What HTML5 Tag Should be Used for a "Call to Action" Div? -



seo - What HTML5 Tag Should be Used for a "Call to Action" Div? -

i new html5 , wondering html5 tag should used on phone call action div sits in column next main content on home page.

option 1:

<aside> //call action </aside>

option 2:

<article> <section> //call action </section> </article>

the reason inquire because don't see either alternative beingness perfect fit. perhaps missing something. thanks!

my html phone call action:

<section class="box"> <hgroup> <h1 class="side">call now</h1> <h2 class="side">to schedule free pick-up!</h2> <ul class="center"> <li>cleaning</li> <li>repair</li> <li>appraisals</li> </ul> <h3 class="side no-bottom">(781) 729-2213</h3> <h4 class="side no-top no-bottom">ask bob!</h4> </hgroup> <img class="responsive" src="img/satisfaction-guarantee.png" alt="100% satisfaction guarantee"> <p class="side">we guarantee thrilled our services or money back!</p> </section>

this box on right column of 3 column layout. content in big middle column gives summary of company's services. if wanted utilize services, have schedule pick-up, hence phone call action.

does object utilize of html5, or have improve way?

my take best practices new html5 structural elements still beingness worked out, , forgiving nature of new html5 economic scheme means can found conventions create sense application.

in applications, have separate considerations markup reflects the layout of view (that is, template creates overall consistency page page) versus the content itself (usually function or query results receive additional markup before beingness inserted various regions in layout). distinction matters because layout element semantics (like header, footer, , aside) don't help differentiation of content during search since markup repeated page page. particularly favor using semantic distinctions in html5 describe content user searching on. illustration utilize article wrap primary content , nav wrap associated list of links. widget wrappers tied page layout, i'd go convention of template guideline.

whenever have decide on semantic vs generic names, general heuristic is:

if there possible precedent in page template, follow precedent; if element in question new part of page layout (vs content query rendered part in layout) , there no guiding pattern in template already, div fine associating page layout behavior to; if content created dynamically (that is, gets instanced layout @ request time--posts, navigation, widgets), wrap in semantic wrapper best describes item (vs how think should appear) whenever authoring or generating content, utilize semantic html5 markup appropriate within content (hgroup bracket hierarchical headings, section organize chunks within article, etc.). future-proof enrichment search.

according this, div fine wrapper widget unless page template establishes different widget wrapper. also, utilize of heading elements creating large, bold appearance within widget using markup appearance rather semantics. since particular usage appearance-motivated, improve utilize divs or spans css classes can allow specify sizes, spacing, , other adornments needed non-specific text rather having override browser defaults heading elements. i'd save heading elements page heading, widget headings, , headings within primary content part of page. there can seo ranking issues misuse of headings not part of main content.

i hope these ideas help in consideration of html5 markup usage.

seo html5

javascript if statement checking if div is visible not working -



javascript if statement checking if div is visible not working -

i cannot life of me figure out why if statement not working.

the retrieveinfo function passed event, code, , target div seen here:

onmouseover="return retreiveinfo(event, 'm003', 'target')"

i must utilize code provided much possible school assignment.

function retreiveinfo(e, moviecode, div) { if(e.pagex) { this.x = e.pagex; } else { this.x = e.clientx; } if(e.pagey) { this.y = e.pagey; } else { this.y = e.clienty; } div = document.getelementbyid(div); if(div.style.visibility == "visible") { console.log("more good"); } else if(div.style.visibility == "hidden"){ console.log("hidden"); } }

checking "style" object works if html markup included "style" attribute, or if it's been modified elsewhere code. if there's css making object's "visibility" property "hidden", won't able tell method.

there other ways objects not visible well:

display: none position: absolute; left: -10000px;

etc. element can within element that's hidden well. thus, determining whether particular element in dom visible not simple task :-)

now, if code elsewhere like:

document.getelementbyid(whatever).style.visibility = "hidden";

then code should work fine.

javascript

python - Share model code files between client and server -



python - Share model code files between client and server -

i'm developing 2 python flask apps: 1 api server, tied database through flask-sqlalchemy, , other 1 databaseless web frontend, between user , api server.

i'd reuse model code, example, if define "house" object in apiserver, reuse same code define same object in frontend server.

what i'm trying accomplish is, let's add together property "number of windows" "house" object, 1 time , have alter in database model, json code interchanged between apiserver , webfrontend , output of webfrontend.

some possible approachs come mind are:

somewhat automatically derive sqlalchemy database model initial shared model. use as-it-is sqlalchemy model in nondatabase code, can utilize objects if there no database behind.

has tried of approachs ? ideas ?

python python-2.7 sqlalchemy flask-sqlalchemy