Posts

Showing posts from February, 2010

c++ - The use of declaring function inside a function? -

possible duplicate: is there use function declarations inside functions? i know inside function can declare function. use of it? can please bring simple example? there little value declaring function inside function, unless intend on defining later , having available function- i.e., function declaration encapsulated. int main() { void foo(); foo(); } void some_other_func() { foo(); // error } void foo() { } but that's it. in comparison triggering vexing parse, extremely limited benefit @ best.

C Pointer Pointer Question -

struct instruction { int value; }; int n; // number of instructions struct instruction **instructions; //required use ** , dynamic array say want store n number of instructions , store value in each instructions. how **instructions?? want able call value specific instruction later. many thanks so far tried these, few scanfs , dynamic array creating. takes number of counters, takes number of thread (pthreads), takes number of instructions within each thread. trying find way store instructions in each thread. ** structure given int main(void) { scanf(" %d", &ncounters); //ask number of counters int i; if(counters = malloc(sizeof(struct counter)*ncounters)){ for( i=0; < ncounters ;i++){ counters[i].counter = 0; } } scanf(" %d", &nthreads); //ask number of threads if(ninstructions = (int*) malloc(nthreads*sizeof(int))){ for( i=0; < nthreads ;i++)...

c - Using objdump/readelf and extern variable -

i have library ab.so compose of 2 sources file a.m , a.h , b.m , b.h in a.m have define variable foo , in b.m have declare extern . now using readelf/objdump know , how can see variable foo in a.o file, b.o , ab.so ? thanks lot tricky question. must realize readelf/objdump not display c code result, assembly code. if prepared read that, go ahead , disassembly application objdump -d ab.so , relevant code there. there bunch of readelf/objdump tutorials available on web. don't afraid them.

c++ - Istream consume at most N whitespace characters -

is possible tell std::istream consume fixed number (namely, 1) of whitespace characters when applying operator>>? have string i'd parse parameters, of parameters empty, causing subsequent calls operator>> fail. try std::noskipws : std::cin >> std::noskipws; char ws; std::string firstfield, secondfield, thirdfield; std::cin >> firstfield >> ws >> secondfield >> ws >> thirdfield; or, slurp entire line string (see std::getline ), , split boost .

javascript - JQuery each append and fadeIn one by one -

i have each function on array , want create div each array row , fade them in sequentially. preferably how ordered in array. manage fade in @ once, want sequentially. code: $.each(data, function(key, val) { var generateddiv = $(document.createelement('div')); generateddiv.attr('id',"div-"+val.id); generateddiv.css({//somecssproperties}); $('#results').append(generateddiv); generateddiv.fadein("fast"); }); any ideas? thanks. try code var t = 100; $.each(data, function(key, val) { var generateddiv = $(document.createelement('div')); generateddiv.attr('id',"div-"+val.id); generateddiv.css({//somecssproperties}); $('#results').append(generateddiv); t += 100; generateddiv.delay(t).fadein('fast'); }); demo

gwt - Simple example of MultiSelectionModel -

i'm trying make cellbrowser capable of multi-selection. start learning new concept of cells in gwt 2.2 , i'm @ example google has in gwt showcase code not clear. can find same example easier read.

actionscript 3 - "Refreshing" SharedObject -

so, stuffed while testing program , want "fresh" when export game. possible? mean, in current project, sharedobject has lots of information when should empty when being ran first time on computer. you can use new name object or simple use .clear function. dont forget remove clear function before publish. var _sharedobj:sharedobject; try { _sharedobj = sharedobject.getlocal("yourobjectname"); } catch (error:error) { trace("sharedobject error:"+error.tostring()); return; } _sharedobj.clear(); clear():void local shared objects, purges of data , deletes shared object disk. http://help.adobe.com/en_us/flashplatform/reference/actionscript/3/flash/net/sharedobject.html?filter_flash=cs5&filter_flashplayer=10.2&filter_air=2.6

c# - Why I can't recieved messages from Chat Server? -

why can't recieved messages chat server ? i developed chat client in visual studio c# mono android. want receive mesagens chat server sent chat client may receiving them , can not seem show in text1.text the source code chat client receiving messages: //criado por ecoduty, frederico vaz using system; using android.app; using android.content; using android.runtime; using android.views; using android.widget; using android.os; // using system.collections.generic; using system.componentmodel; using system.data; using system.text; using system.net; using system.net.sockets; using system.io; using system.threading; using system.runtime.interopservices; namespace chatclient_android { [activity(label = "chatclient_android", mainlauncher = true, icon = "@drawable/icon")] public class mainchat : activity { public delegate void onrecievedmessage(string message); public mainchat form; const int wm_vscroll = 0x115; c...

regex - How to extract all strings from application in Java -

in android application, of strings values hard coded (labels, dialog titles, buttons, etc). task extract these strings resource file. without manually going through code , making lot of c/p, there way can extract strings application? using regexes? thinking of writing pattern someting ".*" or somehow parsing through code? edit: aware of externalize strings eclipse, creates .properties file , need .xml file. so, take effort again convert .xml file. i thinking of writing simple program extract strings names of classes found in. eclipse provides externalize strings wizard. android-specific solutions: externalize strings android project . hope helps.

.net - Visual Studio 2010 - After build performance issue (application start takes ages) -

prologue two days ago installed few obfuscators. setup process of eazfuscator took while , said optimizing , [something else]. seemed bit weird me, remembered step. because eazfuscator didn't work me decided uninstall it. did try program, dragging solution eazfuscator-window. anyway, after installing few obfuscators , try-outs decided not use of them. so, while not using obfuscators... if compile wpf application (.net 4.0 client profile) no build errors or whatsoever. when building done, start-up of application takes ages! 23 seconds while 2 or 3 before... this morning tried solution on vs2010 installation (another computer) , fast before!! what did far in meanwhile reinstalled complete .net 4 framework (full , client) no success application still readable via ildasm code analyzers/optimizers nothing weird so, any hints settings (or so) highly appreciated! edit : solution thanks suggestion of mr dissapointment got vs2010 working should! use devenv /r...

iphone - Matching string format -

how possible perform matching of string, regex ? for example have array of strings, want match if these string in format of "abc def xxx" , xxx number 1 , 11 , 12 , 100 , 111 , etc. how can achieve this? the arrays: nsarray *array1 = [nsarray arraywithobjects:@"abc def 1", @"abc def 64", @"abc def 853", @"abc def 14", nil]; nsarray *array2 = [nsarray arraywithobjects:@"abc def 3", @"abc def 856", @"abc def 36", @"abc def 5367", nil]; the regular expression: nsstring *regex = @"abc def [0-9]{1,3}"; to check if strings in array matche regex: nspredicate *predicate = [nspredicate predicatewithformat:@"all description matches %@", regex]; bool allstringsmatch = [predicate evaluatewithobject:array1]; // output: yes allstringsmatch = [predicate evaluatewithobject:array2]; // output: no all objects in array1 matches regex, array2 contains string @...

ios - How to keep keyboard and dissmiss after finish with UIView -

i have uiview few uitextfields. on load call [textfield becomefirstresponder] bring keyboard on screen. don't want dismiss keyboard until done view. keyboard dissapear after "touch" outside textfield. i tried set - (bool)textfieldshouldendediting:(uitextfield *)textfield { return no; } however can't dismiss keyboard after unloaded. hints how keep keyboard time , dissmiss before uiview remove? when viewwilldisappear (or viewdiddisappear ) called, call resignfirstresponder on uitextfield . - (void) viewwilldisappear:(bool) animated { [self.textfield resignfirstresponder]; }

PHP & MySQL How to display categories any sub categoires from database -

i wondering how display hierarchical data create categories , endless sub categories using php & mysql? a quick example of how php & mysql code should out lot. mysql table categories structure id parent_id category 1 0 & w 2 0 b & f 3 1 c & y 4 1 d of course it's possible. code render <ul> <li> hierarchical tree, regardless of number of levels <?php //connect mysql server $cn = mysql_pconnect("server", "username", "password"); mysql_select_db("database_name"); $rs = mysql_query("select id, parent_id, category categories", $cn); $childrentree = array(); //will store array of children each parent $categorynames = array(); //will store category name each id //we fill $childrentree , $categorynames database while($row = mysql_fetch_array($rs)){ list($id, $parent_id, $category) = $row; $categorynames...

android - URLSpan in SpannableString -

i following example in using spannablestring : http://developer.android.com/resources/samples/apidemos/src/com/example/android/apis/text/link.html i trying create string has 'r.string.text1' following r.string.text2 r.string.text2 (has 10 characters) in url format: spannablestring ss = new spannablestring(getstring(r.string.text1)); ss.setspan(new urlspan(getstring(r.string.text2)), 0, 10, spanned.span_exclusive_exclusive); but getting is i don't see string r.string.text2 @ all and first 10 characters in url format how can fix problem? may correct ? spannablestring ss = new spannablestring(gettext(r.string.text1)+" "+gettext(r.string.text2)); ss.setspan(new urlspan(getstring(r.string.text2)), getstring(r.string.text1).length()+1, ss.length(), spanned.span_exclusive_exclusive); quite late, @ least done others ^^ you can way : spannablestring ss1 = new spannablestring(gettext(r.string.text1)); // want ss1 spannablestring...

c++ - Enums, overlapping values, C# -

apologies in advance i'm sure must have asked before can't find it. just had surprise, colleague , both added same value in enum, , compiled, e.g. enum myenum { mine = 1, = 1 } looks c/c++ supports (?). reason behaviour, cases it's useful? saw 1 case difference human languages (one = 1, eins = 1, etc) i'm not convinced thanks let's take simple example enum privilegelevel { none, reporter, reviewer, admin, defaultfornewuser = none, defaultforprojectowner = reviewer, };

c# - What to use in this SqlDataAdapter? -

i have sqldataadapter looks like: ("select prodid, catalogtype, prodname, catid, integration, itemprofilecatalogid shoppingcart t1 inner join itemcatalogprofile t2 on t1.catalogtype = t2.catalogtype sessionid = '" + session["id"] + "' , catalogid ='" + session["customer"] ....) there few more included in statement, 1 cannot seem work is: itemprofilecatalogid .. i need include narrow down items down 1 of each , variable if can figure out use in statement. i've tried viewstate[""] request.querrystring[""] session[""] and cant seem work.. the problem having is, current shopping cart if not have item filter, return every instance of particular product in database because there 250 listings of 1 item different catalogs, , itemprofilecatalogid comes in, filter down 1 item any suggestions? thank you catalogid numeric , using string in sql statement. it have syntax error i...

c++ - How to define an AnimationSet in 3DS Max for the Direct3D Animation Controller -

i'm building direct3d app using c++. managed load mesh hierarchy x file found in tutorial had different animations or tracks build it. , tutorial explained worked fine. able switch between animations in app. i had no luck custom made x file however. the animation defined in 3ds max , converted x plays nice. don't seem find way switch between animations. can't define different animation sets in 3ds max. possible achieve using 3ds max? i tried find programing solution define animationsets animationcontroller using code can't seem find tutorial on topic. so if knows of such tutorial or knows how make animations sets (tracks) in 3ds max, please enlighten me. you not state exporter use, dug 1 you, http://www.andytather.co.uk/panda/directxmax.aspx this plugin 3dsmax supports animation naming named animation sets, amongst many other features.

xml - android customize spinner -

i want know if possible customize textview. want spinner define xml used layout background in xml put <?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <stroke android:color="#ffffff" /> <solid android:color="#ffffff" /> <padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" /> <corners android:radius="10dp" /> <size android:height="70dip" /> </shape> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/arrow_icon" android:gravity="right" /> but doesn't work want have in css, define round corners, pad...

How should I bind lua functions to C++ functions? -

i have class called entity, has many functions onpickup, ondrop, onuse etc. want is, write script defines of these functions , make them callable c++ functions. functions defined in c++ calling corresponding lua functions have functionality. but here's problem, want every script write, every entity in program working in it's own scope. i'm using luabind, , have no prior experience lua, i'm little lost here. i don't use lua bind may help. idea register lua functions in c++ class , keep reference lua function in c++ class. to define lua function callable c/c++ use lual_ref store reference callback function in c++ object. // little helper function template <typename t> t *lua_getuserdata(lua_state *l) { assert(lua_isuserdata(l, 1) == 1); t **v = (t **) lua_touserdata(l, 1); assert(v != null); return *v; } int lua_formregistermethods(lua_state *l) { entity *f = lua_getuserdata<entity>(l); assert(lua_istable(l, 2)...

change color value with colorpicker -

how change bgcolor of 'colorid'. tried code below , want bgcolor change in value 'val'. on m doing wrong. <script type="text/javascript"> function updatevariable(elm) { val = elm; var divelement = document.getelementbyid(colorid); divelement.bgcolor = val; } </script> <table width="150" border="0" cellspacing="1" cellpading="0" align="center"> <tr> <td bgcolor="#190707" onclick="updatevariable(this.bgcolor)">&nbsp;</td> <td bgcolor="#fa5858" onclick="updatevariable(this.bgcolor)">&nbsp;</td> <td bgcolor="#f4fa58" onclick="updatevariable(this.bgcolor)">&nbsp;</td> <td bgcolor="#00ff00" onclick="updatevariable(this.bgcolor)">&nbsp;</td> <td bgcolor="#fbefef" onclick=...

Reading a mix of strings, ints and doubles from a file in C++ -

i have .txt file looking this: 1 string other string 3 10,5 20 20 i need read these values different type of variables. far ints , doubles reading file seems working comes strings fun begins. seems strings read try output them whole console crash. edit: "crash" mean "not responding" type of message appears. , code use basically: ifstream file; file.open ("c:\path\file.txt"); file >> int1; getline(file, string1); getline(file, string2); file >> int2; file >> double1; file >> double2; file >> double3; // .... file.close(); edit 2: somehow instead of 1 value of int1 -858993460. i getting confused... edit 3: vales being set not values written in file. first int , first srting fine second string red 0 , doubles red -92559631349317830000000000000000000000000000000000000000000000 since there more values in file , accept pattern type ran cycle them problem after first read values not red again. file.o...

How to write a Perl script to convert file to all upper case? -

how can write perl script convert text file upper case letters? perl -ne "print uc" < input.txt the -n wraps command line script (which supplied -e ) in while loop. uc returns all-uppercase version of default variable $_ , , print does, well, know yourself. ;-) the -p -n , print in addition. again, acting on default variable $_ . to store in script file: #!perl -n print uc; call this: perl uc.pl < in.txt > out.txt

jersey RESTful & shiro & oAuth tutorial -

i'm looking jersey & shiro & oauth tutorial secure resouces. hint great. i've written jersey + shiro tutorial weeks ago. shiro's team working on oauth authentication integration. a complete integration , guess you'll have wait version 1.2.

casting - Java annotation dynamic typecast -

i have 2 java annotation types, let's xa , ya. both have method(). parse source code , retrieve annotation object. i'd dynamicaly cast annotation real type of able call method(). how can without instanceof statement? want avoid switch-like source. need this: annotation annotation = getannotation(); // recieve annotation object here string annotationtype = annotation.annotationtype().getname(); ?_? myannotation = (class.forname(annotationtype)) annotation; annotation.method(); // need, method() called ?_? means have no idea myannotation type. cannot use base class xa , ya annotations since inheritance in annotations not allowed. or possible somehow? thanks suggestion or help. why don't use typesafe way retrieve annotation ? final yourannotationtype annotation = classtype.getannotation(yourannotationtype.class); annotation.yourmethod(); if annotation can't found, null returned. please note works fields , methods.

javascript - Submitting passwords via ajax -

given following scenario: have html form changing account's password. looks this: currentpassword: __________________ newpassword: __________________ newpasswordagain: __________________ we want send request via ajax call. if send , leave our computer (without logging out , staying on exact same page) open webkit inspector (or firebug) , see this: http://cl.ly/3y213w1q0u2y2e251k0o what solution making more secure? possible using ajax call here or better use "normal" html form reloads whole page after sending? the author not interested in encrypted connections here. may doing already. wants able hide password (and username) 1 has access computer, , can open inspector tools view networking occurred on page. one of simplest things refresh page in case authentication succeeded. something should refresh page whenever user pressed "log out". should clear previous network data. the less options encrypting, obfuscating , hashing passw...

matlab - store index of matrix for minimum -

i have 2d matrix ac(yr,j) . want compare each value of 1d array , store value of array absolute minimum coming. for yr=1:32, j=1:12, in=1.5:1:32.5, actin=ac(yr,j); kar(in-0.5)=abs(in-actin); dab(yr,j)=min(kar(kar>=0)); end end end i'm able find least positive value not value of in coming. you need call max shown below in order index instead of value . [~, dab(yr,j)] = min(kar(kar>=0)); in order rid of nested loops try arrayfun . define operation performed on every array element. function [index] = myminfunction(value, data) [val, index] = min(abs(data - value)); end execute defined operations. dab = arrayfun(@(x)myminfunction(x, in), ac)

What data structure should I use in Java multithreading? -

there new project planning start in few days , review done on design points. there old legacy code uses hashtable in memory database. there 1 thread consumes xml feed files , sockets , populates hashtable , thread validation , update , third thread persists validated data in database if validation successful. as performance struggling during update (meaning other 2 threads catching fast , waiting validation thread complete), planning use concurrenthashmap prototype solution , create more 1 thread validation. still in prototyping stage feedback on if going in right direction. thank in advance. i don't think concurrent hash map going help. assume create number of entries in hash table , upon validation, store them in database. problem persistence thread has wait validation complete. if entries in hash table interrelated , validator must check of them - there not can wait. however, if can break down validation in smaller chunks (easiest case if entries not relate...

ios4 - Use VirtualBox to compile iPhone app (via PhoneGap or Titanium) on Windows 7 machine? -

is possible use virtualbox (https://www.virtualbox.org) compile iphone app on windows 7 machine? specifically, utilize phonegap (http://www.phonegap.com) or titanium (http://www.appcelerator.com/) build iphone app. phonegap requires mac os x snow leopard, install on instance of virtualbox. has done before? yes, understand violates apple's tos. prototype. i recommend looking phonegap build https://build.phonegap.com/ phonegap build allows upload source build service , app-store ready packages variety of platforms. as far can tell, thing need mac in process set provisioning profiles , developer certificate. upload phonegap's service. there seems should able use non-apple computer develop , upload service.

android - IndexOutOfBounds on Spinner? -

i have problem interpretation of stack trace.. peoblem there no class package , hard me find out happening.. fallowed trace, think it's adapter , spinner, on page have 6 spinners, debug them , didn't find weird (like selecteditemposition or something).. maybe had similar problem? here's th trace. if need code, tell me uncaught handler: thread main exiting due uncaught exception java.lang.indexoutofboundsexception @ java.util.arrays$arraylist.get(arrays.java:72) @ android.widget.arrayadapter.getitem(arrayadapter.java:298) @ android.widget.arrayadapter.createviewfromresource(arrayadapter.java:351) @ android.widget.arrayadapter.getview(arrayadapter.java:323) @ android.widget.absspinner.onmeasure(absspinner.java:198) @ android.view.view.measure(view.java:7987) @ android.view.viewgroup.measurechildwithmargins(viewgroup.java:3023) @ android.widget.linearlayout.measurechildbeforelayout(linearlayout.java:888) @ android.wi...

php - Advice me on the algorithm to match people -

currently working on project need match people based on categories of food like: this scenario: i have list of users , favorite foods in database. database structure follows: users(id,name,email,gender,dob) fav_food (id,user_name,food,desc) data users table: 1, alice, alice@lala.com, female, 11 oct 2010 2, bob, bob@lala.com, male, 12 oct 2010 3, jason, jason@lala.com, male, 13 oct 2010 data fav_foods table: 1, alice, apple, desc 2, alice, banana, desc 3, alice, pear, desc 4, bob, apple, desc 5, bob, custard cake, desc 6, jason, banana,some desc 6,jason,apple,some desc imagine alice apple,banana & pear. how able match people based on favorite food? example, first check if likes apple,banana , pear (inclusive of three) , go permutation of 2 combination (apple,banana)(apple,pear)(banana,pear)(banana,apple) ....and on..... imagine venn diagram interaction interested. interested suggest users matched. there algorithm available can use php? ...

version control - Comparison of TFS and CVS -

i migrate java project cvs tfs . use eclipse ide development , unsure drawbacks of tfs on cvs. please let me know if know any. tfs works best visual studio suite, else , find quite struggle. eclipse doesn't have hooks tfs unlike visual studio, struggling little when comes checking in/out files (unless there plugin not aware of) tfs expensive. need tfs server, , need client access (vs team edition , similar or team explorer) also, can't check out multiple branches/versions (from memory). you're stuck 1 working directory managed team explorer. to fair, tfs step cvs. why stop there? please 4th generation source control git, mercurial (being main 2) etc.

android - facebook authentication dialog disappearing instantly -

i using latest facebook android sdk when call mfaceboo.authorize(...) method dialog box not appearing instead full screen page showing second , instantly disappears. i noticed have updated official facebook client app in device. when have removed updates facebook client authentication dialog working fine. but problem can't force users of app not update facebook client app. facing same problem or knows solution please help. following snippet using. mfacebook.authorize(myprofilescreen.this, permissions, new dialoglistener() { @override public void oncomplete(bundle values) { /* * here we'll token can store further use. */ log.v(tag, "facebook login success! "); launchprofilescreen(); } @override public void onfacebookerror(facebookerror e) { // todo auto-generated method stub log.v(tag, "onfacebookerror"+e.getmessa...

c# - IL: ldfld vs ldflda -

i'm writing small il-weaving application using mono.cecil, requires me manipulate target assembly on il level. my question quite simple, still find matter confusing. what practical difference between ldfld , ldflda instructions? i have consulted msdn, , appears while ldfld fetches value of field, ldflda gets address of field. okay... mean? first thought former used value types (and string), , latter reference types, have compiled c# snippet , checked in reflector, , proved me wrong. i haven't been able find distinct pattern in when c# compiler emits ldflda instead of ldfld , , searches didn't reveal articles explain this. when use ldflda instead of ldfld ? any appreciated. i guess used struct ures: struct counter { public int i; } struct { public counter c; } s; s.c.i++; i pretty sure c here loaded address otherwise create copy of counter . that's why can't propery.

c++ - Retrieving and editing private members of objects in a vector -

i have code adds few objects vector. wish retrieve specific object vector , able both write out , edit private member variables. this code have: class product { public: product(int n, const string& na, int p) : number(n), name(na), price(p) {}; void info() const; private: string name; int number, price; }; the member function looks this: void product::info() const { cout << number << ". " << name << " " price << endl; } i create vector , push objects, so: vector<product> range; range.push_back(product(1, "bagpipe", 25)); to retrieve , list information objects, have following function: void listproducts (const vector<product>& range1) { for_each (range1.begin(), range1.end(), mem_fun_ref(&product::info)); } but stuck. to boil problem down: have no idea how retrieve individual objects vector , edit them. need able search vector objects containin...

android - Howto make a layout similar to the ones in settings -

i have android activity need have user enter information. data lends preferenceview listpreferance elements. sure use preferences interfaces need, cludgy. there way these same widgets in regular view? i solved same issue following similar approach 1 listed here . boils down providing preference xml preferenceactivity , backing own model, instead of default sharedpreferences. in example uses database if don't have backing database (or don't want commit whenever setting changed) can use map backing editor.

Adding wordpress shortcodes with template file -

i'm making wordpress theme, , got stuck on page template making, need help... i want template add shortcodes users text edit box, when selected. example: 3 column home page should add: [column1][/column1] [column2][/column2] [column3][/column3] is there way code this? this plugin you'd like, or if you'd rather write 1 suggest wordpress codex , this page . code you'd little large , complex slap in here , wouldn't learn useful.

email - Which MX server should I enter for my Mail to go to the mail hosting company -

i going set application on heroku not offer mail services. the company doing has mail service company. previous web host changed mx record on servers point company. my domain name provider network solutions. set mx records on network solutions point mail service company if domain points dns on heroku? i noob , don't want mess companies email. appreciated. yes, should point mx record mail service company. should investigate how setup ptr record mx host maps ip hostname. may need have mail service provider you. ptr record helps in getting domain's email through other mail servers' spam filter.

cython - Can someone tell me what this c code is doing? -

cansome tell me going in cython code. full code can seen at: https://github.com/scipy/scipy/blob/master/scipy/spatial/ckdtree.pyx # standard trick variable-size arrays: # malloc sizeof(nodeinfo)+self.m*sizeof(double) bytes. cdef struct nodeinfo: innernode* node double side_distances[0] it's old c trick. if don't know how many side_distances needed, because varies 1 instance of nodeinfo another, declare array size zero. when allocate memory node, allocate size of struct as defined ( sizeof(nodeinfo) ), plus memory number of values want in particular instance ( +something * sizeof(double) ). result for instance , have enough memory array of size specified. it's "trick" in sense uses allocate separate array , store pointer in array. keeping in 1 allocation (attempted) optimization. iirc, though, zero-sized array allowed c++ standard, not c standard. in c, should define flexible-sized array side_distances[] , although no doubt many comp...

eclipse - Android : opening existing Android project -

Image
when import existing project or create new project create show windows not shows package pane show files list. goto window menu >> show view >> package explorer can show package explorer @ left side.you can show import project

visual studio - cant understand the concept of the many projects in one solution in vs2010 -

i seem having difficulty in understanding reason behind need of having many projects inside 1 solution (in case visual studio 2010 c#). the use comes mind if creating new classes can test them in console application first, add project solution use these classes project want. kindly guide me correct way, thanks. there 3 main reasons come mind splitting solution multiple projects: reuse, encapsulation, , project-specific settings. reuse may have utilities project shared between more 1 solution. may have data access , business rules defined in class libraries, shared between multiple ui projects, such having business application has web interface, desktop interface, , web services. need share same logic , data model, wouldn't want replicate in each solution separately. encapsulation reason achieve encapsulation, 1 of main principles of oop. classes may have internal methods , properties (or classes may defined internal), makes them visible other classes in same ...

python - How to invoke the right method in django inherited model -

i have model classes b , c implements method f , inherits model class a. want invoke function f on instances (b , c). why do for in a.objects.all(): a.f() doesn't work expected? that's because default django manager doesn't manage polymorphism. when do for in a.objects.all(): … all a objects of type a, , no type b or c. you need use django-model-utils application, , it's select_subclasses tool: for in a.objects.select_subclasses(): # type(a) returns correct subclass

python - Sqlalchemy many to many mapping with extra fields -

i created many many relationship sqlalchemy this: subject_books = table('subject_books', base.metadata, column('subject_id', integer, foreignkey('subjects.id')), column('book_id', integer, foreignkey('books.id')), column('group', integer) ) class subject(base): __tablename__ = 'subjects' id = column(integer, primary_key=true) value = column(unicode(255), unique=true) class book(base): __tablename__ = 'books' id = column(integer, primary_key=true) title = column(unicode(255)) isbn = column(unicode(24)) subjects = relationship('subject', secondary=subject_books, collection_class=attribute_mapped_collection('group'), backref='books') after created test following: book = book(title='first book',isbn='test') book.subjects[0] = subject(value='first subject') book.subjects[1] = subject(value='second subject') session....

I want to know all about encodings -

i don't understand encodings. also want know differences between different encodings , how space 1 character take in encoding? , how encodings matter? how matter web browser when sending html? best encoding use in web applications made in english? ascii? it if can explain starting basics. you can start following books: unicode explained, http://www.amazon.com/unicode-explained-jukka-k-korpela/dp/059610121x fonts & encodings, http://www.amazon.com/gp/product/0596102429/ you can check out following free e-books (currently in draft version) provide lots of information encoding , multi-lingual text processing: lingpipe , text processing books, http://alias-i.com/lingpipe-book/index.html

Thousand separator in C++ -

i want create string in c++ following format: string + numberswithformatandthousandseparator + string i not sure whether std::string or snprintf() provides format thousand separator. me this? fast , easy way: std::ostringstream ss; ss.imbue(std::locale("en_us.utf-8")); ss << 1033224.23; return ss.str(); would return string "1,033,244.23" but requires en_us.utf-8 locale configured on system.

Javascript/JQuery event arguments. I don't understand what this 'e' argument is or does -

jquery: this.savebutton.click(function (e) { scope.saveform(); }); this simple line of jquery binds .click() event savebutton object , calls saveform function when event fired. when event called, 'e'? don't think ever used. the e can used obtain specific information click (left, right or center; coordinates clicked; dom object clicked on), specific code sample doesn't use it. see http://api.jquery.com/category/events/event-object/ details what's available.

windows - C++ How to make two programs communicate? -

question: what best way make 2 programs (both running on same computer) communicate , interact? (windows, c++) theoretical situation: on windows pc, have 3rd party software use stuff (like open/edit/save files...it's not important). 3rd party software has available c++ sdk can develop plugins it. i develop separate standalone windows c++ program (most using qt) gui. program made run on same windows computer 3rd party software. program act remote control or sender. using 3rd party software's sdk, develop tiny plugin 3rd party software . program acts receiver, qt gui can send commands plugin receive , remote control 3rd party software accordingly . so basic example, press button on standalone gui communicate plugin open specified file in 3rd party software. what i'm looking develop standalone software communicate , forth plugin develop 3rd party software. what best approach this? have no clue start or at. there common c++ libraries make type of thing e...

c# - MVC 3 solution with two views/controller/model. (Possible MVC, MVP hybrid?) -

i starting mvc 3 , planning in separating model , controllers own separate projects. i'll follow suggestions made post this: asp.net mvc put controllers separate project the purpose of separating them separate projects there chances may have add web service project solution , i’d reuse same functionality exposed controller project. solution formed of 2 view projects, webservices , website, controller project , model project. i’d know if possible , if it’s common scenario mvc. update 1: with suggestions agree , think it’s best keep view , controllers together. would possible have hybrid of mvc , mvp? have feeling overdoing things here please let me know think. so have: 1 – web project controllers. 2 – webservices project 3 – presenters/interfaces. 4 – model. the controllers become views in mvp model. each web service become view in mvp model. for instance have following, interface, presenter , controller. public interface icustomers { string[] cust...

c - Read double from void * buffer -

please excuse lack of understanding, i'm beginner c. so, have void * buffer calloc this: void * databuffer = calloc(samples, sizeof(double)); and later read this: double mydoubledb = databuffer[sampleindex]; but error because of different types (void , double). how can achieve this? arch arm , i'm using gcc compile update: databuffer out of reach (other library) , comes void * if can make pointer double in first place, better. double * databuffer = calloc(samples, sizeof *databuffer); double mydoubledb = databuffer[sampleindex]; otherwise, unsafely explicitly convert void* double* cast: void * databuffer = calloc(samples, sizeof (double)); double mydoubledb = ((double*)databuffer)[sampleindex];

javascript - backbone.js - controller properties from a view -

i have controller property called authenticated defaults false . however, in login view need able set true . also, in logout view need able set false . how can expose property within view? var controller = backbone.controller.extend({ ... authenticated: false, login: function() { if(this.authenticated) { location.hash = '!/dashboard'; } else { new loginview(); } }, logout: function() { $.post('/admin/logout', {}, function(resp){ }, "json"); this.authenticated = false; location.hash = '!/login'; } ... }); your controller correctly doing login , logout functionality. need have view fire backbone.js events , have controller registered receive those. somewhere in controller, need like: var loginview = new loginview(...); // params needed loginview.bind("login_view:login", this.login); loginview.bind(...

java - wrong setting an arraylist -

i want ask question arraylist. in program defined arraylist , user defined object. problem when want add object arraylist, adds object, next time when give different values user object, sets values of old object added before new one. mean, example have 13 in old object , new 1 14, makes old 1 14. couldn't find solution this. i'm working on drawing program. i'm posting parts of code. public class tester extends jpanel implements mousemotionlistener, mouselistener { arraylist<lines> array = new arraylist<lines>(); lines l1; ... public tester(){ l1 = new lines(); l1.point1 = new point(); l1.point2 = new point(); l1.denklem = new int[3]; and thi how add object arraylist else if(lineci == true){ if(mouseclicks == 0){ l1.point1.x = e.getx(); l1.point1.y = e.gety(); statusbar.settext( string.format( "clicked @ [%d, %d]", e.getx(), e.gety() )...

How to initialize a multi-dimensional array in a C++ constructor -

i have class contains few multi-dimensional arrays. trying initialize these arrays in constructor, having trouble figuring our how it. array of fixed size. here's have far: class foo { private: int* matrix; //a 10x10 array public: foo(); foo:foo() { matrix = new int[10][10]; //throws error } the error is: cannot convert `int (*)[10]' `int*' in assignment how can accomplish this? preferably, array default 10x10 array of 0s. #include <memory.h> class foo { public: foo() { memset(&matrix, 100*sizeof(int), 0); } private: int matrix[10][10]; }; that is, if you're not binding doing pointers (otherwise can pass in pointer memset, rather reference array).

android - Bitmap size exceeds VM budget -

i passing image xml,by resize image size using: scaled = bitmap.createscaledbitmap(bp, h, w, true); imgv.setimagebitmap(scaled); but getting bitmap size exceeds vm budget. 04-30 18:36:16.552: error/androidruntime(7164): fatal exception: main 04-30 18:36:16.552: error/androidruntime(7164): java.lang.outofmemoryerror: bitmap size exceeds vm budget 04-30 18:36:16.552: error/androidruntime(7164): @ android.graphics.bitmapfactory.nativedecodeasset(native method) 04-30 18:36:16.552: error/androidruntime(7164): @ android.graphics.bitmapfactory.decodestream(bitmapfactory.java:460) 04-30 18:36:16.552: error/androidruntime(7164): @ android.graphics.bitmapfactory.decodestream(bitmapfactory.java:525) 04-30 18:36:16.552: error/androidruntime(7164): @ com.webrich.bachflower.topiccontroller.getimagebitmap(topiccontroller.java:103) 04-30 18:36:16.552: error/androidruntime(7164): @ com.webrich.bachflower.topiccontroller.oncrea...

css3 - Why is webkit radial gradient not working in Safari? -

this working in chrome not in safari: background: -webkit-radial-gradient(center, ellipse cover, #fdfdfd, #d3d3d3); how can fix safari? try using safari: background: -webkit-gradient( radial, <point>, <radius>, <point>, <radius>[, <stop>]* ) <color>; examples , more explanation can found here: http://www.the-art-of-web.com/css/radial-gradients/

iphone - insertRowsAtIndexPaths crashes on endUpdates in tableView:willDisplayCell:forRowAtIndexPath only if user scrolls quickly -

ok title suggests, trying insert more rows in uitableview when user scrolls bottom of list. whole reason lazily load data performance reasons large data set. the odd thing if scroll works fine, if scroll crashes on [tableview endupdates]; the datasource nsmutablearray loads data coredata, using common fetchrequest. cannot use fetchedresultscontroller in current circumstances. the datasource count correct before , after insert called. row count (and data source count) correct. if scroll , later @ point scroll quickly, crashes, same error index being beyond bounds, index , bounds in error message incorrect original counts when tableview first bound (and before insertions occured). ie row count of 4 , datasource count of 4 & etc. this error: terminating app due uncaught exception 'nsrangeexception', reason: '*** -[__nsarraym objectatindex:]: index 3 beyond bounds [0 .. 2]' i tried inserting rows during cellforrowatindexpath method same result. any ...

android - Bitmap size exceeds VM budget -

actually using background image image(these downloaded image),images in different size keep image fit insite background image using create scaled bitmap.i have 38 image ,i need display 1 one when press nextbutton backbutton using imageid in xml passing 38 images in single xml,in case showing bitmap exceeds vm budget try use small size bitmap, error occurs because of buffer

wpf - ErrorTemplate for PasswordBox with AttachedProperty -

i know passwordbox in wpf not use validation.errortemplate, anyhow have show user, wrong. my passwordbox has binding <passwordbox name="password" local:passwordhelper.text="{binding passwordprop, mode=twoway}" /> is possible same style default errortemplate (red border) passwordbox, if wrong? this errortemplate use other controls <style x:key="basecontrolstyle"> <setter property="control.fontfamily" value="verdana" /> <setter property="control.fontsize" value="12" /> <setter property="tooltipservice.showondisabled" value="true" /> <setter property="validation.errortemplate" > <setter.value> <controltemplate> <dockpanel lastchildfill="true"> <image x:name="bild" dockpanel.dock="right" ...

Visual C++ assertion failure -

i creating program copy text file. have main.cpp file reads in text file given filenamein array , output copy of text file given filenameout array. have function declared in fileutilities.h bool textfilecopy(char filenamein[], char filenameout[]); then fileutilities.cpp contains #include <iostream> #include <fstream> #include <string> #include "fileutilities.h" bool fileutilities::textfilecopy(char filenamein[], char filenameout[]) { ifstream fin(filenamein); if(fin.is_open()) { ofstream fout(filenameout); char c; while(fin.good()) { fin.get(c); fout << c; } fout.close(); fin.close(); return true; } return false; } when compile visual c assertion failure. dialog box titled "microsoft visual c++ debug library" contains following: "debug assertion failed! program: .....parser.exe file f:\dd\vctools\c...

c - Segmentation Fault - Could not Access Memory, Kern_Invalid_Address -

im getting error, be??? program received signal exc_bad_access, not access memory. reason: kern_invalid_address @ address: 0x0000000000000000 0x00007fff86703c00 in strlen () i ran in gdb , first thing appears. doesnt tell me on line can find error... on terminal error: segmentation fault im positive error in area "funcion busqueda" im pasting whole thing can tell me if spot else. i need find cause segmentation fault!!! beeeee!? #include<stdio.h> #include<stdlib.h> #include<string.h> #include "clientes.h" int ordena(lista1 *inicio,lista1 *aux,lista1 *nodo,lista1 *aux2); int agrega_cliente(lista1 *inicio, lista1*aux,lista1 *nodo,lista1 *aux2); int busca_cliente(lista1 *inicio, lista1*aux,lista1 *nodo,lista1 *aux2,lista2 *inicioventas,lista2 *auxventas,lista2 *nodoventas,lista2 *aux2ventas); int main(void) { int menu,pops=0; lista1 *inicio, *aux,*nodo, *aux2; inicio=null; aux=inicio; lista2 *inicioventas, *auxventas,*nodoventas...

mysql - Group by doesn't give me the newest group -

i trying distinct result table, , people said should use group by. worked half way... distinct result result not newest thread... table contains status on apartments several buildings. apartments can found many times since it's history table... need make select retrieves distinct apartments current status. id building apartment_id status 1 1 1 1 2 1 1 2 3 2 2 3 4 2 4 2 5 2 3 2 6 2 5 1 7 2 6 1 i'm working with: select * `ib30_history` group apartment_id, building order id desc select building , appartment_id , status ib30_history id = ( select max(id) ib30_history b b.building = a.building , b.appartment_id = a.appartment_id)

ruby - How to extend class Object in Rails? -

i add method nil_or_empty? classes, therefore define module objectextensions def nil_or_empty? return self.nil? || (self.respond_to?('empty?') && self.empty?) end end ::object.class_eval { include ::objectextensions } it works fine in simple ruby script p nil.nil_or_empty? #=> true p ''.nil_or_empty? #=> true p [].nil_or_empty? #=> true p 0.nil_or_empty? #=> false however, when add library file lib/extensions.rb in rails 3 app, seems not added nomethoderror (undefined method `nil_or_empty?' nil:nilclass): app/controllers/application_controller.rb:111:in `before_filter_test' i load library file (all other extensions file working fine) and # config/application.rb # ... config.autoload_paths << './lib' where wrong? first, it's cleaner reopen object class directly: class object def nil_or_empty? nil? || respond_to?(:empty?) && empty? # or shorter: nil? || try(:empty?) ...

optimization - Swarm Intelligence - what kinds of problems are effectively solved? -

i looking practical problem (or implementations, applications) examples algoritmized using swarm intelligence . found multicriteria optimization 1 example. there others? imho swarm-intelligence should added tags are looking toy problems or more real-world applications? in latter category know variants on swarm intelligence algorithms used in hollywood cgi animations such large (animated) armies riding fields of battle. related more towards toy-problem end of spectrum can model large crowds similar algorithms, , use example simulate disaster-scenarios. afaik dutch institute tno has research groups on topic, though couldn't find english link googling. one suggestion place start further investigation pdf book: http://www.cs.vu.nl/~schut/dbldot/collectivae/sci/sci.pdf that book has appendix (b) sample projects try , work on. if want head start there several frameworks (scientific use) multi-agent systems such swarming intelligence (most of 'em written ja...