Posts

Showing posts from April, 2010

I want to create game using OpenGL ES for iphone -

i want use opengl es games of iphone3 , iphone4 don't know start ,please me. please go through book- http://iphone-3d-programming.labs.oreilly.com/ch01.html

Interacting with events and listeners in MATLAB -

i want write gui code orthogonal. lets have circle class , square class , need interact. right now, circle , square talking each other - circle object sends message square object, use square_obj.listen_for_circle(circle_obj) listen_for_circle method implements addlistener. this problem me since 2 objects linked - , removing 1 object code break it. looking circle_obj able broadcast global message 'circle_event' . additionally square_obj listening global message broadcasts of type 'circle_event' , , upon hearing event - action.(ahhh, objects have no links each other in code base!) is possible or reasonable in matlab? (or maybe i'm going crazy). always, advice appreciated. i'm not sure why addlistener problematic you. adds event listener doesn't if event-origin object (the circle) deleted. alternately can use event.listener or handle.listener . undocumented work well, , used within matlab codebase (m-files). see explanation here: http://u

objective c - Why release a property that you've already set to nil? -

here 2 methods in view controller apple tutorial: - (void)viewdidunload { self.eventsarray = nil; self.locationmanager = nil; self.addbutton = nil; } - (void)dealloc { [managedobjectcontext release]; [eventsarray release]; [locationmanager release]; [addbutton release]; [super dealloc]; } couldn't dealloc method shortened following? if not, why not? - (void)dealloc { [managedobjectcontext release]; [super dealloc]; } - (void)viewdidunload not guaranteed called, should release things in dealloc too. see this question find out when it's called, , should when is.

.net - Sharepoint 2010 SPListTemplate how to get list of fields? -

i need fields list template? how can this? var web = site.openweb(); var template = web.listtemplates["sometemplate"]; template ... ???? -there no method fields. there no built-in method fields list template. way can fields parsing schema xml of list , getting <field> , <fieldref> tags. easier create list instance, can query later on following examples. to fields list can use splist.fields property, e.g. so: foreach (spfield spfield in mylist.fields) { //your code here } msdn splistitem.fields you can fields list item "in reverse" splistitem.fields property . might interested in thread: check if list column exists using sharepoint client object model?

xmlhttprequest - How can Node.js detect browser side has ended one HTTP session? -

i'm trying implement comet (xhr streaming) node.js. since, xhr streaming make client side xhr.responsetext keep growing, necessary client side close current xhr , restart xhr streaming again. in server side, each xhr streaming, http.serverresponse object should held until http session over. the problem is: how can node.js detect browser side has ended 1 http session? i thought, ideally, there 1 callback argument http.serverresponse.write. writing closed http session trigger callback , let know aborted. but, there no such callback argument. i think http://socket.io/ need client.on('disconnect', function(){ … })

How to fetch data from different sources on the internet with Rails 3? -

i coding application want fetch megavideo, spike,live video, youtube ,facebook, etc......so how can solve there method in rails 3 ? i looked everywhere on net solution seems confusing me. know of good, simple gem can use remote apis? simple in php. thankful input! there many youtube : https://github.com/kylejginavan/youtube_it facebook : http://facebooker.rubyforge.org/ , http://rfacebook.rubyforge.org/ google : http://code.google.com/apis/gdata/articles/gdata_on_rails.html

c# - Where should I edit BaseModelView (in BaseController)? -

i have created base-controller controllers inherit. controller fills data (which use in views) viewdata -container this: protected override void initialize(system.web.routing.requestcontext rc) { base.initialize(rc); viewdata["cms_configuration"] = new cmsconfiguration(); // etc. } i don't fact need read (and cast) viewdata within views. i'd introduce baseviewmodel viewmodels inherit from, defining properties instead of using viewdata. how or can populate baseviewmodel within basecontroller? there kind of hook? or need define function in basecontroller, call in child-controller? e.g. (child-controller: //{...} base.populatebaseview(myview); return view(myview); thx tipps. sl3dg3 you optionally use actionfilters stuff this: check out article: http://www.asp.net/mvc/tutorials/understanding-action-filters-cs it explains actionfilters nicely. way can separate different populate-logic different filters, , tur

php - Updating PK values mysql -

i have 2 tables wish update articles , articles_entities articles has pk of id , articles_entities has fk article_id both these fields char(36) uuid. looking convert these fields int(10). is there way can update 2 tables 1 query , key keys matching? or have write script through each articles , update references? i using innodb if helps. two steps: ensure foreign key set "on update cascade", update mother table's id field contains numbers. on update cascade constraint have innodb update child table updates mother... if have lot of rows, prepared extremely slow. change type of both columns int. may need drop foreign key before , re-create afterwards.

javascript - Difference between window.location.href=window.location.href and window.location.reload() -

what difference between javascript's window.location.href = window.location.href and window.location.reload() functions? if remember correctly, window.location.reload() reloads current page post data, while window.location.href=window.location.href not include post data. as noted @w3max in comments below, window.location.href=window.location.href not reload page if there's anchor (#) in url - must use window.location.reload() in case. also, noted @mic below, window.location.reload() takes additional argument skipcache using window.location.reload(true) browser skip cache , reload page server. window.location.reload(false) opposite, , load page cache if possible.

JMeter: run parameterized threads -

i've written simple test plan in jmeter, plan consists of 1 thread group , 1 controller "http request" elemets. plan performes login website, session refresh , logout. there way preform thread running, different params (login/password) each time? thanks. there lots of different ways parametrize test. if have lot of users want use, recommend using csv data set config . if have few want use, can try user defined variables or user parameters . make sure check out documentation, each 1 used differently.

How can i align the text to right side in Textbox in Javascript.... ??? By default it is left-align -

my problem couldn't align text in textbox right side... generally kind of align used in calculator... digits align right side... i want in html using javascript.... <input type="text" style="text-align: right" /> should work. other interesting attributes are: direction:rtl;unicode-bidi:bidi-override;

.net - Fluent NHibernate 1.2 + NHibernate 3.0, specify table name Options -

i new nhibernate, , doing first project. have simple table named "user", has columns of userid, firstname, lastname, username, password. and created entity class: public class useraccount { public virtual int? userid { get; private set; } [required(errormessage = "please enter username.")] public virtual string username { get; private set; } [required(errormessage = "please enter password.")] public virtual string password { get; private set; } public virtual string firstname { get; private set; } public virtual string lastname { get; private set; } } i created ma

Junit with new Date() -

what junit test when have following method: @override public void savelastsuccesfulllogin(final user user) { gebruiker.setlastlogin(new date()); storeuser(user); } submethode storeuser: @override public void storeuser(final user user) { entitymanager em = emf.createentitymanager(); em.gettransaction().begin(); em.merge(user); em.gettransaction().commit(); em.close(); } the problem have date, being set entity user , stored. im using junit , easymock. try pulling new date() method default access specifier below @override public void savelastsuccesfulllogin(final user user) { gebruiker.setlastlogin(getdate()); storeuser(user); } date getdate() { return new date(); } in test class override class below using mock or stubbed date. <classundertest> classundertest = new <classundertest> () { @override date getdate() { return mockdate; } } in way can assert date value going stubbed out.

wordpress - menu_icon not displaying -

i have custom post_type created in wordpress admin control panel. working fine except menu_icon 'menu_icon' => get_stylesheet_directory_uri() . '/images/my_menu_icon.png', it's not loading @ all... image file located in my_theme/images is there code instead use template directory menu_icon? or need save image file somewhere else? i have no clue.. thanks! try this: 'menu_icon' => get_bloginfo('template_directory'). '/images/my_menu_icon.png',

php - Need help with comet, and what to choose -

i'm new comet, have read , realize php bad comet long polling. all of project written in codeigniter php framework, code php. need request data seconds update auctions products, , i'm looking comet, php bad way comet, how can it? also possible read mysql , send listener? thanks. one solution ajax push engine - dish out own server handling connections clients, can use whatever backend feed data ape - including php. can work mysql directly - see example one , two . note: ape server can run on linux, bsd or mac os x (though, seem port windows should possible, since it's written in pure c, afaict). the other 1 nginx_http_push_module - use nginx push server (no need server running, it's in ape's case) , protocol easy work with/straightforward imho.

asp.net mvc2???? when to use models, controllers, view, script? -

when create class or new item? how know or in directory should create class??? mean how know class has created under models or controllers or views or scripts???? i suggest start going through tutorials on official microsoft mvc site.

c++ - Boost serialization assertion fail -

i use boost's binary serialization , worked until now. have std::list of pointers serialize output (oarchive) serialization fails inside object's serialize() function msvc's dialog: r6010 -abort() has been called and such string printed console window: assertion failed: 0 == static_cast<int>(t) || 1 == static_cast<int>(t), file c:\program files\boost\boost_1_44\boost\archive\basic_binary_oprimitive.hpp, line 91 what mean? project pretty big, sources distributed cannot post it's code here, tried simulate error within simple project - there works fine strange. p.s. use boost 1.44 msvc2010ee on windows xp. when click " retry " on " debug error! " window debugger shows arrow on code line next serialization archive << mylist; line - mean seems error occurred @ destructor or something. when make changes inside objects serialize() function - applied when rebuild whole project (clean before compiling) - if compile (whe

web applications - Automated Testing with Javascript for any web app - need more suggestions and ideas -

Image
background: i've been looking auto-testing tools web-app developed in c# having ajax. tried find tools complex, paid , not allow me tweak in. listed below wanted on had total control , v.light weight , portable. my inspirations :) http://watin.sourceforge.net http://sahi.co.in/w/ http://seleniumhq.org/projects/ide/ solution: so, getting old javascript skills ended creating own simple (and effective) auto-testing tool! idea create wrapper parent html page 'host' web-page tested in iframe , access controls, populate value , perform clicks, etc... *note: both pages need on same machine tested (cross domain testing not allowed) here's sample image explaining method - and here's wrapper page code : http://www.codeupload.com/3813 i'd know suggestions , idea same , prefer. see many usage of method - auto-testing, showing automated demo, automated-data-entry,... on same domain. here's codeproject article : http://www.code

c++ - Do polymorphic C-style casts have any overhead? -

does casting pointer instance of dervived class instances base class have run-time overhead in c++, or resolved @ compile-time? if have any, has computed in casting operation? example: class foo; class bar : public foo; bar* y = new bar; foo* x = (foo*) y; (i know should use c++-style casts , answer same them) yes, though it's negligible. in case, c-style cast interpreted static_cast , may incur pointer adjustment. struct base {}; struct derived: base { virtual ~derived(); } // note: introduced virtual method int main() { derived derived; base* b = &derived; derived* d = (derived*) b; void* pb = b; void* pd = d; printf("%p %p", pb, pd); return 0; } this overhead happens whenever base subobject not aligned @ same address derived object, happens when: introducing first virtual method using multi-inheritance of course, pointer adjustment counted negligible, , compiler shall smart enough eliminate if it's unnecess

android - Set a ViewFlipper weight programmatically -

i'd change weight of viewflipper programmatically. have tablerow in have 2 columns. first column contains relativelayout element when second column contains viewflipper. viewflipper contains 2 views. somehow in java code, change visible view of viewflipper when click on button. want able, when change viewflipper view (by calling shownext()), change viewflipper weight in order larger in screen. in other words, first column of row has weight=1 , second (the viewflipper) has weight=0.8. when click on button want change weights programmatically. possible ? how ? below xml code. i've searched on web, found solution: myflipper.setlayoutparams(new linearlayout.layoutparams(linearlayout.layoutparams.wrap_content, linearlayout.layoutparams.wrap_content, 0.3f)); this doesn't work, crashes, is, think normal viewflipper isn't linearlayout. here xml code: <tablerow android:layout_width="wrap_content" android:layout_height="match_parent&

java - Richfaces modalPanel load with Ajax -

i use richfaces in project , particularly tag rich:modalpanel allows display popups in pages. so this, include popup this: <ui:include src="popup.xhtml" /> this popup contains code: <rich:modalpanel id="sra" width="400" autosized="true" left="100" > ... </rich:modalpanel> finally display popup, in main page: <a4j:commandlink id="linksra" value="#{msg['sra']}" action="#{controller.checksra}" oncomplete="#{rich:component('sra')}.show()" /> all work fine problem next: in page, have many popup , each popup included in main page. weight of 1 big nothing. so, how can load popup's content in ajax when want load popup ? thanks re-render panel content via action , open modal in oncomplete=".."

model view controller - Android Architecture Design - How to do it right? -

how architecture android app like? should "work/business logic" been done in background service , activity communicates service query/fetch data somewhere (local/distant)? would implement "service" activity calls real android-service? or pojo-singleton work (perhaps using background threads). or instantiate background threads in activity time-consuming actions (query webservice). how abstract data access right way? use contentprovider access/abstract data? how/from should queried? activity? service? ..? i've tried search app architecture design, found how android architecture looks like, not how android app should like. so what's opinion that? components of android application should communicate each other ensure best extensibility/encapsulation,...? there's no 1 answer question. oo design isn't android specific. i'd rule - if framework gives high level object (such service in case of android) fits use case, use it. if fin

android - Is there any good solution for searching in TabActivity for each activity in tab respectively? -

i have problem activities navigation, searching works good. activities hierarchy looks that: / mylistactivitya -- itemactivitya mainactivity -- mytabactivity -- mylistactivityb -- itemactivityb \ mylistactivityb -- itemactivityc tabs in tabactivity created using intents mylistactivity . mylistactivities declared in manifest below: <activity android:name=".views.orderlistview"> <intent-filter> <action android:name="android.intent.action.search" /> </intent-filter> <meta-data android:name="android.app.searchable" android:resource="@xml/searchable_orders" /> </activity> every mylistactivity has own searchrecentsuggestionsprovider. first resolved problem when invoked search on of mylistactivity got activity outside mytabactivity . therefo

Convert C# regex Code to Java -

i have found regex extractor code in c#. can tell me how works, , how write equivalent in java? // extract songtitle metadata header. // trim needed, because stations don't trim songtitle filename = regex.match(metadataheader, "(streamtitle=')(.*)(';streamurl)").groups[2].value.trim(); this should want. // create regex pattern pattern p = pattern.compile("(streamtitle=')(.*)(';streamurl)"); // create matcher matches pattern against input matcher m = p.matcher(metadataheader); // if found match if (m.find()) { // filename second group. (the `(.*)` part) filename = m.group(2); }

.net - VB.NET 2K8: How to make all imports visible within a class? -

generally speaking, common vb.net class should following: public class myclassname end class besides, have seen, if remember correctly, of import statements visible in c#: imports system imports system.data imports system.linq public class myclassname end class how make these default imports visible default in vb.net using visual studio 2008? is there setting or in options shall set? thanks! =) good question. vb.net language spec mentions "implicit imports" without giving authoritative list. can reverse-engineer command line shown in output window, vs2008 , vs2010 uses /imports command line option: microsoft.visualbasic, system, system.collections, system.collections.generic, system.data, system.diagnostics, system.linq, system.xml.linq msbuild sets these in microsoft.visualbasic.targets import variable. set in .vbproj file: <itemgroup> <import include="microsoft.visualbasic" /> <import include=

Outlook VBA open excel -

i trying open existing excel sheet outlook. can see workbook open , imediately closes again. have excel.application set visible. ideas? here code. function opennewform(todosubject) msgbox ("called") dim xlapp object dim sourcewb workbook dim sourcesh worksheet set xlapp = createobject("excel.application") xlapp .visible = true .enableevents = false end strfile = "c:\users\peter\documents\asi\ordersystem\newordersheet.xlsm" set sourcewb = workbooks.open(strfile, , false, , , , , , , true) set sourcesh = sourcewb.worksheets("orderform") sourcewb.activate end function again code running in outlook. want keep file open once opens. i got figured out. opening different workbook , closing before try open second 1 , interfering it. fix kept excel app open , reset workbook object new workbook wanted.

json - Twitter Trends PHP -

i trying use http://api.twitter.com/1/trends/current.json?exclude=hashtags having trouble. so, i'm trying use: <?php $init = 'http://api.twitter.com/1/trends/current.json?exclude=hashtags'; $ch = curl_init(); curl_setopt($ch, curlopt_url,$init); curl_setopt($ch, curlopt_returntransfer,1); $result = curl_exec($ch); curl_close($ch); $obj = json_decode($result, true); foreach ($obj[0]['trends'] $trend) { print $trend['query']; echo "<br>"; print $trend['name']; echo "<hr>"; } ?> and getting error: notice: undefined offset: 0 in \index.php on line 11 warning: invalid argument supplied foreach() \index.php on line 11 you read json wrong. need following: foreach ($obj['trends']['2011-02-23 18:00:00'] $trend) { print $trend['query']; echo "<br>"; print $trend['name']; echo "<hr>"; }

wpf - How to use a TextBlock that allows the left-most characters to be dropped -

i have following scenario thought have simple solution, i'm stumped... i have constructed wpf user control set of numeric buttons , textblock record buttons have been selected. when user control opens, textblock empty. button selected, digit represents appended right-hand-side of displayed text. what need solution digits keep getting appended on right-hand-side , if results in exceeding fixed displayable size of textblock dropping left-most character. in effect after one-character-at-a-time marque effect. i can not use scroll bars. thoughts welcome databindings friend here. suppose got viewmodel. , in viewmodel got property of string binded textblock text propetry. now need manipulate string inside viewmodel using regular c# string methods display correctly. hth ariel

javascript - HTML select onchange accessibility concerns -

we have request use select element's onchange trigger move new page. in past, web accessibility literature i've read has advised against doing this. on grounds breaks user expectation, , browsers (particularly ie < 6) fired change event when moving through options keyboard, making impossible keyboard-only users make selection. ie6+ , other more modern browsers have tested fire select onchange when option selected mouse or enter key. analytics application in question show earlier ie browsers eradicated (< 0.01%) given our users able operate these select elements keyboard only, should feature still considered impediment accessibility? behavior seems common nowadays wonder if still break user expectation in meaningful way? edit: ie behaves differently if select focused mouse or keyboard. when focused mouse, keyboarding through options not fire onchange when tabbing focus via keyboard, onchange fire when arrowing through. using onchange even

asp.net mvc - Ajax request to fetch partial view -

i have main view this: <%@ page title="" language="c#" masterpagefile="~/views/shared/site.master" inherits="system.web.mvc.viewpage" %> index <script src="../../scripts/jquery-1.3.2.js" type="text/javascript"></script> <script src="../../scripts/microsoftajax.js" type="text/javascript"></script> <script src="../../scripts/microsoftmvcajax.js" type="text/javascript"></script> <h2> index</h2> <script type="text/javascript"> $(function() { $('#mylink').click(function() { $('#resultpartial1').load(this.href); return false; }); }); $(function() { $('#mysecondlink').click(function() { $('#resultpartial1').load(this.href, { id: 123 }); return false; }); }); </script>

How to optimize 'string.split("&").sort.join("&")' using Ruby on Rails? -

i using ruby on rails 3 , in code have this: string = "surname=testsurname&name=testname" string.split("&").sort.join("&") # 'string' value "name=testname&surname=testsurname" there better way that? if better mean faster, not. that's straightforward implementation of you're intending do. how calling method? context being called in? optimize @ ways avoid performing operation more times strictly required.

sql - Missing expression and then group function not allowed error -

i wondering doing wrong. have 2 tables odetails , orders odetails has following columns: ono, pno, qty, cost orders has following columns: ono, cno, eno, received, shipped, order_cost update orders set order_cost= 1 * sum( select cost odetails orders.pno=odetails.pno ) ; try this. (sum in wrong place) update orders set order_cost= 1 * ( select sum(cost) odetails orders.pno=odetails.pno ) ;

android - Populate editText from a listView -

i have edittext, next button. when click button, use onclick trigger intent start new activity, brings listview. when click item in listview, want listview activity close , populate edittext item. seems i'm going @ wrong, suggestions? when fire intent, use "startactivityforresult", described in starting activities, getting results . when fire intent activity listview, line should this: intent someintent = new intent(someaction, someuri); startactivityforresult(someintent, some_request_code); within activity listview, before returning, use "setresult" method set proper resultcode (the 1 passed in), , intent holding data. ... intent data = new intent(); data.putextra("key",value); setresult(result_ok, intent data) .... then, in calling activity, onactivityresult called, containing data. @override protected void onactivityresult(int requestcode, int resultcode, intent data) { if (requestcode == some_request_code) {

c# - How to save dynamic image from WebBrowser control -

i looking way save dynamically generated image webbrowser control. scenario need login website , there form containing user data plus 1 image that's been provided server upon runtime. need process data after scraping it. means can see image in webbrowser control can't save cause doesn't have url. webclient doesn't seems option out of box due login thing. have implement state full communication if choose webclient replace webbrowser control? the hurdle dynamic image , after brainstorming lot unable make progress it. no matter way choose ended in dead end. can see webbrowser control showing image must have downloaded somewhere. reason unable figure out keeping image , how can grab it. wondering silent complete page save there windows prompt message. i appreciate suggestions this. this came while ago, here link webbrowser copy image clipboard

Regex - pattern capture everything except for pattern [.net] -

i capture to, not including particular patter. actual problem has parsing out information html, distilling problem down example to, hopefully, clarify question. source xaxbxcabcabc desired match xaxbxc if use lookahead expression capture first occurrence .*(?=abc) => xaxbxcabc i along lines of negated character class, negated pattern. .*[^abc] //where abc pattern instead of list giving a, b or c i using http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx testing if anchor regex you'll solve problem (+ use of lazy quantifier): "^.*?(?=abc)"

sql server - How to reducing impact on OLTP when performing ETL Process -

i new in designing etl process. have 2 database, 1 live database application use every day transaction. other 1 data warehouse. i have table in live database regularly have new data insert it. goal every night etl process transfer data in live database data warehouse, follow deleting data in live database. due lack of knowledge, solution got implement call rolling table. on live database, have 2 tables have same structure. call them tbllive1 , tbllive2 . has synonym call tbllive . insert done on synonym. synonym point @ 1 of table. when run etl process, have stored procedure drop , create new synonym point tbllive2 . allow etl process transform data tbllive1 without effecting application. assumption etl process takes hour run, , won't want etl process lock table preventing application insert new data it. this solution should theoretically work, not elegant. i sure problem common problem, there other solutions out there? to add bob's answer (above), usu

python - unicode().decode('utf-8', 'ignore') raising UnicodeEncodeError -

here code: >>> z = u'\u2022'.decode('utf-8', 'ignore') traceback (most recent call last): file "<stdin>", line 1, in <module> file "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, true) unicodeencodeerror: 'latin-1' codec can't encode character u'\u2022' in position 0: ordinal not in range(256) why unicodeencodeerror raised when using .decode? why error raised when using 'ignore'? when first started messing around python strings , unicode, took me awhile understand jargon of decode , encode too, here's post here may help: think of decoding go regular bytestring to unicode , encoding from unicode. in other words: you de - code str produce unicode string and en - code unicode string produce str . so: unicode_char = u'\xb0' encodedchar = unicode_char.encode('utf-8') encode

php - how to store an image and a text in a database in mysql -

i want to store recipes in database, format of recipes should small photo on top , text below. explain me how structure should be? thanks in advance i avoid storing actual bytes of image in database, that's bad idea (see storing images in db - yea or nay? ). instead, create simple text field stores perhaps markdown version of recipe page. page include image tag pointing image or recipe instructions.

Problem with input in c++ -

i have basic question want take integer input in range user. if user gives string or char instead of integer. program goes infinite loop. my code that cin >> intinput; while(intinput > 4 || intinput < 1 ){ cout << "wronginput "<< endl; cin >> intinput; } i allowed use c++ libraries not c libraries. the solution answer read lines standard input. std::string input; int value = 0; { // read user's input. typed line, read line. if ( !std::getline(std::cin,input) ) { // not read input, handle error! } // attemp conversion of input integer. std::istringstream parser(input); if ( !(parser >> value) ) { // input wasn't integer, it's ok, we'll keep looping! } } // start on while ((value > 4) || (value < 1));

wpf - Enterprise Library C# WCF & Mutliple UI (Silverlight,UI,ASP.NET) -

i wondering if out there on here has been able succesfuly use enterprise library work across n-tier layer structure, ui of different mediums. i have design wcf common library service layer working across following platforms: silverlight wpf asp.net mvc just reference documentation or point me in right direction. thought out there may have done same kind of thing, wouldn't mind bit of of may have been talked or done before. thanks robbie the following 2 projects may interesting at: domain oriented n-layered .net 4.0 app sample (from ms spain) layered architecture sample .net

MySQL Query with MySQLParameters in C# -

i developing application windows using mysql , c#. have following code: private void cbocategories_selectedindexchanged(object sender, eventargs e) { databasework dbase = new databasework(); try { dbase.openconnection(); string query = "select * budgetcategory budc_userid=@userid , budc_category=@category"; mysqlcommand cmd = new mysqlcommand("", dbase.conn); cmd.commandtext = query; cmd.parameters.addwithvalue("@userid", userid); cmd.parameters.addwithvalue("@category", cbocategories.selecteditem.tostring()); mysqldatareader reader = cmd.executereader(); while (reader.read()) { setcatid(reader.getstring("budc_category_id")); console.writelin

visual studio - C++ registry handling without .NET -

for script check/set windows registry value. no gui. writing in visual studio, not want .net - c++. however, haven't figured out , methods exist natively in c++ [not visual c++] interface registry. haven't worked out how compile c++ code in visual studio 2010 without .net. can please direct me documentation (or better, tutorials) of standard c++ registry related methods. , furnish me instructions or point out tutorial allow complete , total noob compile in vs non .net program. please not argue aversion .net, has been subject of other threads. to create native c++ console application in vs 2010: http://msdn.microsoft.com/en-us/library/46e82t5z.aspx to check/set registry values using win32 apis: http://msdn.microsoft.com/en-us/library/ms724875%28v=vs.85%29.aspx

Javascript closures with google geocoder -

i still have problems javascript closures, , input/output variables. im playing google maps api no profit project: users place marker gmap, , have save locality (with coordinates) in db. the problem comes when need second geocode in order unique pairs of lat , lng location: lets 2 users place marker in same town in different places, dont want have same locality twice in database differents coords. i know can second geocode after user select locality, want understand mistaking here: // first geocoding, take marker coords locality. geocoder.geocode( { 'latlng': new google.maps.latlng($("#lat").val(), $("#lng").val()), 'language': 'it' }, function(results_1, status_1){ // initialize html var inside closure var html = ''; if(status_1 == google.maps.geocoderstatus.ok) { // stuff here for(i = 0, geolen = results_1[0].address_components.length; != geolen) { // second type o

c# - Exclude results from Linq query excluding everything when exclude list is empty -

i have following code: public ilist<tweet> match(ienumerable<tweet> tweetstream, ilist<string> match, ilist<string> exclude) { var tweets = f in tweetstream m in match f.text.tolowerinvariant().contains(m) select f; var final = f in tweets e in exclude !f.text.tolowerinvariant().contains(e.tolowerinvariant()) select f; return final.distinct().tolist<tweet>(); } i've been building tests haven't included final resultset , been matching happily i've added exclude if ilist<string>exclude empty items removed. so test passes should: [testmethod] public void should_exclude_items_from_exclude_list() { ienumerable<tweet> twitterstream = new list<tweet> {

Get dynamic data from external host - establish mysql-connection or get data via curl? -

i need integrate sidebar-widget high traffic page of mine (referred sitea). widget should contain latest articles 1 of other pages (referred siteb). on mind have 2 possible solutions. curl-call on sitea retrieving content (php-file) siteb on sitea connect mysql-db siteb which way prefer? better , why? i'd prefer setting rss feed articles on sitea , pulling them in existing library, nice , tidy, , means others can articles via rss too. if had pick i'd go option 1 (i'm assuming returned snippet of html can embed in page).

zepto - Correct way to insert a view with Backbone.js -

i have simple backbone.js app. want render view dom of html page, view detail view model. html page has div element want render view into. if try render view this: detailview = new rulespanelview({model : @model}) $("#detail").html(detailview.render().el) it fails , [object htmldivelement] inserted dom, not rendered html. this way can work , seems hack: $("#detail").html('') detailview = new rulespanelview({model : @model}) $("#detail").append(detailview.render().el) having empty html of div before rendering don't multiple views rendered inside #detail happend append. also aren't creating way many views way, seems cleaner replace html in first code segment? what correct way render view? what want pass inserted dom node view 'el' option constructor: new rulespanelview({el: $("#detail")}); this way, won't render again. still need make sure view's 'render' method able render corr

Best practice for naming Read model tables in a CQRS architecture? -

i'm new idea of cqrs, , usual deciding how name things 1 of hardest parts of learning process. if following convention of 1 table per view in read database cqrs application, how should go naming tables different views? let's have number of different clients consuming read model, should name tables based on client , ui view consuming data? is there no concern here coupling our ui read model database , webservices used performing queries? or purpose of cqrs architecture, push complexity of aggregating data read model, rather performing work in query webservices , client? can give examples of tablenames use in denormalized read models? or purpose of cqrs architecture, push complexity of aggregating data read model, rather performing work in query webservices , client? yes, case. don't need worry coupling read model ui because read model built directly support ui needs. as examples: tables reflect path specific view built for. th

.net - C# try catch pattern help -

we need try catch in our code , becomes ugly like public void foo() { try { dosomething(); } catch(exception e) { //do whatever e } } public int fooreturnint() { try { return intaftersomecalculation(); } catch(exception e) { //do whatever e foo() } } imagine have huge class many public functions , have apply same try catch in every single function. ideally, since try catch part identical, , can pass down func<> parameter helper function like public void trycatch(func<something> thefunction) { try { thefunction(); } catch(exception e) { //processthe common exception } } then i'd imagine tidy code alot, problem how write function? return type of function depended on return type of thefunction. if really think needed, use: public t trycatch<t>(func<t> thefunction) { try { return thefunction(); } catch(exception e) { // you'll need either rethro

python - What are the advantages/disadvantages of using Jython/IronPython/Pyjamas? -

edit okay, rookie here please bear me. i'm trying ask following: is plausible python-syntax fan use 1 of these options while other team members "plain vanilla" version? matter of personal preference, or require converting other people using these technologies well? is possible convert between, say, jython , java or pyjamas , javascript? also, in general, advantages/disadvantages have people experienced using these in "real world"? i think states little more i'm looking for. input uses these technologies in industry helpful. thanks in advance insights. you talking 2 different things. first, jython , ironpython python implementations can embed in java or c# application provide scripting capability. reduces amount of code have write overall. or can @ them way glue , leverage existing collection of class libraries. @ it, these things , lots of people use them. but pyjamas else entirely. complicates web stack , makes harder pass pro

winapi - How can I assign clipboard text to a variable in c++? -

i've written program highlights numbers , copies them. able basic math copied text, such multiplication or addition, can't figure out how assign clipboard data variable. basically, able copy number, assign variable "a", repeat variable "b" , multiply 2 together. have figured out how select , copy number part isn't issue. appreciated, different approach have tried. here latest attempt @ problem: handle clip0; openclipboard(null); emptyclipboard(); clip0 = getclipboarddata(cf_text); variable = (char)clip0; closeclipboard(); where "variable" variable. whenever run program , tell output "variable", returns value of 0. another attempt made this: handle clip1; if (openclipboard(null)) clip1 = getclipboarddata(cf_text); variable = (char)clip1; closeclipboard(); but "variable" take on value of -8 the text content of clipboard c-string pointed c. if(openc

.net - How to center text in a specific column in WPF ListView? -

i tried , horizontalalignment, instead of textalignment still show aligned left. <window x:class="editorwindow.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" datacontext="{binding relativesource={relativesource self}}" title="mainwindow" height="800" width="600"> <grid> <listview itemssource="{binding effects}"> <listview.view> <gridview> <gridviewcolumn width="100" header="name" displaymemberbinding="{binding name}" /> <gridviewcolumn width="100" header="type" > <gridviewcolumn.celltemplate > <datatemplate> <textblock

android - back button in listView causes crash -

i have edittext , button. push button, launches listview activity. click on item in listview, closes activity , sets edittext item clicked on. but if listview , hit button clicking item, crashes. think need in onpause not sure if that's best way go it. listview, when item clicked... intent intent = new intent(); bundle b = new bundle(); b.putstring("text", ((textview) view).gettext().tostring()); intent.putextras(b); setresult(success_return_code, intent); finish(); onactivityresult.... bundle b = data.getextras(); meditcategory.settext(b.getstring("text")); you getting exception: data null because activity did not return result. by default, key end activity without setting result. check resultcode parameter onactivityresult see whether sub-activity returned because list item clicked: @override protected void onactivityresult(int request

objective c - Leak when calling SSL_connect -

i using openssl , according instruments, have memory leak started @ ssl_connect. ssl_ctx *ctx = ssl_ctx_new(sslv23_method()); if (!ctx) { nslog(@"could not initialize ctx"); [self release]; return nil; } if(!ssl_ctx_use_certificate_chain_file(ctx, [pemfile utf8string])) { nslog(@"can't read certificate file"); [self release]; return nil; } if(!(ssl_ctx_use_privatekey_file(ctx, [pemfile utf8string], ssl_filetype_pem))) { nslog(@"can't read key file"); [self release]; return nil; } _sock = [self _tcpconnectwithhost:host port:port]; if (_sock < 0) { [self release]; return nil; } _sslpointer = ssl_new(ctx); bio *bio = bio_new_socket(sock, bio_noclose); ssl_set_bio(_sslpointer, bio, bio); if(ssl_connect(_sslpointer) <= 0) { nslog(@"ssl connect error"); [self release]; return nil; } ssl_ctx_free(ctx); i release when dealloc called. when leak appears. ssl_free(_sslpointer)

what code should be in upload.php for jquery swfupload? -

i started using jquery swfupload plugin , have working besides upload part... don't know put in upload.php file. i error: alert: {"name":"","type":"","size":""}; file: mayday-parade.png upload.php had code: $file = $_files['file']; echo '{"name":"'.$file['name'].'","type":"'.$file['type'].'","size":"'.$file['size'].'"}'; obviously doesn't work added following: if (file_exists($_server['document_root'].'/band_photos/' . $_files["file"]["name"])) { echo 'file exists'; } else { $uploaddir = 'uploads/'; $uploadfile = $uploaddir . basename($_files['file']['name']); if(move_uploaded_file($_files["file"]["tmp_name"], $uploadfile)) { echo 'success'; } else {

optimization - Best algorithm for optimizing the decisions in a simulation -

i'm looking best algorithm optimise decisions made in simultaion find fast result in reasonable amount of time. simultaion number of "ticks" , occasionaly needs make decision. goal state reached. ( possible never reach goal state if make bad decisions ) there many many goal states. want find goal state least number of ticks ( tick equates second in real life." want decide decisions make goal in few seconds possible, some points problem domain: straight off bat can generate series of choices lead solution. won't optimal. i have reasonable heuristic function determine decision i have reasonable function determine minimum possible time cost node goal. algorithms: i need process problem 10 seconds , give best answer can. i believe a* find me optimal soluton. problem decision tree large won't able calculate quick enough. ida* give me first few choices in 10 seconds need path way goal. at moment thinking start off known non optimal path goal

Setting aspNetCompatibility Enabled in wcf screwing anonymous access -

i have given anonymous access service. , m able access out establishing credentials. wanted make use session in wcf service, m trying use aspnetcompatibility enabled true in system.servicemodel. when included line, redirecting me login page whenever m requesting service.svc file. guess why aspnetcompatibility enabled overriding access policy? should overcome this? once aspnetcompatibilityenabled true, asp.net pipeline comes play , authentication , authorization dome. check system.web/authorization section in web.config. have deny users? if so, remove it. may try add <system.web> <authorization> <allow users="*" /> </authorization> </system.web>

Python: from import error -

i'm running python 2.6.6 on ubuntu 10.10. i understand can import module , bind module different name, e.g. import spam eggs also, from eggs import spam foo my problem when running pyside examples , following import code not run: import pyside pyqt4 pyqt4 import qtcore, qtgui it generates import error: traceback (most recent call last): file "<stdin>", line 1, in <module> importerror: no module named pyqt4 clearly, according python interpreter above code incorrect, question why incorrect or rather why doesn't work? import , from special syntax. they module name, means file in sys.path starts module name. and seems don't have pyqt4 installed, fail. the fact have variable called pyqt4 in namespace after running import pyside pyqt4 not change anything, python still looking actual module called pyqt4 when from pyqt4 import qtcore, qtgui . try doing import pyside pyqt4 qtcore = pyqt4.qtcore qtgui = pyqt4.qtgu

nhibernate - Convert SQL to linq in activeRecord -

i have statement sql select * messages messageid in (select messagesid publisher pubid = 22) in project asp.net using activerecord: from m in activerecordlinq.asqueryable<message>()select m this correct project but i've written from m in activerecordlinq.asqueryable<message>() activerecordlinq.asqueryable<publisher>().any(t => t.messagepublishersitekey.messageid == m.messageid && t.publishersiteid == 22) select m what isn't working. i found this, don't know how is. http://www.sqltolinq.com/

jquery - Returning PHP value to the page -

i have remote php program generates 2 random numbers, call on form page populate text box used in validation. can't return numbers. <?php $randomnum = rand(0,9); $randomnum2 = rand(0,9); echo ($randomnum + $randomnum2); $randomnumtotal = $randomnum + $randomnum2; ?> it returning total, not # + # please help! ok, below got output correct on page. i'm doing parent page brings in forms via ajax. forms validated remote php script "random.php" in forms there math problem human verification, math problem populated "random.php" file via .get command. got working. issue can't solve problem correctly... answer input has validation: somename: { equal: "<? php echo $randomnumtotal ?> } but it's not working...any ideas? you use . in php string concatenation try $randomnumtotal = $randomnum ."+". $randomnum2;

php - explode string and set key for array with text that is in front of the delimiter? -

is there way take input this: | testing==one 2 3 | setting==more testing | and this array['testing'] = "one 2 three"; array['setting'] = "more testing" right i'm exploding string , setting array numbered index, i'd user able enter items in order , able use array keys first value. function get_desc_second_part(&$value) { list(,$val_b) = explode('==',$value); $value = trim($val_b); } thanks! something this? pipes adds maybe needless complexity (separator new lines): $arr = array(); foreach (explode('|', $str_input) $line) { $l = explode('==', trim($line)); if (isset($l[1])) $arr[$l[0]] = $l[1]; } print_r($arr); /* array ( [testing] => 1 2 3 [setting] => more testing ) */

How to generate RDF/XML using a template in javascript? -

i have working javascript code generates rdf/xml document using variables picked html fields: ... peopledoap += " <foaf:name>" + person_name + "</foaf:name>\n"; if (person_url != "") { peopledoap += " <foaf:homepage rdf:resource=\"" + person_url + "/\"/>\n"; } if (person_pic != "") { peopledoap += " <foaf:depiction rdf:resource=\"" + person_pic + "/\"/>\n"; } ... it's hard, looking @ code, sense of output (especially code scattered amongst sub functions etc). i'm wondering if there easy way enable me have this: ... <foaf:name>%person_name%</foaf_name> <foaf:homepage rdf:resource="%person_url%"/> <foaf:depiction rdf:resource="%person_pic%"/> ... and substitution code. 1 slight complication if fields left blank, want not generate whole element. ie, if person_url='',

Creating a Custom Button in a ListView in ASP.NET -

i have results.aspx page displays resulting records queried using sqldatasource object via listview. want add "view" button appear next each record, , when clicked take me separate page display details record. how accomplish this? edit i have tried said, citronas , here's i've come with: <td> <asp:checkbox id="checkbox1" runat="server" /> </td> <td> <asp:linkbutton id="linkbutton1" runat="server" commandname="viewbuttonclick" commandargument='<%# eval("serviceid") %>'>view</asp:linkbutton> </td> and here method want called: protected void viewbuttonclick(object sender, commandeventargs e) { var serviceid = convert.toint32(e.commandargument); servicetoview = dataaccesslayer.service.select(new service { serviceid = serviceid }); server.transfer("~/viewservice.aspx"); } unfortunately nothing

java - java_cup cannot be resolved -

Image
i installed weka in eclipse, , got following java_cup error. what should do? can java_cup can reference part in project weka says needs (at runtime) in weka.jar, java_cup here

json - JQuery - Serialize cookie string value to object/array type -

im using jquery.cookies.2.2.0.js in retrieving cookie values: $cookie = $.cookies.get('ci_session'); //generates a:5:{s:10:"session_id";s:32:"46645fe9eb70e1b157f24b724932be24";s:10:"ip_address";s:9:"127.0.0.1";s:10:"user_agent";s:50:"mozilla/5.0+(windows;+u;+windows+nt+6.1;+en-us;+rv";s:13:"last_activity";s:10:"1298530444";s:15:"promos_userinfo";a:1:{s:8:"username";s:9:"requester";}}c53a500fb3108c3930da58d50b6db036 my problem how convert string object type or array type. have tried parse using json.parse() there error. please how use json.parse or method can parse string. you can use version of php's unserialize() ported javascript .

uialertview - How to disable alertview's button in iPhone? -

i have alert view having 2 buttons "ok" , "cancel" , textfield. want disable "ok" button until user enter text in textfield. how can this? in advance you can create 2 buttons ok , cancel.then add 2 sub views in uialertview.now checking text(text length) in textfield,you can perform enable , disable actions.

define - constant or literal Objective-C -

we have following code (in .h. or .m file of objective-c app) #define square_size 28 #define app_delegate [[uiapplication sharedapplication] appdelegate] are both of them constants or literals ? what proper name? , literals suspect, why call them constants :)? they're neither, they're macros. a constant this: const int square_size = 28; the difference between macro , constant here constant has type while macro text fragment gets inserted @ place it's mentioned before compiler parsing source code. and literal 28 or @"this string" , value.

iphone - Animating only part of a UIView drawn context? -

i drawing text , images view in "drawrect" method. wish understand : does drawings separated objects? i know how animate uiviews how reach 1 of them can animate properties ? thanks shani o.k if 1 wants know answer. can not animate drawn text or objects unless draw calayer.

java - Stack-based machine depends on a register-based machine? -

normal cpus (for example, android devices) register-based machines. java virtual machine stack based machine. stack-based machine depend on register-based machine work? can't stack-based machines run lonely, because not os? there stack-based machine examples except jvm? saying 1 operand, 2 operand; why need this? the jvm not mention existence of registers anywhere. perspective, memory exists in few places, such per-thread stack, method area, runtime constant pools, etc. said, if wanted implement physical device adhered jvm, you'd need registers hold of temporary values generated when executing bytecodes, or maintain scratch information on side. example, try looking multianewarray instruction , see if implement without registers. :-) one parallel can find in real cpus these days while there dedicated set of registers available programmers, cpus have substantially more registers used internally various purposes. example, mips chips have huge number of reg