Posts

Showing posts from May, 2010

performance - Do I create a duplicate function with slightly different algorithm, or use a slower, more general function? -

i've been advocate of dry principle: in other words, write code once , once. have function filters out data "latest unique report". in algorithm, function assumes incoming data sorted, making efficient. however, function potentially has handle data not sorted. better practice: having 1 general solution slower, or having 2 different functions, 1 being more efficient? edit: should make note while performance nice thing have, not critical application internal tool. the way put it sounds make function sorts data, , puts filtering function. so function filterdata(object data) { ... } function sortandfilterdata(object data) { // sorting ... // filtering filterdata(data); }

jsf 2 - JSF Unknown System Events -

i working on jsf 2.0 project, , learning benefits of using system events. however, book i'm referencing 'core java server faces 3rd edition' lists total of 14 system event types can used in f:event tag's type attribute. of them work expect, e.g. "prerendercomponent" on uicomponent tag, or "prerenderview" on uiviewroot tag. but, besides two, , select few others, none of other events mentioned in book work. example, can't postrestorestate type of event work on uicomponent. instead, when jsf tries render page, classnotfound exception, presumably system event class supposed handle postrestorestate events, or whatever event i'm trying listen for. why don't these other event types work? there other library need, or there other way of implementing system event listener need use. below example of 1 such tag failing: <h:commandlink action="editplant" value="#{appmessages.usersn

Cakephp select list of numbers with corresponding values -

i have select list generate : echo $this->form->input('number_of_vehicles', array('empty' => 'select...', 'type' => 'select', 'options' => range(1, 10, 1))); now generates nice numbered select list 1 10, incremented 1...great. option value starts @ 0 eg. <select name="data[contact][number_of_vehicles]" id="contactnumberofvehicles"> <option value="">select...</option> <option value="0">1</option> <option value="1">2</option> <option value="2">3</option> <option value="3">4</option> <option value="4">5</option> <option value="5">6</option> <option value="6">7</option> <option value="7">8</option> <option value="8">9</option> <option value="9">10</option>

c# - Creating an island for separate gravity control on XNA using Farseer Physics Engine 3.0 -

i started using farseer engine , far it's been pretty easy understand , implement in aps. wondering if there way put control different "world" can manipulate gravity of object allow other objects stay @ default world gravity. know how accomplish or know of resources might me? thanks, tom the idea change gravity specific objects bit unusual, gravity global constant in physics simulation (unless using space stuff). don't know farseer engine assume gravity works same in other physics engines. usually in physics manipulate 1 object's 'gravity' lower it's weight/mass (and air friction?). or give slight upward force (a negative gravity).

android - How do I dump my sqlite db back into my assets folder -

i have succeeded in generating sqlite3 database in android app initial sqlite3 file in assets folder. helpful have similar routine dump modified database folder a) verify updates/inserts/deletes working correctly , b) possible way pass bulk revisions process. does have utility this? i don't think if can that. if want save data inserted, can keep database in /database folder, in order database not rewritten (think of this: when start app, code again writes database asset folder /database folder, have old data again) this file filedb = new file("data/data/[package-name]/databases/"+database_name); if( !filedb.exist()) { //if database file not exist, means database not copied asset folder /database folder, copying, } with test have prevented database in /database folder rewriten database have in asset folder. verify if inserting/deleting/updateing working fine, pull out database file emulator , open sqlite browser. don't forget put in assets ;)

c# - DateTimeOffset display after daylight savings change -

i have question datetimeoffset , daylight savings time. explain question lets assume right date , time is: 11/6/2010 10:15:00 if run code: datetimeoffset mytime = datetimeoffset.now; console.writeline("local time: " + mytime.tolocaltime().datetime); then result: local time: 11/6/2010 10:15:00 am meaning event happened @ 10:15 in morning (my time zone mountain daylight time (-6 offset)). so, save datetimeoffset sql server 2008 db (as datetimeoffset). next day want display user. daylight savings has expired. if run above writeline saved off value (from previous day) display? the offset stored in database -6. daylight savings over, current offset -7. understand documentation , first convert time utc time (so takes 10:15 , adds 6 hours (4:15 pm). subtract current offset of local time (4:15 pm - 7 = 9:15 am). so if math right, when display event, show occurred @ 9:15 rather 10:15 am. this not good. want store time zone information, need tim

grails - call to .save() on domain class fails with no signature of method .save() in unit test -

i'm using grails 1.3.2 in netbeans. have simple unit test fails error: no signature of method: com.maxrecall.maxrequire.domain.release.save() applicable argument types: (java.util.linkedhashmap) values: [[flush:true]] possible solutions: wait(), any(), wait(long), iscase(java.lang.object), use([ljava.lang.object;), sleep(long) the relevant code is: release rel = new release() ... rel.save(flush:true) the same code works in bootstrap.groovy. have tried various variations on .save() (.save , without parameters. it's unit test, there's no spring, hibernate, etc. have mock behavior want. if you're testing persistence, need convert test integration test, since testing persistence unit tests tests mocking framework. integration test uses @ minimum in-memory database, although can switch test instance of mysql/oracle/etc. if you're testing controllers or other users of domain classes , want them work can focus on testing current class, u

css - position div to the bottom -

how can content div @ bottom instead of odd position? http://jsfiddle.net/madprops/6ffxl/1/ <div> <div style='float:left'>name&nbsp;</div> <div style='float:left'>date&nbsp;</div> <div style='float:left'>comments&nbsp;</div> </div> <div id="contenido" style="font-size:20px;">content</div> edit: removed float:top it @ bottom me in example, (ff5), should make safe setting content clear floated divs, this: <div id="contenido" style="font-size:20px;clear:both;">content</div> also, float:top on first div invalid, there no top property of float.

vb.net - Algorithm problem -

i have divided circle rows , columns , each block(square) formed in circle of equal size. have x , y co-ordinates of each square/block. each block either defined or bad. problem: need add 2 blocks on same row , determine if result or bad. if of block bad, group of 2 block called bad. if both good, group good. algorithm it? need in visual basic language. also, need more cases adding 3 blocks , determine if group of 3 block or bad. in this, if block bad, whole group bad. update: when divided circle rows , columns i.e blocks, remove blocks not in shape of square. is, square/blocks touching circumference of circle deleted. can upload photo tomorrow now. if adding two, 1 badblock means both on either side bad leading 3 bad on 1) set nxn array of struct {bool incircle, badblock, badgroup;} incircle true if block in circle, badblock true if block bad on , badgroup false. 3) int length=2; length--; (int i=0; i<n;i++) for(int j=0; j<n;j++) if(array[i,j].bad

php - codeigniter: pagination + table libraries (not working) -

i need on code igniter app..i can't seem find out what's causing pagination not work here's controller $limit = 15; $uri_segment = 4; $this->load->helper('string'); $offset = $this->uri->segment( $uri_segment ); log_message('error',date('y-m-d h:i:s', time())); //load //$products = $this->products_model->get_all(); $products = $this->products_model->get_products($limit, $uri_segment); //var_dump($products); log_message('error', $products ); //pagination $this->load->library('pagination'); $config['base_url'] = site_url('admin/products/index/'); $config['total_rows'] = $this->products_model->count_all(); $config['per_page'] = $limit; $config['uri_segment'] = $uri_segment; $this->pagination->initialize($config);

jquery - Specifying name of rails partial to render using a variable -

is possible in rails 3.0 render partial name of partial stored in variable? i attempting similar to: <%= escape_javascript(raw render :partial => @partial_name, :locals => { :value => @value} )%> updated more details in application have set of models using multi-table inheritance, example lets have base model 'cupcake' , variants such 'awesomecupcake' , 'alrightcupcake'. each of these models have own custom partial displaying information , follow naming scheme: '_awesome_cupcake' , '_alright_cupcake'. on page have links each type of cupcake in want controller accept parameter , dynamically derive partial render. following works wanted if (in new.js.erb file) replace '@partial_name' such 'awesome_cupcake'. here little more information how components laid out: application.js $('#set_cupcake').click(function () { $.getscript('/cupcakes/new.js?cupcake_type=awesome'); }); cup

Using Java to test for file damage and corruption -

i looking @ writing program can test files corruption and/or damage. prefer write program in java. now tricky part, possible use java test files corruption/damage in many different file types? looking @ checking .pdf .html , .txt files, fear more files added onto list soon. have no idea if possible write or not. if java can not possible c? i think going have take file file basis. example text files - make sure can read file using filereader html - make sure text file , html file valid pdf - use pdf generator see if can read pdf , valid but alex has suggest, doesn't matter if in java. long can read bytes can check. you have define corruption. if corruption mean correct disk blocks on hd might need lower level programming language. if mean bytes represent correct data can in language.

Which is the best structure for an Android SVN project? -

which better structure svn repository hold single android project (and why)? http://myserver/svn /trunk /myproject /src /res /assets /branches /tags or http://myserver/svn /trunk /src /res /assets /branches /tags basically want know if project root folder should explicitly named in hierarchy. repository hold 1 project have many branches , tags. i'm using eclipse svn plug-in. thanks, barry i have this: http://myserver/svn myproject1 /trunk /src /res (external) /assets /branches /tags myproject2 /trunk /src /res (external) /assets /branches /tags resources haven't done of android development, stuff resources keep outside main source structure , make use of svn:externals link think , potentially use them across various projects

draw and scale custom rectangle on a view in android -

i want custom view,it can include effect:first draw pic on view background draw rectangle on image,and draw other image named in rectangle, know rectangle have 4 fixed point,when drag 1 of these,the rectangle can scale,at same time scale, have read more link,but not find example,i have done something,but cannot finish scale rectangle,my code is: public class drawview extends view implements ontouchlistener { private static final string tag = "drawview"; private static final int linelength = 30; paint paint = new paint(); float locationx, locationy; private int mlasttouchx; private int mlasttouchy; private int mposx; private int mposy; private int mposx1; private int mposy1; bitmap bitmap, bmp, xiao; int screenwidth, screenheight; int xlength; boolean isfirst = true; boolean isleft = false; rect r, rbig,outrect; public drawview(context context) { super(context); setfocusable(true); setfocusableintouchmode(true); this.setontouchlistener(this);

asp.net mvc - Fluent nHibernate Issue in Many to Many Mappings -

i have interesting issue happening me , not know m doing wrong, m using fluent nhibernate mvc 3, got user , roles , , usersinrole table many many relationship. user mapping: id(user => user.userid).generatedby.guid(); map(user => user.username).not.nullable(); map(user => user.password).not.nullable(); map(user => user.fullname).not.nullable(); map(user => user.email).not.nullable(); map(user => user.isactive).not.nullable(); map(user => user.creationdate).not.nullable(); hasmanytomany<role>(x => x.roles).table("tbluserinroles") .parentkeycolumn("userid") .childkeycolumn("roleid") .cascade.all() .not.lazyload(); roles mapping: id(role => role.roleid).generatedby.identity();

iphone - simplest way to throw up disclaimer text after user click on information icon? -

any advice/suggestions regarding simplest way throw disclaimer text after user click on information icon? iphone/ipad development. jumping across separate xib/controller might overkill? (although perhaps simpliest setup?) requirements be: main screen has small "info" button in 1 corner clicking on button should bring "modal" view of disclaimer text should support scrolling (in case of lot of text) should allow user somehow dismiss , main page the simplest way think present text in uitextview , scrollable, in custom view controller present modally. can store the text in. adding button dismiss it, , done.

asp.net - How access hyperlink control in a repeater i c# .net -

there repeater in program includin hyper link.i cant cess hyper link control. <asp:hyperlink id="hyperlink15" runat="server" navigateurl="abc.aspx"> set enabled=false so use hyperlink = (hyperlink)repeater1.findcontrol("hyperlink15"); the hyper link enabled user , b... use code: if (a && b) { hyperlink link = (hyperlink)repeater1.findcontrol("hyperlink15"); link.enabled=true; link.navigateurl="efg.aspx"; } but following error: system.nullreferenceexception: object reference not set instance of object. hyperlink = (hyperlink)repeater1.items[0].findcontrol("hyperlink15"); use above, , items contain index. or for (int count = 0; count < repeater1.items.count; count++) { hyperlink = (hyperlink)repeater1.items[count].findcontrol("hyperlink15"); }

Destroy files when session will destroy in php -

is possible remove files folder when session destroy. doing when user come site , can upload files(images, or textfiles), etc.. out login site. , files 'll store project's folder. need if user quits browser out login need delete files upload in project folder. how ? thanks in advance. you can implementing own session handler. way, can define callback various events, including destruction of session. see link more information: http://www.php.net/manual/en/function.session-set-save-handler.php update: problem solution need implement rest of session handling code (initialize session, close session, read storage, write, garbage collect). however, linked page above gives full example can add functionality to.

java ee - EJB method processing hangs somewhere during execution -

i have strange problem, here quick snapshot of system: have web application calls local ejb bean, lets call local ejb 'localejb', ejb calls remote ejb - 'remoteejb' method processing on external system , returns string result. happens within weblogic 8.1 here example processing: web application: //create reference local bean lochome = (localhome)servicelocator.getinstance().getlocalhome("ejb/localejb"); beanref = lochome.create(); //call bean method string result = beanref.updatesmth(data.getid(),data.getrelatedids(),integer.valueof(data.getstate())); //print result log.debug("result is: " + result); i have logging enabled on local bean inside ejb application: log.debug("state " + state); res = session.updatesmth(id, relatedids, state); log.debug("result inside bean call: " + res); where 'session' reference remote bean. now happens, request comes application, method 'beanref.updatesmth'

Javascript invalid assign left hand side -

possible duplicate: invalid assignment left-hand side, javascript var htmltoadd = '<label for="a'+indexnr+'" class="pricelabel">min</label>' += '<input style="width:3em" name="b'+indexnr+'" id="b'+indexnr+'" type="text" />' += '<label for="c'+indexnr+'" class="maxpricelabel">max</label>' += <input style="width:3em" name="d'+indexnr+'" id="d'+indexnr+'" type="text" />'; i trying create html string , use append html element. firebug giving me invalid assignment left-hand side [break on error] += '<input style=...rcentage'+indexnr+'" type="text" />' replace += + += me

fopen works in normal PHP but not inside Drupal -

some php code worked well. however, when port code drupal module, $fp = fopen( 'language/unicode-big5.tab', 'r' ); not work expect, giving warning: warning: fopen(language/unicode-big5.tab) [function.fopen]: failed open stream: no such file or directory in /users/me/documents/html/drupal/sites/all/modules/test_module/language.inc.php on line 197. i tried put required files , folder in sites/default/files : $fp = fopen( file_directory_path().'/language/unicode-big5.tab', 'r' ); returns same warning. how can fix it? that work fine. however message stating path wrong, have tried looking @ path it's trying open? just following, , correct path accordingly. echo realpath(file_directory_path() . '/language/unicode-big5.tab'); if path is correct, need check permissions, user have access file @ all? try chmod 777 , see if helps issue, if does, remove chmod 777 , fix accordingly (user/group permissions).

How to enable/disable the field "State / province / country" in Magento? -

how enable/disable field state / province / country in magento/index.php/customer/address/edit/ page? my client wants show state/province option in site.in existing code label state/province showing input field not showing. can plz solve issue? this old question , op ended having broken template, answer others coming google. since (i think) 1.7, there setting in admin area this. system > configuration > general > general > states options "display not required state " = no

iphone - How to make UITableView rearrangeable? -

i'm trying make uitableview editable can move cells around. right when click edit button, lets me delete not re-arrange. the methods have are: code: - (bool)tableview:(uitableview *)tableview caneditrowatindexpath:(nsindexpath *)indexpath { return yes; } - (void)setediting:(bool)editing animated:(bool)animate { [self.routinetableview setediting: !self.routinetableview.editing animated:yes]; if (self.routinetableview.editing) [self.navigationitem.leftbarbuttonitem settitle:@"done"]; else [self.navigationitem.leftbarbuttonitem settitle:@"edit"]; } -(void)tableview:(uitableview *)tableview commiteditingstyle:(uitableviewcelleditingstyle)editingstyle forrowatindexpath:(nsindexpath *)indexpath { if (editingstyle == uitableviewcelleditingstyledelete) { nsmanagedobjectcontext *context = [self.fetchedresultscontroller managedobjectcontext]; [context deleteobject:[self.fetchedresultscontroller objec

Why ruby on Rails is agile? -

i'm hearing ror agile implementation. plaese summarize statement , explain me why examples. p.s can't read "agile web development rails" yet. tools never agile in matter of software engineering. tools support in being agile. ruby on rails framework rapidly build basic functionalities ease , agile in minds way build system without having knowledge of every requirement needed system. so tools support developers rapidly bootstrap software or change functionalities rapidly in being agile. because of times understanding of "how things work" differs between customer , developer perspective. aligning perspectives success factor on every project , of times better show common understanding painting flow charts, uml charts or whatever imply domain knowledge. another thing if may bootstrap project rapidly may react on reordering of priorities more flexible. for nitpickers.: agile buzzword. there lots of definitions , different understandings wha

JSON parsing to Java - Android application -

i need parsing json string in java android appl. text of json file: {"data":{"columns":["location_id","name","description","latitude","longitude","error","type","type_id","icon_media_id","item_qty","hidden","force_view"],"rows":[[2,"editor","",43.076014654537,-89.399642451567,25,"npc",1,0,1,"0","0"],[3,"dow recruiter","",43.07550842555,-89.399381822662,25,"npc",2,0,1,"0","0"] [4,"protestor","",43.074933,-89.400438,25,"npc",3,0,1,"0","0"],[5,"state legislator","",43.074868061524,-89.402136196317,25,"npc",4,0,1,"0","0"],[6,"marchers bascom","",43.075296413877,-89.403374183615,25,"node",22,0,1,"0",

python - If list object contains something remove from list -

i have python script checks folder new files , copies new files directory. files in such format 1234.txt , 1234_status.txt. should move 1234.txt , leave 1234_status.txt unattended. here's little piece of code in python while 1: #retrieves listdir after = dict([(f, none) f in os.listdir (path_to_watch)]) #if after has more files before, adds new files array "added" added = [f f in after if not f in before] my idea after fills added, checks values have status in , pops array. couldn't find way though : / thanks in advance, tanel-nils added = [f f in after if not f in before , '_status' not in f] i recommend refrain long 1 line statements make code impossible read

visual studio - VS2008 Website Application Project, Long Wait to see page after build -

just started new web site application project, , find takes long open webpage straight build it. brand new project has minimum number of files, there other files in folder not part of project not included in project. anyway press build, build complete, try open webpage i.e. http://unitedcms/default.aspx . need wait 1 min before loads, after initial load loads instantly ofcourse im wondering why initial load takes long ? the reason iis/cassini compiles project after every build. compilation takes time complete. once compiled, iis/cassini stores them in cache. on subsequent requests, iis/cassini not recompile code serve cache. that's reason first request slow. here example. using notepad, edit web.config file (just add empty line or space). save it. , try open site again. take time load. that's because iis checks web.config file's last modified time stamp , if it's newer 1 in cache, re-compile code. hope helps.

python - formencode Schema add fields dynamically -

let's take, example, user schema site admin sets number of requested phone numbers: class myschema(schema): name = validators.string(not_empty=true) phone_1 = validators.phonenumber(not_empty=true) phone_2 = validators.phonenumber(not_empty=true) phone_3 = validators.phonenumber(not_empty=true) ... somehow thought do: class myschema(schema): name = validators.string(not_empty=true) def __init__(self, *args, **kwargs): requested_phone_numbers = session.query(...).scalar() n in xrange(requested_phone_numbers): key = 'phone_{0}'.format(n) kwargs[key] = validators.phonenumber(not_empty=true) schema.__init__(self, *args, **kwargs) since read in formencode docs : validators use instance variables store customization information. can use either subclassing or normal instantiation set these. and schema called in docs compound validator , subclass of fancyvalidator guessed it's

activerecord - What is the Correct Ruby on Rails Syntax to Write to a Nested Model within a Virtual Attribute? -

trying divide , conquer these problems ( 1 , 2 ) still having. write first step of blt recipe in nested, many-to-many model virtual attribute. later on have more complex form, doing in model. i have hard-coded in model except name of recipe. here recipe model: class recipe < activerecord::base has_many :steps, :class_name => 'step' has_many :stepingreds, :through => :steps has_many :ingredients, :through => :stepingreds accepts_nested_attributes_for :steps, :stepingreds, :ingredients attr_writer :name_string after_save :assign_name def name_string self[:name] end def assign_name if @name_string self[:name] = @name_string self[:description] = "addictive sandwich" self.steps = step.create({ :number => 1, :instructions => 'cook bacon', :stepingreds => [{ :ingredient => { :name => 'bacon' },

c++ - Using mpl::vector to define boost::variant types -

i'm using library boost::variant store large number of types. number of type growing, reach limit of 20 types. in documentation seems possible define variant using mpl::vector , allows more 20 types (up 50 if i'm correct). tried replace variant definition this: #include <boost/variant.hpp> #include <boost/mpl/vector.hpp> typedef boost::mpl::vector< float, math::float2, math::float3, relative_point<1>, relative_point<2>, relative_point<3>, std::string, color, group, dictionnary, reference, line, strip, text, font > variant_mpl_vec; typedef boost::make_variant_over<variant_mpl_vec>::type data_type; // old definition /*typedef boost::variant< float, math::float2, math::float3, relative_point<1>, relative_point<2>, relative_point<3>, std::string, color, group, dictionnary, reference, line, strip,

jquery - event, when (inner) html changes -

i catch event when innerhtml of element changes due "ajaxing". i mean this: $('.t_error span').html.change(function(){ ... }); thanks help! there no way ask - however, instead can use construct: $.ajax({ type: "get", url: yoururl:, success: function (data) { ajaxcomplete(); } }); function ajaxcomplete() { .... } edit: if want cleverer, use custom events : basically define customevent function: var customevent = function() { //name of event this.eventname = arguments[0]; var meventname = this.eventname; //function call on event fire var eventaction = null; //subscribe function event this.subscribe = function(fn) { eventaction = fn; }; //fire event this.fire = function(sender, eventargs) { this.eventname = eventname2; if(eventaction != null) { eventaction(sender, eventargs); } else { alert('there no function subscribed ' + meventname

c# - How Play YouTube video in webBrowser control? -

is there way play youtube video in webbrowser control? because when tap on watch video nothing happens... thanks! as far know windows phone 7 not support flash yet. take @ this: http://answers.microsoft.com/en-us/winphone/forum/wp7-wpdevices/will-windows-phone-7-play-you-tube-and-flash/29c69dc1-658f-4729-b24d-67b46a4138d2

java - Annotate StatelessBean with @Depends to HornetQ-JMS Queue -

i have simple definition of jms-queue in file my-hornetq-jms.xml : <configuration xmlns="urn:hornetq" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="urn:hornetq /schema/hornetq-jms.xsd"> <queue name="my.test.queue"> <entry name="/queue/mytest"/> </queue> </configuration> the queue activated correctly , want add dependency in @stateless bean. question similar how can ensure hornet queues there when webapp starts in jboss 6.0? , want define dependency annotation. tried (in several permutations), didn't find right way: @depends(value="org.hornetq:module=jms,type=queue,name=my.test.queue") i errors this: dependency "<unknown jboss.j2ee:jar=my.war,name=mybean,service=ejb3>" (should in state "installed", in state "** unresolved demands 'org.hornetq:module=jms,name=my.test.queue,type=queue'

iis - Automatic machine key generation in ASP.NET -

by default, machine key setting auto generate , per application (autogenerate,isolateapps). msdn states decryption key , validation key based on web application id. hosting 2 asp.net mvc 2 sites on iis 7 server found out machine key same. verified using reflection see validationkeyinternal , decryptionkeyinternal property. tested generating anti forgery token cookie on 1 site , pass other , cookie can read. after trial , error, found key change if application pool identity changes. 2 sites have same keys because running under network service credential. once change application pool identity of 1 site, begin have different validation/encryption keys. however, after deploy 2 sites server, same machine keys after changing application pool identity. 2 servers have same hardware , software configuration. i know if there reference actual logic of how machine key generated under autogenerate,isolateapps setting. on web, there lot of articles talking setting same machine key in web f

How to write insert trigger in sql server 2005? -

hello want create 1 insert trigger in have table table hardwaremaster hardwareid hardwarename quantity 1 hdd 5 , second table 2 ram 2 table transdetails transid hardwareid 1 1 2 1 3 1 4 1 5 1 6 2 7 2 here want create trigger in once value come in hardwaremaster update table transdetails . how write trigger in this can : create trigger tr_ins_whatyouwant on hardwaremaster after insert declare @hardwareid int select @hardwareid = hardwareid inserted go insert dbo.transdetails (hardwareid) values (@hardwareid) but suggest read before make trigger work : create trigger

java - How to set a proper layout -

i want set layout following: 1 column , 5 rows , in center. tried using gridlayout(5,0) remains in left, suggestions how make center? import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.jpanel; public class testswinglisteners1 { private static int cnt1; private static int cnt2; public static void main(string[] args) { jframe fr1 = new jframe("swing window"); container cp; jbutton bt1; jbutton bt2; cnt1 = 0; cnt2 = 0; final string scr = null; final string wnr = null; jbutton btok, btcancel; fr1.setdefaultcloseoperation(jframe.exit_on_close); fr1.setsize(200, 200); fr1.setresizable(true); cp = fr1.getcontentpane(); cp.setlayout(new gridlayout(5,0)); // cp.setlayout(new boxlayout(boxlayout.y_axis)); btok = new jbutton("ac milan"); btcancel = new jbutton("real madrid&q

image - Save pdf to jpeg using c# -

i need convert pdf file jpeg using c#. , solution (library) have free. i have searched lot of information seems don't nothing clear. i tried itextsharp , pdfbox (but this, pdf2image java, think) no success. i tried extract images pdf individually, have error of invalid parameters when try extract images... seems have strange encoding. anyone can recommend me library save pdf jpeg? examples appreciated too. thanks! solution: how convert pdf image using c# go to: http://www.codeproject.com/kb/cs/ghostscriptusewithcsharp.aspx download de library follow steps in web add code application, (very simple): //transform pdf jpg pdftoimage.pdfconvert pp = new pdfconvert(); pp.outputformat = "jpeg"; //format pp.jpegquality = 100; //100% quality pp.resolutionx = 300; //dpi pp.resolutiony = 300; pp.firstpagetoconvert = 1; //pages want pp.lastpagetoconvert = 1; pp.convert(path_pdf+ "report.pdf", path_image + "n

java - Concurrency when calling webservice clients -

i have webapp use webservice clients data displays. when load not high app work fine. unfortunately when load bigger servers become overloaded because of following stucked threads... any idea might cause ? ]", more configured time (stuckthreadmaxtime) of "600" seconds. stack trace: com.sun.org.apache.xml.internal.resolver.catalog.parsecatalog(catalog.java:660) com.sun.xml.ws.util.xml.xmlutil.createdefaultcatalogresolver(xmlutil.java:251) com.sun.xml.ws.client.wsservicedelegate.parsewsdl(wsservicedelegate.java:265) com.sun.xml.ws.client.wsservicedelegate.<init>(wsservicedelegate.java:228) weblogic.wsee.jaxws.spi.wlsservicedelegate.<init>(wlsservicedelegate.java:52) weblogic.wsee.jaxws.spi.wlsprovider$servicedelegate.<init>(wlsprovider.java:371) weblogic.wsee.jaxws.spi.wlsprovider.createservicedelegate(wlsprovider.java:79) weblogic.wsee.jaxws.spi.wlsprovider.createservicedelegate(wlsprovider.java:62) javax.

mySQL command Explain ignore LIMIT? -

i use mysql server version 5.5.14 , trying simple sql query explain command: explain select id, name, thumb `twitter_profiles` limit 10; and shows me result: +----+-------------+-------+------+---------------+------+---------+------+-------+-------+ | id | select_type | table | type | possible_keys | key | key_len | ref | rows | | +----+-------------+-------+------+---------------+------+---------+------+-------+-------+ | 1 | simple | tp | | null | null | null | null | 40823 | | +----+-------------+-------+------+---------------+------+---------+------+-------+-------+ 1 row in set (0.02 sec) my question why scans whole table instead of taking first 10 rows specified in limit clause? thank advice in advance! cheers, jakub here link of article mysql explain limits , errors limit not taken account while estimating number of rows if have limit restricts how many rows examined mysql still print full number

c# - How to add user control into groupbox -

i have c# winform application , 1 wpf user control. how can add groupbox(which in winform) controls wpf usercontrol? add elementhost control groupbox , add wpf usercontrol in elementhost. see here , here articles.

php - How can I edit my code to echo the data of child's element where my search term was found in, in XMLReader? -

i new in xmlreader, , think kind of hard find tutorials/code or advanced examples. question how can transform code have now, if search (through form) term jquery give me opportunity output value of <info></info> (and later other elements) in every <name></name> found in ? this code output names of books. <?php $reader = new xmlreader(); $reader->open("books.xml"); while ($reader->read()) { switch ($reader->nodetype) { case (xmlreader::element): if ($reader->localname == "name") { $reader->read(); echo $reader->value; break; }}} ?> the xml file <?xml version="1.0" encoding="iso-8859-1"?> <library> <book isbn="781"> <name>scjp 1.5</name> <info>sun certified java programmer book</info> </book> <bo

apache - Where can I download pdo_sqlite.so or sqlite.so -

i'm running zend application on mamp (macos), , need apache extension pdo sqlite (pdo_sqlite.so or sqlite.os). do know can downlaod it? thanks! its included mamp installations , must see link see included modules

c - Running time vary on Microblaze after code modification -

when modifications in code runs on microblaze, see large discrepancy in runtime execution of code follows same path. illustrate, mean same path, take example, if ( condition ) execute_this(); else execute_that(); // modified function so if modified code function execute_that , see change in runtime when condition set , function execute_this has not been modified. can cause this? memory alignment of functions? cache? clue? does timing only change when change other function, or variable anyway? are running os? other tasks pre-empt yours? are interrupts running? interrupt during function change runtime. and, yes, cache effects could cause this.

c# - How can I define control as a resource and then place it onto form? -

i want this: <window x:class="wpfapplication10.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" title="mainwindow" height="350" width="525"> <window.resources> <button x:key="butt" content="yeah!" /> </window.resources> <grid> <!-- place button here --> </grid> </window> how it? want create library of small user controls in single file. <grid> <staticresource resourcekey="butt"/> </grid> should work...

objective c - Trying to remove a decimal from NSString -

this bizarre. developing iphone have nsstring: distancefromtargetstring = @"6178266.000000" // not code, value taken elsewhere. proper nsstring though. when use nsarray *listitems = [distancefromtargetstring componentsseparatedbystring:@"."]; distancefromtargetstring = [listitems objectatindex:0]; or this [distancefromtarget settext: distancefromtargetstring]; i this -[nsdecimalnumber isequaltostring:]: unrecognized selector sent instance 0x1cac40 2011-07-21 14:29:24.226 assassinbeta[7230:707] *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: '-[nsdecimalnumber isequaltostring:]: unrecognized selector sent instance 0x1cac40' any ideas? you try : nsinteger = [distancefromtargetstring integervalue]; nsstring s = [nsstring stringwithformat:@"%d", i]; // got string

naming conventions - Google's CSS styling -

having been inspecting few elements on google, noticed naming conventions funky, ie. .n-wa-q-dc, .n-xb .n-wa-q-dc:hover this not readable/manageable human. opinion google's css , class names largely auto generated server side technology. i cant see people maintaining such css file myself. would advisable such large system (google) have any people managing css , let systems handle it? they should have version human-readable (for development) and, that, generate obfuscated version (for deployment). likely, search-n-replace performed on names of scripts or stylesheets (from using human-readable obfuscated ones) before deployment.

R - how do I declare a vector of Date? -

for example, tried following create vector of dates, length 5. none work: date(5) date(5) vector(5, mode = "date" ) this works, wondering if there shortcut? as.date( numeric( 5 ) ) also, see mode( as.date("2011-01-01" ) ) numeric , understand underlying data structure dates numeric, given vector() has mode , length argument, seems me impossible create vector of date without coercion? edit this solution, except length = 0? date = function( length = 0 ) { newdate = numeric( length ) class(newdate) = "date" return(newdate) } you can use sequence, or just add: r> seq( as.date("2011-07-01"), by=1, len=3) [1] "2011-07-01" "2011-07-02" "2011-07-03" r> as.date("2011-07-01") + 0:2 [1] "2011-07-01" "2011-07-02" "2011-07-03" r> and both work same way nice illustration of why object-orientation nice programming data. date, saw, has underlyi

swing - Java JFrame Size according to screen resolution -

i created java gui using myeclipse matisse. when screen resolution 1024x768 works fine when change resolution gui not working fine. want gui window should re-sized according screen resolution extending jframe create main window. public class myclass extends jframe { //i putting controls here. dimension screensize = toolkit.getdefaulttoolkit().getscreensize(); setbounds(0,0,screensize.width, screensize.height); setvisible(true); pack() } this not working, ever do, setting size hardcoded or toolkit using, frame size remains same. you calling pack() changes frame size fits components inside. that's why shrinking think. remove pack() line , should work.

c# - Using datasource with CheckBoxList -

i use checkboxlist in windows forms application , trying apply datasource it. having datatable, 'dt', columns id , name , ischecked , use such code: ((listbox)mycheckboxlist).datasource = dt; ((listbox)mycheckboxlist).displaymember = "name"; ((listbox)mycheckboxlist).valuemember = "id"; how set checkstate items in mycheckboxlist? i keep value in datatable , want link them mycheckboxlist. i've decided problem in 2 steps. first, applied datasource, , in circle set checked property each item in following code: ((listbox)mycheckboxlist).datasource = dt; ((listbox)mycheckboxlist).displaymember = "name"; ... (int = 0; < folloving.items.count; i++ ) { datarowview row = (datarowview)mycheckboxlist.items[i]; bool ischecked = convert.toboolean(row["checked"]); mycheckboxlist.setitemchecked(i, ischecked); }

How to recover from a Silverlight UnhandledException -

in app() initialization code, include generic handler unhandledexception += application_unhandledexception; private void application_unhandledexception(object sender, applicationunhandledexceptioneventargs e) { debugger.break(); } i have 2 screens work fine, when navigating , forth between 2 screens number of times (varies between 7 , 12) hit breakpoint exception {system.windows.applicationunhandledexceptioneventargs} base {system.eventargs}: {system.windows.applicationunhandledexceptioneventargs} exceptionobject: {system.argumentexception: value not fall within expected range.} handled: false and if remove unhandledexception , set debugger break on unhandled, following: unhandled error in silverlight application code: 4004 category: managedruntimeerror message: system.windows.markup.xamlparseexception: 2028 error has occurred. [line: 0 position: 0] ---> system.argumentexception: [arg_argumentexception] arguments: debugging resource strings

How to approach Java 2D performance variations between different computers? -

i've been designing card game in java on windows. runs on laptop , few others, on lot of other systems (even few newer ones both mac , windows) animation incredibly slow. i've found user interface toolkits java best resource far, haven't been able make significant improvement. i'm using awt/swing libraries. question: looking @ my game , (<1.5mb), how on computers (of similar spec) performance seems less on laptop? entire app event-driven , i've done of optimization reckon done given implementation. i have feeling memory-related. create (compatible) , store images array @ start, , reference them there. note: decided make game can learn , practice new ideas, i'm not trying share - i'm interested find out what's going on here. on not operating systems, java 2d rendering pipeline supports hardware acceleration gpu. depends on java implementation you're using. one of new features oracle's java se 7 implementation (which co

configuration - Disabling localization in Visual Studio 2010 -

i have installed ms visual c++ express on localized windows machine. due automagical language configuration, have non-english version of vs. it's not problem menus, compiler messages quite cryptic : exception de première chance [...]: le mappeur de point final n'a plus de point final disponible. is possible switch english, @ least compiler messages ? how ?

vb.net - How to use HttpWebRequest to download file -

trying download file in code. current code: dim uri new uribuilder uri.username = "xxx" uri.password = "xxx" uri.host = "xxx" uri.path = "xxx.aspx?q=65" dim request httpwebrequest = directcast(webrequest.create(uri.uri), httpwebrequest) request.allowautoredirect = true request = directcast(webrequest.create(downloadurlin), httpwebrequest) request.timeout = 10000 'request.allowwritestreambuffering = true dim response httpwebresponse = nothing response = directcast(request.getresponse(), httpwebresponse) dim s stream = response.getresponsestream() 'write disk dim fs new filestream("c:\xxx.pdf", filemode.create) dim read byte() = new byte(255) {} dim count integer = s.read(read, 0, read.length) while count > 0 fs.write(read, 0, count) count = s.read(read, 0, read.length) end while 'close fs.close() s.close()

iphone - writeImageToSavedPhotosAlbum save only a few images -

i've been following apples example, qa1702 , on how capture images using avfoundation. won't cite code here because of space concern. brief description of i'm trying achieve: use iphone camera pass "video" (actually sequence of images) web server, , know possible. in order able pass image using http post in this example , have save image. not in photos album wan't able view pictures there in debug purposes. the apple qa1702 contains 3 methods: - (void)setupcapturesession - (void)captureoutput:(avcaptureoutput *)captureoutput didoutputsamplebuffer:(cmsamplebufferref)samplebuffer fromconnection:(avcaptureconnection *)connection //this modified void might see, - (void) imagefromsamplebuffer:(cmsamplebufferref) samplebuffer in setupcapturesession start session in example. captureoutput running imagefromsamplebuffer, , that's i've added changes: // create quartz image pixel data in bitmap graphics context cgimageref quartzimage = c

.net - Apache POI Update Custom Fields -

i have used ikvm.net create .net dll apache poi, used update properties of microsoft word 2003 document - author , company , custom fields. the document references of these fields in content. for example ref: account number [account number held in custom field] when open document have right-click on field , "update field" show new information written poi. for documents not big deal there going 20+ custom fields need updating. hand not preferable option. any way in poi update fields they're correct when document opens? or need resort macro of sort fires when document opens? thanks

javascript - Change the value of a variable after it's been set -

here's problem. i have piece of code sets user location coordinates in textbox. var initiallocation; $('#from').val(initiallocation); the initiallocation variable gets user current location coordinates , $('#from').val(initiallocation); puts coordinates in textbox "from". but instead of boring coordinates "45.542307, -73.567200" i'd textbox show "your location". so basically, want have coordinates in textbox, change user sees "45.542307, -73.567200" "your location". is possible such thing ? thanks ! you can use data method of jquery stores data specific element $("#from").data("currentlocation", initiallocation).val("your location"); //to retrieve currentlocation $("#from").data("currentlocation");

c# - DisplayFormat unit testing with HtmlHelper -

mymodel _model = new mymodel() { pricedate = new datetime(2000, 1, 1)}; var helper = new system.web.mvc.htmlhelper<mymodel>(new viewcontext(), new viewpage()); var result = helper.displayfor(m => _model.pricedate); assert.that(result, is.equalto(expected)); i want test output produced calling displayfor in format specified by... [displayformat(dataformatstring = "{0:dd/mm/yy}")] public datetime? pricedate { get; set; } the code compiles fails nullreferenceexception @ displayfor . can me make work? (note: trivial example of larger problem) the steps quite long couldn't write here. wrote @ blog :d http://thoai-nguyen.blogspot.com/2011/07/unit-test-displayformat-attribute.html cheers

java - Passing a string between voids -

i'm new java , i'm not sure if ask question right. have 2 voids, in second 1 string , want use main void. code that: public void oncreate(bundle savedinstancestate) { shuffle(); //here want use string correctanswer } public void shuffle() { string correctanswer = "whatever"; } if want use string calculated in second function, why use void? public void oncreate(bundle savedinstancestate) { string s = shuffle(); //use s; } public string shuffle() { string correctanswer = "whatever"; return correctanswer; } you make correctanswer instance variable: private string correctanswer; public void oncreate(bundle savedinstancestate) { shuffle(); //use instance variable correctanswer; } public void shuffle() { correctanswer = "whatever"; }

css - jquery add a class to $('<a/>').click(function(){...}) -

how can add class tags such a & span in these examples: $('<a/>').click(function(){...}) $("<span/>").text(chars.substr(0, limit-1)); ================= here full script. adds spans , tags portions of text. need have classes added spans or tags can style selections. has jquery 1.3x: var limit = 200, chars = $("#showhidediv").text(); if (chars.length > limit) { var visiblepart = $("<span/>").text(chars.substr(0, limit-1)); var hiddenpart = $("<span/>").text(chars.substr(limit-1)).hide(); var readmore = $('<a/>').click(function() { hiddenpart.toggle(); readmore.toggle(); readless.toggle(); return false; }).text ("show more") var readless = $('<a/>').click(function() { hiddenpart.toggle(); readmore.toggle(); readless.toggle(); return

c# - satellite assemblies used from a .dll -

i trying implement satellite assemblies. scenario though different ordinary case. i have executable assembly ( let's call a.exe) , .dll assembly (b.dll) a.exe references b.dll , a.csproj start project in solution my strings file in assembly b (the class library) i created satelite assemblies , placed them in bin folder of prject b. the issue no matter culture provide, falls on default culture embedded in project.(the satelite assemblies not) when try place default strings file , satelite assemblies in .exe project work, transfer them .dll project don't does have solution situation. can't place strings file in .exe project (business requirement) thanks in advance. since can't answer own question in separate reply, here solution: you need place satellite assembly's .dll files both in library , executable assembly's \bin directories. i started project on site: example and elaborated include library class. wish there way post here...let

javascript - How can I create a file upload using jQuery and php? -

how can create jquery multiple image upload(upload without refresh page after choose file displaying image not insert databse) , submit additional form data , submit click on button without refresh page data insert database. jquery , php? like: there in tag form: checkbox, input:text, input:textarea, selection:option , input:file upload php know,but not know upload jquery. start , should use? give me link tutorial or explain? not use of plugin, , not want idea. with respect jquery ajax file upload plugin http://www.phpletter.com/demo/ajaxfileupload-demo/