Posts

Showing posts from August, 2011

how to detect mic position on iPhone? -

iphone 4 has mic on bottom-left, iphone 3gs , earlier had mic on bottom-right. how can detect mic on iphone? function that? i not use method said in comment post. minute new ipad or ipod touch released front facing camera, application off. why not use method in post: determine device (iphone, ipod touch) iphone sdk the code (if scroll bit down) shows how detect version of ipod/iphone/etc running on.

Fill a form with XML (Java) -

i have form , xml, , fill form xml datas. the xml file have structure that: <patient > <general> <name>peter</name> <dataofbirth>6/nov/2010</ dataofbirth > <sex>2</sex> </general> <medicaldata> <weight>100</ weight > <height>170</ height > </ medicaldata > </ patient > and when can’t access @ data of second tag <medicaldata> . i'm programing in java , use jdom create xml file. can me? thank you. 1.use xstream 2.create class xml data structure 3.obtain collection of objects of class xml 4. use them simply. here quick start

c++ - would you propose this method for copying strings? -

to achieve higher performance, propose using method below when copying strings specially when there lot of characters in string, lot more 12? unsigned char one[12]={1,2,3,4,5,6,7,8,9,10,11,12}; unsigned char two[12]; unsigned int (& three)[3]=reinterpret_cast<unsigned int (&)[3]>(one); unsigned int (& four)[3]=reinterpret_cast<unsigned int (&)[3]>(two); (unsigned int i=0;i<3;i++) four[i]=three[i]; no, (almost) never. use std::strcpy (although not in case, since “strings” aren’t 0 terminated), or std::copy , or std::string copy constructor. these methods optimized job you. if code (or similar) happens faster naive character character copying, rest assured strcpy use underneath. in fact, is happens (depending on architecture). don’t try outsmart modern compilers , frameworks, unless you’re domain expert (and not then).

php - Build SQL Select a better way ? (Oracle) -

i have following code part in 1 of classes: $l = new location(); $result = $l->getlocidsbycity($city); // returns csv $ids = explode(',', $result); $where = 'loc_id = ' . $ids[0]; unset($ids[0]); foreach ($ids $id) { $where .= ' or loc_id = ' . $id; } $select->where($where); is there more "elegant" way build select stmt? need records 1 of provided ids.. assuming csv injection safe (contains trusted values , no user-provided input): $l = new location(); $result = $l->getlocidsbycity($city); // returns csv $where = "loc_id in ($result)"; $select->where($where); if it's not, should explode it, mysql_real_escape_string each value , implode back.

c - How to programmatically stop reading from stdin? -

fgetc() , other input functions can return when there's no data on file descriptor. can simulated console applications reading stdin typing ctrl-d on keyboard (at least on unix). how programmatically? example, how return fgetc() in reader thread in following code (nb: ignore possible race condition)? #include <pthread.h> #include <stdio.h> void* reader() { char read_char; while((read_char = fgetc(stdin)) != eof) { ; } pthread_exit(null); } int main(void) { pthread_t thread; pthread_create(&thread, null, reader, null); // fgetc in reader thread return pthread_exit(null); } thanks! it seems want threads stop blocking on fgetc(stdin) when event occurs handle event instead. if that's case select() on both stdin , other message pipe thread can handle input both: fd_set descriptor_set fd_zero(&descriptor_set); fd_set(stdin_fileno, &descriptor_set); fd_set(pipefd, &descriptor_set); if (s

spring - hibernate @onetomany relationship updates instead of insert during save -

please me figure out. i've tried many combinations nothing seems work. i'm trying implement hibernate mapping using annotations during saving of parent object , children noticed update statement being called instead of insert statement. i have 2 classes have one-to-many relationship each other. these class' mappings: receipt has one-to-many collections @entity public class receipt implements serializable { @id @generatedvalue(strategy=generationtype.auto) private long id; @onetomany @joincolumn(name="receiptid") private list<collection> collections; //setters, getters } @entity public class collection implements serializable{ @id @generatedvalue(strategy=generationtype.auto) private long id; @manytoone @joincolumn(name="receiptid", insertable=false, updatable=false) private receipt receipt; //setters getters } the problem during saving receipt like: receipt r = new receipt(

Rebranding Wordpress Android app for the self hosted blog -

i downloaded source of wordpress app. on process of rebranding wordpress app (icons & lebels) self hosted site. wondering, if there process / configuration option remove wordpress links & wordpress blogging options app. doesn't make sense user download app market place & go wordpress site it. this generic android question: i want users able use both default wordpress app & self hosted app. however, that, think need change package name in android manifest , refactor old package names of java class. loose ability sync & update of latest build of wordpress app. is there way can install same code same package (as different application) without conflicting wordpress app ? can point me direction can find more details on application namespace / package name conflicts? there few things must rebrand: you need edit androidmanifest.xml , change references wordpress. change icons (/res/drawable) show worpress logo. change strings (/res/values &

Asp.net MVC Architecture -

i'm coming end of first mvc project, , i'm not overly happy how constructed model objects , i'm looking ideas on how improve them. i use repositories each db table get, save, delete etc methods. repositories use linq2sql db access. i mapping linq2sql objects mvc model objects, in main, these 1 1 mappings. my problem is, don't think mvc model objects granular enough, , passing more data , forth needed. for example, have user table. admin can edit users details can user themselves, reckon should have "adminusermodel" , "usermodel" objects, "adminusermodel" has greater set of values (isenabled example). so bigger question really, kind of architectures people using out there in wild, in order map many similar, related model objects down through layers db? any sample architecture solutions can suggest beyond nerddinner? thanks in advance! in case of user model, should use inheritence in stead of 2 seperated models. in

database - What are advantages of SQL Server 2008 transparent encryption TDE over encrypting db backup? -

what advantages of sql server2008+ tde ( transparent data encryption) on encrypting database backup file (with password)? update: sorry - removed oracle question (sql server tde whole database , encrypted data stored in database). encrypting not difficult organize using c# without 3d-party tools, though there plenty of 3d party tools. i've never used either feature, cursory review of 2008 books online documentation makes clear password option backup database command (i'm guessing that's meant?) doesn't encrypt anything: the protection provided password weak ... [it] not prevent reading of backup data other means or replacement of password and apparently shouldn't use @ anyway: this feature removed in next version of microsoft sql server so whatever security requirements, password unlikely useful. whether or not tde useful depends on risk you're trying mitigate, e.g. encrypts data on disk not during transmission on ne

vb.net - ASP.Net Auto-populate field based on other fields -

i've moved web development , need know how can implement below requirement using asp.net , vb.net. i have 3 fields in form filled users. based on these 3 values, need auto-populate 4th field. have planned implement in following way write separate class file function calculate possible values 4th fields based on 1st 3 inputs. function can return between 1-10 values. i've decided use drop-down 4th field, , allow users select appropriate value. call above function in onchange function of 3rd field , take , use return values populate 4th field. i'm planning return values in array field.( does need post back? ) please let me know how if there better way implement this. thanks. you may want consider doing javascript. read , control fields pretty pure javascript, or using nice library jquery (my favorite). if did way, no post-back required , 4th field update immediately. (nice users) you can asp.net part. "onchange" in asp.net still requires j

c - How to add GtkExpander to GtkScrolledWindow? -

i have code this: gtkwidget *scrollwin; void appenddatatowindow(gtkwidget *widget, gpointer data) { gtkwidget *expander; expander = gtk_expander_new("get somepage.html 200 ok 100k"); gtk_scrolled_window_add_with_viewport(gtk_scrolled_window(scrollwin), expander); } int main() { // initialize window // add vbox window scrollwin = gtk_scrolled_window_new(null, null); gtk_box_pack_start(gtk_box(vbox), scrollwin, false, true, 5); // add button vbox // when button clicked, appenddatatowindow called gtk_widget_show_all(window); gtk_main(); return 0; } what want when button clicked, new gtkexpander added scrolled window, doesn't work.. suggestions helpful. maybe you're missing gtk_widget_show() calls

nhibernate - Fluent Mapping : using join-table and cascades -

having little trouble mapping following table setup currently: shop [1] [1] / \ [n] [n] category-[m]---[n]-article the behaviour should following : 1 - when deleting shop, articles , categories should deleted 2 - when deleting category, related articles should unassigned not deleted 3 - when deleting article, related categories should unassigned not deleted here's current mapping: public class shopmap: classmap<shop> { public shopmap() { this.table("shop"); id(x => x.id).column("id").generatedby.native(); map(x => x.name).column("name"); hasmany(x => x.categories).cascade.alldeleteorphan; hasmany(x => x.articles).cascade.alldeleteorphan; } } public class categorymap: classmap<category> { public categorymap() { this.table("category"); id(x =>

wix3.5 - Wix - How to automate call to Heat on DLL file to receive regasm information -

in order simulate "regasm file.dll /codebase" execution during install, run heat.exe on file.dll want add registry. add generated content our installer.wxs file, , works. we automate process, don't have manually run heat.exe each time .dll file changes. instead, call executed each time build wix project. how can it? code example appreciated. thanks, maxim are sure need this? have bunch of comvisible(true) assemblies in our installer , did heat once , never had again. using installshield has .net com interop setting similar steps @ build time , 1 of our migration requirements make sure we'd ok doing 1 time when switched wix.

Making jQuery Code More Correct/ Efficient -

hey! i've started feeling comfortable using jquery, i'm trying improve write code. there me make code more efficient? $("a.more_info").toggle(function(){       var itemid = $(this).parent().parent().parent().parent().attr('id');       var itemid_hash = "#" + itemid + " .details_exp";       var itemid_tog_more = "#" + itemid + " a.more_info";       $(itemid_tog_more).addclass("less_info").removeclass("more_info");       $(itemid_hash).fadein(); }, function () {       var itemid = $(this).parent().parent().parent().parent().attr('id');       var itemid_hash = "#" + itemid + " .details_exp";       var itemid_tog_less = "#" + itemid + " a.less_info";       $(itemid_tog_less).addclass("more_info").removeclass("less_info");       $(itemid_hash).fadeout(); }); first, there way go 4 levels in dom without stacking .parent() 4 times? se

Javascript define variable notation question -

saw js notation today i've never seen before, bear me if common knows. var cookiepath = cookiepath || ''; now, saying, if variable named cookiepath exists, set cookiepath or if doesn't, set ''? the cookiepath variable being declared, initialized. the var statement doesn't make harm if identifier declared in current lexical scope. if cookiepath wasn't declared yet, var statement, before run-time, initialize variable undefined . after that, in run-time, assignment made, if it's value falsy (other null , undefined , empty string, 0 , nan , or false ) it's set empty string. keep in mind have access cookiepath variable in local scope . consider following example: var cookiepath = 'outer'; (function () { var cookiepath = cookiepath || ""; alert(cookiepath); // alerts empty string, not "outer" })(); in above example, have global cookiepath variable, on global scope, when function

visual studio 2010 - Blog and ref recommendations for vs2010 Extensibility -

i know potentially wide open topic there blogs, tutorials, guides or references visual studio extensibility related material. i've swam through msdn , seen couple potentially guides provided know i'm doing materials but, far starting off without getting lost there out there? i've found carlos quintero's blog 1 of best places huge variety of useful information on vs extendability: http://msmvps.com/blogs/carlosq/ also msdn page on vs extensibility starting point: http://msdn.microsoft.com/en-gb/vstudio/vextend.aspx

Problem understanding java code? -

i don't understand code can explain me grid int[][] distbest initialized double distbest int turn = 60; if (g > 1) this.grid = turn(distbest * turn).grid; else this.grid = turn(-distbest * turn).grid; this section: turn(distbest * turn) means there's function turn returns object contains grid takes double parameter. what's not shown in code return type. hence, can say, function declared like grid turn(double d); where grid (ficticious) has public attribute of int[][] grid (that's why turn(distbest * turn).grid possible). i'm basing sample code listed above. other turn parameter.

Hiding cursor in Text component in Eclipse RCP application -

in eclipse rcp application there few buttons & few input boxes & below text component. problem press 1 of buttons cursor starts blinking in below test component. can please let me know how solve this. i tried: setting focus false text. swt.read_only text . code: cursor cursor = new cursor(parent.getdisplay(), swt.cursor_no); protocolfilterdescription.setcursor(cursor); nothing seems rid of unnecessary cursor. protocolfilterdescription = new text(parent, swt.none | swt.read_only ); formdata protocolfilterdescriptionldata = new formdata(); protocolfilterdescriptionldata.left = new formattachment(0, 1000, 650); protocolfilterdescriptionldata.top = new formattachment(0, 1000, 290); protocolfilterdescriptionldata.width = 450; protocolfilterdescriptionldata.height = 12; protocolfilterdescription.setlayoutdata(protocolfilterdescriptionldata); protocolfilterdescription.setforeground(new color(parent.getdisplay(), 204, 153, 0)); protocolfilterdescription.setbackgro

java - spring mvc annotation @Inject does not work -

i have following in app-servlet.xml <mvc:annotation-driven /> <context:component-scan base-package="com.merc.myproject.web.controllers"/> <context:component-scan base-package="com.merc.myproject.web.forms"/> what ever have in controller package gets injected same thing in forms package null. my form looks this public class selectdatesform { @inject iuserservice userservice; ..... } my controllers looks this @controller public class selectdates { @inject iuserservice userservice; ..... } somebody please help i guess selectdatesform instantiated manually new rather obtained spring context. in case not spring bean , therefore not subject dependency injection. usually don't need inject dependencies manually created objects. if need so, have several options: declare selectdatesform prototype-scoped bean , obtain fresh instance of spring context instead of creating new : @component @scope(&q

sql - How to list cached queries in MySQL? (Qcache_queries_in_cache) -

show status 'qcache_queries_in_cache' returns: +-------------------------+----------+ | variable_name | value | +-------------------------+----------+ | qcache_queries_in_cache | 327 | +-------------------------+----------+ how print these 327 queries? in attempt optimize mysql caching want trying switching "on demand" caching. before want definitive sense of queries being cached or discarded. tried mysql docs, google, , stackoverflow search no luck. afaik sql queries not stored qcache hash. there no way find queries cached exept execute 1 of query , see changes of value column.

sqlalchemy - Pylons + SQLA: One to One Relationship -

newbie question. pylons 1 + sqla using declarative style. new python. i have "master" class called entity, "child" classes must belong them valid. link master class on child object level. issue can't seem figure out how 1 creates child object , create master object create link between objects. make use of relations linking. thus create ono on 1 link below: entity 1 - client 1 entity 2 - client 2 entity 3 - producer 1 entity 4 - producer 2 etc. the code might explain better. class entity(base): __tablename__ = "entities" # primary key entity_id = column(integer, primary_key=true) # data fields name = column(unicode(255), nullable=false) def __init__(self, name, description): self.name = name def __unicode__(self): return self.name __str__ = __unicode__ class client(base): __tablename__ = "clients" client_id = column(integer, primary_key=true) # data fields name = col

AutoMagic select box not populating in CakePHP -

i've got following relationship set-up between 2 models story belongsto storytype storytype hasmany story i've set-up form select storytype each story using following code: echo $this->form->input('story.story_type_id', array('tabindex' => 2)); with code in controller populate list $this->set('story_types', $this->story->storytype->find('list', array ('order' => 'title'))); but it's not populating select box anything. know find() option working because doing debug within controller produces this: array ( [1] => first person [3] => third person ) the weird thing it's same code, querying other models, populate select lists things users , genres, it's story types isn't working. any ideas? cheers. you don't mention version of cakephp you're using, try setting storytypes rather story_types : $this->set( 'storytypes', $this->

android - How can I get the URL of an HTTPResponse -

how can url of httpresponse? tried: response.getheaders("locations") but obtained: 11-15 21:14:03.355: info/system.out(880): [lorg.apache.http.header;@43ea9568 you maybe thinking of redirecting client new url in case want set location not locations requests have urls, responses data packets sent client.

visual studio - How to remove "encrypt contents to secure data" -

my website had problems loading image, css file , javascript file downloaded package "superfish". i found problem "encrypt contents secure data" on each of files. ok, right-click -> properties -> advanced , unchecked "encrypt contents secure data" setting. however, when re-publish using visual studio 2010, published files have setting flagged again. source files not have flag set, published files. files deleted prior commencing publish. i have re-created each file pasting contents in new file, still when copied across flag reset. i have tried publishing folder, alas new file still created encrypted contents setting. it seems though visual studio still thinks setting should flagged, or copying cached version of file somewhere hasn't had setting removed. how stop setting being re-flagged after each publish? i had same issue css file. file somehow encrypted inside project folder, when deployed, carrying on flag. fixing i

javascript - My PHP code is just a comment in my html -

sorry guys pretty simple, i've been way late now. have basic html page javascript on it, , when try put php in body reads comment. <html> <head> <link rel="stylesheet" href="style.css" type="text/css" media="screen"> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> <script type="text/javascript" src="jquery.tablesorter.min.js"></script> <script type="text/javascript" src="jquery.tablesorter.pager.js"></script> <script type="text/javascript"> $(function() { $("table") .tablesorter({widthfixed: true, widgets: ['zebra']}) .tablesorterpager({container: $("#pager")}); }); </script> </head> <body> <div id="main"> <h1>demo</h1> php in here

visual studio - When removing file from version control, how can it also be deleted from my local working directory? -

when delete file tfs version control , "check-in" change, file still exists in local working directory. is there way can tfs or visual studio clean-up after without having manually deleting files myself or changing workspace different directory? cheers. if delete file in tfs (2010), deletes straight away local drive (tfs shows delete pending change), if undo pending change in tfs file reappears. are deleting file through solution explorer or team explorer?

java - JUnit: Tool to compare result reports -

i'd compare 2 or more junit test results reports. have 3 test runs of same testsuite , want e.g. html table shows 1 test per row, column each test run informing status of test, evt. first line of failure reason. i not doubt there's such tool already, haven't found googling. i've created such tool. http://ondra.zizka.cz/stranky/programovani/java/apps/junitdiff-junit-test-results-report-comparison.texy case closed.

ipad - UIInterface Orientation Issue -

i have following code allows me rotate specific view landscape, once goes landscape not rotate portrait? appreciated. @implementation submenusviewcontroller @synthesize submenusview; @synthesize mainmenudata; // designated initializer. override if create controller programmatically , want perform customization not appropriate viewdidload. - (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil { if (self = [super initwithnibname:nibnameornil bundle:nibbundleornil]) { // custom initialization submenusview=[[submenusview alloc] initwithframe:[uisettings rectoffullscreen:uiinterfaceorientationportrait]]; } return self; } //override allow orientations other default portrait orientation. - (bool)shouldautorotatetointerfaceorientation:(uiinterfaceorientation)interfaceorientation { // return yes supported orientations return yes;//(interfaceorientation == uiinterfaceorientationportrait); } thanks help! try shouldautorotat

php - What is the best way to handle "Warning: mysql_connect(): Too many connections" with Kohana 3? -

i've got web application used company logging employees' work. a lot of people logged in @ once. the application runs on shared host. i receive... warning: mysql_connect() [function.mysql-connect]: many connections which lets further errors cascade... errors mysql_select_db() , mysql_error() , mysql_errnon() , uncaught database_eexception . when run main request, wrap in try , capture exception , display not found page. because controllers throw exceptions if resource not found (though route may valid) e.g. http://example.com/products/30 valid route, product #30 doesn't exist. what best way handle too many connections ? ideally i'd capture exception separately, display nice page informs employee try again in 5 minutes. the code runs main request in application/bootstrap.php looks this... $request = request::instance(); try { $request->execute(); } catch (exception $e) { if (kohana::$environment === kohana::development) throw $

Setting up devise / mongomapper on Rails 2.3.8 -

i trying basic authentication working using devise , mongomapper. following instructions here: http://johnwyles.com/2010/03/15/sessions-in-mongodb-using-mongomapper-and-devise/ (except deferring routes.rb changes until after generators run address errors) i got far getting following paths work: /users/sign_up :: /users/sign_in :: /users/password/new :: /users/confirmation/new however, trying hit "/" gives me error nameerror in usercontroller#sign_in uninitialized constant usercontroller rails_root: /users/bentrevino/documents/dev/devisetest application trace | framework trace | full trace /library/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:443:in `load_missing_constant' /library/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:80:in `const_missing' /library/ruby/gems/1.8/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:92:in `const_missing' /library/ruby/gems/1.8/gems/activesupport-2.

javascript - Get modified column ordering for Extjs GridPanel -

as part of gridpanel functionality after rendering gridpanel can modify columns ordering click drag. example present column ordering first name | last name. can click drag first name , put after last name i.e last name | first name. now requirement want save modified order of column. i.e want save format change have made. extjs functionality provide me modified ordering of column. by tejas, visit mobedio ,the public opinion platform political domain. take @ gridpanel's stateevent , stateid , , stateful config options in api documentation . concerning stateful : a stateful component attempts save state when 1 of events listed in stateevents configuration fires. stateevents gridpanel defaults stateevents: ['columnmove', 'columnresize', 'sortchange', 'groupchange'] , use case handled automatically 'columnmove'. keep in mind you'll have set few config options work, including state provider (most of deta

open source - Opensource platform for prediction market software, Hubdub.com clone etc -

i used frequent player on hubdub.com, 'predict' (or bet on) news. hubdub sadly closed in april, i've been considering on smaller scale different domain. my question - there working prediction software clone tools out there can configure, setup many users, many topics , scales well? pligg digg.com, i'm after prediction market software. i've looked @ zocalo, it's bit academic. bookmaker has many bugs open , hasn't been developed in years, , prediction market , betting system still in infancy , don't have working websites based on software example. any suggestions welcomed, if have code whole thing myself fine, i'd hate reinventing wheel... there module drupal , development seems have stalled. anyway, have been looking at, there no viable off-the-shelf open source prediction market products.

c# - How to call invoke when use Func<string, bool> -

in function test(func<string,bool> f) , how call f.invoke()? received error delegate 'func' not take '0' arguments the delegate func<string, bool> delegate takes string argument , returns bool. invoke it, need supply string. e.g., either should work f("foo"); f.invoke("foo");

c++ - How to unit test function writing to stdout / std::cout -

these days, studying unit test. unit test use return value or reference value expected value in test case. if has not return value , reference value in function. expected value? exsample- void unit_test() { cout << "hello" << endl; } sure, unit_test function simple. so, function not seem need unit test. but, sample. think unit_test function has side-effect. thank you, , please understand fool english. if writing function know should tested, should design testable in framework. here, if testing done @ process level can verify process output, writing std::cout fine. otherwise, may want make output stream parameter function, in: void unit_test(std::ostream& os = std::cout) { os << "hello" << endl; } then can test in: std::ostringstream oss; unit_test(oss); assert(oss && oss.str() == "hello"); as illustrates, making well-tested software requires bit of give , take... testing require

c# - LINQ - accessing an Int column on Child table and handle the situation when there are no child rows -

here cut down version of linq query; var list = inv in db.inventories inv.inventorycode.startswith("005") select new { inv.inventorycode, inv.inventorymedias.where(im => im.mediatype == 0).firstordefault().synopsis, inv.inventorymedias.where(im => im.mediatype == 0).firstordefault().inventoryid }; ...because inventory record not have have rows in inventorymedia, have added .firstordefault(), returns null , linq smart enough not throw onstioo error, error. the cast value type 'int32' failed because materialized value null. either result type's generic parameter or query must use nullable type now understand change anonymous type class , define integer nullable type, dont want that. have tried using if null command "?? 0", not suppo

networking - C# port forwarding -

i'm developing simple p2p program meant work on internet, works fine on lan, when router , internet connection involved nothing gets machine. aware network question more c# question, can't have users of program set port forwarding every time want use software. have read other posts regarding this, seem old, wondering if vs2010 has way tackle this. note: code networking complete, , uses tcplsteners , clients, can't switch other method... thanks, pm is there upnp library .net (c# or vb.net)? looks promising...

mysql - select where member only belongs to one customer -

i having trouble figuring out query. have 3 tables messages --------------- message_id phone_num body received_time subscribers --------------- phone_num keyword_id keywords --------------- keyword_id client_id subscribers can belong many keywords of different clients. want find recent messages of subscribers belong 1 particular client no others, 1 client total. for example looking recent messages subscribers belong client 1, data: message_id phone_num body received_time 1 111 hi 123456 2 222 test 123489 3 333 msg 213445 phone_num keyword_id 111 1 111 2 222 3 333 4 333 5 keyword_id client_id 1 1 2 1 3 1 4 1 5 4 i want get: message_id phone_num body received_time 2 222 test 123489 1 111 hi 12345

spring - Question regarding value returned from WebAuthenticationDetails.getRemoteAddress() -

i writing custom accessdecisionvoter allow access resources if remote address of request found in list of allow ip addresses. however, value of remote address returned webauthenticationdetails.getremoteaddress() in format appears ipv6. when running app locally, returned above method: 0:0:0:0:0:0:0:1%0 i'm storing allowed address in comma-delimited list in properties file. list parsed , each allowed address compared remote address, since have no idea how translate ipv4 address ipv6 address comparison fail. so value returned webauthenticationdetails.getremoteaddress() or seeing because i'm running locally? is there way convert string ipv4 string? is there way have method in question return ipv4 string instead? thanks! you cannot convert ipv6 address ipv4 address. represent 2 different protocols. address of getremoteaddress() in format depending on protocol used create request webapp. guess see ipv6 address when using app locally. 0:0:0:0:0:0:0:1 add

.net - Indicating Selection in Flowdocument -

this 1 tricky, have number of table cells in flowdocument, need able indicate different items colored left border. i've solved putting 4 pixel transparent border on tablecell name, , using findname find element , switching borderbrush colored border. <tablecell borderbrush="transparent" borderthickness="4 0 0 0" padding="0 0 4 0" name="cell_1"/> the problem is slow large documents, think changing borderbrush on tablecell causing whole layout recalculate itself anyone have ideas around this, guess either have prevent layout recalculating, option try find rectangle/coordinates of cell , overlay marker have been able find way that. i know flowdocument not suited control kind of stuff layout reasons it's 1 have use. help/ideas appreciated i recommend using adorners . however, since tablecell doesn't inherit uicontainer, can't adorn it. instead, can set content of each of tablecell's blockcollecti

regex - Question On Text Parsing In Perl -

i want parse line this, s1,f2 title including several white spaces (abbr) single,here<->there,reply and want output below, 1 2 title including several white spaces abbr single here22there # identify <-> , translate 22; reply i wondering how parse line above? method 1. plan split whole line 4 segments parse individual sub segments. segment1. s1,f2 segment2. title including several white spaces segment3. abbr segment4. single,here<->there,reply method 2. write complex regular expression statement parse it. which method more make sense practice? appreciated on comments or suggestions. assuming input in format specified use regex like: ^s(\d+),f(\d+)\s+(.*?)\((.*?)\)\s+(.*?),(.*?),(.*)$ codepad link

Text scroller using javascript -

i tried implementing text scroller , did not appear. what's problem? i based here , followed steps : http://javascript.internet.com/text-effects/news-scroller.html do guys have idea of text scroller aside this? works movie credits. :) html <html> <body> <marquee behavior="scroll" direction="down" scrollamount="2" height="100" width="350"> hello! </marquee> </body> </html> if desire jquery plugin : jquery scroller v1.0 jquery marquee and if using other jslib there independent script of vertical scrolling: vertical scrolling text

unicode - setting a UTF-8 in java and csv file -

i using code add persian words csv file via opencsv : string[] entries="\u0645 \u062e\u062f\u0627".split("#"); try{ csvwriter writer=new csvwriter(new outputstreamwriter(new fileoutputstream("c:\\test.csv"), "utf-8")); writer.writenext(entries); writer.close(); } catch(ioexception ioe){ ioe.printstacktrace(); } when open resulting csv file, in excel, contains "ứỶờịỆ" . other programs such notepad.exe don't have problem, of users using ms excel. replacing opencsv supercsv not solve problem. when typed persian characters csv file manually, don't have problems. unfortunately, csv ad hoc format no metadata , no real standard mandate flexible encoding. long use csv, can't reliably use characters outside of ascii. your alternatives: write xml (which have encoding metadata if right) , have users import xml excel. use apache poi create actual excel documents.

c++ - libavcodec, how to transcode video with different frame rates? -

i'm grabbing video frames camera via v4l, , need transcode them in mpeg4 format successively stream them via rtp. everything "works" there's don't while re-encoding: input stream produces 15fps, while output @ 25fps, , every input frame converted in 1 single video object sequence (i verified simple check on output bitstream). guess receiver correctly parsing mpeg4 bitstream rtp packetization somehow wrong. how supposed split encoded bitstream in 1 or more avpacket ? maybe i'm missing obvious , need b/p frame markers, think i'm not using encode api correctly. here excerpt of code, based on available ffmpeg samples: // input frame avframe *picture; // input frame color-space converted avframe *planar; // input format context, video4linux2 avformatcontext *ifmtctx; // output codec context, mpeg4 avcodeccontext *octx; // [ init ] // ... octx->time_base.num = 1; octx->time_base.den = 25; octx->gop_size = 10; octx->max_b_frames = 1; octx-&g

regex - JAVA email message - clip quoted lines -

is there java library clip quoted text email message? if it's html message, used html parser far , removed blockquotes dom tree have more trouble plain text format. i tried regex: emailbody = emailbody.replaceall("\n>[^\n]*?\n", "\n"); but i'm far mastering it, though there has solution since it's problem concerning more people guess. code above replaces lines new lines (after \n) , beginning >, not containing other new lines long there other content , ending \n. think replacement should done starting end of message, , on. it's bit more complicated line of code. so welcome! cheers, balázs do right consider each line starts > char quoted line ? here's quick solution: string[] lines = emailbody.split("\n"); stringbuilder clippedemailbuilder = new stringbuilder(); (string line:lines) if (!line.startswith(">")) clippedemailbuilder.append(line); emailbody = clippedemailbuilder.to

ruby on rails - Specific order (sql) -

i have got model pupil , has got field score . need make list strange rule: order score (desc) (!) scores more 100 should ordered zero: pupil.all( :order => 'score desc' ...?) 100 86 34 21 6 3 1 0 143 125 354 0 456 0 0 i can order using ruby, need sql aslo can create additional field in db storing data new_score = score > 100 ? 0 : score think can make sql without it you can order 'score > 100' (order booleans), order score. score > 100 pre-ordered boolean, , sub-order order other scores after >100 ones. i hope clear enough , looking :)

java - Generic Method Covariance - valid restriction or compiler oversight? -

does know definitive answer why following isn't allowed java compiler? class baseclass { public <t extends number> t getnumber(){ return null; } } class subclass extends baseclass{ @override public <t extends integer> t getnumber(){ return null; } } this causes compiler complain with: "the method getnumber() of type subclass must override superclass method" now, when put colleagues have tried explain cause confusion compiler. however, pointed out following, conceptually similar, compilable. class baseclass<t extends number> { public t getnumber(){ return null; } } class subclass<t extends integer> extends baseclass<t>{ @override public t getnumber(){ return null; } } this can abused if subclass calls super implementation, compiler provides warning effect. conclusion compiler oversight on part of folks @ sun (

sorting - c bead sort would like help -

i have large list of positive integers in array , use bead sort have found in not documented. have code bead sort? this page has implementations in several languages, including c: http://rosettacode.org/wiki/sorting_algorithms/bead_sort

Finalizers with Dispose() in C# -

see code sample msdn: ( http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.100).aspx ) // design pattern base class. public class base: idisposable { private bool disposed = false; //implement idisposable. public void dispose() { dispose(true); gc.suppressfinalize(this); } protected virtual void dispose(bool disposing) { if (!disposed) { if (disposing) { // free other state (managed objects). } // free own state (unmanaged objects). // set large fields null. disposed = true; } } // use c# destructor syntax finalization code. ~base() { // call dispose(false). dispose (false); } } in dispose() implementation calls gc.supressfinalize();, provide destructor finalise object. what point of providing implementation destructor when gc.suppressfinalize() called? just little bit confused intentions are? there 2 scenarios: your c

python print and whitespace -

i trying print result example: for record in result: print varone,vartwo,varthree i trying concatenate variables sql query, getting whitespace. how can strip whitespace 'print'? should feed result variable 'strip(newvar)' print 'newvar'? this: print "%s%s%s" % (varone,vartwo,varthree) will replace first %s in quotes value in varone , second %s contents of vartwo , etc. edit : of python 2.6 should prefer method: print "{0}{1}{2}".format(varone,vartwo,varthree) (thanks space_c0wb0y)

Incrementing the for loop (loop variable) in scala by power of 5 -

i had asked question on javaranch , couldn't response there. posting here well: i have particular requirement increment in loop variable done multiplying 5 after each iteration. in java implement way: for(int i=1;i<100;i=i*5){} in scala trying following code- var j=1 for(i<-1.to(100).by(scala.math.pow(5,j).toint)) { println(i+" "+j) j=j+1 } but printing following output: 1 1 6 2 11 3 16 4 21 5 26 6 31 7 36 8 .... .... its incrementing 5 always. how got multiplying increment 5 instead of adding it. let's first explain problem. code: var j=1 for(i<-1.to(100).by(scala.math.pow(5,j).toint)) { println(i+" "+j) j=j+1 } is equivalent this: var j = 1 val range: range = predef.intwrapper(1).to(100) val increment: int = scala.math.pow(5, j).toint val byrange: range = range.by(increment) byrange.foreach { println(i+" "+j) j=j+1 } so, time mutate j , increment , byrange have been computed. , range immuta

python: how to get a subset of dict -

i have dict has many elements, want write function can return elements in given index range(treat dict array): get_range(dict, begin, end): return {a new dict indexes between begin , end} how can done? edit: not asking using key filter... eg) {"a":"b", "c":"d", "e":"f"} get_range(dict, 0, 1) returns {"a":"b", "c":"d"} (the first 2 elements) i don't care sorting... implementing server side paging... edit: dictionary not ordered . impossible make get_range return same slice whenever have modified dictionary. if need deterministic result, replace dict with collections.ordereddict . anyway, slice using itertools.islice : import itertools def get_range(dictionary, begin, end): return dict(itertools.islice(dictionary.iteritems(), begin, end+1)) the previous answer filters key kept below: with @ douglas ' algorithm, simplify using generator e

agile - How granular should tasks within a story be? -

we've been implementing scrum , 1 of things wonder granularity of tasks within stories. a few people inside our company state ideally tasks should finely grained, is, every little part contributes delivering story should represent task. argument enables tracking on how performing in current sprint. that leads high number of tasks detailing many technical aspects , small actions need done such create dao component x persist in database. i've been reading ken schwaber , mike beedle's book, agile software development scrum, , i've taken understanding tasks should have kind of granularity; in 1 of chapters, state tasks should take between 4 16 hours complete. what i've noticed though, such small tasks tend overspecify things , when our solution differs we've established in our planning meetings need create many new tasks or replace old ones. team members refrain having track each , every thing doing inside sprint , creating new tasks since means we'll

prediction - __builtin_expect from GCC with probability -

__builtin_expect gcc can used programmer show variants expected , rare. __builtin_expect have "true" , "false" (0% or 100% probability) for big projects vary hard profile feedback ( -fprofile-arcs ), , programmer know, probability of branch have in point of program. it possible give hint compiler branch have probability >0% , <100% ? true , false mean "the first variant more likely" , "the second variant more likely". there's no practical need values other these. compiler won't able use information.

java - How can I handle this exception within this method? -

i have jdbc connection code similiar following java jdbc tutorial: public static void viewtable(connection con) throws sqlexception { statement stmt = null; string query = "select cof_name, sup_id, price, sales, total " + dbname + ".coffees"; try { stmt = con.createstatement(); resultset rs = stmt.executequery(query); while (rs.next()) { string coffeename = rs.getstring("cof_name"); int supplierid = rs.getint("sup_id"); float price = rs.getfloat("price"); int sales = rs.getint("sales"); int total = rs.getint("total"); system.out.println(coffeename + "\t" + supplierid + "\t" + price + "\t" + sales + "\t" + total); } } catch (sqlexception e ) { jdbctutorialutilities.printsqlexception(e); } { stmt.close(); } } my problem way of handling connection closes statement

android - how to call parameterized javascript function in the WebKit? -

i trying pass 2 parameters javascript function.this code webview.loadurl("javascript: function_to_call();"); works fine without parameters couldn't use parameters. this javascript junction : function changelocation(_lon , _lat){ var zoom=16; var lonlat = new openlayers.lonlat( _lon , _lat ).transform( new openlayers.projection("epsg:4326"), map.getprojectionobject()); map.setcenter (lonlat, zoom); } and how call java : webview.loadurl("javascript:changelocation( -0.1279688 ,51.5077286 );") ; edit: couldn't find problem , changed approach, injecting whole javascript function desired changes everytime when need to. not best solution works. thank help. what have looks fine. here sample project demonstrates identical syntax.

ruby - Dynamic routes with Rails 3 -

i have task develop rails application following model routing. i need have pagecontroller , page model. page urls must /contacts, /shipping, /some_page . also need have catalogcontroller , category model. categories urls must /laptops, /smartphones/android . and productscontroller , product model, urls of products must line /laptops/toshiba_sattelite_l605 , /smartphones/android/htc_magic i understand problem can solved using urls like /page/shipping /catalog/smartphones/android but customer not want see insertion of " /page " or " /catalog " in url. please tell me direction solving problem. sorry bad english. you'll have write "catch-all" rule: on routes.rb: get '*my_precioussss' => 'sauron#one_action_to_rule_them_all' your precious controller: class sauroncontroller < applicationcontroller def one_action_to_rule_them_all @element = find_by_slug(params[:my_precioussss]) render

silverlight - Silverlight4 client timouts on long running WCF calls -

hi have silverlight client timeout problem tried timespan getsessionmaptimout = new timespan(0, 20, 0); client.endpoint.binding.closetimeout = getsessionmaptimout; client.endpoint.binding.receivetimeout = getsessionmaptimout; client.endpoint.binding.sendtimeout = getsessionmaptimout; client.endpoint.binding.opentimeout = getsessionmaptimout; client.innerchannel.operationtimeout = getsessionmaptimout; options including innerchannel.operationtimeout , none of them work silverlight client still timesout in 30 secs . the interesting thing ie regestry settings "receivetimeout"=dword:00007530 seem override silverlight client settings, cause if remove registry, works fine. how make these timeout working in silverlight , override ie registry settings. what kind of binding using? i'm using duplex binding hours / days @ time , there's no issue. did check timeout on server side? there's asp.net connection timeout take consideration (i think it'

is it okay to add icon credits in the "About" screen of a commercial Mobile App -

just quick question, know done on website okay add icon credits in "about" screen of mobile application espercially paid apps in iphone or android. has seen being done?. wondering if sounds professional. thank you. yes, icons licenced under lgpl or creative commons , these licences suggest putting credits.

How do I assign multiple textures into single a mesh in OpenGL? -

first example: can take huge rock shaped mesh , put tiled rock texture on it. now, places needs covered grass texture (or other vegetation). another example: usually, terrain built tiled textures. in order achieve less "tilly" look, can apply 4 times bigger (or 16 , on..) tiled texture on it, , you'll gain nice "random" tiled texture (seen in udk's docs). blender (the 3d graphics app) opengl based, , allows assign multiple materials single mesh. how can in own opengl application? thanks, amir p.s: i'm looking better solution rendering 50 tris tex , and 3 more tris tex b. what you're looking called multitexturing . modern graphics cards have several texture units each can sample different texture. when render rock specify vertices have uv coordinates each texture want render. in opengl can use glactivetexture select active texture unit can bind texture , use in subsequent rendering. vertices need additional texture coord

How can I run R interactively on a slave node, from emacs running on the head node? -

is there way start run r interactively on slave node? although can login server using qlogin, not allow launch emacs + ess, runs on head node. thanks! as per @newuser's request, found following parts of path variable found when on head node, removed path when on slave node /opt/eclipse:/opt/maven/bin:/opt/dell/srvadmin/bin there fair chance emacs not installed on slave nodes. may need discuss installation cluster admin. need install emacs on each node in order use there. keep in mind, however, sort of breaks typical grid paradigm master node controls jobs , slave nodes worker bees. in paradigm 1 not edit files manually on slave nodes. suspect why emacs not installed on slaves.

Why do Native PHP Sessions Not Work in IE8 'Protected Mode'? -

have strange scenario site. browsers work expected ie8 in 'protected mode', think default ie8, causes browser use different session ids on every page load. so, in shopping cart app, if bouncing around site adding items cart (which stored in native php session on server), cart has different state on every page load. in fact goes previous states after number of clicks. not sure if matters, using codeigniter not using using built-in session handler, using own works native sessions. when turn off 'protected mode' works expected.

uipopovercontroller - how to add the buttons to the popover view in ipad app -

i want add text fields , buttons popover view ... how add , hav read text added text field user later ... ....should need seperate view controller class control popover view or can control existed 1 calls popover view.... any appreciated.. create uiviewcontroller using ib or programatically. add needed buttons, textfields , maybe logic there , use viewcontroller initializing uipopovercontroller (as gendolkari suggested).

wcf - Correlation in WF 4 on workflow InstanceId -

in windows workflow foundation under .net 4.0, there way correlate operations based on instanceid (guid) of long-running persisted workflow? for example: operation 1 creates workflow instance, returns workflow instance id client client may later query instancestore database retrieve instanceid instances view client calls operation 2 , passes instanceid content-based correlation i can of if have client create , pass guid first operation, use value in content-based correlation, promote value when persisting. seems redundant, though, since workflow creating guid instance. create activity retrieve workflow instance id context passed in , return sendreply activity. next use correlationinitializer on sendreply setup request correlation.

c# - EntityClient Provider - What exactly does it do? -

i created new mvc application , added entity framework model generated nerddinner database. i looked @ connectionstrings section of web.config , confused @ connection string created: <add name="nerddinnerentities" connectionstring="metadata=res://*/models.nerddinner.csdl|res://*/models.nerddinner.ssdl|res://*/models.nerddinner.msl;provider=system.data.sqlclient;provider connection string=&quot;data source=tinctom;initial catalog=nerddinner;integrated security=true;multipleactiveresultsets=true&quot;" providername="system.data.entityclient" /> what each piece of connection string do? don't know entity framework , trying mess around learn bit more. i wrote a detailed examination of connection strings explains options metadata.

performance - Forcing sequential processing in Haskell's Data.Binary.Get -

after trying import basic java runtime library rt.jar language-java-classfile, i've discovered uses huge amounts of memory. i've reduced program demonstrating problem 100 lines , uploaded hpaste . without forcing evaluation of stream in line #94, have no chance of ever running because eats memory. forcing stream before passing getclass finishes, still uses huge amounts of memory: 34,302,587,664 bytes allocated in heap 32,583,990,728 bytes copied during gc 139,810,024 bytes maximum residency (398 sample(s)) 29,142,240 bytes maximum slop 281 mb total memory in use (4 mb lost due fragmentation) generation 0: 64992 collections, 0 parallel, 38.07s, 37.94s elapsed generation 1: 398 collections, 0 parallel, 25.87s, 27.78s elapsed init time 0.01s ( 0.00s elapsed) mut time 37.22s ( 36.85s elapsed) gc time 63.94s ( 65.72s elapsed) rp time 0.00s ( 0.00s elapsed) prof time 13.00s ( 13.18s elapsed)