Posts

Showing posts from August, 2013

How do I build from the trunk of the jsoup github project? -

i've realised java project i'm working on affected bug: jsoup google groups i don't think sort of question suitable posting in group discussion , don't want sit , wait next release kind enough explain implementing fix asap entail? how 1 build trunk of project? just clear, looking end patched version of jsoup .jar inclusion in project. thanks always! the reply got on #git irc : jsoup github download link you can either use git archive repository, or use github's download functionality. after need compile jar source there. if choose use github, when click download pick either of .tar.gz or .zip buttons next "branch: master" lesson learnt: try irc first!

PostgreSQL foreign key not existing, issue of inheritance? -

i struggling foreign keys in db, possibly has inheritance? here's basic setup: -- table address create table address ( pk_address serial not null, fk_gadmid_0 integer not null, -- table exists, no problem here street character varying(100), zip character varying(10), city character varying(50), public boolean, constraint address_primarykey primary key (pk_address), constraint gadmid_0_primarykey foreign key (fk_gadmid_0) references adm0 (gadmid_0) match simple on update cascade on delete no action ) ( oids=false ); alter table address owner postgres; -- table stakeholder (parent) create table stakeholder ( pk_stakeholder integer default nextval('common_stakeholder_seq') not null, fk_stakeholder_type integer not null, -- table exists, no problem here name character varying(255) not null, constraint stakeholder_primarykey primary key (pk_stakeholder), constraint stakeholder_fk_stakeholder_type foreign key (fk_stakeho

android - "Token expired" Obtaining Google Auth Token -

i'm getting following error when trying google auth token using accountmanagerfuture<bundle> amf = am.getauthtoken( accounts[0], "finance", null, activity[0], null, null ); try { auth_token = amf.getresult().getstring("authtoken"); log.v("portfolio", "getting token...: "+auth_token); } catch (exception e) { e.printstacktrace(); } i valid-looking token, when try , use it, "token expired" error back: v/portfolio(11970): <html> v/portfolio(11970): <head> v/portfolio(11970): <title>token expired</title> v/portfolio(11970): </head> v/portfolio(11970): <body bgcolor="#ffffff" text="#000000"> v/portfolio(11970): <h1>token expired</h1> v/portfolio(11970): <h2>error 401</h2> v/portfolio(11970): </body> v/portfolio(11970): </html> along with: w/defaultrequestdirector(11970): authentication error: unable respond of t

python - django how to use AUTH_PROFILE_MODULE with multiple profiles? -

assuming have different profiles different user types - staff, teacher,students: how specify auth_profile_module in order appropriate profile get_profile ? there no way use generic key. from django.contrib.contenttypes import generic django.contrib.contenttypes.models import contenttype class userprofileone(models.model): pass class userprofiletwo(models.model): pass class userprofile(models.model): content_type = models.foreignkey(contenttype) object_id = models.positiveintegerfield(db_index=true) content_object = generic.genericforeignkey('content_type', 'object_id') example: userprofile.objects.create(content_object=any_profile_instance) user(pk=1).get_profile().content_object.some_special_field if provide more infos, when might possible find better solution :)

jQuery Multiple Draggable Object Creation -

this complicated problem me. here want: i have designed div draggable , 1 instance on page ready dragging. when user drags it, want dynamically create new instance of it. should able remove click of button should accessable. can point me out right path this? here have far: $(document).ready(function() { $('#dragthis').resizable({ stop: function(event, ui) { var w = $(this).width(); var h = $(this).height(); var tr = $('#contentdiv'); tr.each(function() { //alert( fields[$(this).index()] ) $(this).height(h - 45); }); console.log('stopevent fired') console.log('width:' + w); console.log('height:' + h) } }).draggable( { containment: $('body'

python - Checking if x>y without if statement -

in python, possible check whether x>y without using if statement? there variety of ways go this: print "yes" if x > y else "no" or: print ["no", "yes"][x > y] or: print x > y , "yes" or "no" (at least, mind-reading powers think you're doing)

c++ - When a boost::shared_ptr might not be freed? -

afer reading topic c++ interview preparation (matt's answer) i've got question boost::shared_ptr. possible shared_ptr leak memory? how? shared_ptr uses reference counts, , means circular references can cause leaks. concretely: struct { shared_ptr<a> other; }; shared_ptr<a> foo() { shared_ptr<a> one(new a); shared_ptr<a> two(new a); one->other = two; two->other = one; return one; } the data structure returned foo never deallocated without manual intervention (set either of other pointers null). now fact every programmer should know; more interesting interview conversation it. options include: redesigning data structure pointer cycles not necessary; demoting @ least 1 pointer in every cycle non-owning reference (a bare pointer or weak_ptr ); a dedicated cycle collector ; as last resort, manually nulling out pointers @ appropriate points (this breaks exception safety).

tsql - Write out to text file using T-SQL -

i creating basic data transfer task using tsql retrieving records 1 database more recent given datetime value, , loading them database. happen periodically throughout day. it's such small task ssis seems overkill - want use scheduled task runs .sql file. where need guidance need persist datetime last run of task, use filter records next time task runs. initial thought store datetime in text file, , update (overwrite) part of task each time runs. i can read file in without problems using t-sql, writing out has got me stuck. i've seen plenty of examples make use of dynamically-built bcp command, executed using xp_cmdshell. trouble is, security on server i'm deploying precludes use of xp_cmdshell. so, question is, there other ways write datetime value file using tsql, or should thinking different approach? edit: happy corrected ssis being "overkill"... you can build small app or cmd file wraps start of sql script scheduler. in app can store dat

ruby - Rails 3: User Created custom forms? -

i trying wrap head around how allow user create custom forms field types. if there gem great, cannot seem find 1 anywhere. so have db setup which: t.integer :form_id t.string :name t.string :hint t.integer :position t.string :field_type t.boolean :required t.integer :size t.boolean :multiple t.text :values t.timestamps and pretty am. cant think of how iterate thru field_type , return values, associate them forms being filled out. thanks i assume have kind of form model, , kind of field model, , form has_many :fields . correct? building form quite straightforward: retrieve form, iterate on fields, , depending on type, render correct code. if use formtastic or simple_form code pretty straightforward. but make work, inside controller have create dummy object, has getter , setter fields. use simple hash this, or openstruct (better). while iterating on fields set hash empty or default values. i think want save results of form? think easie

c# - Facebook SDK FQL: Getting profile URL? -

i using fql facebook , querying user table profile_url string facebook_info = convert.tostring(facebookappextensions.query(app, "**select profile_url user uid=" + facebook_id**)); facebook_info = facebook_info.substring(17); char[] charstotrim1 = { '}', ']', ' ', '"' }; facebook_info = facebook_info.trimend(charstotrim1); the problem users url works while other users, facebook says "unknown" page, bug? thanks behrouz no need query: http://www.facebook.com/profile.php?id=uid

sql - LOAD DATA INFILE (*.csv) - ignore empty cells -

i'm import large (500 mb) *.csv file mysql database. i'm far that: load data infile '<file>' replace table <table-name> fields terminated ';' optionally enclosed '"' ignore 1 lines ( #header <column-name1>, <column-name2>, ... ); i have problem 1 of coluns (it's data type int) - error message: error code: 1366 incorrect integer value: ' ' column @ row i looked @ line in *.csv-file. cell causes error has whitespace inside (like this: ...; ;...). how can tell sql ignore whitespaces in column? as *.csv-file big , have import bigger ones afterwards, i'd avoid editing *.csv-file; i'm looking sql-solution. thank you! [edit] solution is: load data infile '<file>' replace table <table-name> fields terminated ';' optionally enclosed '"' ignore 1 lines ( #h

Dynamically add facebook like button using jquery -

how can dynamically add facebook button using jquery? i'm planning have gallery , want add add buttons under every image? i've tried doesn't render anything: $('.share_button').append("(fb:like layout='button_count' font='tahoma')(/fb:like)") share_button classname of div tag contain button. thanks in advance, ivan first of all, should be: $('.share_button').append("<fb:like layout='button_count' font='tahoma'></fb:like>") then, should add line: fb.xfbml.parse($('.share_button').get(0)); however, suggest use id instead of class, or codes above parse nodes containing class .share_button .

Will Visual Studio 2010 SP1 (beta) break asp.net MVC 3 (RTM)? -

i've got vs 2010 (no service pack) , asp.net mvc 3 installed. try out vs2010 sp1 beta afraid break mvc 3 projects. does know if can install sp1 beta right on top of mvc 3 rtm? it looks being discussed here: installation of visual studio 2010 service pack 1 beta , asp.net mvc 3

Android application that display the notification for any application start or Stop. I want code for it -

my code broadcast recevier broadcastreceiver allapp = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { if (intent.getaction().equalsignorecase(intent.action_all_apps)){ log.i("appname", "changes in applications"); } } }; hi below sample code getting application has been started(user using) activitymanager = (activitymanager) getsystemservice(context.activity_service); list runningtask = .getrunningtasks(4); activitymanager.runningtaskinfo ar = runningtask.get(0); activitymanager.runningtaskinfo br = runningtask.get(1); ar.topactivity.tostring(); classname = ar.topactivity.getclassname().tostring(); packagename = ar.topactivity.getpackagename().tostring(); put code in timestask , package name , class name used user. activitymanager.runningtaskinfo br = runningtask.get(1)

android textview links clickable using Html.fromHtml -

i have textview in app. have string set in textview. string html string has lots of html images, bold , italics. used code follows: content.settext(html.fromhtml(articledet.tostring(), imggetter, null)); i want links should click-able. achieved easily. want when user clicks on link, link should opened in browser want track external links clicked. i.e. on click of link, should able write url in file. can using spanned. if used spanned then, have load images, stop working. please me this.

jquery .live('click') vs .click() -

i wondering whether there circumstances better use .click(function {...}); rather .live('click', function {...}); ? from gather live option seems better option , hence using in circumstances instead of plain .click(), given lot of code loaded asynchronously. edit: part question. if i'm asynchoronously loading javascript in, .click still pickup elements in dom. right? there might times when explicitly want assign click handler objects exist, , handle new objects differently. more commonly, live doesn't work. doesn't work chained jquery statements such as: $(this).children().live('click',dosomething); it needs selector work because of way events bubble dom tree. edit: upvoted this, people still looking @ it. should point out live , bind both deprecated . can perform both .on() , imo clearer syntax. replace bind : $(selector).on('click', function () { ... }); and replace live : $(document).on('click', selecto

Vi: Search for lines containing string1 as well as string2 -

i know how search single expression. how combine two? /string1 & string2 you'd use .*string1\&.*string2 http://vim.wikia.com/wiki/search_patterns has many tips, @ least vim.

php - Click name from one mysql table to show report from another table -

i have table following fields: email - name - username - userid data in table pulled html table. in seperate table have user's data / information. what click on name first table (consisting of email - name - username) and have users information shown on own report generation. both tables have same unique userid's applied enlighten me best way this? thanks. surround name anchor tag has id parameter. i'd 2 templates 1 lists users (userlist.php) , other 1 shows detailed information user (userinformation.php). userlist.php: <table> <tr> <th> <a href="userinformation.php?id=<?php echo $user->id;?>"> <?php echo $user->username;?> </a> </th> <td><?php echo $user->email;?></td> <td><?php echo $user->propn;?></td> </tr> ... ... </table> userinformati

c# - Event parameter; "sender as Object", or "sender as T"? -

when write public events business objects, i've adapted habit of passing instance " sender object ", in addition additional specific parameters. asked myself why not specifying class ? so more experience; do ever pass distinct class sender in event ? , if so, decision criteria when ok/not ok? don't extreme. eventhandler(object sender, eventargs e) has object sender can use in many circumstances. doesn't mean strongly-typed sender evil. strongly-typed sender useful when delegate not going used(like eventhandler ) e.g. public delegate void savehandler(controller sender, eventargs e); now other developers(or using library) can recogonize sender have to controller , , glad not code this: public void mysavehandler(object sender, eventargs arg) { var controller = sender controller; if (controller != null) { //do } else { //throw exception @ runtime? //it can avoided if sender strongly-typed } } and can

php - Can't connect to mongoDB with lithium -

i have uncomented mongodb connection in bootstrap/connections.php , seems ok i'm getting following error: ( ! ) fatal error: uncaught exception 'lithium\core\networkexception' message 'could not connect database.' in c:\wamp\www\libraries\lithium\data\source\mongodb.php on line 792 ( ! ) lithium\core\networkexception: not connect database. in c:\wamp\www\libraries\lithium\data\source\mongodb.php on line 792 call stack # time memory function location 1 0.0004 370296 {main}( ) ..\index.php:0 2 0.0328 2618640 lithium\action\dispatcher::run( ) ..\index.php:36 3 0.0328 2619848 lithium\core\staticobject::_filter( ) ..\dispatcher.php:122 4 0.0329 2621472 lithium\util\collection\filters::run( ) ..\staticobject.php:128 5 0.0330 2623800 {closure}( ) ..\filters.php:182 6 0.0397 2692456 lithium\util\collection\filters->next( ) ..\cache.php:47 7 0.0397 2692488 {closure}( ) ..\filters.p

php - How can I put the link to fan page on canvas page? -

i want add link fan page on canvas page. put html code below. <a href="*******">go fanpage</a> i clicked link on canvas page, screen shows facebook logo instead of shows fan page. anyway clicked facebook logo, move fan page. how can make move fan page directly? you need break out of iframe specifying target: <a href="*******" target="_top">go fanpage</a>

javascript - how to use node.js module system on the clientside -

i use commonjs module system in clientside javascript application. chose nodejs implementation can't find tutorial or docs on how use nodejs clientside, ie without using node application.js i included node.js in html page: <script type="text/javascript" src="node.js"></script> note didn't make nodejs on local machine, i'm on windows anyway (i'm aware of cygwin option). when want use require function in own javascript says it's undefined. var logger = require('./logger'); my question is, possible use nodejs this? node.js serverside application run javascript on server. want use require function on client. your best bet write require method or use of other implementations use different syntax requirejs . having done bit of research seems no-one has written require module using commonjs syntax client. end writing own in near future, recommend same. [edit] one important side effect require func

delphi - "old format or invalid type library" -

we have application that, amongst many other things, has export excel function. uses excel com interface , exports data new sheet in excel , formats came from. years known if machine locale set different office installed under "old format or invalid type library" arise. however, under excel 2003 possible download , install mui (multi-language user interface) pack fix problem. excel 2007 , later there not seem equivalent pack - there language packs (we downloaded 7gb pack msdn office 2007) these either don't work (setup.exe "corrupted"), or don't work in sense still "old format or invalid type library" problem. does know if there pack office 2007 , office 2010 solve problem, , from? alternatively, there ms link ( http://support.microsoft.com/default.aspx?scid=kb;en-us;q320369 ) shows code (in vb.net think) purportedly sets culture temporarily "en-us" before doing stuff in excel, sets back. sceptical solution because seems assume o

serialization - Howto jquery Serialize formvalue -

collecting data formfields append post script. var datastring = 'name='+ name + '&company_name='+ company_name + '&adres='+ adres + '&zip='+ zip + '&city='+ city + '&email=' + email + '&phone=' + phone + '&message=' + message + '&imgs=' ; but last value imgs can multiple values added trough ajax upload script , generated dynamicly created hidden form field, dont know how pass hidden form vars datastring, can me out here? //add uploaded file list if(response==="success"){ $('<li></li>').appendto('#files').html('<input name="image" class="img" type="hidden" value="mailatt/'+file+'" /><img src="mailatt/'+file+'" alt="" width="300" /><br /><p>'+file+'</p>').addclass('suc

java - Update Table GUI that extends custom AbstractTableModel -

i created java gui displays table using following syntax: table = new jtable(new mytablemodel(columnnames, updatetable(cmbadversary.getselecteditem().tostring(), cmbdatatype.getselecteditem().tostring()))); where columnnames vector of strings cmbadversary , smbdatatype selection od combo boxes. and updatetable method returns vector of vectors depending on combo box selection follows: static vector updatetable(string filterval1 , string filterval2) { try { myvector = tssc.testseverityfunctionservice(filterval1,filterval2); } catch (exception e) { e.printstacktrace();} return myvector; } this how custom class mytablemodel extends abstracttablemodel looks like: class mytablemodel extends abstracttablemodel { vector columnnames = new vector(); vector fdb = new vector(); public mytablemodel(vector cname,vector rname){ this.columnnames = cname; this.fdb = rna

jquery - JavaScript treeviews with knockout.js -

i've been using knockout.js in latest web-app, , it's great. however, need implement treeview, , current contenders here: http://www.programmingsolution.net/useful-js/jquery-treeview.php jstree 1 under current development, seems require initialised html or json - under knockout, ideally have ul list built automatically, , treeview automatically update after that. "treeview" 1 seems able use existing ul list, has been deprecated has else had experience of using treeview knockout? turns out 1 does: http://bassistance.de/jquery-plugins/jquery-plugin-treeview/ so far, anyway. hope of use else

c# - Multiple anonymous event handlers - but only last one is called -

i have following code use simulate live data feed simultaneously sends message each object of type "symbol" in collection inside "portfolio.symbols" should respond (by method doing work on it). in order true simultaneously, try register anonymous event handlers following way: static public void registerevents() { foreach (symbol symbol in portfolio.symbols) { generatequoterequest += () => { somemethod(symbol); }; } } static public void run() { ongeneratequoterequest(); thread.sleep(100); } public delegate void ongeneratequoterequesteventhandler(); public static event ongeneratequoterequesteventhandler generatequoterequest = delegate {}; ... i try raise event, hoping number of "somemethod" instances firing up. unfortunately, last "symbol" added called. what missing here? the infamous captured-variable/foreach glitch; try: foreach (symbol symbol in p

regex - Help decoding a regular expression for use with Google Analytics -

Image
update i missed in original explanation. set yesterday, , ran on night. no data populated in profile overnight. so, either regex wrong, or google cannot see internal traffic ips. it seems has own variation on syntax regular expressions. i'm trying include internal traffic on 1 of profiles in google analytics can verify me expect regular expression match? in cider notation? i don't know cider notation is, regex matches string that starts 10. followed 90. or 60. followed 10 or 9 followed 0 or more dots. you want ^10\.[96]0\.(10|9)\..*$ since last bit ( .* ) bit vague (unless know there ever valid ip addresses in live data), might want change \d+ or (if want restrict valid range 0 255) 25[0-5]|2[0-4]\d|1?\d?\d

Stop SQL Reporting Server Hijacking /Reports -

how stop sql server reporting services hijacking /reports virtual folder on websites on server it's installed on. have discovered websites on box reporting server on (its dev box), have /reports overridden reporting services manager. how turn off? have tried stopping service, disabling in config file, no avail (the service still hijacking url, "service unavailable" error instead of report manager). short of uninstalling reporting services, there way switch off? i had exact same problem - annoying when own web application uses /reports folder, couldn't understand why getting "file or directory not found" errors on iis when navigating reports page. phil correct easiest solution (using sql server 2008 r2) run reporting services configuration manager, connect local instance , change virtual directory under "report manager url" more unique (i used "/reportingservices"). this fixed problem , /reports folder restored own web a

c# - What is better: int.TryParse or try { int.Parse() } catch -

i know.. know... performance not main concern here, curiosity, better? bool parsed = int.tryparse(string, out num); if (parsed) ... or try { int.parse(string); } catch () { something... } better highly subjective. instance, prefer int.tryparse , since don't care why parsing fails, if fails. however, int.parse can (according documentation ) throw 3 different exceptions: the input null the input not in valid format the input contains number procudes overflow if care why fails, int.parse better choice. as always, context king.

css - Google CSE Stylesheet -

Image
i have created search engine website using google webmaster tools. i'd customise format of results given cse. google offers me download css file in whole, when attach php document inside head section, nothing happens - custom style doesn't work. when put google's style inside body tag, worked normally. problem way isn't according rules of world wide web consortium, plus code gets "dirty" , untidy if insert such long css code inside body of page. how can make external style sheet change default appearance of search engine? were able figure out if external css stylesheet can used custom google search box? this i've done today, , validates in w3c validator: check out link: a homepage google custom search , external stylesheet. if view source, can see downloaded google custom search's "source css" link on "get code" page. uploaded website's server (after changing css liking). then took script portions of c

Beginner Javascript: jQuery 'toggle' problem -

hi all, i'm veritable js beginner , i've been using simple bits of jquery give me effects want. has been going until tried implement jquery toggle effect. want code apply multiple elements , i'm trying slim down , make generic rather writing line each toggle tab. i can't seem work! head w/ javascript: <head> <title>my title</title> <link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.3.0/build/cssreset/reset-min.css" /> <link rel="stylesheet" type="text/css" href="style.css" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $('#content div[id^=toggle]').hide(); $('[class^=info]').click(function() { var x = $(this).attr("idname");

winforms - C# FilePath Help -

i use openfiledialog search specific file. when user chooses file, want store path in variable. however, these doesn't seem option within openfiledialog? does know how this? thanks. edit: winforms, , don't want save path inclusive of filename, location file is. this retrieve path based on filename property of openfiledialog . string path = system.io.path.getdirectoryname(openfiledialog.filename);

nservicebus - The destination queue '<QueueName>@<servername>' could not be found -

while testing pub/sub model, changed name of subscriber queue, while subscription old queue still exists in db, there dangling subscription in db. so when publisher , subscriber started , tried send message publisher, following exception happened , publisher stopped , no longer send more message 2011-02-09 09:56:21,115 [6] error publisher.serverendpoint [(null)] <(null)> - problem occurred when starting endpoint. system.configuration.configurationerrorsexception: destination queue 'storeinputqueue@' not found. may have misconfigured destination kind of message (message.eventmessage) in messageendpointmappings of unicastbusconfig section in configuration file.it may case given queue hasn't been created yet, or has been deleted. ---> system.messaging.messagequeueexception: queue not exist or not have sufficient permissions perform operation. @ system.messaging.messagequeue.mqcacheableinfo.get_writehandle() @ system.messaging.messagequeue.stalesafesendme

c# - silverlight 4 - fastest/simplest way of scheduling work on the UI thread? -

ui tree: listbox april 2010 toolkit's listboxdragdroptarget listbox item template includes control has a couple of buttons the click handler in question in 1 of buttons (and therefore part of actual listboxitem in ui, potential drag-drop operation) the overall listbox item should able drag (to rearrange within listbox, or move listbox), goal keep click handlers on these buttons triggering drag currently click handler on 1 of buttons (see above) appears take long enough (it bunch of updates viewmodel, cause various other ui changes, needs on ui thread afaict) causes drag event start. the first thought on getting code out of click handler create backgroundworker no dowork , put in runworkercompleted. however, feels both abuse of backgroundworker , kind of heavyweight. effect want akin postthreadmessage on same thread (the ui thread) i'm not seeing jump out @ me how quickly. i queue threadpool or new thread , have marshal on ui thread, again seems quite abuse.

Tool to combine multiple javascript files into one... -

is there tool can combine multiple javascript files 1 , compress them? for php, try minify: http://code.google.com/p/minify/ from docs: minify php5 app helps follow several of yahoo!'s rules high performance web sites. it combines multiple css or javascript files, removes unnecessary whitespace , comments, , serves them gzip encoding , optimal client-side cache headers.

java - How to set eclipse console locale/language -

Image
when developing web application eclipse (helios) tomcat output being sent console. ok, messages being translated os language. in fact, eclipse in english, tomcat output (logging) being translated portuguese. it's tomcat configuration issue, can't find where... how change behaviour? want entire eclipse in english, including tomcat. go window > preferences > java > installed jres > select preferred jre > edit , add following default vm arguments : -duser.language=en -duser.country=us

Load JQuery into a Chrome extension? -

i'm attempting load jquery chrome extension , make equal object i'm wondering how go this? i'd like... jquery = loadlibraries("jquery-1.4.2.min.js"); how this? edit: i'm injecting content script. you can put jquery.js extension folder , include in manifest: { "name": "my extension", ... "content_scripts": [ { "matches": ["http://www.google.com/*"], "css": ["mystyles.css"], "js": ["jquery.js", "myscript.js"] } ], ... } you don't need worry conflicts jquery on parent page content scripts sandboxed.

javascript - livequery behaving strangely for dynamically added elements -

when use following, see divs static , dynamic 1 one including dynamically added div #xyz jquery('div').livequery(function() { alert($(this).attr("id") + " div added") }) but when use jquery('#xyz').livequery(function() { alert($(this).attr("id") + " div added") }) i nothing. - if xyz in static html, above works. eventually want able click button programmatically when added dynamically. any appreciated. just use jquery.live . attach event handler elements match selector , in future. example $('a.foo').live('click', function() { alert('clicked!'); }); i don't know if can catch event, when new elements added dom, in general want apply behaviour (when event occurs) them anyway.

html - javascript - Order a list item up or down -

Image
a simple example of tryin below . link/button on left move item up, link/button on right move item down. not working, , getting error: object doesnt support property or method at line: items[counter-1] = curr;// move previous item, current example image here code: javascript: <script type="text/javascript"> function moveitem(id, direction) { var ul = document.getelementbyid('groupby'); var items = ul.getelementsbytagname('li'); var counter = 0; var previousitem = null; var movenextitemup = false; (var item in items) { //if current item, 1 moved if (item == id) { if (direction == 1) { // item move down movenextitemup = true; } else if ((direction == -1) || (movenextitemup == true)) { // item move var curr = items[counter]; var prev = items[counter-1]; items[counter-1] = curr;// move previous i

c# - Turning a table "on it's side" in asp.net - how? -

how turn table: +------------+-----------------+ | category + subcategory | +------------+-----------------+ |cat..........+ persian.........| |cat..........+ siamese........| |cat..........+ tabby...........| |dog.........+ poodle..........| |dog.........+ boxer............| +------------+----------------+ on it's side following: +------------+-----------------+ | cat......... + dog............. | +------------+-----------------+ + persian..+ poodle.........+ + siamese + boxer...........+ + burmese + ...................+ +------------+-----------------+ the initial table following mysql query: select c.categoryname, sc.name subcategorydefinition sc join categorydefinition c on sc.categoryid = c.categoryid c.isdeleted = 0 order categoryname, name asc and want display in (probably) gridview. cheers! pivot static in sql. need know in advance columns want in output, if list of categories not fixed, can't use pivot directly. if us

iphone - Core Data NSPredicate with SQLITE store -

this code returns 0 objects not correct. however, when removing predicate, fetch request returns objects. nserror *error = nil; nsentitydescription *entitydescription = [nsentitydescription entityforname:@"person" inmanagedobjectcontext:[self managedobjectcontext]]; nspredicate * pr = [nspredicate predicatewithformat:@"%k beginswith '%@' ", @"fullname", searchtext]; //nspredicate * pr = [nspredicate predicatewithformat:@"personid == %@", searchtext]; works fine nsfetchrequest *request = [[[nsfetchrequest alloc] init] autorelease]; [request setentity:entitydescription]; [request setpredicate:pr]; nsarray * arr = [[self managedobjectcontext] executefetchrequest:request error:&error]; the fullname attribute contains unicode data(arabic). any appreciated. try: nspredicate * pr = [nspredicate predicatewithformat:@"fullname beginswith %@",

c++ - Array Initialization Macro -

i trying come macro following, my_macro(type,name,args...) my_macro(int,_array,1,2,3) and expand to, int _array[] = {1,2,3}; coll* __array = my_call(&array[0],&array[1],&array[2]); is possible with/without compiler specific magic? my_call expects variable number of arguments , not want pass array directly. edit: using accepted answer following question var args, macro returning number of arguments given in c? so can find how many elements in array. you can start (c99, not gcc-specific): #define my_macro(type, name, ...) \ type name[] = {__va_args__}; the my_call part more difficult; there macros online can count number of arguments, need boost.preprocessor (which should work in c) apply my_call consecutive elements of array. how many elements have maximum? might want like: #define count(...) count2(__va_args__, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0) #define count2(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, cou

C# ASP.NET GetType() with WebUserControl issue -

in project have custom webusercontrols form elements (they encapsulate standard validators , other system specific functions). user controls "dropdownlistfield" , "textboxfield". in code behind of page have code: string parametervalue = null; foreach (object control in mymultiview.views[mymultiview.activeviewindex].controls) { if (control.gettype() == typeof(dropdownlistfield)) parametervalue = ((dropdownlistfield)control).value; if (control.gettype() == typeof(textboxfield)) parametervalue = ((textboxfield)control).value; } for reason "if" statements return false when step through code , see "control" getting assigned web user control. code in place in project same except in other location standard .net controls "textbox" , "dropdownlist" used , in other location code works. does know why wouldn't work web user controls? update: hmm in debugging found this: ?control.gettype(); basety

stored procedures - MySQL CREATE TRIGGER, Syntax Error. What I'm doing wrong? -

delimiter || create trigger `monthly_insert` before insert on `history_monthly` each row begin new.`uid` = concat(old.`year`, old.`month`, old.`charactersid`); end; || delimiter ; and returns error: #1064 - have error in sql syntax; check manual corresponds mysql server version right syntax use near '.`uid` = concat(old.`year`, old.`month`, old.`charactersid`); end' @ line 4 it's first time triggers , doing best try find soultion failed ;< you need add word set in line: set new.`uid` = concat(old.`year`, old.`month`, old.`charactersid`); also, commenter pointed out, there no old value in before insert trigger.

c++ - How to byteswap a double? -

i'm trying write byteswap routine c++ program running on win xp. i'm compiling visual studio 2008. i've come with: int byteswap(int v) // { return _byteswap_ulong(v); } double byteswap(double v) // doesn't work values { union { // trick first used in quake2 source believe :d __int64 i; double d; } conv; conv.d = v; conv.i = _byteswap_uint64(conv.i); return conv.d; } and function test: void testit() { double a, b, c; cstring str; (a = -100; < 100; += 0.01) { b = byteswap(a); c = byteswap(b); if (a != c) { str.format("%15.15f %15.15f %15.15f", a, c, - c); } } } getting these numbers not matching: -76.789999999988126 -76.790000000017230 0.000000000029104 -30.499999999987718 -30.499999999994994 0.000000000007276  41.790000000014508  41.790000000029060 -0.000000000014552  90.330000000023560  90.330000000052664 -0.000000000029104 this aft

lucene - PrefixQuery case sensitive? -

i have untokenized field in index file. i'm using prefixquery values. i'm using auto suggesting(when give keyword start suggesting relevant data). for example: field name 'country'. has list of countries values australia, america, india, singapore, south africa, new zealand...( with title case ) when give query string(input) 'a' , not suggesting countries.. instead if give 'a' means suggesting australia, america... how can overcome case problem? wrong this?? your appreciated... thanks perumal s from http://wiki.apache.org/lucene-java/lucenefaq#are_wildcard.2c_prefix.2c_and_fuzzy_queries_case_sensitive.3f are wildcard, prefix, , fuzzy queries case sensitive? no, not default. unlike other types of lucene queries, wildcard, prefix, , fuzzy queries not passed through analyzer, component performs operations such stemming , lowercasing. reason skipping analyzer if searching "dogs*" not want &quo

c++ - const char * const versus const char *? -

i'm running through example programs refamiliarize myself c++ , have run following question. first, here example code: void print_string(const char * the_string) { cout << the_string << endl; } int main () { print_string("what's up?"); } in above code, parameter print_string have instead been const char * const the_string . more correct this? i understand difference 1 pointer constant character, while 1 constant pointer constant character. why both of these work? when relevant? the latter prevents modifying the_string inside print_string . appropriate here, perhaps verbosity put off developer. char* the_string : can change char the_string points, , can modify char @ points. const char* the_string : can change char the_string points, cannot modify char @ points. char* const the_string : cannot change char the_string points, can modify char @ points. const char* const the_string : cannot change char the

algorithm - Maximum Coin Partition -

since standing @ point of sale in supermarket yesterday, once more trying heuristically find optimal partition of coins while trying ignore impatient , nervous queue behind me, i've been pondering underlying algorithmic problem: given coin system values v 1 ,...,v n , limited stock of coins a 1 ,...,a n , sum s need pay. we're looking algorithm calculate partition x 1 ,...,x n (with 0<=x i <=a i ) x 1 *v 1 +x 2 *v 2 +...+x n *v n >= s such sum x 1 +...+x n - r(r) maximized, r change, i.e. r = x 1 *v 1 +x 2 *v 2 +...+x n *v n - s , r(r) number of coins returned cashier. assume cashier has unlimited amount of coins , gives minimal number of coins (by example using greedy-algorithm explained in schoening et al.). need make sure there's no money changing, best solution not give of money (because solution optimal in case). thanks creative input! if understand correctly, variant of subset sum . if assume have 1 of each coin ( a[i] = 1 each i ), sol

html - How to make a file 'download' when clicked in Windows IE -

i have button in form tag generates csv file , prompts download when user clicks it. when try accomplish in ie, ie tries open file ie shouldn't. want download file. my html : <form accept-charset="utf-8" method="post" action="/generate_csv?calc[]total_interest=189.08"> <div style="margin: 0px; padding: 0px; display: inline;"><input name="utf8" value="✓" type="hidden"> <input name="authenticity_token" value="4o1dedofbbdoc3scpnhdaqpptpfm5nittoryqa0au5k=" type="hidden"> </div> <input id="print_csv" name="commit" value="print csv" type="submit"> </form> my rails controller : headers['content-disposition'] = "attachment;" send_data(csv_string, :type => 'text/csv; charset=utf-8; header=present; disposition=attachment', :filename => @filename, :disp

eclipse - Replace Alt+Click Binding Of Mylyn -

is there anyway replace alt+click binding of mylyn in eclipse. use alt+click show or hide files of active task it in conflict operating system's alt+click function. thank you this 1 of annoying issues mylyn. , reason eclipse swt not support bind meta or win key instead of alt-click. so moment option reconfigure window manager.

php - Magento - Checking if an Admin and a Customer are logged in -

i have web server magento 1.4.0.1 installed. have web site shares credential it. i've managed check if customer logged in or not (after having changed cookies location in magento), things got complicated when tried figure out if admin logged in. can proper answer first session asked (either customer or admin, second 1 never logged in). how can have both answers? here code i'm using test out: require_once '../app/mage.php'; umask(0) ; mage::app(); // checking customer session mage::getsingleton('core/session', array('name'=>'frontend') ); $session=mage::getsingleton('customer/session', array('name'=>'frontend') ); if ($session->isloggedin()) { echo "customer logged in"; } else { echo "customer not logged in"; } // checking admin session mage::getsingleton('core/session', array('name'=>'adminhtml') ); $adminsession = mage::getsingleton('admin

declaration - Why doesn't C# let you declare multiple variables using var? -

given following: // not problem int = 2, j = 3; so surprises me this: // compiler error: implicitly-typed local variables cannot have multiple declarators var = 2, j = 3; doesn't compile. maybe there don't understand (which why i'm asking this)? but why wouldn't compiler realize meant: var = 2; var j = 3; which compile. it's point of possible confusion programmer , compiler. for example fine: double = 2, j = 3.4; but mean? var = 2, j = 3.4; with syntactic sugar kind of thing headache no 1 needs--so doubt case ever supported. involves of compiler trying little bit clever.

java - code after socket statement does not execute -

i'm working on project need socket programming, unfortuanatly when use call socket statement , read input stream of socket or write application crash , nothing work, in fact problem code handles action of buttons , other things not work, execution stop @ line calls method create reads input stream of socket. solved problem times ago thread , putting statement works socket inside run method. ui works correctly still not have functionality. here 2 line of calling method conection_manager cm = new conection_manager(jtextfield1.gettext()); jtextarea1.settext(cm.getmessage()); in first line use call method in connection manager class there data on socket read correctly , can see printing data, when in next line want set text area string every thing crash. if makes sense use 2 lines of statement inside jdialog in advance probably blocking waiting written socket. that's why appears crashed, when in fact waiting data. have checked data being written socket? also, se

java - Tomcat Configuration using DBCP -

we getting communicationsexception (from dbcp) after iding while (a few hours). error message (in exception) @ end of question - dont see wait_timeout defined in of configuration files. (where should look? somewhere out of tomcat/conf directory?). secondly, suggested exception, 1 put "connector/j connection property 'autoreconnect=true'"? here resource definition in file conf/context.xml in tomcat set up: <resource name="jdbc/tomcatresourcename" auth="container" type="javax.sql.datasource" maxactive="100" maxidle="30" maxwait="10000" removeabandoned="true" removeabandonedtimeout="60" logabandoned="true" username="xxxx" password="yyyy" driverclassname="com.mysql.jdbc.driver" url="jdbc:mysql://127.0.0.1:3306/dbname?autoreconnect=true"/> thirdly, why jvm wait till call exec

javascript - how to move a div with arrow keys -

i move div arrow keys using jquery. right, left, down , up. found demo of want accomplish here i able move div around in div. how can done? html: <div id="pane"> <div id="box"></div> </div> css: #pane { position:relative; width:300px; height:300px; border:2px solid red; } #box { position:absolute; top:140px; left:140px; width:20px; height:20px; background-color:black; } javascript: var pane = $('#pane'), box = $('#box'), w = pane.width() - box.width(), d = {}, x = 3; function newv(v,a,b) { var n = parseint(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0); return n < 0 ? 0 : n > w ? w : n; } $(window).keydown(function(e) { d[e.which] = true; }); $(window).keyup(function(e) { d[e.which] = false; }); setinterval(function() { box.css({ left: function(i,v) { return newv(v, 37, 39); }, top: function(i,v) { return newv(v,

php - centre text between 2 coords -

i trying centre line of text, of known width along line specified start , end coordinates. the purpose write text around polygon, lines not horizontal. currently have following function takes start x , y , finish x , y of line , width of text (in pixels). the text drawn starting @ x1, y1 @ correct angle follow line. to centre text on line have tried calculate left padding in pixels should applied x1, y1 move text correct amount left origin. the following function attempt @ modifying coordinates implement above concept. not quite right. end text off line, x out y, depends on face neither x or y correct. private function centertextonline(&$x1, &$y1, &$x2, &$y2, $width) { $distance = $this->getdistance($x1, $y1, $x2, $y2); //calculate left padding required in pixels $padding = ($distance - $width) / 2; //what factor need alter x1, y1 by? $factor = ($distance / $padding); $gradient = ($y2-$y1)/($x2-$x1); //gradient a

ibm midrange - To function or not to function, that is the question at hand -

i working on sql statements asp.net application. 1 of things required display information in open period. period updated automatically vendor software previous period closed. finding myself doing bunch of sub selects like: where date >= (select date(concat('20', concat(yy, concat('-', concat( mm, (concat('-', dd))))))) lib/file') yes, each portion of date in separate fields. would making query function make query more efficient? have never created function before how that? thought having like: isinrange(date) so can where isinrange(date) . or there better way? create function todate(yy char(2), mm char(2), dd char(2)) returns date return date('20' || '-' || yy || '-' || mm || '-' || dd) select * table date <= todate(yy, mm, dd)

c# - Constraining windows wpf -

i have window needs constrained within window. in order this, hook sizechanged event on top level window....and in event need adjust second window aligned nearest edge if there intersection between 2 i.e if smaller window gets outside boundary of bigger window. lot of math calculation this...and im still not near solution! im having trouble doing because involves lot of messy code wondering if of guys had easier solution this? basically im dealing 2 rectangles , need ensure when size of bigger rectangle changes...if there intersection between two, smaller rectangle should align edge of bigger rectangle smaller rectangle within bigger rectangle. could simple math problem in c# forms? any suggestions welcome thanks! for both windows need x , y coordinates of location of window in systemcoordinates. how in wpf can found here http://blogs.msdn.com/b/llobo/archive/2006/05/02/code-for-getting-screen-relative-position-in-wpf.aspx next need have 2 windows react on each

mysql - How to use $_GET to get multiple parameters using the same name in PHP -

i'm starting php bare me.. i'm using checkboxes search mysql database have created. checkboxes use same name, when use $_get, gets last value in url. for example: http://www.website.com/search.php?features=textures&features=items&style=realistic&submit=search would return items, , override textures. is there way store both values, , use these values search database? thanks in advance! php little odd here. using standard form data parser, must end name of controls [] in order access more 1 of them. <input type="checkbox" name="foo[]" value="bar"> <input type="checkbox" name="foo[]" value="bar"> <input type="checkbox" name="foo[]" value="bar"> will available array in: $_get['foo'][] if don't want rename fields, need access raw data ( $_server['request_uri'] ) , parse (not i'd recommend).

android - Tween animation on a Canvas in a custom View -

i have class extends view , , draw need inside canvas in ondraw() method, this: protected void ondraw(canvas canvas) { synchronized (this) { float h = mheight; float w = mwidth; canvas.drawcolor(color.white); float roadline= (85.0f/100.0f)*h; canvas.drawbitmap(mtop, 0, roadline-mtop.getheight(), null); //this i'd animate canvas.drawbitmap(msmoke); } } how make animation (tween animation) draw in here? you can't draw imageview inside ondraw() method of class. this more you're after. public class simpleanimation extends activity { sprite sprite; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); sprite = new sprite(this); setcontentview(sprite); } class sprite extends imageview { bitmap bitmap; paint paint; rotateanimation rotate; alphaan