Posts

Showing posts from September, 2012

use doctest and logging in python program -

#!/usr/bin/python2.4 import logging import sys import doctest def foo(x): """ >>> foo (0) 0 """ print ("%d" %(x)) _logger.debug("%d" %(x)) def _test(): doctest.testmod() _logger = logging.getlogger() _logger.setlevel(logging.debug) _formatter = logging.formatter('%(message)s') _handler = logging.streamhandler(sys.stdout) _handler.setformatter(_formatter) _logger.addhandler(_handler) _test() i use logger module of print statements. have looked @ first 50 top google links this, , seem agree doctest uses it's own copy of stdout. if print used works if logger used logs root console. can please demonstrate working example code snippet allow me combine. note running nose test doctest append log output @ end of test, (assuming set switches) not treat them print statement. i'm not sure why want this, if need it, can define own subclass of doctestrunner , ,...

multithreading - c++ multithread -

i use c++ implement thread class. code shows in following. have problem how access thread data. in class thread, create thread use pthread_create() function. calls entrypoint() function start thread created. in run function, want access mask variable, shows segment fault. so, question whether new created thread copy data in original class? how access thread own data? class thread { public: int mask; pthread_t thread; thread( int ); void start(); static void * entrypoint (void *); void run(); }; thread::thread( int a) { mask =a; } void thread::run() { cout<<"thread begin run" <<endl; cout << mask <<endl; // show segmentfault here } void * thread::entrypoint(void * pthis) { cout << "entry" <<endl; thread *pt = (thread *) pthis; pt->run(); } void thread::start() { pthread_create(&thread, null, entrypoint, (void *)threadid ); pthread_join(thread, null); } int main() { int inp...

django admin - selecting a single model to publish to site -

hey, i'm making popup radio player attached shoutbox django , i'm having trouble getting admin functionality want. i have 2 models: 1) stream (which represents radio stream admin can publish play on frontpage - i.e. there multiple saved streams, 1 playing on frontpage @ time, @ discretion of admin) 2) shout (a shout has been entered shoutbox, , associated stream, i.e. every stream has multiple shouts entered users of site.) i want admin able log end, create multiple streams, select 1 published @ 1 time. presumabley each stream should have attribute (i.e is_published) , should create admin action perform check of every stream, , publish correct one? correct way go or missing something the potential problem forsee is, if has connected , listening stream before admin changes it. should person hear new stream or continue hear stream listening to? other that, way you've described it, see working. make url/view returns current stream, /stream/current/ . ...

computer vision - Tips for background subtraction in the face of noise -

background subtraction important primitive in computer vision. i'm looking @ different methods have been developed, , i've begun thinking how perform background subtraction in face of random, salt , pepper noise. in system such microsoft kinect, infrared camera give off random noise pretty consistently. if trying background subtract depth view, how can avoid issue random noise while reliably subtracting background? as said, noise , other unsteady parts of background might give problems in segmentation, mean lighting changes or other moving stuff in background. but if you're working on indoor-project shouldn't big of issue, except of course noise thing. besides substracing background image segment objects in try subtract 2 (or in methods three) following frames each other. if camera steady should leave parts have changed, objects have moved. easy method detecting moving objects. but in operations might use have noise described. easiest way rid of u...

Facebook Credits/Payment API in C# or VB .net? -

i can't seem find code examples anywhere online hint @ way use facebook api or facebook sdk c#.net (or vb.net) use facebook credits features. does know of .net examples show how use facebook credits features? most of calls required use credits api graph calls work fine c# sdk. other stuff the callbacks going have own own.

php - Automated URL checking from a MySQL table -

okay, have list of urls in mysql table. want script automatically check each link in table 404, , afterward want store whether url 404'd or not, store time last checked. is possible automatically, if no 1 runs script? ie, no 1 visits page few days, no 1 visiting page, automatically ran test. if possible, how go making button this? no need use curl, file_get_contents($url); return false if request fails (any other http code other 2xx), might more useful you're trying do, example: function urlexists($url) { return (bool) @file_get_contents($url); } will return true if url returns useful content, false otherwise. edit : here faster way (it requests headers) , the first byte instead of whole page: function urlexists($url) { return (bool) @file_get_contents($url, false, null, 0, 1); } urlexists('https://stackoverflow.com/idontexist'); // false however, in combination your other question may wiser use this: function url($url) { ...

Facebook sharer,share image -

i found lot of posts, none of them me. i want share image not visible. issue is, when click share, images page available sharing. how can fix images want share visible sharing? i have read facebook open graph protocol , didn't me. here function create share button : function wp_fb_sharer($post) { $link = js_escape(get_permalink($post->id)); $button = '<a name="fb_share" type="box_count" share_url="' . $link . '" href="http://www.facebook.com/sharer.php">share</a><script src="http://static.ak.fbcdn.net/connect.php/js/fb.share" type="text/javascript"></script>'; $button = ' <div style="float: left; margin-left: 10px; margin-bottom: 4px;"> ' . $button . ' </div>'; return $button; } is there image size limit facebook? have read of answer . facebook recommending use of like plugin instead of ...

python - How to update records in SQL Alchemy in a Loop -

i trying use sqlsoup - sqlalchemy extention, update records in sql server 2008 database. using pyobdc connections. there number of issues make hard find relevant example. i reprojection geometry field in large table (2 million + records), many of standard ways of updating fields cannot used. need extract coordinates geometry field text, convert them , pass them in. fine, , individual pieces working. however want execute sql update statement on each row, while looping through records 1 one. assume places locks on recordset, or connection in use - if use code below hangs after updating first record. any advice on how create new connection, reuse existing one, or accomplish way appreciated. s = select([text("%s fid" % id_field), text("%s.stastext() wkt" % geom_field)], from_obj=[feature_table]) rs = s.execute() row in rs: new_wkt = reprojectfeature(row.wkt) update_value = "geometry :: stgeomfromtext('%s',%s)...

How do I antialias the clip boundary on Android's canvas? -

Image
i'm using android's android.graphics.canvas class to draw ring . ondraw method clips canvas make hole inner circle, , draws full outer circle on hole: clip = new path(); clip.addrect(outercircle, path.direction.cw); clip.addoval(innercircle, path.direction.ccw); canvas.save(); canvas.clippath(clip); canvas.drawoval(outercircle, lightgrey); canvas.restore(); the result ring pretty, anti-aliased outer edge , jagged, ugly inner edge: what can antialias inner edge? i don't want cheat drawing grey circle in middle because dialog transparent. (this transparency isn't subtle on on other backgrounds.) afaik, can't antialias clip regions. i'd suggest using bitmap masking instead. render the pink, white, , light gray foreground 1 bitmap, render outer/inner circle mask (the grayscale alpha channel) bitmap, , use paint.setxfermode render foreground bitmap mask alpha channel. an example can found in apidemos source c...

java - What is the best way to iterate over a large result set in JDBC/iBatis 3? -

we're trying iterate on large number of rows database , convert objects. behavior follows: result sorted sequence id, new object created when sequence id changes. object created sent external service , have wait before sending 1 (which means next set of data not used) we have invested code in ibatis 3 ibatis solution best approach (we've tried using rowbounds haven't seen how iteration under hood). we'd balance minimizing memory usage , reducing number of db trips. we're open pure jdbc approach we'd solution work on different databases. update 1 : we need make few calls db possible (1 call ideal scenario) while preventing application use memory. there other solutions out there type of problem may pure jdbc or other technology? update 2 query backend driven , have 1 instance executing @ given time. thanks , hope hear insights on this. it seems need sort of pagination . ibatis through standard limit/offset parameters in query (and...

android - Open context menu by clicking on menu options item -

i use android make application. have activity create option menu below @override public boolean oncreateoptionsmenu(menu menu) { menuinflater inflater = getmenuinflater(); inflater.inflate(r.menu.mymenu, menu); return true; } the menu loaded xml file : <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:title="item1" android:id="@+id/item1" /></menu> when click on item 1, use onoptionsitemselected on activity work after click : @override public boolean onoptionsitemselected(menuitem item) { switch(item.getitemid()) { case r.id.item1 : // here, open contextual menu return true; default : return super.onoptionsitemselected(item); } } so, when user click on item 1 open contextual menu. first, don't know if it's possible open contextual menu directly without using hold ...

qt - Child QGraphicsItem move event (ItemIsMovable) to its parent -

how can child qgraphicsitem move parent item ? i set child item's itemismovable flag , when try move child item, parent item not move, child item moves. // child items's mousemoveevent void textdiagram::mousemoveevent(qgraphicsscenemouseevent *event){ parentitem()->moveby(event->pos().x() - lastpos.x() , event->pos().y() -lastpos.y() ); qgraphicsitem::mousemoveevent(event); } void textdiagram::mousepressevent(qgraphicsscenemouseevent *event){ lastpos.setx( event->pos().x() ); lastpos.sety( event->pos().y() ); qgraphicsitem::mousepressevent(event); } this works if select more 1 item, moves item under mouse. how can solve ? i solved invoking parent's mouse events in child's mouse events .

c++ - Advice on postfix-to-infix parsers -

i've come across proprietary stack-based scripting language looks simplified version of x86 asm. i built stack-based linear parser language in c++ hope produce pseudo-c code make language lot easier read. i've encountered @ least 1 serious issue feel has linear nature of parser... example, let's have following code: push const int push const str call some_method pop const str pop const int return last return val with current implementation, generate following: retval = some_method(str, int) return retval but following major pain: return some_method(some_str, some_int) when encounter instruction/opcode, aware of -variables- pushed onto stack, it... what boils down can go postfix infix combination similar instructions (pushes + calls example), not multiple ones. i unexperienced when comes language parsers go easy on me! suggestion? what want symbolic execution . arrange have c++ representation of expressions, such as class expression{...}; c...

c++ - Generalized plugable caching pattern? -

given it's 1 of the hard things in computer science , know of way set plugable caching strategy? what i'm thinking of allow me write program minimal thought needs cached (e.i. use sort of boiler-plate, low/no cost pattern compiles away nothing anywhere might want caching) , when things further along , know need caching can add in without making invasive code changes. as idea kind of solution i'm looking for; i'm working d programing language (but halfway sane c++ fine) , template. the nearest thing comes mind memoization pure functions. maybe interesting might book pattern oriented software architecture patterns management has caching pattern in it.

jar - Android SDK - Other ways? -

if needed build android sdk other developers can integrate android apps, jarring sdk way go it? far have learnt, jarring has following considerations: if app uses layout, have create programmatically. since jar files cant carry resources. the jar needs placed in lib/assets folder , added build path (in eclipse) -- learnt here: android - invoke activity within jar the main app have create intent object , specify package , class name in jar start activity. any 1 have other ideas of going of above steps? thanks george creating jar is, in opinion, bad decision. android has specific features kind of thing you're looking for. if jar: provides sort of (structured) data used in other applications, use contentprovider ; does backround processing , makes processing's results available other applications, use service ; provides activity gets input user (or shows information something), processes , returns calling activity , create activity , application able ...

python - Why doesn't Django's per-site cache middleware work for me? -

i using django 1.3 beta 1 , set memcached. made changes settings.py per django's instructions : caches = { 'default': { 'backend': 'django.core.cache.backends.memcached.pylibmccache', 'location': '127.0.0.1:11211', } } middleware_classes = ( 'django.middleware.cache.updatecachemiddleware', 'django.middleware.common.commonmiddleware', 'django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.middleware.cache.fetchfromcachemiddleware', #'debug_toolbar.middleware.debugtoolbarmiddleware', ) cache_middleware_seconds = 100000 cache_middleware_key_prefix = 'site_cache' this test view function i'm hitting: def home(request): print 'uncached' # ...view's code... i uncached printed on devel...

php - RegEx to check 3 or more consecutive occurrences of a character -

i want check input string validate proper text. a. want users allow writer alphanumeric characters including period, comma, hyphen , round bracket () b. however, dont want users enter number 3 or more digits together. eg: 12 allowed while 185 not. c. dont want users enter strings "............." or "----------" or "aaaaaaaaaaaaaa" or "bbbbbbbb" etc. please suggest regular expression same. you can use regex: (?!.*(.)\1{2})^[a-za-z0-9.,()-]*$ it uses negative lookahead (?!.*(.)\1{2}) ensure there no group of 3 repetitions of of characters. then uses regex ^[a-za-z0-9.,()-]*$ ensure string made of alphabets, numbers, period, comma, parenthesis , hyphen. rubular link

php - have PDF form, need to port to website -

so here have: pdf form (job application) client requesting put on website form , data gets sent them when applicant on site fills form out. idea follows: dissecting pdf, taking fields , making html form, processing on server side, creating new pdf , emailing attachment client. however, tells me there better, more effective way of doing it. so? if client asks pdf sent mail in return no there no better way :p if not have specifications perhaps storing pdf applications in database can retreive them themself through webpage better idea. still notify them email new application have been received. way can organize new applications better, because lets face it.. management makes mess out of mailbox.

Is it a good practice to pass struct object as parameter to a function in c++? -

i tried example live below: typedef struct point { int x; int y; } point; void cp(point p) { cout<<p.x<<endl; cout<<p.y<<endl; } int main() { point p1; p1.x=1; p1.y=2; cp(p1); } the result thats printed out is: 1 2 which expected. question is: parameter p full copy of object p1? if so, wonder if practice? (i assumed when struct gets big in size, create lot of copy overhead). there nothing wrong passing structs parameters. passed value in c++ full copy indeed made. the struct gave in example small it's not problem if pass value. if work bigger data structures, may want pass reference. beware though, passing reference means if modify struct inside function, original struct modified. sure use const keyword in every case don't modify struct. give immediate information if functions modify information or not. your example modified work references way : typedef struct point { int x; int y; ...

css - Why style effect remains after location.hash in Firefox? -

i creating program online psych experiment on web design. (please see code below) trying is, if user clicks on input box, invokes onfocus event, page jumps place (i.e. box comes top of page), , box has effect on outline indicate has focus. implement using location.hash, anchor, , style.outline. however, in firefox, once page jumps anchored point, outline style remains there though have event onblur remove outline style. know why happens , how fix it? related functions problem jump() , noeffect() in code. this works in chrome , safari, not in firefox. (ie not working. ie not show outline style @ all. if know how fix in ie, please let me know too) preferably, want program used in major browsers. thanks in advance! ---------code----------- <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> <script type="text/javascript" > function loadings() { var bcolor = "...

css - Cut off text before read more -

i have texts of time fit in div, doesn't fit. there no way determine how many characters/words/paragraphs fit in div, can't cut off way. the div had fixed height , width, can that? or have suggestion how in div, correct way? if text isnt going fit, use css elipses make bit cleaner. perhaps place text in hidden element , measure height see if need include (more) link. see http://mattsnider.com/css/css-string-truncation-with-ellipsis/

design - C# IQueryable or AsQueryable -

i'm prototyping sort of repository , want know if it's enough have methods, operate on sequences only . for example: public void addentities<t>(iqueryable<t> sequence); now, method prototype seems fine , generic , sucks when wants like: var t = new t(); // add single entity. repository.addentities(???); what solutions case? should make interface larger , add methods addsingleentity<t>(t t) , removesingleentity<t>(t t) or should leave , use like: repository.addentities(new list { new t() }.asqueryable()); both choices have drawbacks: first 1 makes interface uglier , less compact, second looks bit weird. what , why? i create additional methods handle single entities operations, because cleaner , lot of common interfaces (list) edit: if want have 1 method group: public void add<t>(ienumerable<t> entities) { ... } public void add<t>(params t[] entities) { this.add(entities.asenumerable()); } you can...

Generate MySQL data dump in SQL from PHP -

i'm writing php script generate sql dumps database version control purposes. dumps data structure means of running appropriate show create .... query. want dump data i'm unsure best method. requirements are: i need record per row rows must sorted primary key sql must valid , exact no matter data type (integers, strings, binary data...) dumps should identical when data has not changed i can detect , run mysqldump external command adds system requirement , need parse output in order remove headers , footers dump information don't need (such server version or dump date). i'd love keep script simple can can hold in standalone file. what alternatives? i think mysqldump output parsing still easiest. think there few meta-data have exclude, , dropping should few lines of code. you @ following mysqdump options: --tab, --compact

Points, Lines, and Polygons on Spheres with C/C++ -

my application represent shapes on earth's (using sphere sufficient) surface. can points, lines, , polygons. coordinates should defined using degrees or radians (just geographic coordinates). a line segment between 2 points on surface of sphere should lie on great circle . polygons should consist of collection of such lines. furthermore, perform set - basic operations intersection, union, difference, complement on shapes mentioned. these operations need output collections of points. i tried figure out using cgal's 3d spherical geometry kernel , 2d boolean operations on nef polygons embedded on sphere . actually, had problems putting line on sphere. additionally cgal works in euclidean space, still leaves me geometric operations necessary, work great circles placed on sphere. my question is, if can assist me in realizing functionality mentioned in cgal or if can recommend library c/c++ that. thank much! i'd suggest take @ this: http://www.codeguru.co...

How to get all the network names of a VM using powershell -

am new powershell.i have names of network vm can connect to.so, please can me out. if using hyper-v can try install powershell management library hyper-v http://pshyperv.codeplex.com/ or have find wmi can use get-wmiobject win32_networkadapter

secure message in IE for ASP.Net website -

can please tell me, why no-secure message comes on site's homepage in internet explorer following message: "the web page contains content can not delivered using secure https connection" message box comes yes/no option. your webpage using https items (picture example) on page linked using http (not https). why ie warns users although of page secured not content on is. if want rid of message should serve items on page via https.

apache - Favicon for all the pages in my website -

i've learned way add favicon web page have following lines in page. <link rel="shortcut icon" type="image/x-icon" href="http://mysite.com/faviconfilename.ico"/> <link rel="icon" type="image/x-icon" href="http://mysite.com/faviconfilename.ico" /> should add code in each , every page site has?? use apache - tomcat clustering serve pages. there other easy way this? it enough place file called "favicon.ico" in root of website.

c - Is a server an infinite loop running as a background process? -

is server background process running infinite loop listening on port? example: while(1){ command = read(127.0.0.1:xxxx); if(command){ execute(command); } } when server, not referring physical server (computer). referring mysql server, or apache, etc. full disclosure - haven't had time poke through source code. actual code examples great! that's more or less server software does. usually gets more complicated because infinite loop "only" accepts connection , each connection can handle multiple "commands" (or whatever called in used protocol), basic idea this.

regex - .net webservice proxy class organization/regular expression to match c# class definition -

i'm working .net webservice has several hundred methods in it. (i've no control on webservice, can't refactor it). however i'm working client side of , i've generate client side proxy class whenever changes in ws. (and changes quite often). i generate proxy class using wsdl.exe. wsdl.exe http://url.asmx /o:proxy.cs /n:my.name.space this generated proxy class contains classes return types, input types used in ws. imagine example: i've dto assembly called my.application.dto.dll contains class called mydtoclass . assembly referred both webservice project , windows app project calls webservice through proxy class. imagine webservice has method this [webmethod] public mydtoclass getsomedtomethod(int id) { ... } now when generate proxy this, proxy contain definition mydtoclass . inside different namespace of course. then use proxy class follows: my.application.dto.mydtoclass dto; dto = wsproxy.getsomedtomethod(x); this fails saying ...

Not getting the response body for http post request in android? -

not getting response body http post request in android. mentioning userid, password in name value pairs , putting in httppost request postrequest.setentity(new urlencodedformentity(namevaluepairs)); but on executing getting response sc_ok(200), response body null . one more problem if specify header in httpget or httppost's request using setheader() function getting bad request (404) response. please me in resolving above issue. thanks & regards, ssuman185 here's method easy post page, , getting response string. first param (the hashmap) key-value list of parameters want send. there no error handling you'll have that: public static string dopost(hashmap<string,string> params, string url) { httppost httpost = new httppost(url); try { httpost.seturi(new uri(url)); } catch (urisyntaxexception e1) { // todo auto-generated catch block e1.printstacktrace(); } h...

.net 3.5 - Zipping files preserving the directory structure -

i using dotnetzip dll(http://dotnetzip.codeplex.com/) codeplex zip files in program. problem facing after zipping files preserving directory structure , when extracting zip file parent folders getting created again , able view file. annoying when source file exists in so, if zipping file g:\archive\logfiles\w3svc1\abc.log , creating 'abc.zip' file after extracting it, folders archive\logfiles\w3svc1\ getting created , able see abc.log file. here 'g:' name of shared drive. i want rid of these parent folders can straight away extract , reach zipped file , open it. have checked path property of zipped file , showing archive\logfiles\w3svc1. somehow need remove programatically not finding option easily. code using this: using (zipfile zip = new zipfile()) { if (fileextension != null) { zip.addfiles(from f in sourcedir.getfiles() f.fullname.endswith(fileextension) select f.fullname); } else { zip.addfiles(from f in sourcedir....

ide - Regions in Delphi - is it possible to define them unfold by default? -

since delphi 2005 borland/codegear introduced regions in ide. idea in casses want regions unfolded default in other folded. if there argument or options job? i'm using delphi 2007. @ntodorov, can turn off code folding pressing ctrl + shift + k + o check these links delphi tips , tricks: turn off code folding keyboarding [part 3] – code folding

windows - Win32: How to crash? -

i'm trying figure out windows error reports saved; hit send on earlier today, forgot want "view details" can examine memory minidumps. but cannot find stored (and google doesn't know). so want write dummy application crash, show wer dialog, let me click "view details" can folder dumps saved. how can crash on windows? edit: reason ask because i've tried overflowing stack, , floating point dividing zero. stack overflow makes app vanish, no wer dialog popped up. floating point division 0 results in +inf, no exception, , no crash. should start: int main(int argc, char* argv[]) { char *pointer = null; printf("crash please %s", *pointer); return 0; }

cakephp - Two PHP foreaches causing repeating of rows -

hey guys, have bit of problem , it's been frustrating me no end. i've got cakephp application i've been working on, , can't seem find way display things way i'd to. this code in controller method: function index(){ $this->order->recursive = 2; $orders = $this->order->findallbyvendor_id($this->auth->user('vendor_id')); foreach($orders $order){ $item_ids = explode(',', $order['order']['items']); foreach($item_ids $item_id){ $products = $this->product->findbyid($item_id); $order_products[] = $products['product']['product_name']; } $vendor_orders[] = $order_products; } $this->set('orders_products', $vendor_orders); $this->set('orders', $this->paginate('order', array('order.vendor_id' => $this->auth->user('vendor_id')))); } this view code: <div class...

iphone - How to Pass paramenter to javascript in webview -

i have pass argument javascript function webview, calling properly. thanks vadivelu well ! going give example. know late ( year :p ) [self.mywebview stringbyevaluatingjavascriptfromstring:[nsstring stringwithformat: @"window.scrollto(0,%i);",kpagesize*(self.currentpage-1)]]; you can notice that, have passed parameter javascript objective-c. this cause webview scroll some-where within webview. hope helps. note : please not forget accept answer if helpful you. ( noticed of questions not accepted. )

Handling missing resources -

i've found myself in situation needed handle exception i'll never get, out of curiosity, let's small poll. do validate presence of resources in programs? mean, resources installed program, icons, images , similar. generally, if missing, either install didn't job, or user randomly deleted files in app. if validate presence, do when files not there? of course, web apps, you'll have nice 404 page or broken link, rest? fail early, yes, leave handling failures compiler, or what? in python, many folks rely on simple exception handling kind of thing. might wrap application in big-old-try-block reports "serious problems" unhandleable exceptions , tries clean , exit gracefully. it's hardly worth checking in advance. if it's possible user super delicate , precious part of application , app dies undoing hours (or years) of work, should rethink use case create more robust scenario crash not destructive.

Creating xml in c# -

hi creating xml programatically.i using namespace.in places dont need namespace , passing string.empty.my element names contains colon ex gd:city.the problem if passing null in third parameter of createelement in output getting city , not gd:city.how solve problem.i need o/p gd:city @ same time dont want pass namespace. regards sanchaita chakraborty you need use namespacemanager. like: xmlnamespacemanager nsm = new xmlnamespacemanager(myxmldocument.nametable); nsm.addnamespace("gd", "http://mynamespacehere"); xmlnode nde = myxmldocument.createelement("gd", "newelement", "http://mynamespacehere"); edit : per other poster's comments, can't create element name containing colon (see w3spec here , tut on namespaces here ). if element has colon (:), means using namespace - corresponding xmlns:gd="http://mynamespacehere" in parent node of city element (or city itself). "gd" placeholder (called ...

linux - How to cut first n and last n columns? -

how can cut off first n , last n columns tab delimited file? i tried cut first n column. have no idea combine first , last n column cut -f 1-10 -d "<ctr>v <tab>" filename cut can take several ranges in -f: columns 4 , 7 onwards: cut -f -4,7- or fields 1,2,5,6 , 10 onwards: cut -f 1,2,5,6,10- etc

mysql - SQL Query to duplicate records based on If statement -

i'm trying write sql query duplicate records depending on field in table. running mysql 5. (i know duplicating records shows database structure bad, did not design database , not in position redo - it's shopp ecommerce database running on wordpress.) each product particular attribute needs link same few images, product need row per image in table - database doesn't contain image, filename. (the images of clipart customer select from) based on these records... select * `wp_shopp_spec` name='can personalised' , content='yes' i want this.. for each record matches query, copy records 5134 - 5139 wp_shopp_asset change id it's unique , set cell in column 'parent' have value of 'product' table wp_shopp_spec. mean 6 new records created each record matching above query, same value in 'parent' unique ids , every other column copied original (ie. records 5134-5139) hope that's clear enough - appreciated. it sou...

Ruby regex: replace double slashes in URL -

i want replace multiple slashes in url, apart in protocol definition ('http[s]://', 'ftp://' , etc). how do this? this code replaces without exceptions: url.gsub(/\/\/+/, '/') you need exclude match preceeded : url.gsub(/([^:])\/\//, '\1/')

Resolving Images after URL Changes - .htaccess -

i have done few changes , unable images resolved correctly. old = http://www.domain.com/dir/images/*.jpg new = http://www.domain.com/old_dir/images/*.jpg i using following rewriterule, rewriterule ^dir/images/(.*)\.jpg$ old_dir/images/$1\.jpg [r=301] doesn't work, pointers on how work images resolved correctly ? thanks i suspect rewriterule ^dir/images/(.*)\.jpg$ old_dir/images/$1\.jpg [r=301] should be rewriterule ^/dir/images/(.*)\.jpg$ /old_dir/images/$1\.jpg [r=301] the ^ signifies anchor @ beginning, , anchor followed dir excludes required leading / see apache docs details. debugging steps as far specific steps debugging try: rewriterule ^.*$ /test.html [r=301] make sure rewriting engine working. if works, can try absolute uri instead of regex one: rewriterule ^/dir/images/image1.jpg$ /old_dir/images/image1.jpg [r=301] if works, can try tweaking regular expressions make sure you're getting them right. are there indicatio...

javascript - Using the following tree navigation script, how to make the heading trigger the drop down? -

we're using following script have dropdown navigation: http://www.onlinetools.org/tools/dom-tree-menu-puredom/# however, drop down triggered when [+] or [-] clicked. happen headings trigger dropdown. like: [+] heading [+] heading 2 [+] heading 3 when click on [+] , word "heading" drop down list appear so: [-] heading -- content 1 -- content 2 -- content 3 [+] heading 2 [+] heading 3 currently, [+] triggers drop down , "heading" merely allows put normal link. linkparent:false change linkparent:true if change true have feeling allow heading linking too. if take @ line 41 sets click handler. first tag [0] arrow , second tag [1] believe title pde.addevent(parentli.getelementsbytagname('a')[0],'click',pde.showhide,false); parentli.getelementsbytagname('a')[0].onclick=function(){return false;} // safari hack if(pde.linkparent){ pde.addevent(parentli.getelementsbytagname('a')[1],'click',pd...

java - JSF : able to do mass update but unable to update a single row in a datatable -

i have simple data object: car. showing properties of car objects in jsf datatable. if display properties using inputtext tags, able modified values in managed bean. want single row editable. have placed edit button in separate column , inputtext , outputtext every property of car. edit button toggles rendering of inputtext , outputtext. plus placed update button in separate column used save updated values. on clicking update button, still old values instead of modified values. here complete code: public class car { int id; string brand; string color; public car(int id, string brand, string color) { this.id = id; this.brand = brand; this.color = color; } //getters , setters of id, brand, color } here managed bean: import java.util.arraylist; import java.util.list; import javax.faces.bean.managedbean; import javax.faces.bean.requestscoped; import javax.faces.component.uidata; @managedbean(name = "cartree") @request...

java - Need help to display the return of SOAP request from webservice -

i try make first android app ! call webservice ksoap2 details of account. have function witch return array (resultrequestsoap). in resultrequestsoap there array of object. below function : public array listall(string session){ final string soap_action = "http://www.nubio.net/soap/vps#listall"; final string method_name = "listall"; final string namespace = "http://www.nubio.net/soap/vps"; final string url = "http://www.nubio.net/soap/vps"; array myarray = null; soapobject request = new soapobject(namespace, method_name); //soapobject request.addproperty("session",session); soapserializationenvelope envelope = new soapserializationenvelope(soapenvelope.ver11); envelope.setoutputsoapobject(request); httptransportse androidhttptransport = new httptransportse(url); try { androidhttptransport.call(soap_action, envelope); resultrequestsoap = envelope....

c++ - Memory leak using shared_ptr -

both code examples compile , run without problems. using second variant results in memory leak. ideas why? in advance help. variant 1: typedef boost::shared_ptr<parametertabelle> spparametertabelle; struct partabspaltedata { partabspaltedata(const spparametertabelle& tabelle, const string& id) :tabelle(tabelle), id(id) { } const spparametertabelle& tabelle; string id; }; variant 2: struct partabspaltedata { partabspaltedata(const spparametertabelle& tabelle, const string& id) :id(id) { // causes memory leak tabelle2 = tabelle; } spparametertabelle tabelle2; string id; }; have checked, not have cyclic shared pointer references? for example: class { public: shared_ptr<a> x; }; shared_ptr<a> a1(new a()); shared_ptr<a> a2(new a()); a1->x = a2; a2->x = a1; here a1 , a2 never released, because have po...

rest - jersey restful + grizzly server + hibernate -

i can bring jersey + grizzly server up. problem occur during "sessionfactory sessionfactory = new configuration().configure().buildsessionfactory;" error says "severe: service exception: org.hibernate.hibernateexception: /hibernate.cfg.xml not found .. know how make hibernate can access hibernate.cfg.xml location. put in 'src/main/resources' directory of project. also, if you've specified "/hibernate.cfg.cml", try removing slash reads "hibernate.cfg.xml" if doesn't work (no directory, classpath wrong, etc...) can hardcode working. file f = new file("/wherever/the/file/is/hibernate.cfg.xml"); sessions = new configuration().configure(f).buildsessionfactory(); then circle later , repay technical debt.

html - PayPal return URL -

here's code paypal button: <form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post"> <input type="hidden" name="cmd" value="_xclick"> <input type="hidden" name="business" value="my@email.com"> <input type="hidden" name="lc" value="gb"> <input type="hidden" name="button_subtype" value="products"> <input type="hidden" name="no_note" value="1"> <input type="hidden" name="no_shipping" value="1"> <input type="hidden" name="rm" value="0"> <input type="hidden" name="return" value="http://www.example.com"> <input type="hidden" name="item_name" value="my item"> <input type="hi...

making valgrind able to read user input when c++ needs it -

i trying run c++ program valgrind, have points in program require user input stdin, when run valgrind, wont let user input program, there way around this? been searching around have not found answer. i haven't tried it, found in man pages: --input-fd=<number> [default: 0, stdin] specify file descriptor use reading input user. used whenever valgrind needs prompt user decision. what happens if specify different fd (say, 3) valgrind use input?

How to enable PHP support in TOMCAT 6 under CENTOS? -

i trying make tomcat6 support php in centos, don't know how, have been searching solutions, none of them works please advise thanks i have both php , java running on server, different approach. have apache running php interpreter, , tomcat running seperately. use mod_jk create vhost tomcat, , regular vhost php. this means must have java , php running under different domains or subdomains, can have them both on same server.

php - Best place to store large amounts of session data -

i'm building application needs store , re-use large amounts of data per session. so example, user selects large list of list items (say 2000 or more) have numeric value key save selection , go off page, else , come original page , need load selections page. what quickest , efficient way of storing , reusing data? in text file saved session id? in temp db table? in session data (db sessions size isn't limit) using serialized string or using gzcompress or gzencode ? although i'd recommend users keep data in database rather simple files, exception. in general, there slight overhead in storing data in database compared files - former provides lot of flexibility on access , removes lot of locking problems. unless expect page turns particularly slow and users run multiple browsers accessing same session, concurrency not big problem, i.e. using sort of database slower (also, if you're going dealing large cluster of webservers - more 200 - sharing sa...

gcc - How to deal with recursive dependencies between static libraries using the binutils linker? -

i'm porting existing system windows linux. build structured multiple static libraries. ran linking error symbol (defined in liba) not found in object libb. linker line looked like g++ test_obj.o -la -lb -o test the problem of course being time linker finds needs symbol liba, has passed by, , not rescan, errors out though symbol there taking. my initial idea of course swap link (to -lb -la) liba scanned afterwards, , symbols missing libb in liba picked up. find there recursive dependency between liba , libb! i'm assuming visual c++ linker handles in way (does rescan default?). ways of dealing i've considered: use shared objects. unfortunately undesirable perspective of requiring pic compliation (this performance sensitive code , losing %ebx hold got hurt), , shared objects aren't needed. build 1 mega ar of of objects, avoiding problem. restructure code avoid recursive dependency (which right thing do, i'm trying port minimal changes). do have othe...

javascript - When is case sensitivity important in JSON requests to ASP.NET web services (ASMX)? -

i've done following tests json requests sent asp.net 2.0 asmx web service (using ajax extensions 1.0 asp.net 2.0) , seems case sensitivity important in situations not in others. see following examples: case matches 100%: {"request":{"address":{"address1":"123 main street","address2":"suite 20","city":"new york","state":"ny","zip":"10000","addressclassification":null}}} result: http/1.1 200 ok case of contained object name address not match: {"request":{"address":{"address1":"123 main street","address2":"suite 20","city":"new york","state":"ny","zip":"10000","addressclassification":null}}} result: http/1.1 200 ok case of web service parameter request not match: {"request":{"address":{...

MySQL GUI Programs -

are there programs gui let create mysql database, create tables, define primary , foreign keys , insert data? tired of having use mysql command line client, tedious. i suggest use phpmyadmin . there mysql workbench .

datatable - Refresh Excel ListObject from a Commandline application -

i'm trying update information of listobject hosted in workbook created excel addin (example code1) commandline application. i've tried creating instance of excel , accessing @ listobjects getvstoobject returns null objects. think security problem, don't know how resolve it. (example code2). i've tried serverdocuments don't have cacheddata, , it's not possible use @ application add-in level. suggestion? thanks in advance. code1 using system; using system.data; using excel = microsoft.office.interop.excel; using office = microsoft.office.core; using microsoft.office.tools.excel; using microsoft.office.tools.excel.extensions; namespace exceladdin2{ public partial class thisaddin{ private void thisaddin_startup(object sender, system.eventargs e){ datatable thedatatable = getdatatable(); workbook workbook = globals.thisaddin.application.activeworkbook.getvstoobject(); worksheet worksheet = ((exc...

wolfram mathematica - Matrix catenation in MATLAB -

i have code in mathematica: nxbin = table[{-5 sx + (i - 0.5)*step, nbin[[i]]}, {i, 1, length[nbin]}] and did in matlab: a=zeros(length(nbin),1); nxbin=zeros(length(nbin),1); i=1:length(nbin) anew=a*step*(i-0.5) -5*sx; b=zeros(length(nbin(i)),1); nxbin(i,:)=[anew , b] end but matlab says ??? error using ==> horzcat cat arguments dimensions not consistent. error in ==> begin @ 52 nxbin(i,:)=[anew , b] can tell me why error? also, can fewer lines? you want catenate n-by-1 array nbin steps (probably x-values histogram). thus, can create "x-vector" , combine them. nxbin = [ -5*sx + ((1:length(nbin))' - 0.5) * nstep, nbin(:)] here's same step-by-step %# make vector values 1 nbin x = 1:length(nbin); %# transpose, since it's 1-by-n , want n-by-1 x = x'; %'# %# apply modification x x = -5*sx + (x-0.5)*nstep; %# catenate nbin (the colon operator guarantees it's n-by-1 nxbin = [x, nbin(:)]; edit in...

python - Why is this string always the highest possible number -

this question has answer here: how test multiple variables against value? 14 answers if month == 1 or 10: month1 = 0 if month == 2 or 3 or 11: month1 = 3 if month == 4 or 7: month1 = 6 if month == 5: month1 = 1 if month == 6: month1 = 4 if month == 8: month1 = 2 if month == 9 or 12: month1 = 5 this code always returns month1 equal 5 . i'm quite new @ programming, doing wrong? (i guess involves fact 12 highest number, == means equals right?) edit: first gave wrong reason why not working. others have pointed out, if month == 1 or 10: # ... is equivalent to if (month == 1) or 10: # ... so ... gets executed. you use if month in (1, 10): month1 = 0 or better a = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5] month1 = a[month - 1] or d = {1: 0, 2: 3, 3: 3, 4: 6, 5: 1, 6: 4, 7: 6, 8: 2, 9: 5, 10: 0, ...

get - HTTP Request from a PC to load the contents of a wap site -

when try load wap site php http request pc, host of web site recognizes i'm sending request pc , redirects me actual web site , can't load wap site. there way behave mobile browser , prevent redirection? although answer regarding programming language ok, php specific answer better. this behavior dictated user-agent string on http request. can spoof user-agent string, , replace user-agent of mobile device, or if you're using firefox, can download user-agent switcher plugin.

Is it possible to use a global variable in Java to Jsp -

possible duplicates: accessing constants in jsp (without scriptlet) reference interface constant el hi, i have public or global variable res used in protected void function in admin.java. can use variable in function login in index.jsp page within same application. possible? i have tried using admin.res in function in 1 more class semanticsearch.java. value of res retrieved not in case if need use in index.jsp. have tried printed in index.jsp using alert value not printed. please help, regards, archana here's tutorial how that

javascript - Detect if selected element is an anchor on right click -

i'm writing small firefox addon grab urls , send them site. want able right click on link (but not have highlight it) , able click send , links href value grabbed , sent. bit i'm having trouble detecting if selected element anchor , grabbing it's href. many given :) nvm, found solution at: https://developer.mozilla.org/en/xul/popupguide/extensions#determining_what_element_was_context_clicked

android Problem with checkBox with baseAdapter -

i have used baseadepter display 3 view in list . first 2 textview , last checkbox view . when going check checkbox , scroll list ,after in specific number of item ,the other check box automatic checked unaseptedlly .. i don't have idea why kind of thing occur . is der know solution of .. here code baseadepter .. private static class adeptergetunit extends baseadapter{ private layoutinflater minflater; public adeptergetunit (context context){ minflater = layoutinflater.from(context); } @override public int getcount() { positionlist = sharedpreferences.getint(unitscreen.position, 0); if(positionlist==0){currentlistlenght=arrayholder.dbspeed.size();} else if(positionlist==1){currentlistlenght=arrayholder.dbangle.size();} else if(positionlist==2){currentlistlenght=listtemperature.length;} else if(positionlist==3){currentlistlenght=arrayholder.dblenght.size();} else if(positionlist==4){currentlistlenght=arrayholder.dbweightmass.size...