Posts

Showing posts from May, 2011

java - Calling a function every 10 minutes -

i'm not expert, beginner. kindly ask write code me. if have 2 classes, class a , class b , , inside class b there function called funb() . want call function class a every ten minutes. you have given me ideas, didn't quite understand. can post example code, please? have @ scheduledexecutorservice : here class method sets scheduledexecutorservice beep every ten seconds hour: import static java.util.concurrent.timeunit.*; class beepercontrol { private final scheduledexecutorservice scheduler = executors.newscheduledthreadpool(1); public void beepforanhour() { final runnable beeper = new runnable() { public void run() { system.out.println("beep"); } }; final scheduledfuture<?> beeperhandle = scheduler.scheduleatfixedrate(beeper, 10, 10, seconds); scheduler.schedule(new runnable() { public void run() { beeperhandle.cancel(true); } }

c# - Can this MVC code be refactored using a design pattern? -

i've got controller code on asp.net mvc 3 site: [httppost] public actionresult save(postviewmodel viewmodel) { // vm -> domain mapping. definetely belongs here. happy this. var post = mapper.map<postviewmodel, post>(viewmodel); // saving. again, fine. controllers job update model. _postrepository.save(post); // no. noooo..caching, thread spawning, user?? why.... task.factory.startnew(() => { _cache.refreshsomecache(post); _cache2.refreshsomeothercache(post2); _userrepository.giveuserpoints(post.user); _someotherrepo.auditthishappened(); }); // should 3rd line in method. return redirecttoaction("index"); } basically, i'm referring code in threading block. things need happen, user doesn't need wait them (good case background thread, right?). just clear, use caching (regular asp.net data cache) on site, , of has "no expire" cache policy, manually evict when required (like above)

c# - Rename Folders in Outlook PST-File -

since few days i'm trying rename sent mail folder, deleted elements , inbox folder via c#. i've tryed this: list<outlook.mailitem> mailitems = new list<outlook.mailitem>(); outlook.application app = new outlook.application(); outlook.namespace outlookns = app.getnamespace("mapi"); // add pst file (outlook data file) default profile outlookns.addstore(pstfilepath); outlook.mapifolder rootfolder = outlookns.stores[pstname].getrootfolder(); outlook.folders subfolders = rootfolder.folders; foreach (outlook.folder folder in subfolders) { folder.name = (folder.name == "deleted elements"?"deleted":folder.name); } but without success. exceptiion not have permissions change name. other custom created folders i'm able rename without problems. is there unlock folder? or there other possibility access folders? thanks lot edit:

Django unable to parse POST data with webhooks -

i'm writing webhook view parse data 3rd party. have created view csrf_exempt decorator django unable parse regular post data (not json). @csrf_exempt def webhook(request): if request.method != "post": return httpresponse("invalid request.", status=400) print data = request.raw_post_data print request.post this print correct raw data (i tested "domain=example.com&username=user") returns empty post dict: post:<querydict: {}> any advice? i'm running django 1.3 first of make sure have set attribute name on inputs <input type="text" name="input_name" />

How do I factorize a matrix(m x n) into two factors (m x r, r x n) in Matlab? -

i want start mxn matrix , factorise 2 matrices mxr , rxn. r can greater dimensions of matrix a. nnmf allows r< min(size(a)) is there way can factorise matrix 2 matrices? there factorization functions available in matlab, see here: http://www.matrixlab-examples.com/matrix-decomposition.html e.g. lu / qr - factorization, cholesky etc...

c# - Relative paths in an ASP.NET application code behind -

being new asp.net i'm unsure of best solution problem. have line of code like: xdoc.load("templates/template1.cfg"); xdoc xmldocument . in project, @ top level there directory called templates. when run project in debug mode, directorynotfoundexception , , apparently it's looking templates dir in c:\program files\common files\microsoft shared\devserver\10.0\templates . how can correctly point directory without hardcoding it? server.mappath - returns path of relative path; ~ ensures relative path related application root xdoc.load(server.mappath("~/templates/template.cfg"));

c++ - Array of heteregenous function pointers in C -

i have array of function pointers, each pointing differ function. function differ in prototype, , number of parameters. i looking following similar functionality in c/c++. the following code not compilable in c #include <stdio.h> typedef int (*func)(int a,int b); int func_one(int a) { printf("\n in function 1 1 parameter %d \n",a); return 1; } int func_two(int a,int b) { printf("\n in function 2 2 parameter %d %d \n",a,b); return 2; } typedef struct{ func fnc; enum type{ one,two} type_info; }str; int main() { str str[2]; int ret; int i; str[0].fnc = func_one; str[0].type_info = one; str[1].fnc = func_two; str[1].type_info = two; for(i=1;i>=0;--i) { if(str[i].type_info == one) ret = str[i].fnc(10); else if(str[i].type_info == two) ret = (str[i].fnc)(10,20); else perror("error in implementation \n"); printf("\n return value %d \n",ret); } return 0; } in c, safe

How can make facebook friend request box showing in canvas page? -

i want make application appear friends of user in canvas , user choose friends want send request app. i know how popup window, want without it. want show friend request box in canvas page is these way it? you used able fbml functionality being / has been removed. you can create own friend selector if have permission read logged in user's friend list, , use request dialogue, , use requests dialog send requests selected users this: fb.ui({method: 'apprequests', message: invite_message to: facebook_user_id_array }, callback);

ruby - How do I set the session param for multiple namespaces? -

if handling authentication manually, , setting session so: session[:user_id] = authenticated.user.id user_id not show in session hash when viewed namespace. in instance have namespace :api, , session doesn't show @ api/show/current. how set session hash viewed in both namespaces? the session independent namespaces, maybe there else wrong app? where set user_id? maybe providing more code helps

Replace loop in VBA -

i have csv files special characters such 'è' instead of 'é' (the csv file in french). referenced special characters , trying write code vba it. unfortunatelly not working. code : sub replacetest() ' referenced 35 issues dim replacewhat(35) variant dim replaceby(35) variant ' reference special caracters , link them ones application.sheets("specialcaracters").select replacewhat(35) = application.range("a1:a35").value replaceby(35) = application.range("b1:b35").value dim integer = 0 34 application.sheets("sheet1").select activesheet.columns("a:ah").select selection.replace what:=remplacerwhat(i), replacement:=remplacerby(i), lookat:=xlpart, _ searchorder:=xlbyrows, matchcase:=false, searchformat:=false, _ replaceformat:=false next end sub any idea? thanks assuming having this: specialcharacters sheet \ | | b 1 | à | 2

objective c - Broken encoding while fetching data from sqlite database -

i store app data (cyrillic strings) in sqlite. when try display data in app strange characters instead of text. here how data. -(nsstring *)getdata { sqlite3 *database; if(sqlite3_open([[self datafilepath] utf8string], &database) != sqlite_ok) { sqlite3_close(database); } nsstring *query = [nsstring stringwithformat:@"select name users kind = '%@' order random() limit 1", self.kind ]; sqlite3_stmt *statement; nsstring *selectedquestion; if(sqlite3_prepare_v2(database, [query utf8string], -1, &statement, nil) == sqlite_ok) { sqlite3_step(statement); selectedquestion =[nsstring stringwithformat: @"%s",(char *)sqlite3_column_text(statement, 0)]; sqlite3_finalize(statement); } sqlite3_close(database); return selectedquestion; } assuming you're using utf-8 , not utf-16 sqlite databases, you're going happier using: selected

apache - Unable to brew using R -

httpd.conf file config brew this: <directory /usr/local/apache2/htdocs/brew> sethandler r-script rhandler brew::brew defaulttype text/html </directory> under brew folder, have file: <html> <body> <% library(cairo) filename <- paste(tempfile(tmpdir='/usr/local/apache2/htdocs'), '.png', sep='') cairopng(filename) x<-1:10000 plot(x, type="l", col="red") dev.off() %> <img src="<%=filename%>"/> </body> </html> i set permission 777 on safe side, @ least until working. when call http://localhost/brew/temp.brew , see file being generate under htdocs folder browser not displaying image, broken image. missing? again group. when try brew simple this, print out on browser: <% x<-1:1000 print(x) %> this may apache related. when this: <%=filename%> i on browser: /usr/local/apache2/htdocs/file199c5ea9644c.png my apache ho

c++ - When is 'this' required? -

is this pointer ever required? guess you'd need if functionally passing around instance of class pointed this . in terms of setting/retrieving/calling/whatever members, this optional? i've tagged c++ because that's language i'm wondering about, if can confirm construct same java , other oo languages use this pointer, it'd appreciated. you need when have local variable has exact same name member variable. in case, local variable said shadow member variable. member variable in situation, must use this . some people consider practice explicitly mention variable modifying member variable using this time, not case.

ASP.Net MVC 3: Routing URLs result in 404 when I move from local to dev server -

i have simple home , game controller set so: public class homecontroller : basecontroller { public actionresult index() { return view(); } } public class gamecontroller : basecontroller { [httppost] public actionresult new(int level = 1) { ... } public actionresult flipcard(int row, int column,guid nonce) { ... } [outputcache(duration=constants.cache_image_expiration_seconds)] public fileresult image (guid imageid) { ... } public actionresult finish() { ... } } i have routing set such in global.asax.cs: public class mvcapplication : system.web.httpapplication { ... public static void registerroutes(routecollection routes) { routes.ignoreroute("{resource}.axd/{*pathinfo}"); routes.maproute( "default", // route name "{controller}/{action}/{id}", // url parameters new { c

jsp - When to use forwardslash and when not to use forwardslash? -

i trying out basic login using jsp , servlets , don't understand how forwardslashes used indicate path. login.jsp located in loginapp/webcontent/login.jsp loginservlet.java located in loginapp/src/org/koushik/javabrains/loginservlet.java i have following code in login.jsp file - <form action="login" method="post"> <br>user id input type="text" name="userid" /> <br>password <input type="password" name="password" /> <br><input type="submit" /> </form> the corresponding servlet code @webservlet("/login") // <-- forwardslash here public class loginservlet extends httpservlet { private static final long serialversionuid = 1l; protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string userid, password; userid = request.getparam

How to serve static files in Django development -

here directory structure pf project. mysite \media \static \images \css base.css \js \templates base.html \settings.py #and other .py files now if have file c:\mysite\static\css\base.css or image c:\mysite\static\images\ball.png .how going serve using django development server. know not recomment way, in development want work. have read docs , other answers on stackoverflow don't seem work. may being confused media , static , urlpatterns . have spent hours trying figure out still no luck. new django , seems me overkill css or image showing up. changes or editing need make work. how referece image , css in template? here how static files django documentation takes through whole process step-by-step. add following urls.py from django.contrib.staticfiles.urls import staticfiles_urlpatterns # ... rest of urlconf goes here ... urlpatterns += staticfiles_urlpatterns() then 'this view automatically enabled

c# - using & try/catch nesting -

this question more of right way something... the question...is there proper nesting order between using block , try/catch ? is ok nest entire using statement inside of try/catch , maintain benefits of using block? (or exception cause closing portion of using statement thrown out window) or should nest try/catch inside using statements , surround statements database access? is... try { using( tsmtcowebentities db = new tsmtcowebentities() ) { violationlist = ( in db.drivertrafficviolationdetails a.drivertrafficviolation.driverapplicationid == driverappid orderby a.dateofoccurance descending select ).tolist<drivertrafficviolationdetail>(); generalviolation = ( in db.drivertrafficviolations a.driverapplicationid == driverappid select ).firstordefault(); } } catch { } less/more correct tha

Using WSDL with Netty -

one of clients provided me wsdl generated in microsoft visual studio. claims way connect wsdl on tcp/ip. so thinking use netty manage connection i'm not sure how handle wsdl/soap methods in way work best netty framework. please advise. looks person mixing tcp/ip , http, lower layer protocol http tcp/ip! access wsdl service, genrally need use soap nothing xml on http. netty provides http protocol encoders , decoders. need add own handlers handle incoming xml. take @ restexpress project, not soap creates web services using netty. imho, should using tried , tested web service framework axis, jboss-ws, metro, spring-ws etc etc instead of trying build own.

android - Nvidia tegra profiler 1.0 crashes -

nvidia tegra profiler 1.0 gets crash when used profiling application (ndk build) on android device. any advice helpful. or please suggest other profiler. it helpful (to give answer) if provide information test system like: device(s) tried use , android version(s) tegra profiler version attach logs profiler components screenshot error message have read tegra profiler user guide? has troubleshooting section...

javascript - How do we get index of select node in a extjs tree? -

on page have 2 trees. there form on page. 1 tree shown on page , inside form. have create trees below: var mytree1 = ext.create('ext.tree.panel', { store: store, //where store hardcoded json tree data .... }); similarly mytree2 declared different store. shown inside form. when select on node on mytree2 , click on create button must able add new leaf node inside mytree1 @ same index. help need are: 1. how index of selected node. 2. how go index in mytree1, should equal selected index mytree2. 3. how add leaf node @ specific index. for reference: ext js 4 treepanel documentation ext js 4 nodeinterface documentation the select event provides both index , record. if need general access it, mytree1.getselectionmodel().getselection() return array of records, can check against store index. i'm assuming want compare selected records on both trees. given sample in #1, try this: var tree1rec = mytree1.getselectionmodel().getselection[0],

javascript - JS Lightbox2 html 5 video tag disrupting close button function -

we've been testing html5 video pages on our site , have encountered strange issue in chrome , safari when using lightbox tag around video. here's link 1 of test pages it's problem close button. don't know how phrase this, appears rendering close button img above close button functioning area. doesn't happen in other pages using lightbox such one so figure must html5/video tag issue. anyone had experience recently? check out post: http://outburst.jloop.com/2009/06/19/lightbox-close-button-not-working/

java - How to add all elements in list to Abstract Syntax Tree without knowing how many elements? -

so have abstractsyntaxtreenode.java class (here part of it) public abstract class astreenode implements iterable<astreenode>{ protected list<astreenode> children; protected astreenode(){ children = new linkedlist<astreenode>(); } protected astreenode(astreenode... children){ this(); for(astreenode c: children) { this.addchild(c); } and have class operation extends astreenode public class operation extends astreenode { char s; private operation(term t) { //question regarding part super(t, t.getchild(0), t.getchild(1)); } } how throw in of object t's (which extends astreenode) children super ctor arguments? without hardcoding that? tried super(t, t.children) constructor not take list in argument, astreenodes taken. oh , class term public class term extends astreenode { char symbol; private term(factor f) { super(f, f.getchild(0)); } } and theres bunch more classes send children node add constructor in astree

gdb - Using cgdb for a ncurses c application -

when debug ncurses appplication following: gdb --tty=/dev/ttys000 ... this make ncurses application run in different terminal 1 gdb runs in. recently discovered cgdb , it. unfortunately not seem respect --tty option. are there other way of doing this? how cgdb people debug cgdb :) ? thanks. yes, can use tty command same way --tty option, either in gdb or in cgdb. see debugging ncurses programs . can use gdb in tui mode. cgdb.

.htaccess - Apache rewrite parses URL twice unexpectedly -

i'm trying redirect webpages domain names specific web application handles several sites. have web app in folder "skylight2" , folder, named "testsite", .htaccess file: rewriteengine on rewriterule ^(((?!skylight2).)*)$ /home/stefano/webroot_aliases/skylight2/$1/?site=testsite [qsa] i'm using virtual roots, , httpd-vroot.conf looks this: <virtualhost *:80> servername webserver serveralias *.webserver usecanonicalname off virtualdocumentroot /home/stefano/webroot_aliases/%1 options -indexes followsymlinks -multiviews rewritelog "/var/log/httpd/vroot_rewrite.log" rewriteloglevel 3 <directory /home/stefano/webroot_aliases/> order allow,deny allow allowoverride fileinfo indexes limit options rewriteengine on rewritebase / </directory> </virtualhost> if try acces

c# - In which cases should parameters be pinned when performing a P/Invoke call -

i have dll need p/invoke following c method: int daopen(handle *hopen, unit *flags, void *callback, char *userdata) i've come following c# signature: [dllimportattribute("<libname>", entrypoint="daopen")] static extern int daopen( out intptr hopen, ref uint flags, intptr callback, intptr userdata); assuming native code keeps reference parameters longer duration of p/invoke call: aside keeping instance of hopen , should pin it? should keep reference of flags variable? should pin since it's passed reference in particular case? i'm assigning callback delegate in following way: private intptr callbackonnativeevents; ... this.callbackonnativeevents = marshal.getfunctionpointerfordelegate( new callback(this.callbackonnativeevents)); should keep reference delegate in (not pointer)? should pin it? finally, i'm defining userdata parameter in following way: private intptr userdata; ... string

python - Django accessing ForeignKey model objects -

let's have following: class employee(models.model): firstname = models.charfield(max_length = 30) lastname = models.charfield(max_length = 30) class license(models.model): employee = models.foreignkey(employee) type = models.charfield(max_length = 30) and in custom management command, i'm pulling in employee objects employees = employee.objects.all() ... how can access associated license objects each employee object? have seen questions talk using contenttype purpose, i'm confused on it's practical use. can provide example on how use contenttype (or solution) in context? employee.license_set.all() https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects

twitter - Assigning Facebook like send div, tweet iframe, Google Plus dynamic width -

i using facebook send, tweet , google plus this. specifying width 320 facebook div , width 105 tweet. facebook , tweet button's (div/iframe) should automatically increased , decreased on own based on content width inside them. can suggest me way achieve this. main idea cut gap between these sections. <script type="text/javascript"> var snimpl= "<%=snimpl%>"; if (snimpl == "true") { (document, 'script', 'facebook-jssdk'); (function(d, s, id) { var js, fjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) return; js = d.createelement(s); js.id = id; js.src = "//connect.facebook.net/en_us/all.js#xfbml=1"; fjs.parentnode.insertbefore(js, fjs); } (document, 'script', 'facebook-jssdk')); (function() { var scrgoogleplus = document.createelement('script'); scrgo

architecture - Need guidance on inventory application design -

currently i'm working on inventory management application (later on can integrated accounting application too), , need in deciding 1 of important system design related decision on following: requirements: factories having multiple accounting firm (company), , goods come , go these multiple accounting firm, physically consumed in 1 factory , production being managed single manufacturing unit. there no separation of physical stock or produced items based on accounting firm. again goods sold different accounting firm. inventory data, sales & purchase given company wise no production related records being managed separately inventory , production data managed in single application companies (accounting firms) unified, customer can have reliable tracking of stock/inventory items now, want suggest on following: what suggest, whether keep company wise data separate db different each other or store them in single db separate identifier company , have single applicati

c++ - Run command in emacs, get output in clickable buffer -

i run shell command , output in clickable buffer in emacs. command shell script runs glimpse on bunch of source files. output looks grep's output. includes file name , line number. able click on file or enter while standing on , emacs take me line in file. suppose need custom function that, new emacs don't yet know how program it. m-x grep type in command instead of default. m-x apropos "grep.*null" finds grep-use-null-device if need not send "/dev/null"

c++ - Unnamed namespace access rules -

i looking on section 7.3.1.1 in c++03 standard expecting find description of access rules items defined in unnamed namespace. the rules seem little different unnamed namespaces, since cannot qualify access items in one. know @ least within same translation unit, 1 can access items in unnamed namespace if not in namespace. example: namespace { int foo; } void something() { foo = 4; } if namespace had name, not this. so, rules defined in standard these exceptional rules apply unnamed namespaces? an anonymous namespace treated as: namespace unique_per_tu { // stuff } using namespace unique_per_tu; i'll try find reference here in minute. edit: it appears found in 7.3.1.1/1 an unnamed namespace definition behaves if replaced by namespace unique { /* empty body */ } using namespace unique; namespace unique { namespacebody } where occurrences of unique in translation unit replaced same identifier , identifier differs other identifiers

java - Layouting custom buttons -

Image
i trying create buttons shaped in following picture: this works pretty doing following: class arrowbutton extends composite { arrowbutton(composite parent, int style) { [...] setregion(customregion); } } addstuff(composite parent) { arrowbutton b = new arrowbutton(parent, swt.none); b.setbounds(x, y, width, height); } however, want use layout manager layout these buttons. ideally, buttons layouted on standard size, after can still paint outside of region. is @ possible? how can this? layout managers have 2 functions: calculating size of composite applied , setting bounds of composite's children. given relative simplicity of requirements (line buttons horizontally) i'd you're better off doing layout (rather trying hack existing implementation). can put code delegate behind layout interface, if feels better.

Jquery function passing around select options -

$('#addallbutton').click(function () { var options = ''; $('#fromlist').find('option').each(function () { alert($(this).val()); //options += '<option value="' + $(this).val() + '">' + $(this).text() + '</option>'; }); $('#tolist').append(options); }); <select id="fromlist" name="drop1" class="listbox" multiple="multiple"> <option value="1">item 1</option> <option value="2">item 2</option> <option value="3">item 3</option> <option value="4">item 4</option> <option value="0">all</option> </select> <select id="tolist" name="drop1" c

Inserted Nested Item in Generated JSON in Groovy/Grails -

i using grails 2.1 render json part of restful api created. domain class, based on sqlserver table, looks this: string firstname string lastname string officialaddress1 string officaladdress2 string preferredaddress1 string preferredaddress2 (etc.). . . which returns json similar this: { "firstname": "joe", "lastname": "hill", "officialaddress1": "1100 wob hill", "officialaddress2": "apt. # 3", "preferredaddress1": "1100 wobbly lane.", "preferredaddress2": "apartment 3." } it working fine client wants me nest results in fashion: { "firstname": "joe", "lastname": "hill", preferredaddress { "preferredaddress1": "1100 wobbly lane.", "preferredaddress1": "apartment 3." }, officialaddress { "officialaddress1": "1100 wob hill", "offic

objective c - Obj C - Creating Unique Property List Keys using 'For' -

for (int x = 0; x < openslots; x++) { nsnumber* slotvaluesave = [[nsnumber alloc] initwithint:[[slotvalues objectatindex:x] intvalue]]; nslog(@"saving slot %@.", (x+1)); [valuesavesdictionary setobject:slotvaluesave forkey:@"slot value %i", (x+1)]; } hello, i'm trying saving 9 string , corresponding numbers property list key. don't want write out every key @"slot value 1", @"slot value 2", etc. so wondering how have 'for' statement insert 'x' integer after every title saved under key. thank you. use +stringwithformat: : [valuesavesdictionary setobject:slotvaluesave forkey:[nsstring stringwithformat:@"slot value %i", (x+1)]];

Random sample of rows from subset of an R dataframe -

this question has answer here: sample random rows in dataframe 7 answers is there way of getting sample of rows part of dataframe? if have data such gender <- c("f", "m", "m", "f", "f", "m", "f", "f") age <- c(23, 25, 27, 29, 31, 33, 35, 37) then can sample ages of 3 of fs sample(age[gender == "f"], 3) and [1] 31 35 29 but if turn data dataframe mydf <- data.frame(gender, age) i cannot use obvious sample(mydf[mydf$gender == "f", ], 3) though can concoct convoluted absurd number of brackets mydf[sample((1:nrow(mydf))[mydf$gender == "f"], 3), ] and want gender age 7 f 35 4 f 29 1 f 23 is there better way takes me less time work out how write? your convoluted way pretty how - think answers v

SQL Database ER Diagram -

Image
so software engineering course, part of larger project, need implement database using hsqldb. unfortunately, haven't taken database design yet, , 3 out of 5 people in our group have dropped course, leaving part me do. as of now, i've come er diagram our project: what have list of courses, , each course contains many modules. every account can registered in course, giving them access each module of course, graded, , mark stored on account. i think diagram i've come represents well; however, started learning today, i'm still bit shaky, say. is there jumps out wrong this, or parts improved? p.s - noticed in module table, contains grade, should in module_grade. course_grade table absolutley useless in model. should store grade information inside course_grade , module_grade instead of module directly. think of module master data (so want use students) means should not store student specific information inside it. i add timestamps model @ least inside

jquery - mousewheel outside the jscrollpane -

i have jscrollpane: http://www.complexproduction.com/aladdin/work/totalbanken client insists wants mousewheel work if mouse outside pane. ideas on how that? i'd try use library handles mousewheel events whole page.

monodevelop - how to add wcf reference in Monodevelp -

new monodevelop how add reference wcf in monodevelop. not see option add wcf reference version using 2.8.6.5 , running on windows 7 thanks the add web reference command supports adding references based on wcf. when adding reference, , combo box allows selecting target framework, can wcf. right-click on project in solution explorer , go add web reference.

set global encoding in Zend Framework -

my bootstrap sets encoding views: protected function _initview () { $view = new zend_view(); // snip... $view->setencoding('utf-8'); // snip... return $view; } however, not set encoding form validators. stringlength uses default encoding (i'm not sure is) , counts diacritics 2 characters. i know can set 'encoding' => 'utf-8' option when creating validator, it's kind of pesky update validators across entire (huge) application. there way set encoding validators @ same time? in zf 1.1x stringlength validator uses iconv_strlen : int iconv_strlen(string $str [, string $charset = ini_set("iconv.internal_encoding")]) so 1 thing try call ini_set (or iconv_set_encoding('internal_encoding', $encoding); ).

android : customized action when home logo in action bar si clicked -

i changed logo action icon , want perform action when logo clicked. how can customize action when home logo in action bar clicked? thank you in onoptionsitemselected() of activity, watch id of android.r.id.home -- when home icon/logo pressed. can perform whatever action makes sense (e.g., move app's main screen).

Type mismatch exception when using java.math classes on Android -

i need divide 2 bigdecimals in android 2.2 application : bigdecimal = new bigdecimal(1); bigdecimal b = new bigdecimal(3); bigdecimal c = a.divide(b,2,roundingmode.half_up); when executing divide operation following exception : type mismatch can't assign java.math.roundingmode java.math.roundingmode i'm using android sdk 2.2 platform , java sdk 1.6.0.24 in ide , program deployed on device running android 2.2.

objective c - iOS YouTube Video Upload Error -

i trying upload video using objective-c , youtube api not working , return error @ last step. error reads "user authentication required". i following api document 1 without metadata. got authentication token clientlogin api i checked authentication token nslog , it's there. see upload api returns upload url when send http put request retrieved upload url, returns error mentioned above. here's upload code - (bool) upload:(nsstring *)file { nsdata *filedata = [nsdata datawithcontentsoffile:file]; nsurl *url = [nsurl urlwithstring:self.uploadurl]; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url]; [request sethttpmethod:@"put"]; [request setvalue:@"content-type" forhttpheaderfield:@"application/octet-stream"]; [request setvalue:@"content-length" forhttpheaderfield:[nsstring stringwithformat:@"%ud", [filedata length]]]; [request sethttpbody:filedata];

javascript - <html: image directly calling struts action class -

i want call submitformfinal(this.form); client side validation.but problem html:image property directly calls struts, server side validation takes place before calling submitformfinal(this.form). if submitformfinal fails , server side validations should not take place ,but in case html:image directly calls struts action classs.... suggestions? right code is:- <html:image src='<%=contextpath + "/img/save_orange.gif"%>' onclick="javascript:submitformfinal(this.form); "/> what returning value submitformfinal() : <html:image src='<%=contextpath + "/img/save_orange.gif"%>' onclick="return submitformfinal(this.form);"/> now if submitformfinal() returns false wont submit, if returns true submitted. update : after seeing next problem, here thoughts. 1) should not use <html:image> submitting form. <html:submit> correct

c# - Define composite primary key in Entity Framework -

i have table has no primary key defined. when adding datamodel tool generates following message: errors found during generation: warning 6013: table/view 'charge_details' not have primary key defined , no valid primary key inferred. table/view has been excluded. use entity, need review schema, add correct keys, , uncomment it. i cannot modify table in way - reckon construct composite key 2 columns in order satisfy these requirements. however it appears within entitytype element key can contain zero or one elements. so how instruct ef treat 2 columns key? you can create composite primary key on database side. use odp.net? automatically map database pk.

wordpress - finding php page in complicated structure -

is there easy way find exact php page (including path) line of code appears in? example, if i'm editing wordpress theme hundreds of php files in multiple nested folders, finding where, say, line 349 in compiled source code appears in file structure? the php language interpreted , not compiled usually tell u full path file when error occurs . if not can display using : $path = dirname(__file__); echo $path ;

jQuery Mobile - firing pageshow event only once -

i trying execute snippet of js once, after page has loaded , jqm has taken care of ui modifications (i.e. listviews, buttons, etc.). want execute on page, , not on subsequent pages. what tried first, pageshow <script> $('[data-role=page]').live("pageshow", function() { alert("ready!"); }); </script> this has problem function attached page div , gets executed every time subsequent page gets shown. however, want executed once, , page contains js snippet. is there way listen pageshow event, without attaching function it. the way able binding , unbinding this: <script> $('[data-role=page]').bind("pageshow.test", testfun); function testfun() { alert("ready!"); $('[data-role=page]').unbind("pageshow.test", testfun); } </script> but there more elegant way so? jquery has one function bind event handler executed once. check reference .

php - Saving a friend's Facebook picture to disk from the server does not work -

tl;dr viewing images friend's profile image album works on web page fb javascript api page passes url server, server cannot download image url (http status 0) user logged in both js api , php-sdk api , has fb photo permissions current profile images work great this issue not affect users, some. my facebook photos app my app creates video montage of friend's facebook images. the app asks permissions: "user_photos" and "friends_photos". the user chooses pictures add montage javascript in browser. pass url of chosen image server, downloads image url , stores on amazon s3. everything works on client , always works friends profile images . other images i.e. ones album or previous profile pics, server cannot download image @ all. using curl, status code returned 0. other images, code 200. how can access these images? server need pass other data able access cdn images? the image urls passed js long links , this: http://fbcdn-sphotos

android - Cannot drop shadow on bitmap with SetShadowLayer -

i trying add shadow bitmap image, cannot figure out why not happening: public static bitmap pimpmybitmap(bitmap bitmap) { // scales down, adds rounded edges , shadow bitmap output = bitmap.createbitmap(360, 240, config.argb_8888); canvas canvas = new canvas(output); final int color = 0xff424242; final paint paint = new paint(); final rect rect = new rect(0, 0, bitmap.getwidth(), bitmap.getheight()); final rectf rectf = new rectf(0, 0, 360, 240); final float roundpx = 12; paint.setshadowlayer(5.5f, 6.0f, 6.0f, 0xff000000); paint.setantialias(true); canvas.drawargb(0, 0, 0, 0); paint.setcolor(color); canvas.drawroundrect(rectf, roundpx, roundpx, paint); paint.setxfermode(new porterduffxfermode(mode.src_in)); canvas.drawbitmap(bitmap, rect, rectf, paint); return output; } if using honeycomb , above, make sure use software layers because of version 4.2 setshadowlayer not supported accelerated canvas pipel

Emacs resize vertical windows with mouse -

Image
i using emacs on gui , both vertical , horizontal split windows. in order resize horizontal windows, grab (with mouse) name of buffer , drag , down. with vertical windows, can't that, though. can't grab scrollbar, there no "slider". know can use c-x { , , c-x } , these shortcuts unnatural, , i'd mouse. is there way can that? the status bar between 2 top windows draggable.

chain - jQuery and chaining issue -

i'm jquery rookie , maybe i'm ask basic question, i'm struggling while figuring out why jquery chaining doesn't work in case. var container = $('#container'), items = container.find('ul.items'), moreitems = items.children('li.moreitems'); var config = { container : container, items : items, moreitems : moreitems } var app = myapp(config); function myapp(config) { this.container = config.container; this.items = config.items; this.moreitems = config.moreitems; this.current = 0; } myapp.prototype.myusefulfunction() { this.moreitems[this.current].fadein(); } let's suppose have div#container filled ul elements have more 1 li each. i'd access n-th li , fade element in, console throws me error, stating fadein has no such method. can please me sort out? jquery returns jquery object, a sort of array containing domelements . when do: this.moreitems[this.current] extract domelement jquery array --> have turn jquery object

Loading navigation properties in NHibernate 3.2 -

i have these entities: public class post { public virtual int id { get; set; } public virtual icollection<tag> tags { get; set; } public virtual icollection<comment> comments { get; set; } } public class tag { public virtual int id { get; set; } public virtual icollection<post> posts { get; set; } } public class comment { public virtual int id { get; set; } public virtual post post { get; set; } } i want load post it's related tag s , related comment s's count linq . use this: var posts = session .query<post>() .orderby(t => t.id) .select(t => new { post = t, commentscount = t.comments.count(), tags = t.tags }).tolist(); do think enough? or have suggestion may better code? thanks. this highly depends on mapping , want fetched result. imho eager loading tags speed performance (select n+1) if want access tags list (assuming tags mapped lazy). var po

filesystems - amazon s3 partitioning of files best practices -

hopefully simple question - apologies if it's been answered nothing came in search. on s3 better organizes images smaller subdirectories, or keep them in 1 directory? in typical filesystem 1 namespace images in directories improve performance. flat structure thousands of images in 1 directory doesn't perform well. case on amazon s3? i can put user images users folder, post images posts folder, etc. or can put user images folders users/{userid} avoid having thousands of images in 1 users folder. this problem amazon s3 well, albeit significant storage requirements, see amazon s3 performance tips & tricks detailed answer including strategies partitioning object space. update (september 2013) – information in above link, while still largely accurate, has been supplanted newer document, s3 request rate , performance considerations .

c# - WebRequest to post data in Login page -

i read questions similar titles , test codes problem not solved. problem: need program in c# post dates modem login page. modem wimax bm632. address of login page htp://192.168.1.1/ , action of form there in http://192.168.1.1/ http://192.168.1.1/index/login.cgi (form action). want when login success go http://192.168.1.1/html/wimax/security.asp , page source. login page : http://chamalz.persiangig.com/image/1.jpg i write code: webrequest request = webrequest.create("http://192.168.1.1/index/login.cgi"); request.method = "post"; string postdata = "username=admin&password=ywrtaw4%3d"; byte[] bytearray = encoding.utf8.getbytes (postdata); request.contentlength = bytearray.length; stream datastream = request.getrequeststream (); datastream.write (bytearray, 0, bytearray.length); datastream.close (); webresponse response = request.getresponse (); textbox1.text=(((ht