Posts

Showing posts from April, 2011

java - Upload Image to Folder and send path to database in struts? -

upload image folder , send path database in struts? you should take @ apache commons fileupload http://commons.apache.org/fileupload/using.html . and perhaps article http://struts.apache.org/2.0.14/docs/file-upload.html .

CMIS and Sharepoint -

i looking @ cmis connectivity 1 of our internal applications. know cmis part of (or be) part of sharepoint, there workable c# api (the openapi c# project seems in initial stages)? thanks you talking sharepoint 2010 , difficulties around " cmis , sharepoint 2010 details hard find ". microsoft provided cmis connector sharepoint 2010 administrative toolkit (download) . the cmis connector sharepoint server 2010 includes 2 features: the content management interoperability services (cmis) consumer web part, can added sharepoint page. web part displays , lets users interact contents of cmis repository. the content management interoperability services (cmis) producer, allows applications interact sharepoint lists , document libraries programmatically means of interfaces defined in cmis standard. please note need sharepoint server 2010 - sharepoint foundation not enough.

jquery - Content upload progress using ajax -

i have page in user input content , save it. i have function sends data server using xmlhttprequest. requirement show progress percentage while data being saved. 1 know way this? i thought use swfupload, appears specific file upload opposed dynamic content upload. any appreciated. thanks latest xmlhttprequest level 2 spec has added support events. specifically, can show upload progress like: xhr.upload.onprogress = function(evt) { if (evt.lengthcomputable) { var percent = 100 * evt.loaded / evt.total; trace("[onprogress] " + percent); } } the issue today lacking of support in web browsers. you'll have work around via flash or channel server progress notification. can find many discussions in site.

python - How can I serve a (never ending) system call with Tornado -

for instance, suppose have code: def dump(): tcpdump = subprocess.popen("tcpdump -nli any", stdin=subprocess.pipe, stdout=subprocess.pipe, shell=true) outputfile = tcpdump.stdout line in outputfile: print line, how can serve output of such browser? since there no stopping point, have no idea hook polling loop. more that, print line works (i see lines dumped on terminal), browser not same lines, see below: class tcpdumphandler(tornado.web.requesthandler): def get(self): self.write("<form method='post' action='/log'><input type='submit'></form>") @tornado.web.asynchronous def post(self): tcpdump = subprocess.popen("tcpdump -nli any", stdin=subprocess.pipe, stdout=subprocess.pipe, shell=true) outputfile = tcpdump.stdout line in outputfile: print line, self.write(line) self.finish()

python - blocking sockets and select -

i'm playing around sockets, , i'm having doubts using blocking sockets select.let's assume i'm tracking potential readers. right in thinking select go through first socket in list , if data available return , if not block until select's timeout expires? when other sockets in read list checked select? let me illustrate python example simplicity: servsock = socket.socket(socket.af_inet, socket.sock_stream) servsock.bind(("", 2500)) servsock.listen(15) servsock.setblocking(1) readlist = [servsock] while 1: (sread, swrite, sexc) = select.select(readlist, [], [] ); sock in sread: #received connect server socket if sock == servsock: (newsock, address) = servsock.accept() newsock.setblocking(1) print "i got connection ", address readlist.append(newsock) newsock.send("you're connected select server") else: recv_msg = sock.rec

php - Is it better to use fwrite() or move_uploaded_file()? -

it's more of coding standards question one. 1 is, if can call "better" use in file upload handler scripts? i know fwrite() , it's accompanying methods reading , writing can in chunks using move_uploaded_file() more elegant , shorter code. thanks use move_uploaded_file() . checks ensure user not funny business. also, using fread() , fwrite() copies file, instead of moving it, few orders of magnitude more costly moving (which changes it's name , given source , destination on same partition).

performance - How to subtract one huge list from another efficiently in C# -

i have long list of ids (integers) represents items in database: var idlist = getallids(); i have huge generic list items add database: list<t> itemstoadd; now, remove items generic list id in idlist. idlist simple array , subtract lists this: itemstoadd.removeall(e => idlist.contains(e.id)); i pretty sure lot faster, datatypes should use both collections , efficient practice subtract them? thank you! transform temporarily idlist hashset<t> , use same method i.e.: items.removeall(e => idlisthash.contains(e.id)); it should faster

Android build works in Eclipse but not with Ant ("already added") -

my android project uses several git submodules marked android libraries. these submodules have different uses of ormlite android jars , have ormlite jars included in libs directory. eclipse handles situation correctly: includes ormlite jars once during dex processing , generates valid .apk, when run build via ant debug , get: [echo] converting compiled files , external libraries /home/webedit/.hudson/jobs/xyz/workspace/bin/classes.dex... [apply] [apply] unexpected top-level exception: [apply] java.lang.illegalargumentexception: added: lcom/j256/ormlite/android/androidcompiledstatement; [apply] @ com.android.dx.dex.file.classdefssection.add(classdefssection.java:123) [apply] @ com.android.dx.dex.file.dexfile.add(dexfile.java:143) [apply] @ com.android.dx.command.dexer.main.processclass(main.java:338) [apply] @ com.android.dx.command.dexer.main.processfilebytes(main.java:315) [apply] @ com.android.dx.command.dexer.main.access$100(main.java:56) [apply] @

bit manipulation - Bitwise operations in C# -

is there shorter , better-looking alternative to (b == 0) ? 0 : 1; in terms of bitwise operations? also, correct sign (-1, 0 or 1) of given integer a using (a > 0) ? 1 : (a >> 32); are there shorter (but not slower) ways? personally i'd stick first option "equal 0 or not" option. for sign of integer, i'd use math.sign , assume jit compiler going inline - testing assumption benchmarks if turns out potential bottleneck. think readability above - first piece of code blindingly obvious. second isn't. i'm not convinced second piece of code works ... thought right-shifts masked bottom 5 bits, assuming int32 ( int ). edit: checked, , indeed current second piece of code equivalent to: int y = x > 0 ? 1 : x; the shift doesn't end in compiled code. take object lesson caring more micro-optimization readability. it's easier make code work if it's easy understand. if code gives wrong result, don't care ho

Need to write a SQL query to fetch data from a Oracle database -

possible duplicate: need write sql query fetch data oracle database i need write sql query can fetch data 1 table a. senario - lets take table has 2 column c1 , c2. c1 has row_id's , c2 has vaues "site=google;site=gmail;yahoo" requirment - need write query can fetch row_id column c1 of table value should come column c2 "yahoo". means if starts "site=" in value of c2 column should not been shown in data fetch. try select * tablea c2 not 'site=%'

Call function from within jQuery plugin -

i'm modifying lovely jquery.carousel.js plugin have autochange feature. want use setinterval() call function, can't play nice. here code have @ moment: autoswitch: function() { if(runauto) { $('.next').click(); } }, init: function(el, options) { if(this.options.auto) { setinterval("this.('autoswitch')", this.options.autotime); } } this snippet , there other stuff, i've left important bits in. line i'm having trouble setinterval("this.('autoswitch')", this.options.autotime); . whatever try in first argument of setinterval , doesn't work. so. can awesome people me out how call autoswitch() setinterval() function please? i think you're looking jquery.proxy : init: function(el, options) { if(this.options.auto) { // give `setinterval` function call setinterval(jquery.proxy(this.autoswitch, this)), this.options.autotime); } } jqu

C# SMTP email sending code fails for Yahoo Mail but works fine for other servers, can anyone help? -

i using code send smtp email via yahoo smtp server, personal project writing. using system.net.mail; using system.net; smtpclient theclient = new smtpclient("smtp.mail.yahoo.com", 465); theclient.usedefaultcredentials = false; theclient.credentials = new networkcredential("username", "password"); theclient.enablessl = true; mailmessage themessage = new mailmessage("username@yahoo.com", "to.someone@gmail.com"); themessage.subject = "dave test c# subject"; themessage.body = "dave test c# body"; theclient.send(themessage); it's pretty standard code sending smtp email, but... server seems throw error. forcibly terminates connection. not happen if use other smtp servers gmail, windows live or various other isp smtp servers. this exception , stack trace: system.io.ioexception: unable read data transport connection: existing connection forcibly closed remote h

php - Most efficient way to calculate 'popularity' of objects on website -

ok i'm building site people can post news, comments, questions, etc. people can rate of these objects, favorite of them, share them, etc. site php+mysql. wrote script in php following: grab comments , scores added them in past 5 minutes. add record 'popularity' table change in popularity each comment object. grab news , scores/views/favorites/shares added them. calculate popularity each news story (taking account change in popularity of comments attached them step 1) , insert record popularity table change in popularity each news object. repeat step 2 questions , other object types i tried run script (it's symfony task) every 5 minutes cron job , php started choking , eating of server resources. what preferred way run background analytics script calculates new data based on data in mysql db, inserts calculated data db? i'm sure i'm missing basic procedures here. should note db on different server , server had no resource problems. problem seems con

testing - How can I get the unit test cases that the developers of the JDK performed on the JDK classes? -

how can info unit test cases developers of jdk performed on jdk classes? see "quality process" , "test methodologies" of openjdk. see "testing build" : you can test build completed using build run various demos find in build/platform/j2sdk-image/demo directory. the provided regression tests can run jtreg utility the jtreg site .

android - How can I scroll my custom view? I want to see the shapes drawn over the bounds of the screen -

i have custom view ... package nan.salsa.goal.customview; import android.r; import android.content.context; import android.graphics.canvas; import android.graphics.drawable.shapedrawable; import android.graphics.drawable.shapes.rectshape; import android.util.attributeset; import android.util.log; import android.view.view; public class dayview extends view { private static string tag="dayview"; private shapedrawable mdrawable; public dayview(context context) { super(context); } public dayview(context context, attributeset attrs) { super(context, attrs); init(); } public dayview(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); init(); } public void init() { int x = 10; int y = 10; mdrawable = new shapedrawable(new rectshape()); mdrawable.getpaint().setcolor(color.green); mdrawable.setbounds(x, y, x + (width - (x * 2)), y + (he

multithreading - How to keep a python script open while some C code executes some thread? -

i trying add non-blocking audio i/o pyaudio. pyaudio relies on portaudio audio i/o. non-blocking audio in portaudio, define callback function when opening audio stream. when audio stream started, call callback function whenever new audio data required. this part works. test wrote simple script implements callback function looking this: def pyaudiocallback(framecount,inadctime,curtime,outadctime,userdata,inp = none): data=getdata(framecount) return (data,0) this callback called whenever audio stream needs new audio samples. however, script not know audio stream still running , terminates whenever done, which, of course, terminates audio stream also. i can work around issue inserting time.sleep() somewhere. audio playback work fine while script sleeping. however, rather postpone script's completion until audio stream thinks done. is there way keep python session alive until criteria met? or wait loop option? several ways. create pipe. pass read end

MySQL Subquery with User-Defined Variables -

i'm trying accomplish query requires calculated column using subquery passes date reference via variable. i'm not sure if i'm not "doing right" query never finishes , spins minutes on end. query: select @groupdate:=date_format(order_date,'%y-%m'), count(distinct customer_email) num_cust, ( select count(distinct cev.customer_email) num_prev _pj_cust_email_view cev inner join _pj_cust_email_view prev_purch on (prev_purch.order_date < @groupdate) , (cev.customer_email=prev_purch.customer_email) cev.order_date > @groupdate ) prev_cust_count _pj_cust_email_view group @groupdate; subquery has inner join accomplishes self-join gives me count of people have purchased prior date in @groupdate . explain below: +----+----------------------+---------------------+------+---------------+-----------+---------+---------------------------+--------+---------------------------------+ | id | select_type | table | type | possibl

android - SimpleCursorAdapter / ListAdapter with Multiple Sources -

is possible build listadapter having elements come different sources (not 1 cursor). // build list of names // query table1.name // query table2.name // create listadapter passing in list of names. here's example creating cursor single table: simplecursoradapter adapter = new simplecursoradapter(this, android.r.layout.simple_list_item_1, cursor, new string[] { name }, new int[] { android.r.id.text1 }); setlistadapter(adapter); adapter.setfilterqueryprovider(m_filterqueryprovider); if (rememberlastconstraint && m_filterqueryprovider.getconstraint() != null) { adapter.getfilter().filter(m_filterqueryprovider.getconstraint()); } one method compile data listview in data structure outside listview adapter , pass listview , called notify data set changed. way can data different type of sources listview.

JQuery .length of element(s) inside each() function -

assuming have following html <div class="news_item"> <div class="news_content">some content here...</div> <img src="something.jpg" /> </div> i have following jquery code; suppose count how many img elements there within particular div , change css of div.news_content if there no img elements. $('div.news_item').each(function() { if ($('img', this).length == 0) { $('div.news_content', this).css('background-color', '#cccccc'); } }); however $('img', this).length not seem work inside each function. it sounds it's working, here alternative code filters out div's img children. $('div.news_item').not(function(index){return $(this).find('img').length > 0;}).each(function(index, elem){ $(this).css('background-color', '#cccccc'); });

c# - Why does my WinForms context menu not appear where the mouse is? -

in application have datagridview meant configuring options. idea can enter whatever text want in first column, if right click give explicitly supported values. need textbox rather dropdown list because need support editing invalid (or old) configurations. what want user right click in field name column , have context menu valid based on type of configuration is. therefore, coded following event private void grvfielddata_cellmouseclick(object sender, datagridviewcellmouseeventargs e) { // if right click on field name column, create context menu // recognized options field if (e.button == mousebuttons.right && grvfielddata.columns[e.columnindex].name == "clmfieldname") { contextmenu menu = new contextmenu(); if (_supporteddatagrids.containskey((cmbdatagrid.selecteditem datagridfieldlist).gridname)) { // loop through fields , add them context menu l

c# - Overridden Refresh() not called for child UserControl -

i run strange problem (winxp / .net 2.0). use winform usercontrol overrides refresh(): public override void refresh() { dosomestuff(); base.refresh(); } i add usercontrol child control , want refresh child controls: parentcontrol : usercontrol { [...] public parentcontrol (...) { [...] usercontrol childcontrol = modelengine.maincontrol; // usercontrol mentioned above this.controls.add(childcontrol); [...] modelengine.maincontrol.refresh(); //#1 this.refresh(); // #2 } } calling refresh() method directly (#1) works fine. expected can call refresh() on parent class (#2) , trigger recursive refresh() on child controls (as explained in msdn http://msdn.microsoft.com/en-us/library/system.windows.forms.control.refresh.aspx ). however, overridden refresh() in child control not executed. btw: setting controlstyles.userpaint true didn't change behaviour. of course call refresh() directly (as in #1) or write own recur

byte hex calculation in java -

i amature in byte..hex calculation etc...my application requires me send data through sockets in form of bytes... 1st byte -> [ { ] 2nd byte -> [ { ] 3rd byte -> [ 0xd1 ] 4th byte -> [ 0x00 ] 5th byte -> [sum of first,second , third hex value] 6th byte -> [ } ] 7th byte -> [ } ] this sample how can perform such operation of assigningthe hex values in each byte, storing these bytes in array.. got bit stuck this.. me out ??? you can build array of bytes : byte[] data = new byte[7]; data[0] = "{".getbytes()[0]; data[1] = "{".getbytes()[0]; data[2] = (byte) 0xd1; data[3] = (byte) 0x00; data[4] = (byte) 0xd1 + 0x00; data[5] = "}".getbytes()[0]; data[6] = "}".getbytes()[0];

apache - PHP APC apc.shm_size cant be set above 39 -

hi having problems apc caching. reason when set apc.shm_size value above 39 unable load php files. there no entries in apache error logs. my set follows: php 5.3.5 apache 2.2.17 loaded apache modules: core mod_win32 mpm_winnt http_core mod_so mod_actions mod_alias mod_asis mod_auth_basic mod_authn_default mod_authn_file mod_authz_default mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_vhost_alias mod_php5 this may library limitation of whatever apc compiled win32 version. while manual doesn't mention win32, note bsd operating systems have low limit shared memory segment size. having said that, apc allows create multiple shared memory segments using apc.shm_segments setting around shared memory segment size limits. the default 1 segment, 32mb in size.

java - Cost of storing objects into request for JSTL -

we have legacy applications start use common jsp pages. in terms of used technologies each of them using different view technologies. shortly, can use jstl in these pages. i want store bundle implementation in request in order used jstl this request.setattribute("bundle", getbundle()); our bundle has maybe 10000 entry. my question: does storing big objects in request bring cost? update: our bundle static. (per server there 1 instance of it.) mean have reference in request object. maybe should state requirement. common pages have existing has implemented. , implementation sharing different bundle implementation. different java.util.resourcebundle . why not use jstl fmt tags. if reusing created bundle guess storing should not cost (considering fact - request java object , have reference collection holds objects), if creating bundle in each request call costly, again not storing perspective time taken creating bundle 10, 000 entries each time , gar

eclipse - 'Null pointer access' when using java output parameters -

i working in java , wanting use output parameters. here example: classa obja = null; if(mymethod(obja)) { // position (1) //use obja somehow } ====================== public bool mymethod(classa obj) { obj = ..... } i using eclipse , problem i'm having eclipse shows warning: null pointer access. variable obja can null @ location when reach position (1) since there no concept of out parameters in java i'm little stumpped ================================================================== edit: have gotten several people mention change method return object instead of bool. if need method alter several objects? ex: classa obja = null; classb objb = null; if(mymethod(obja, objb)) { // position (1) //use obja , objb somehow } ====================== public bool mymethod(classa obj, classb obj2) { //do stuff } how can this? dont want make custom class every flavor of retur

c# - Pass WPF textbox.text from Window1 to data class -

i have wpf window collects data , sends data class saved xml file. want name file in textbox on window1 form , pass data class file can saved. know have let data class know window1 exists, i'm having trouble syntax - guess. you should try other way around: view (wpf) should know view model (wrapper) knows how collect data, should used save file. vm should know model (the implementation of file save stuff among other models data sources etc.) , feed necessary information. using approach combined nootification, can swap out several parts without affecting others. the model (back end) independant of else. the view can defined elsewhere , shouldn't use code behind (except definition of vm , events). binds vm. the view model puts together. provides data structure, can used , presented in wpf. through binding vm informs wpf of updates etc. in case: design nice gui design vm can collect necessary information. write method takes parameters required fil

wpf - Convert C# ObservableCollection sample to VB.NET dataset or equivalent -

i have c# example populating multiselect combobox. example found online. works fine static values coming observable collection. i want change database driven sql server backend, having issues. did populate combobox, selection acting kind of screwy. here sample code if help. type of simple query northwind table suffice such as: "select categoryname categories". so question is: how convert observablecollection use query database rather static string list used in example below? while implementing same property changed functionality. class datasource : inotifypropertychanged { #region inotifypropertychanged members public event propertychangedeventhandler propertychanged; private void onpropertychanged(string propertyname) { if (propertychanged != null) propertychanged(this, new propertychangedeventargs(propertyname)); } #endregion private observablecollection<string> _animals = new observablecollection<

.net - Looking for a locked down script interpreter -

i'm looking .net library specific task. say app has been sent program (in script language) , want app run script. script come openly hostile individual, want run anyway. (like javascript in browser.) var sc = new securescript("somefilefromanunknownpossiblyhostilesource.xyz"); /* set event handlers. */ sc.run(); during run call, script construct it's own data, mess around simple data types, whatever wants long effects contained within it's own world. if script attempts openfile("c:/windows/something.exe"), fail, because haven't registered openfile function. way script interact outside world using function i've registered use script. doing that, i'm taking responsibility script can't bad it. sure, neglect validate parameters, that's not interpreter's job. if script allocated memory, or take many cpu cycles, interpreter class invoke event handler once threshold has been passed , give me power stop script dead. i'

python - Killing individual Apache processes in mod_python -

we having problem individual apache processes utilizing large amounts of memory, depending on request, , never releasing main system. since these requests can happen @ time, on time web server pushed swap, rendering unresponsive ssh. worse, after request has finished, python fails release memory wild, results in number 500mb - 1gb apache processes lying around. we push few requests per second, each request has potential heavy. what have way kill individual apache process child after has finished serving request if resident memory exceeds threshold. have tried several ways of doing inside mod_python, appears form of system exit results in response not completing client. outside of gracefuling processes (which want avoid) whenever happens, there anyway tell apache arbitrarily kill off process after has finished serving request? ideas welcome. as additional caveat, due legacy nature of system, can’t upgrade later version of python, can’t utilize improved memory performance

How do I make Mercurial require files to have documentation (Javadoc, etc) before pushing? -

is possible via extension or native functionality? thanks, brandon you want pre-commit hook call out "validate document" program. based on response document validation, permit/deny hook.

c# - ListView Item index -

how can doubleclicked item (index) listview? private void listviewmodels_mousedoubleclick(object sender, mouseeventargs e) { //this line doesn't work int = listviewmodels.selecteditem (); string mdl_path=getcurrentitempath(i); } selecteditem isn't function, try listviewitem item = listviewmodels.selecteditems[0];

c# - Has anyone got a solution/workaround for CollectionContainer not being Freezable? -

i'm trying bind source of collectioncontainer (or collectionviewsource matter) relativesource binding - following error system.windows.data error: 2 : cannot find governing frameworkelement or frameworkcontentelement target element. i understand due collectioncontainer not being freezable or not deriving frameworkelement . has got solution/workaround problem. have seen talk of trying implement own freezable collectioncontainer - luck approach? thanks, pete

c++ - Why does this dynamic library loading code work with gcc? -

background: i've found myself unenviable task of porting c++ gnu/linux application on windows. 1 of things application search shared libraries on specific paths , loads classes out of them dynamically using posix dlopen() , dlsym() calls. have reason doing loading way not go here. the problem: to dynamically discover symbols generated c++ compiler dlsym() or getprocaddress() must unmangled using extern "c" linkage block. example: #include <list> #include <string> using std::list; using std::string; extern "c" { list<string> get_list() { list<string> mylist; mylist.push_back("list object"); return mylist; } } this code valid c++ , compiles , runs on numerous compilers on both linux , windows. it, however, not compile msvc because "the return type not valid c". workaround we've come change function return pointer list instead of list object: #include <list>

Encryption of VHD used to boot -

can boot vhd file encrypted , still boot under windows 7 or windows server 2008 r2? not according requently asked questions: virtual hard disks in windows 7 , windows server 2008 r2 what not supported native boot when using vhds? using compressed or encrypted vhds native boot. vhds have been compressed ntfs or encrypted using encrypting file system on host volume not supported native boot.

animation - jQuery horizontal scrolling display -

i'm making horizontal scroller using jquery. have working using following var wrapper = $('#wrapper'), content = $('#scroll-content'); wrapper.bind('mousemove', function(e){ var wrapper_width = wrapper.width(), content_width = content.width(); //wrapper , content width var tmp = e.pagex * (content.outerwidth() - wrapper.outerwidth()) / wrapper.outerwidth(); //calculate new left margin content.css({ 'margin-left': '-'+tmp+'px' }); //set margin according /*content.animate({ 'margin-left': '-'+tmp+'px' }, 30, 'easeoutsine');*/ }); every mousemove event calculate new left margin, slider spans 100% width of screen. this works, have 2 problems. seems bad practise calling calculation on every mousemove event there hundreds. there better way, maybe using timers? another question, when user first hovers slider jumps place, tried use anima

.net - using a pointer to a value type in a Dictionary value -

this small snippet of code increment count value (integer) stored in dictionary using referenced object key. when dictionary small, multiple lookups aren't big deal particular dictionary can quite large. private refcount idictionary(of ilifetimemanaged, integer) ......... code here..... private sub incrementrefcount(byval entity ilifetimemanaged) dim prevcount integer ''# if have no reference entry, add 1 , set count 1 if not refcount.trygetvalue(entity, prevcount) refcount.add(entity, 1) else ''# otherwise increment count 1 refcount.item(entity) = prevcount + 1 end if end sub i find corresponding dictionary entry increment int stored in value, or add new dictionary entry. is bad idea use pointer dictionary value? can avoid second key lookup when have gotten value. how implement it? possible in .net4? can using intptr think? http://msdn.microsoft.com/en-us/library/system.intptr.aspx refcount.item(entity

c# - Find the URL of an application -

i working on asp.net c# application. i wish find url of application. example, application nrcme want return http://localhost:4833/nrcme/ when running locally. server want return http://servername/nrcme/ you can find information url in request.url. include file name default can remove this: request.url.absoluteuri.replace(request.url.localpath, "")

sql - What's the database performance improvement from storing as numbers rather than text? -

suppose have text such "win", "lose", "incomplete", "forfeit" etc. can directly store text in database. instead if use numbers such 0 = win, 1 = lose etc material improvement in database performance? on queries field part of clause at cpu level, comparing 2 fixed-size integers takes 1 instruction, whereas comparing variable-length strings involves looping through each character. large dataset there should significant performance gain using integers. moreover, fixed-size integer take less space , can allow database engine perform faster algorithms based on random seeking. most database systems have enum type meant cases yours - in query can compare field value against fixed set of literals while internally stored integer.

C++: making custom class to work like both container and normal class? -

i want have myobject store collection (vector-like) of someotherobjects (so, being homogeneous, right?), should iterable , accessible via (myobject[i]).someotherobjectfield1 have normal members myobject.dostuff() , myobject.stuff . is there option implement such class, or using private std::vector keep objects (which i'm trying avoid - don't private std:: containers) smarter? prefer composition on inheritance, if goal code reuse. (inheritance should used enable polymorphism, doesn't seem issue in case.)

deployment - No web.xml in Eclipse + Glassfish v3? -

i created simple "hello world" servlet in eclipse (helios) + glassfish v3. using glassfish's plugin eclipse seems there no web.xml sun-web.xml in web-inf/ folder. first time glassfish bit surprised @ absence of web.xml - here of problems: where check url-mappings servlet? on creating new servlet in eclipse asks me url-mapping i'm unable find anywhere in .xml file can tweak settings. if there isn't web.xml, creating scratch quite error prone. suggest? google sample , play around? shouldn't 1 auto-created? has encountered this? tried looking difference between web.xml , sun-web.xml results weren't @ enlightening. wouldn't want learn xml configuration purposes , glassfish specific. we have configure servlet contexts, mappings etc during development/testing sheer absence of web.xml has me stumped. eclipse allows not create web.xml file when create dynamic web project java ee 6, since java ee 6 spec (in general) , servlet 3.0 spec (in p

core data - Resolving an NSManagedObject conflict with multiple threads, relationships, and pointers -

i'm having conflict when saving bunch of nsmanagedobjects via outside thread. starters, can tell following: i'm using separate moc each thread. the mocs share same persistent store coordinator. it's outside thread modifying 1 or many of records i'm saving. ok, out of way, here's i'm doing. in outside thread, i'm doing computation , updating single value in bunch of managed objects. looking object in persistent store primary key, modifying single decimal property, , calling save on bunch @ once. in meantime, believe main thread doing updating of own. when outside thread big save on managed object context, exception thrown stating large number of conflicts. of conflicts seem centered around single relationship on each record. though managed object in persistent store , outside thread share same objectid relationship, don't share same pointer. based on see, that's thing that's different between objects in nsmergeconflict debug

How to find the largest word from the string using C#? -

this code finding largest word given string. have got length of words in string how largest word printed out? have tried largest words not able using code plz help? using system; using system.linq; class largest1{ public void largest(){ console.writeline("enter string:"); string buffer1 = console.readline(); string[] buffer = buffer1.split(' '); int length; string largestword = buffer[0]; for(int = 0; < buffer.length; i++){ string temp = buffer[i]; length = temp.length; if( largestword.length < buffer[i].length ) { largestword = buffer[i]; } } var largestwords = words in buffer let x = largestword.length words.length == x select words; console.write("largest words are:"); foreach(string s in largestwords

SQL query to group different strings of words together that both share at least two of the same words -

i'm trying create feature that's similar google news - groups headlines based on how similar are. i thought grouping headlines headlines share minimum number of same word. is there simple sql query @ strings of text , group them in manner? in query i'd grouping article titles together. any amazing. thanks. i explode headlines' each words separately, , save them "tags" , write query displays other articles sharing common tags. both solve question, , have tag system. win-win.

How to Compile a C program in C? -

i making program in c can produce c code. how to, using first program, compile , run second program after second program has been produced? one way used system() call ... system("cl generated_file.c -o gen_exe") ; system("./gen.exe"); or system("gcc generated_file.c -o gen.exe"); system("./gen.exe"); or use simle batch or script or makefile this

c# - WPF Combobox DataBound to a DataTable, Refresh automatically -

i have 1 combobox databinding datatable fetching data database follows: sqldataadapter adp = new sqldataadapter (@"select [categoryid],[categoryname]from [northwind].[dbo].[categories]", @"integrated security=sspi;initial catalog=northwind;data source=akshay-pc\sqlexpress"); datatable tbl = new datatable(); adp.fill(tbl); cmbcities.itemssource = ((ilistsource)tbl).getlist(); cmbcities.displaymemberpath = "[categoryname]"; cmbcities.selectedvaluepath = "[categoryid]"; when table data changed(added/removed rows), combobox not refreshed because ilist not have change notification built it. is there way can made possible? if it's not possible, there way "refresh" databinding datatable fetch data again. in case, execute above code when window initialized , refresh again without needing execute same code again. cmbcities.data.refresh() . what using observablecollection storage data after fetching

caching - Why nginx does not cache my content? -

i checked cache path /usr/local/nginx/proxy_cache. no cache file found after visit url many times. my configuration: ngnix.conf http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; tcp_nodelay on; client_body_buffer_size 512k; proxy_temp_file_write_size 128k; proxy_temp_path /usr/local/nginx/proxy_temp; proxy_cache_path /usr/local/nginx/proxy_cache levels=1:2 keys_zone=content:20m inactive=1d max_size=100m; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } default server { listen 80; server_name 208.115.202.87; location /test { proxy_cache content; proxy_cache_key $host$uri$is_args$args; proxy_cache_valid 200 15m; proxy_pass http://aaa.com/; } nginx not cache pages

objective c - Code coverage not showing results using Xcode + gcov -

i have been trying code coverage working iphone simulator , 0% coverage. below configuration details , steps have tried. configuration xcode 3.2.5/ios 4.1 , ios 4.2/mac 10.6/gcc 4.2 application uicatalog references http://www.cubiclemuses.com/cm/articles/2009/05/14/coverstory-on-the-iphone/ http://developer.apple.com/library/mac/#qa/qa2007/qa1514.html steps enable “generate test coverage files” enable “instrument program flow” add “ -lgcov ” “other linker flags” uiapplicationexitsonsuspend flag in info.plist set true result i have .gcda files generated coverage show 0%. settings tried changing gcc 4.0 , 4.2. when try change gcc 4.0 26 build errors. set environment variables (const char *prefix = "gcov_prefix"; const char *prefixvalue = [[nshomedirectory() stringbyappendingpathcomponent:@"documents"] cstringusingencoding:nsasciistringencoding]; // gets filepath app's documents directory const char *prefixstrip = "gcov_

reactive programming - What's the difference between Knockout.js and Rx.js? -

does know differences between rxjs , knockout ? me on surface seem trying solve same problem, build event driven ui. has had experience both, how differ/ how similar? can describe them me choose? steve (the creator of knockout) explained difference on blog: i’m familiar rx javascript, having used heavily on big project, , in fact aspects of design of knockout made rx experiences in mind. the key difference between knockout’s implementation of observer pattern , rx’s knockout automatically infers associations , dependencies between observables regular procedural code without having specify them front though special functional api. wanted knockout use regular procedural/imperative-style code it’s more familiar , approachable developers. another difference rx optimised composing streams of events without state. @ first enthusiastic , functional purity, after time felt increasingly jumping through awkward hoops , had invent ways si

cordova - How to store and fetch data on iphone locally -

what want is: store data in iphone. display stored data. can know simple way it? thanks iphone sdk tutorial: reading data sqlite database , 12 sqlite resources iphone developers should started.

How to transfer data from a SQL Server Database to a Oracle Database -

the current application i'm working lets call x archiving application data kept application y. both old applications developed 8 odd years back. far in reading of documentation, have learnt process transfer data used that, sql server database tables snapshot created in flat files , flat files ftp'd correct unix box through ctl various insert statements generated oracle database , that's how data transferred. uses bcp utility. wanted know if there better , faster way accomplished. there should way transfer data directly, feel whole process of taking in files , transfer , insert must slow , painstaking. insights??? create db link oracle database sql server database, , can transfer data via selects / inserts. schedule process using dbms_scheduler if needs done on periodic basis.

javascript - How to determine error if IIS 6 is redirecting to a different page based on error? -

ok, might seem confusing, basically, this: there's form on asp page (not .net), sends info ms sql 2000 based server, running on iis6 (i think, might iis 5.1). server configured accept digits, form not validated. so when user keys in alphabets, , submits, error displayed. have configured iis redirect different page based on http error code, ("sorry, page requested cannot loaded @ time"), i, developer, don't know error code about. is there way can configure error page 'onload' send email containing page address caused error, error message itself, time of error, current user that's logged in, etc.? i'm open solutions, client side javascript, or server side asp code... iis configs valid answers now.. lol... in iis, custom errors tab > change 500 error type url file 'error.asp' in error.asp, loop form, querystring , session elements , send error details home in on error. dim asperr ,asperrstr,intkey dim strquerystring

c# - web calls never timing out -

i have number of applications using various web technologies such soap, wcf services, or simple xmlreader. seem suffer same problem of missing timeout , hanging infinitely if internet connection suffers problems @ wrong time. i have set timeout in scenarios small, e.g. wcf closetimeout="00:00:15" opentimeout="00:00:15" receivetimeout="00:00:15" sendtimeout="00:00:15" or soap _session.timeout = (int)timeout.totalmilliseconds; these timeouts hit, appears there special case if internet drops out @ right time, call hang , never time out (using synchronous calls). i considering starting timer every time make call, , using appropriate .abort() function if timer expires cancel call. however, wondering if there simpler way fix issue , ensure timeout gets hit. does know why occurs, , if clean/simple/good way ensure calls time out? i can guess @ why occurs, without giving solution :( i suspect it's getting caught on d

How to use FastMM in delphi expert(dll) -

i made delphi expert(dll - delphi 5). want test expert memory leak.how use fastmm dll expert? possible use fastmm(for dll) instead of standard memory manager? i emphatically advise use in dll running in ide's address space same memory manager used respective version of ide. madness lies other way.

Is using an API always preferable to scraping? -

i looking large amount (>100k @ least) of data web 2.0 sites research project. thinking of using exposed api data, scrapping work better in case? the api (less work compared writting scraper), have no idea how time need collect data, considering there time/call limit. i'm not saying there no limit in scraping though; curious better way of getting job done. if site provides api, use it. it's simpler, generic, , legal. if site kind of popular, find wrappers language you're using. of course, if develop scraper, won't have limitations, maybe site doesn't allow being scraped, , that's why have api users/developers. about jeffrey04 comment: let's see... moral thing. if want, can obtain amount of data several times without being blocked. can change user-agents , change ip after n requests (of course, of programatically), , tricks cookies , that's not idea. mean advice of not using website scraping not because of getting banned webs

rapidly change data type of table in Access 2007 -

i have table >100 columns imported excel access 2007, , want change datatype of fields memo, being fed of manually clicking datatype pull down list 1 one, can vba or sql statement? thanks! i fixed finally: dim db dao.database dim tdf1 dao.tabledef dim fld dao.field set db = currentdb set tdf = currentdb.openrecordset("ssi_10q12_v5_table") set tdf1 = db.createtabledef("ssi_10q12_v5_table_1") debug.print tdf.name, debug.print tdf.fields.count x = 0 tdf.fields.count - 1 debug.print tdf.fields(x).name, set fld = tdf1.createfield(tdf.fields(x).name, dbmemo) tdf1.fields.append fld next x db.tabledefs.append tdf1 set fld = nothing set tdf = nothing end sub see if can here, again.

How do I install "Ruby Linguistics With Verb Conjugation"? -

i downloaded source code " ruby linguistics verb conjugation ". how can install usage? need compile gem? cd directory , run rake , install gem: $ git clone https://github.com/bdigital/ruby_linguistics_with_verb_conjugation.git $ cd ruby_linguistics_with_verb_conjugation $ rake ...lots of output... built rubygem name: linguistics version: 1.0.8 file: linguistics-1.0.8.gem mv linguistics-1.0.8.gem pkg/linguistics-1.0.8.gem $ cd pkg $ gem install linguistics-1.0.8.gem done!

jquery define own events? -

is possible define event on input fired upon these circumstances. a) called on blur of input if remaining conditions true b) if autocomplete list visible halt event until closed c) if autocomplete list closes without item being selected event fired d) if autocomplete list closes item being selected event not fired e) if reason blur caused because item in autocomplete clicked event not fired as can see event has quite bit it. cant use normal settimeout in blur event because user sitting on the autocomplete list without selecting anything. maybe set variable on autocomplete open know still open. if timer expires , autocomplete still open can reset timer. on close can unset variable. or on select of item can unset timer? what think? it's possible trigger own events using trigger function. means can call event @ separate points in code, don't have write complicated constructions. simply call this: $('.yourclass').trigger('myevent'); li

java - How to load/find a JAR resource from inside GMaven script? -

this gmaven script, trying find , load file located somewhere inside provided dependency (it's section of pom.xml ): [...] <plugin> <groupid>org.codehaus.gmaven</groupid> <artifactid>gmaven-plugin</artifactid> <executions> <execution> <configuration> <source> <![cdata[ def file = // how my-file.txt? ]]> </source> </configuration> </execution> </executions> <dependencies> <dependency> <groupid>my-group</groupid> <artifactid>my-artifact</artifactid> <version>1.0</version> </dependency> </dependencies> </plugin> [...] the my-file.txt located in my-group:my-artifact:1.0 jar file. the answer simple: def url = getclass().getclassloader().getresource("my-file.txt"); then url in following format: jar:file