Posts

Showing posts from August, 2010

Implementing Good hashCode function in java? -

i know days inbuilt utilities available hashcodebuilder apache commons lang trying understand how implement myself , came across example of hascode function employee class @ http://en.wikipedia.org/wiki/java_hashcode() everywhere on google, same kind of technique suggested multiplying non 0 value odd prime number , summing instance variable(do instance variable). questions:- 1)why can't return employeeid hascode becoz aways unique. simple , serves hascode purpose. agreed if not unique need kind of technique. right? 2)even if employee id not unique, why suggested multiply odd prime number? why taking damn integer not considered good? update:- peter ran example mentioned printed [0, 32, 64, 96, 128, 160, 192, 224, 288, 256, 352, 320, 384] [0, 32, 64, 96, 128, 160, 192, 224, 288, 256, 352, 320, 384] i assume output yoy expected understand concept mentioned in answer [373, 343, 305, 275, 239, 205, 171, 137, 102, 68, 34, 0] [0, 34, 68, 102, 137, 171, 20

ios - iCloud sync fails with "CoreData: Ubiquity: Invalid option: the value for NSPersistentStoreUbiquitousContentNameKey should not contain periods" -

coredata: ubiquity: invalid option: value nspersistentstoreubiquitouscontentnamekey should not contain periods: com.yashwantchauhan.outis -pfubiquityswitchboardentrymetadata setuselocalstorage:: coredata: ubiquity: mobile~20bf44c9-c39f-48dc-a8a1-b45fc82c7e20:com.yashwantchauhan.outis i have problem syncing icloud. these 2 errors above thrown @ me. don't know what's problem, setup entitlements file, , set ubiquity container com.yashwantchauhan.outis . i start coredata stack using magicalrecord's method: [magicalrecord setupcoredatastackwithicloudcontainer:@"n6tu2cb323.com.yashwantchauhan.outis" localstorenamed:@"model.sqlite"]; but shouldn't matter since magicalrecord simplifies coredata methods. help appreciated. ok update: -[nsfilemanager urlforubiquitycontaineridentifier:]: error occurred while getting ubiquity container url: error domain=librarianerrordomain code=11 "the operation couldn’t completed. (lib

ruby on rails - Querying changed model attributes in rake task -

i'm performing periodic rake task update attributes in user model. i'd execute mailer if particular attribute has changed, can't call attribute_changed? module doesn't know instance query - you'd in model after_save callback. so have this: task :my_task => :environment user.all.each |user| @howmanythings = user.things.size user.update_attribute(:total_things, @howmanythings) user.save //this bit not work: if user.total_things_changed? == true send mailer end end end at moment, user. total_things_changed? returning false , regardless of whether rake task has updated attribute. in short, how execute after_save callback (or equivalent) within task? many in advance. activerecord::dirty tracks unsaved attribute changes. moment save model, foo_changed? methods start returning false . note update_attribute saves model. you like @howmanythings = user.things.size user.total_things = use

firebase - How to update using angularFireCollection which items not exist previously -

i have parent node text , want add media parent node if text changed update well. { parent: { text: 'this content' } } the media value third-party callback. how pass update() ? tried {media: callbackval} not working. $scope.parent = angularfirecollection(firebaseref.child('parent')); $scope.parent.update(what_to_do_here, function(error){ //something... }); update maybe question not clear enough. in firebase js, can update or insert media node. new firebase(firebaseref).update({ media: 'value'} ); how in `angularfirecollection ? check out annotated angularfire source: http://angularfire.com/src/angularfire.html#section-38 it looks angularfirecollection.update() takes key/item , callback function. need edit entry want update directly in angularfirecollection, (e.g. $scope.parent.getbyname('media').value = 'alligator scrimshaw' ) , call $scope.parent.update($scope.parent.getbyname('media'), function(

java - hasNext and findInLine in Scanner Class using array -

i'm new java, have years experience in c, hope can me. i have decimal file , need find header , there pick data , again header. lets file looks this: 480 124 125 001 047 001 047 001 480 001 001 001 001 001 001 001 001 001 001 001 001 047 001 480 002 002 002 002 002 002 002 002 my header is: 001 047 001 480 the header stored @ int array called "header". i tried multiple ways- code: integer i1 = new integer(this.header[0]); integer i2 = new integer(this.header[1]); integer i3 = new integer(this.header[2]); integer i4 = new integer(this.header[3]); nextdec.hasnext(i1.tostring() + i2.tostring() + i3.tostring() + i4.tostring()); returns false, though expect true. returns false if delete leading zeroes of header numbers in file (in reality can't delete them) the code: nextdec.findinline(i1.tostring() + " " + i2.tostring() + " " + i3.tostring() + " " + i4.tostring()); returns null, though expect return

php - Swift Mailer automatic sending form data -

i'm trying configure swift mailer send form data email account in short: have website, using going sell stuff in local city there 3 simple forms appear when 'buy' button active point send data, filled in these forms directly email account, being newbie php, have tried several days make simple script work, ended failure here code of mail.php: <?php $name=$_post["name"]; $email=$_post["email"]; $phone=$_post["phone"]; if (isset ($name)) { $name = substr($name,0,30); if (empty($name)) { echo "<center><b>invalid name<p>"; echo "<a href=index.php>come , fill form properly</a>"; exit; } } else { $name = "invalid name"; } if (isset ($email)) { $email = substr($email,0,30); //Не может быть более 20 символов if (empty($email)) { echo "<center><b>email invalid!<p>"; echo "<a href=index.php>try again</a>"; exit; } } else { $email = &quo

node.js - Using Q to create an async user input sequence -

i toying q , promptly , trying ask, in sequence, user input stuff. example : what name? bob age? 40 hello bob (40)! (yes! it's simple "hello world!" program.) and here code trying, directly q's github project page : q.fcall(promptly.prompt, "what name? ") .then(promptly.prompt, "what age? ") .done(function(name, age) { console.log("hello " + name + " (" + age + ")"); }); }); but not working expected (maybe i'm reading wrong?). whatever try, seems promptly.prompt listening keystroke in parallel, , .done function called right away, resulting /path/to/node_modules/promptly/index.js:80 fn(null, data); ^ typeerror: undefined not function @ /path/to/node_modules/promptly/index.js:80:9 ... once hit enter . idea why doing , how can accomplish i'm trying do? ** edit ** basically, end goal create reusable function invoked : promptall({ 'nam

android - Comparing two tables in Sqlite using common column -

i'm creating app automatically lists calls , sms of day in order of time. completed codes store both sms , calls database using services. have 2 table: table call(number, name, call_type, call_duration, date, time, time_in_milliseconds (long)) table sms(number, name, message, date, time, time_in_milliseconds (long)) i need compare both tables based on time_in_milliseconds , , retrieves entire row , set text view in order of time_in_milliseconds increases. if understand correctly can use code: ourdatabase.rawquery("select number, name, call_type, call_duration, date, time, time_in_milliseconds " + " call " + " union " + " select number, name, message, date, time, time_in_milliseconds " + " sms " + " order time_in_milliseconds", null);

node.js - Error while installing express using npm -

i have installed express using npm install express but looks in order create apps should install globally. used: npm install -g express but received: npm err! error: eacces, mkdir '/usr/lib/node_modules/express' npm err! { [error: eacces, mkdir '/usr/lib/node_modules/express'] npm err! errno: 3, npm err! code: 'eacces', npm err! path: '/usr/lib/node_modules/express', npm err! fstream_type: 'directory', npm err! fstream_path: '/usr/lib/node_modules/express', npm err! fstream_class: 'dirwriter', npm err! fstream_stack: npm err! [ '/usr/lib/node_modules/fstream/lib/dir-writer.js:36:23', npm err! '/usr/lib/node_modules/mkdirp/index.js:37:53', npm err! 'object.oncomplete (fs.js:107:15)' ] } npm err! npm err! please try running command again root/administrator. npm err! system linux 3.11.2-201.fc19.x86_64 npm err! command "node" "/usr/bin/npm" "

css - Stop borders from expanding into Margins/Padding -

i trying create meta section blog posts using twitter bootstrap. issue i'm running borders around divs expanding out negative margins of row , can't figure out why (borders in other divs not having problem). if me figure out how stop top , bottom borders expanding left , right padding/margins, appreciated. here's applicable css: .row { margin-right: -15px; margin-left: -15px; } .col-md-3 { width: 25%; float: left; } .meta-entry-right{ border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; font-size: 12px; text-transform: uppercase; color: gray; } .meta-entry{ border-top: 1px solid #ddd; border-bottom: 1px solid #ddd; border-right: 1px solid #ddd; font-size: 12px; text-transform: uppercase; color: gray; } and here's html: <footer class="row"> <div class="col-md-3 meta-entry"> author: <br> <?php the

jquery - Chage text options in Wordpress -

i generated form wordpress plugin , can't put spaces on text. want change text of options this: unaestrella -> una estrella ... (not value text) <select id="topics" class="taxonomies-filter-widget-input" name="topics"> <option value="0">todas</option> <option class="level-0" value="unaestrella">unaestrella</option> <option class="level-0" value="dosestrellas">dosestrellas</option> <option class="level-0" value="tresestrellas">tresestrellas</option> <option class="level-0" value="cuatroestrellas">cuatroestrellas</option> <option class="level-0" value="cincoestrellas">cincoestrellas</option> </select> is possible change images? i think want this function cameltospc(str) { return str.replace(/([a-z\d])([a-z])/g, 

Android support v7 can't find ActionBarActivity -

Image
i've used manuals available , managed add v7 support android version 2.3 project. i'm trying add actionbaractivity can't found.. although actionbar found... this me trying actionbaractivity. this sdk manager can see can import v7 path, doesn't have actionbaractivity delete support v4 jar file in project/lib folder. you can have there , work support v7 lib, v7 has v4 lib , must have same version work. remove v4 jar file, add v7.

PHP/MySQL - Best way to work with dates in DD MMM YYYY format? -

i need display dates in dd mmm yyyy format on website i'm working on. first thought store dates in date type in mysql, convert proper format using php. however, returning 01 jan 1970 - not actual date of 04 may 1891 . i found few other places people have asked similar questions , answer select date_format(dt, '%d/%m/%y') giving me 04/05/1891 . want month 3 characters (may, jun, jul, aug, etc). i thought storing dates varchar seems bad practice. looks have store date string , not able use php date() function because cannot handle dates prior 1970. i may want things calculate ages sounds painful when dealing strings... wondering if has more elegant solution? you can use date save dates in db. date can store values '1000-01-01 ' '9999-12-31' ( source ) php's old date functions (i.e. date(), strtotime()) on 32 bits , therefore work unix timestamps (they're limited 1970-2038 range). with php 5's new class datetime can e

php - Codeigniter - move_uploaded_file permission(?) issue -

this problem asked before, did not solve case. working codeigniter. i have simple form submits file , want move file folder on server. after submitting can print_r $_files['new-item-file'] array , everythings looks good. but when use move_uploaded_file error: failed open stream: http wrapper not support writeable connections the folder want write in exists , has 777 permissions. dies have solution this? thanks lot! i solved it: move_uploaded_file not seem accept absolute paths. took out base_url(); , worked.

core data - Creating entity with Magical Record only in OSX (+entityForName: could not locate an entity named '(null)' in this model.) -

hi having problem creating entitys magicalrecord in osx, create model , nsmanagagedsubclasses , on. when run code in applicationdidfinishlaunching(i using magicalrecord 2.2): [magicalrecord setupcoredatastack]; person * person = [person mr_createentity]; person.name = @"alex"; i in log: 2013-10-06 18:01:54.320 testmagicalrecord[7554:303] +[nsmanagedobjectcontext(magicalrecord) mr_contextwithstorecoordinator:](0x7fff71a96238) -> created context unnamed 2013-10-06 18:01:54.321 testmagicalrecord[7554:303] +[nsmanagedobjectcontext(magicalrecord) mr_setrootsavingcontext:](0x7fff71a96238) set root saving context: <nsmanagedobjectcontext: 0x101924d00> 2013-10-06 18:01:54.321 testmagicalrecord[7554:303] +[nsmanagedobjectcontext(magicalrecord) mr_newmainqueuecontext](0x7fff71a96238) created main queue context: <nsmanagedobjectcontext: 0x1001564a0> 2013-10-06 18:01:54.321 testmagicalrecord[7554:303] +[nsmanagedobjectcontext(magicalrecord) mr_setdefaultcontext:]

algorithm - Cumulative frequency table with creation in linear or better than linear complexity? -

i trying solve algorithmic problem, , solve within time constrains need implement cumulative frequency table creation takes linear or better linear time? inputs integers only; hence, keys of frequency table integers only. simple implementation came follows (assume cumulative_freq_table hashmap in following code.): read x key in range(x, n): if key in cumulative_freq_table: cumulative_freq_table[key] += 1 i haven't studied algorithms related course, guess complexity around o(n^2). can done in time better o(n^2)? off-line approach if happy use 2 passes can this: for each x: read x freq_table[x] += 1 t = 0 key in range(0,n): t += freq_table[key] cumulative_freq_table[key] = t this linear. on-line approach the problem linear approach requires data seen before can access cumulative frequency table. there alternative approaches allow continual access cumulative frequency, have higher complexity. for example, have @ fenwick trees approach

sql show partition based on calculated column with mysql -

let's pretend have relation: ╔═══════════════════╗ ║ i++ name score ║ ╠═══════════════════╣ ║ 1 123 ║ ║ 2 joe 100 ║ ║ 3 bill 99 ║ ║ 4 max 89 ║ ║ 5 jan 43 ║ ║ 6 susi 42 ║ ║ 7 chris 11 ║ ║ 8 noa 9 ║ ║ 9 sisi 4 ║ ╚═══════════════════╝ now need subset based on data searching for. instance i'm searching fith place. in result need more record of jan, need 2 records before jan , 2 records behind jan too. have following resultset: ╔═══════════════════╗ ║ id++ name score ║ ╠═══════════════════╣ ║ 3 bill 99 ║ ║ 4 max 89 ║ ║ 5 jan 43 ║ ║ 6 susi 42 ║ ║ 7 chris 11 ║ ╚═══════════════════╝ that sql got: select @a:= id quiz.score username = 'jan'; set @i=0; select @i:=@i+1 platz, s.* quiz.score s id between @a-5 , @a+5 order points desc; the problem here @a id of record. there way use calculated value @i:=@i+1 ? thx lot help. if not ne

c - Can't return a pointer in CUDA -

for reason code seems work; bool * copyhosttodevice(bool * h_input, size_t numelems) { bool * d_output; cudamalloc((void **) &d_output, numelems*sizeof(bool)); checkcudaerrors(cudamemcpy((void *)d_output,(void *)h_input,numelems*sizeof(bool), cudamemcpyhosttodevice)); return d_output; } but generates error: bool * copydevicetohost(bool * d_input, size_t numelems) { bool * h_output; cudamalloc((void **) &h_output, numelems*sizeof(bool)); cudamemcpy((void *)h_output,(void *)d_input, numelems*sizeof(bool),cudamemcpydevicetohost)); return h_output; } i'm running remotely, in udacity class on parallel programming. the output when call second function is: we unable execute code. did set grid and/or block size correctly? your code compiled! so getting runtime error. when remove pieces of 2nd fcn, becomes clear error being generated cuamemcpy() call. thanks in advance! in second code using cuda_malloc allo

jquery - Using javascript, how to select an li relative to a specific other li -

given following html list: <ul> ... <li> <li> // <-- item selected <li> <li class='current'> <li> <li> <li> ... </ul> how select li 2 instances ahead of li class current? pure javascript or jquery solution great! making more generic, i.e if want select li possibly(2nd or 3rd or ever instance appears prior selector), try $('li.current').prevall(':eq(' + n-1 + ')'); here n instance # talking (since 0 based index). in case be: $('li.current').prevall(':eq(1)'); do remember prevall returns elements in order starting selector, can provide index of element position in prevall eq selector. fiddle

package - Creating a binary dependant on Qt 5 -

i created development environment fedora 18 , qt 5 when compile app 64 bit, , depend on qt 5. after research seems problem since centos 6.x still dependong on qt 4.6, , centos 5.x dependant on earlier qt, , i'm guessin ubuntu has own package limitations. is there "safe" version of qt can compile against ensure runs everywhere? if not, how can expect customers run program? if want target linux, recommend using qt 4.8 (available on of linux distros), forget qt 5 year or so. hardly linux distro other ubuntu 13.04 , above comes qt 5. secondly, far compiling considered, if wish target linux distros other ubuntu , fedora never use ubuntu or fedora compilation. these bleeding edge linux distros include new libraries without testing. not face problem of old qt versions in linux distros face bigger problem of glibc (c library). make sure linux distro use compilation has minimum possible glibc version qt 4.8, otherwise if linux distro has qt 4.8 installed, has

python - Django - Multi-table inheritance - reverse relation to SubClass -

i appreciate following problem. lets use models django documentation illustrate situation. models.py from django.db import models class place(models.model): owner = djangomodels.foreignkey('owner', related_name='places') objects = passthroughmanager.for_queryset_class(placequeryset)() class restaurant(place): ... members ... objects = passthroughmanager.for_queryset_class(restaurantqueryset)() class pub(place): ... members ... objects = passthroughmanager.for_queryset_class(pubqueryset)() class owner(models.model): ... members ... queryset.py class placequeryset(djangomodels.query.queryset): .. common place filters ... class restaurantqueryset(placequeryset): .. restaurant specific filters ... class pubqueryset(placequeryset): .. pub specific filters ... so can see above have 1 base model 'place' , 2 sub models 'restaurant' , 'pub'. base model 'place' has link 'owner' o

two keys map in C++ -

i plan use map 2 keys assignment. , create map following: map<pair<string, string>, int> mymap; map<pair<string, string>, int>:: iterator it; i had hard time on how use map.find() , map.insert() finding existing entry in map or insert new value if 2 keys combination new. can 1 give example? it should same map, except have make pairs key. insert : map< pair<string,string>, int > mymap; pair<string, string> key = make_pair("bob", "sue"); mymap[ key ] = 5; // can inline make_pair if prefer. // or can use insert method mymap.insert( key, 5 ); find : pair<string, string> key = make_pair("bob", "sue"); auto = mymap.find( key ); // can inline make_pair if prefer. if ( != mymap.end() ) { cout << it->second; } note using strings key in map can have performance issues. also, order of strings in pair has significance.

How do I make a program where you can communicate with other language CORBA? -

i must make program implements corba client , server in other language, don´t know it. first step decide programming language want use, search implementation language, tao c++, r2corba ruby/jruby, jacorb java, taox11 c++11. have write idl , implement corba client , server. each corba implemention ships set of example applications, use starting point.

java - OpenNI: Recorder create function and .oni file creation -

this might silly question new openni. using openni-linux-x86-2.2 package. when use recorder.create(string filename) , create file or use pre-existing file? asking because can't find creates .oni files other making blank file .oni suffix (which feels risky). if uses pre-existing .oni file, how create one? api seems unclear. also, filename name without .oni suffix? (as in, same directory , not relative/absolute filepath or something) after playing little reached following: filename file path when creating java.nio.file objects using file(string pathname) constructor if no such file exists, creates one. it works if pre-existing file there, did not around testing if overwrites or if writes @ beginning/end

Android NDK. Not a JPEG image: starts with 0x00 0x00 -

i want use jpeg images in android ndk application. downloaded libjpeg9 , compiled static library. load image apk libzip , when begin reading header of image following error: "not jpeg file: starts 0x00 0x00". same error occured when launch application in emulator , real device well. type in terminal command check file: "file myjpeg.jpg" , following message: "myjpeg.jpg: jpeg image data, jfif standard 1.01" file valid. moreover, if load same image file jpeg_stdio_src function in macos app success. part of code responsible loading jpeg files in android: zip * apk = zip_open(apk_path.c_str(), 0, null); if (!apk) return false; zip_file * fp = zip_fopen(apk, path.c_str(), 0); if (!fp) { zip_close(apk); return false; } jsamparray buffer; int stride; jpeg_error_handler jerr; jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpeg_error_exit; jerr.pub.output_message = jpeg_error_msg; unsigned char

vb.net - MessageBox z-order -

i've created messagebox want stay on top of program when appears on screen. worked when hadn't set form stay on top, msgbox hides under , it's hard take on top see it. can set msgbox on top somehow? if you're creating own messagebox, use showdialog instead of show method make messagebox on top regardless of topmost setting. gives advantage of returning different results different buttons used, same built in messagebox.

javascript - Backbone.js Get First Element from JSON file -

while figured out how of elements array, stuck on trying element belonging first. using backbone.js , trying edit 1 of templates. track information getting coming json file. can within html file or must edit .js file? html: <script type="text/template" id="lesson-template"> <span class="lesson-title"><%= title %></span> <select class="sel"> <% _.each(tracks, function(track) { %> //this lets me loop through each of them <option value = "<%= track.text %>" ><%= track.title %></option> <% }); %> </select> //now want figure out way track.text of first track here , put in tracktext! <p id="tracktext">hello world!</p> </script> <p id="tracktext"><%= tracks[0].text %></p> you don't appear using backbo

chromecast - Cast tab from command line -

is possible cast tab via command line? i'd load video on page , tell google chrome cast it. i've looked @ switches available chrome.exe , unsure of start. no, not able command line.

java - Error when calling insertionsort method and how to print an arraylist -

i have created program stores temperature(double) , day(string) in arraylist, uses comparable interface , insertion sort sort arraylist. have left calling insertion sort method , print out original order of arraylist , sorted order. when call insertionsort method gives me error stating "invalid method declaration; return type required". why receiving error? print statement correct print out original arraylist? how update print out sorted arraylist? or can print out insertionsort method? here code: import java.io.*; import java.util.scanner; import java.util.arrays; import java.util.arraylist; public class dailytemperature implements comparable<dailytemperature> { //variables private double temperature; private string day; //gettemp & settemp methods public double gettemp() { return temperature; } public void settemp(double newtemp) { temperature = newtemp; } //getday & settemp methods pub

jar - Can't import library into Google App Engine project -

i use google app engine sdk 1.8.5 eclipse 3.8 on ubuntu. i want add cloud storage service app, downloaded guava-gwt-15.0.jar , appengine-gcs-client-0.3.jar , , put them in apps /war/web-inf/lib/ folder. added these jars build path in eclipse. when fire app in dev mode, runs fine, @ least until try access page relevant gcs library. when that, following error: java.lang.noclassdeffounderror: com/google/common/base/preconditions @ com.google.appengine.tools.cloudstorage.gcsserviceimpl.<init>(gcsserviceimpl.java:35) @ com.google.appengine.tools.cloudstorage.gcsservicefactory.creategcsservice(gcsservicefactory.java:32) ... etc i cleaned project , restarted eclipse multiple times, , still problem persists. do? in addition guava gwt, need core guava library ( guava-15.0.jar ). download .jar war/web-inf/lib , add build path well.

workbench - how to use stored functions mysql (Error Code: 1054 Unknown column 'Right Index' in 'field list') -

how use stored functions mysql drop function if exists finger_name; delimiter \\ create definer=`root`@`localhost` function `finger_name`(finger_id int) returns `varchar`(45) charset `utf8` begin declare name `varchar`(45); case finger_id when 1 set name= `right thumb`; when 2 set name= `right index`; when 3 set name= `right middle`; else set name= `not registered`; end case; return name; end\\ delimiter ; select finger_name(2); error code: 1054 unknown column 'right index' in 'field list if setting string literal in variable, should use single quote , not backtick -- used identifiers such table name, column names, etc... case finger_id when 1 set name= 'right thumb'; when 2 set name='right index'; .....

linux - Perl script log to file, output lag -

i have perlscript logfile parsing , executes bash command: $messagepath = `ls -t -d -1 $dir | head -n 5 | xargs grep -l "$messagesearchstring"\`; i start perl script ./perlscript.pl > logfile.log . now tail on logfile watch progress, output gets stuck every time @ line described above. output stop there seconds , continue. ??? to profile problem wrapped this: print `date`; $messagepath = `ls -t -d -1 $dir | head -n 5 | xargs grep -l "$messagesearchstring"`; print `date`; the output shows command not consume lot of time: so 6. okt 22:35:04 cest 2013 6. okt 22:35:04 cest 2013 if run script without redirecting output file there no lag. any idea why? i haven't tried duplicate behaviour, might stdout buffering problem. try with: $| = 1; $messagepath = `ls -t -d -1 $dir | head -n 5 | xargs grep -l "$messagesearchstring"`; update i have tried duplicate behaviour observe: i've had make assumptions believe suspicion

arrays - Embedding loads of images -

i got 42 images want embed , put on array. tried within loop, doesn't seem work. how can avoid have 42 embed lines + long line array ? the way embed multiple images without embed line each 1 use sprite sheet (sometimes called 'texture atlas', or 'sprite'). take folder of images, , generate 1 large image. , give data file (use xml or json) of images in folder , they're positioned inside sprite sheet. you can embed sprite sheet once. for need 2 things: 1/ software create sprite sheet... there many tools available, 1 use example texture packer : http://www.codeandweb.com/texturepacker 2/ actionscript class or framework, designed handle referencing images sprite sheet... native feature of starling, if you're not ready support flash player 11 can find publicly available frameworks this: example: spriter : http://abeltoy.com/projects/spriteras3/usage.html has class called bitmapspriter handle sprite sheets natively in as3.

printing - Python For loop multiple returns -

i supposed write function 1 of computer science classes in python. function supposed take in startvalue , increment until numberofvalues reached. function far: def nextnvalues(startvalue, increment, numberofvalues): result = int(0) in range(0, numberofvalues): increase = * increment result = startvalue + increase return result i call doing: print(nextnvalues(5,4,3)) the problem output 13. how make returns number each time increments. example, 5, 9, 13? have been having problem previous functions have been adding , removing things without logic work. doing wrong? this perfect use case generators . long story short, use yield instead of return : def nextnvalues(startvalue, increment, numberofvalues): result = int(0) in range(0, numberofvalues): increase = * increment result = startvalue + increase yield result the clients of code can use either in simple loop: for value in nextnvalues(...): print(value) or can list i

git - I Need to restore delete files -

i new git , using source tree. wanted pull new branch didnt want commit changes removed file , pulled didnt know removing them remove them actual project!!! so pulled new project , these files missing. how can undelete/restore these files?

c++ - Replace zero in 2D array with blank space -

if have 2d array has values in indices , has 0 in other. how can convert 0 blank space. tried a[i][j] = ' ' , prints ascii value 32, guess. for (int i=0;i<r;i++) (int j=0;j<c;j++) if (a[i][j]==' ') cout << (char)a[i][j]; else cout << a[i][j];

php - Drupal 7 find the path of a given file name -

if folder path stored file: file.tx $directory= variable_get('file_directory_path', 'sites/default/files'); how path of file: file.txt? try code below. below code drupal file url. $fileuri= variable_get('file_public_path', conf_path() . '/files').'/file.tx'; $file_url = file_create_url(file_build_uri($fileuri)); for private folder use 'file_private_path'. mervyn

colors - How to import colorPickerDialog library in android studio -

i everyone i downloaded library use in application : https://code.google.com/p/android-color-picker/ unfortunally, don't know how "install" on android studio , add in application in preferenceactivity anyone can me? thanks just import other libraries source in "src" folder , add layout preferences file. preferences xml file. <yuku.ambilwarna.widget.ambilwarnapreference android:key="your_preference_key" android:defaultvalue="0xff6699cc" android:title="pick color" />

emacs - Eval form after symbol has been defined -

i have function permanent-set-key automates adding key-binding definitions, both local , global, init file. when user requests add local key-binding, function determines current local keymap using this pretty robust approach answer question asked earlier. so know symbol-name of (current-local-map) , have appropriate sexp define desired key, example: (define-key python-shell-map [3 6] 'python-describe-symbol) however, @ time of initialization, such maps undefined, eagerly evaluating form above cause error. what robust programmatic approach scheduling these forms eval-ed @ appropriate time? what have been doing far has been assume minor mode exists current local map, , guess name of minor mode's file in order wrap above sexp in eval-after-load form, according convention foo-mode-mode-map . example, generated automatically: (eval-after-load 'dired '(define-key dired-mode-map [8388711] 'run_gdmap_dired)) and happens work (since there indeed exist d

JSF dataTable renders an empty record -

this "view", contains "datatable". however, when run application, rendering code not bring records selected jpql note: jpql correct , bringing right result. next, method should brings result , "jsf view" empty record in detail: public datamodel<pessoa> getlistapacientes() { try { datamodel = new listdatamodel(pessoabo.getlistapessoa(jpaconsulta)); } catch (bdexception ex) { logger.severe("classe [pacientemb]; método [getlistapacientes]; exceção [" + ex.getmessage() + "]"); } { return datamodel; } } <h:form> <h:datatable value="#{pacientemb.listapacientes}" var="paciente"> <f:facet name="header" rendered="#{pacientemb.listapacientes.rowcount > 0}" > <h:outputtext value="consulta de pacientes" /> </f:facet> <h:column> <f:facet name="header"> &l

php - Array from nlist() showing periods -

this question has answer here: list files in directory ,extra information coming 2 answers i using nlist() function phpseclib list contents of directory on remote server. result get. array ( [0] => newfile.txt [1] => . [2] => .. [3] => oldfile.txt [4] => readme.pdf ) . i have following files in folder. 1. newfile.txt 2. oldfile.txt 3. readme.pdf but, why putting . , .. in array? seems happen no matter directory in or how many items in directory. . , .. magic, , exist in every folder. first refers current directory, second refers parent directory. you can remove them results list http://php.net/array_diff <? $arr = array('newfile.txt', '.', '..', 'oldfile.txt', 'readme.pdf'); $arr = array_diff($arr, array('.', '..')); print_r($arr) ?>

java - Not able to write : in Property file -

in application user can change propery file.. text contains : colon. while using obj.setproperty("key","value") passes \: please find below example code , needful. string url="http://google.co.in"; properties p=new properties(); fileoutputstream o=new fileoutputstream("abc.properties"); p.setproperties("testurl",url); p.store(o,null); o.close(); thank praveenkumar v refer properties class's store method api. says characters #, !, =, , : saved escaping backslash. the key , element characters #, !, =, , : written preceding backslash ensure loaded. if read saved file load method in properties class, there no problem. if not, you'll have write own custom code escape these characters while loading.

translate the pseudocode into MIPS assembly language -

1). for ( t0 = ´a´; t0 <= ´z´; t0++) mem[a0++] = t0; 2). t0 = 2147483647 - 2147483648; for first one, kind of confuse how translate mem[a0++] , beginner of mips, second, can't find out key point,just think can't simple, anyone can explain please? one more question, different between mult , multu, can example please? 1. addi $t8 $zero 'z' addi $t0 $zero 'a' loop: sw $t0 0($a0) addi $a0 $a0 1 addi $t0 $t0 1 ble $t0 $t8 loop 2. addi $t0 $zero -1

How to pass a variable value to a php page? -

how can pass value of variable $login page try.php ? wish use code: <a href="try.php">vote</a> ? there 2 main ways pass data via url. can create <form> post data next page. alternatively can pass data directly in url, called method. php manual - $_post php manual - $_get the post method means data passed without user being able see it. data sent in http headers next page. common , recommended way pass form data across. the method passes data in url so: http://www.somesite.com/page.php?var1=stuff&var2=morestuff means can craft url pass data via yourself. need urlencode() data before put url won't contain invalid characters cause url invalid. just throrough can use session pass data between pages. in order must first establish session using session_start(). method more useful keeping data persistent across page loads passing user input new page. you'll still need use post or pass information a user types first page secon

c# - declaring a list inside a class and it's the same list in every instance? -

i created class this: public class myclass { public list<int> params = new list<int>(); public void load(int data) { params.add(data); } } then initiate, let's say, 3 instances of class. myclass 1 = new myclass(); myclass 2 = new myclass(); myclass 3 = new myclass(); add list data: one.load(10); two.load(50); three.load(100); then surprisingly when check: one.params.count(); the count 3, also two.params.count(); is 3 each instance list got 3 numbers - i.e. same list. somehow instead of separated lists got pointers same list. how make 3 different stand alone lists each instance ? seems nothing wrong in code presented in original post. click here see live output following code. using system.io; using system; using system.collections.generic; class program { static void main() { myclass 1 = new myclass(); myclass 2 = new myclass(); myclass 3 = new myclass();

C# iTextsharp Replace Page of a multi-page PDF -

say, have 5-page pdf called 'a.pdf' page 2 , 4 empty. , 2-page pdf called 'b.pdf'. want copy the first page of 'b.pdf' page2 of 'a.pdf' , second page of 'b.pdf' page 4 of 'a.pdf'. i found it's quite hard find examples, found provided here, http://itextsharp.10939.n7.nabble.com/replace-pages-with-itextsharp-td2956.html called 'pdfstamper.replacepage()', guess i'm looking for, did simple demo didn't work out. can have check me? string _outmergefile = server.mappath("~/11/a.pdf"); string file2 = server.mappath("~/11/b.pdf"); pdfreader readera = new pdfreader(_outmergefile); pdfreader readerb = new pdfreader(file2); pdfstamper cc = new pdfstamper(readera,new memorystream()); cc.replacepage(readerb, 1, 2); cc.replacepage(readerb, 2, 4); cc.close(); thanks in advance. ================================================================================= jose's suggestion. code works now. i&

qt - Using QObject instead of a container -

after reading on interesting parent-child system of qobject wondering how common qt developers use in place of more traditional container. assuming memory contiguity not requirement, seems offers interesting features. for example, have qobject , give children of different types, , find children based on types, giving qobject dynamic heterogenous container-like feature, opposed required homogenous collection of traditional container. and qobject naturally manages memory of children, convenient well. is common use of feature? qobject::findchildren slower storing objects in normal container qlist because: it iterates on children each time. searches recursively (but can disabled). it performs runtime type check. it constructs new qlist each time. can slow , expensive there many objects in result. all above unnecessary if use qlist<type*> my_objects . in case: you can name collection. qlist<qpushbutton*> panic_buttons clearer findchildren<qp

In GWT Bootstrap, how to assign different styles to different instances of same Bootstrap elements? -

for gwt bootstrap, have navlists definitions as: <b:navlist> <b:navheader>my header</b:navheader> <b:navlink href="#menu1:">my menu1</b:navlink> <b:navlink href="#menu2:" active="true">my menu2</b:navlink> </b:navlist> in same application have 2 kind of components this, (1) 1 placed on white panel left menu, (2) other placed on dargreen panel bottom menu. both navlists. so have problem assign different colours different instances of same bootstrap elements. suppose can straight in uibinder but, after trying not find right settings. bootstrap selector need override in uibinder (from less nav files): .nav-list > li > { padding: 3px 15px; color: #ff0000; <======= how override color in uibinder } i figure out common use case, same element, instances different style. how can addressed? all need add custom style name style. <ui:style> .mycustomstyle &g

random - start app on a different layout each time? -

i want app when executed start different layout, have code allows me choose layout start want random thanks. mypager.setcurrentitem(0); pd: excuse english, not speaking, used translator you can use java's built-in pseudo random number generator random value in defined range. use choose random value setcurrentitem . example: random r = new random(); int randomvalue = r.nextint( 5 ); mypager.setcurrentitem( randomvalue ); the value pass nextint method one more maximum integer want receive; example above return random value between 0 , 4 (excluding 5).

mysql - Pretty basic SQL query involving count -

let's have following schema company: -> company_id -> company_name building_to_company: -> building_id -> company_id so each building has own id company id relates single company. the following query gives 2 columns -- 1 company name, , associated buildings. select company.company_name, building_to_company.building_id company, building_to_company company.company_id = building_to_company.company_id; the returned table this: company name | building id smith banking 2001 smith banking 0034 smith banking 0101 smith banking 4055 reynolds 8191 tradeco 7119 tradeco 8510 so that's simple enough. but need bit different. need 2 columns. 1 company name , on right number of buildings owns. , little challenge want list companies 3 or less buildings. at point real progress i've made coming query above. know how have use count on building_id column , count number of buildings associated each company. , @ point can limit things u

php - HTML Form in CakePHP -

i don't want use formhelper cakephp, because want use ajax in app. how can pass data form controller? i'm using $.post jquery error. thanks! you can use ajax cakephp form helper. in view file .ctp put: echo $this->form->create('model', array('id'=>'yourformid', array('default'=>false))); echo $this->form->input('field'); echo $this->form->submit('save'); echo $this->form-->end notice in form->create passing default=>false tells form not normal "submit". at bottom of view file .ctp put: $data = $this->js->get('#yourformid')->serializeform(array('isform' => true, 'inline' => true)); $this->js->get('#yourformid')->event( 'submit', $this->js->request( array('action' => 'youraction', 'controller' => 'yourcontroller'), array( 'update

Requirejs: paths vs map -

trying understand it's right use "map" wildcard vs "paths". looking @ require source (but not being 100% fluent it) seems there functionally no difference between these 2 snippets. true? using paths: require.config({ baseurl: "include/js/", paths: { foo: "stuff/foo", } }); using map: require.config({ baseurl: "include/js/", map: { '*': {foo: "stuff/foo"}, } }); from requirejs docs "in addition, paths config setting root paths module ids, not mapping 1 module id one." this means "paths" meant mapping path resource when not in default location (baseurl). guess trying do. on other hand, "map" can have several versions of resource (foo1, foo2...) can map loaded different paths (i.e. want load foo1 desktop browser , foo2 modification of first 1 mobile browser). so, unless have different versions of foo use "path&quo

java - Using javascript editor in my eclipse -

Image
i using ubuntu 12.04. have installed eclipse in it. want write javascript files in eclipse installed 1 javascript plugin (programming languages -> javascript development tools) in eclipse. when write java programs default proposals. when write system. list of menu contains properties of system class. why not happening javascript files. when write document. , press ctrl + space, no "no default proposal message". let me know missing here.i want default proposals when write js code in eclipse. you need enable other javascript proposals option in default content asiist list. to that, go windows >> preferences then javascript >> editor >> content assist >> advanced in right pane, make sure other javascript proposals ticked shown in image below:

java - Binary Search using multithreading -

i want make program in java binary search in array taken dynamically,by using multithreading.so how start program? binary search not suitable multi-threading / parallelisation. there (almost) no potential parallel speedup. otoh ... if want know how concurrent binary search of sorted array of elements, provided that: none of searching threads modify array, , the array safely published (with respect searching threads), regular binary search multiple threads thread-safe.

functional programming - Scala and Writing map functions -

so suppose have function expects set definition int => boolean , function f this: def map(s: set, f: int => int): set = {} now how apply f each element of set s . def map(s: set, f: int => int): set = { (i: int) => f(s(i)) } which ofcourse incorrect because in f(s(i)) , 's(i)' returns boolean, , can't apply f on it. problem how access each element of set , apply f on it? this question part of coursera's functional programming scala course. a goal of course understand functional model, , in case, how set can represented function (called charasteristic function set). instead of final solution, here's hint on how reason problem: given characteristic function f: int => boolean defines set , x , int, if f(x) == true , x belongs set. now, if have function g:int=>int want map on set, want apply function elements know belong set: if (f(x)) g(x) . try apply thinking exercise.

Batch processing in JSON using Youtube API V3 -

i'm able use v3 api add single video playlist, i'm having trouble adding multiple videos @ once. to add single video using api explorer, request looks like: post https://www.googleapis.com/youtube/v3/playlistitems? part=snippet&fields=id%2cstatus&key={my_api_key} content-type: application/json authorization: bearer {my_token} x-javascript-user-agent: google apis explorer { "snippet": { "playlistid": "plsocvumhlfzltir58niqsaf2ue1vqwvjo", "resourceid": { "playlistid": "plsocvumhlfzltir58niqsaf2ue1vqwvjo", "videoid": "7mbnb_lzwdm", "kind": "youtube#video" } } } i want submit multiple "videoids" in single request. i've tried "videoid":["id1","id2","id3"], , request successful adds first item in array. data api v3, doesn't support multiple playlistitem inserts @ once

javascript - In laravel 4, How to render in template (blade) plain css or js from file? -

i have in laravel/app/views/css file style.css , not public, how can use in template using <style></style> . don't want link ( <link href="style.css" rel="stylesheet"> ), plain text inside html. i kwon how blade: <link href="style.css" rel="stylesheet"> but want learn how file: <style> //css code </style> with twig know can this: <style> {{ include(//link css file) }} </style> the way know can blade is: rename login.css login.blade.php <style type="text/css" media="screen"> @include('css.login') </style> have way? you don't need way, fine.

css - Bootstrap modal autoresizing after first click -

Image
i have bunch of div's being displayed inside bootstrap modal window gets activated click of button, the problem whenever refresh page , click on button opens fine when close modal dialog box , re-click button div elements appear outside modal window this first time opening modal dialog after refresh page this second time opening modal dialog after close first 1 (the div elements overflowed outside modal dialog box ) this code current modal-dialog <div class="thumbnail"><img src="../images/pix/place.png" href="#supket" data-toggle="modal" /></div><!-- calls pop-up --> <div class = "modal fade" id="supket" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close&qu

php - update column if date is older than 30 days -

i have table have column name 'date' , column name 'status' if use cron job run everyday , check if date older 30 day change status expired, code need run using mysqli , php. mysql event scheduler more better. start mysql event scheduler executing following query in phpmyadmin or mysql command prompt. enter this. set global event_scheduler = 1; this update table. create event newevent on schedule every 1 day update table set status="expired" datefield<=current_date - interval 30 day;

c# - How to consume (*.asmx) web service in Sql server 2008 -

i want consume c# web service inside sql server 2008 stored procedure. main concept behind want run scheduler of sql server (by using sql server agent) every 30 minutes, logic written in c# class. how run web service in sql server 2008 ?