Posts

Showing posts from June, 2013

PHP - Calling functions with multiple variables -

this seems basic question know i've not been able find answer. let's assume basic function: function basicfunction ( $var1, $var2 = 1, $var3 = 2, $var4 = 5 ) { // stuff // return } now let's assume want call function following variables: $var1 = 0 $var2 = 1 $var3 = 2 $var4 = 3 i can this: $someresult = basicfunction( 0, 1, 2, 3 ); $var2 , $var3 set though, how call function without having repeat value $var2 , $var3 ? php not support overloading. therefore, cannot skip them in way if don't move them right of list of arguments. a common solution set default value of different type expected (i.e. null). actual default value set within function. approach not clean , takes lines of code, if situation requires it, can go this: function basicfunction($var1, $var2 = null, $var3 = null, $var4 = null) { if ($var2 === null) { $var2 = 1; } // ...

haskell - Maybe monad usage example -

i'm trying learn haskell i'm having problem in monad usage. i imported module data.maybe . but don't know how use >>= operator. given (>>=) :: monad m => m -> (a -> m b) -> m b cannot understand how define function (a -> m b) . can provide pedagogical example? for maybe monad bind function ( >>= ) looks that: (>>=) :: maybe -> (a -> maybe b) -> maybe b so, let's define maybe a value: > let = 1 :: maybe integer and :: -> maybe b function: > let f = \x -> (x+1) f :: integer -> maybe integer now can use bind infix operator: > >>= f 2 :: maybe integer another example of a -> maybe b function be: let h :: integer -> maybe string; h = return . show . (+1) h :: integer -> maybe string so h increment integer number, convert string , make maybe value return function. > >>= h "2"

php - Call to a member function setName() on a non-object in symfony2 -

i trying edit form form existing values correctly when try put new data in fields , submit form error of call member function setname() on non-object my controller method public function editaction(request $request){ $request = request::createfromglobals(); $group_id = $request->query->get('id'); $em = $this->getdoctrine()->getentitymanager(); $patent_group = $em->getrepository('munichinnovationgroupbundle:pmpatentgroups')->find($group_id); //echo '<pre>'; //print_r($patent_group); //echo '</pre>'; $form = $this->createform(new patentgrouptype(), $patent_group); if ($request->getmethod() == 'post') { $form->bindrequest($request); $name = $form["name"]->getdata(); $description = $form["description"]->getdata(); $patent_group->setname($name); $patent_group->setdescription($description); $em-...

Cookie not getting set for index.php page in Safari 5.1.7 -

i have following script add cookie page visited colorbox: if (document.cookie.indexof('visited=true') === -1) { var expires = new date(); expires.setdate(expires.getdate()+1000); document.cookie = "visited=true; path=/index.php; expires="+expires.toutcstring(); $.colorbox({href:'files/welcome.html', width:"45%", speed:1500}); } this sets cookie in firefox , chrome page visited not in safari (5.1.7). similar script sets cookie page on site, setting path=/mixups/june_2012/ works fine in safari. does know why happening, , if there fix? thanks, nick

anchor - jQuery selector with specific attribute -

i've got code: $('a').click( function() { $("#change_flash").css("display", "block"); $("#my_flash").css("display", "none"); }); but 1 works anchor elements. influence script anchors elements contains rel="lightbox" attribute. how can achieve it? $('a[rel="lightbox"]').click( function() { $("#change_flash").css("display", "block"); $("#my_flash").css("display", "none"); });

xamarin.android - monodroid wcf call -

Image
i'm having difficulties accessing wcf service. service running in same solution monodroid app , hosted visual studio. configured basichttp. reference adds ok @ runtime when call 1 simple test method, ; system.net.webexception it's simple web service public class service1 : system.web.services.webservice { [webmethod] public string helloworld() { return "hello world"; } } and here call button.click += delegate { localhost.service1 se = new localhost.service1(); button.text= se.helloworld(); }; and error snapshot in attachment i agree need add more information. however, responded question sometime ago , doing wcf stuff , it's working great me. using soap in shared mono library wp 7 , android this might out. one other thing thought of. have internet option in network manifest selected shown here: http://docs.xamarin.com/@api/deki/files/1026/=requiredpermissionsvs.png...

Is there a faster way to sum up an arithmetic sequence of numbers in Python? -

total = 0 in range(0, upper bound): total += sorry if basic have lot of these , they're taking more room comfortable. total = sum(range(upper)) or total = upper * (upper - 1) / 2 the first 1 python, second 1 gauss. edit: when not starting @ zero: total = sum(range(lower, upper)) or, again according gauss, same upper , substract same lower : total = upper * (upper - 1) / 2 - lower * (lower - 1) / 2 if on python 2.x, replace range xrange .

sharepoint - Convert SPFieldMultiLineText to HtmlField -

is there way convert spfieldmultilinetext htmlfield using code? spfieldmultilinetext used display text. did tried spfieldmultilinetext.getfieldvalueashtml . returns field value in html format in order render value directly on page. find link

c# - geocoding multiple addresses code behind -

i geocoding multiple address xml file lat/lng plot marker on map. works fine 15 addresses today checked , there 88 addresses , takes while load page. what's happening user clicks link map page , browser spins until addresses have been geocoded, page loads. i'm having use system.threading.thread.sleep(150); before each call google service avoid query limit error. there can make load page load addresses? as you've found, google's geocoding service isn't requests en masse . in fact, it's against terms of service use service bulk downloads or processing batch requests. what ought service doesn't have such low limits , allows submit batch requests api. disclosure purposes, work smartystreets , , provide such api called liveaddress . it sounds you're submitting many requests there addresses geocode , plot. 15-100 requests take anywhere 1 maybe 10 or 15 seconds including network latency. i've seen situation quite few times in line of work ...

objective c - Where to save the file in an application iPhon / iphone? -

i've make web app lot of image , safaris memory can't open of images. build application stores images in ipad. images can change dynamically , don't know can save it. rest of code works withe file put image. notice : in ipad simulator works normally, in ipad have permission problem. my code uiimage *image = [[uiimage alloc] initwithdata:[nsdata datawithcontentsofurl:[nsurl urlwithstring: [nsstring stringwithformat:@"http://link_of_my_image", [splitlink objectatindex: 1],[splitlink objectatindex: 3] ] ]]]; nsdata *data1 = [nsdata datawithdata:uiimagepngrepresentation(image)]; bool test10 = [data1 writetofile:[nsstring stringwithformat: @"%@/%@/folder/%@",linkslidesfile, [splitlink objectatindex: 1],[splitlink objectatindex: 3]] atomically:yes]; nslog(@"creat image --------------------- %@ %i", [nsstring stringwithformat: @"%@/%@/folder/%@",[splitlink objectatindex: 0], [spl...

COM interfaces declared in C++ -

usually create com interface 1 should declare in idl file. in project work on have 1 com interface declared in *.h file in c++: struct declspec_uuid("a67177f7-a4dd-4a80-8ee1-25cf12172068") isomeservice : public iunknown { virtual ~isomeservice() {} virtual hresult initialize(const settings& settings) = 0; // ... }; moreover method initialize takes struct contains std::string fields parameter. corresponding com class implemented in c++ , used c++ module. works fine until run code under appverifier. causes access violation exceptions occur. so questions are is right declare com-interface in *.h file? if yes right specify c++ types parameters com interface methods? or should use com compliant types in such cases (bstr etc)? sure, can describe com interface without using idl. won't able use such idl features type library , marshalling code generation. if using com component in-proc server (dll), , it's ok distribute .h file clien...

logging - Jenkins: Permission denied to a 777 file -

i have created jenkins build compile , distribute modules. output of build commands (e.g., make or ant ) redirected file named build.log . the funny thing redirecting echo same file, using tee , fails: tee: ../../build.log: permission denied the file exists , has 777 permissions (checked ls -ltrh ../.. ). ideas what's wrong write? permissions on file important, permissions on super directories of file. if not have read , execute permissions on directories traversing through, cannot follow relative path file. if lack read permissions on directory "build.log" resides in, cannot list files in directory. read, write, , execute permissions matter directories, , map to: read = allows listing of files write = allows creating / deleting / modifying files execute = allows changing directory directory

Xcode ios: how to costumize a ui item, and apply that to all viewcontrollers? -

i have uitextfield, had costumized in firstviewcontroller. wan't have same behavior on other viewcontrollers. there anyway import propreties on iboutlet? thanks! simple create own customclass , set property in constructor. @interface customtextfield : uitextfield @end @implementation customtextfield - (id)initwithframe:(cgrect)frame { self = [super initwithframe:frame]; if (self) { //customize here self.autocapitalizationtype = uitextautocorrectiontypedefault; self.text = @"blub"; .... } return self; } @end if create new textfield, create object custom class: customtextfield *field = [[customtextfield alloc] initwithframe: ...];

php - inserting variable from actionscript into MySQL table -

i using $_server['http_user_agent'] insert browser , os of users upload files website mysql table. using uploadifive, has fallback using flash (uploadify) browsers don't support html5. when using flash, os , browser not returned using $_server['http_user_agent'], instead see "adobe flash player 11". i can see this tutorial can add actionscript uploadify flash file return browser. externalinterface.call returns same info $_server['http_user_agent'], stored in useragent variable. not sure how integrate insertion mysql database though. need 1 argument inserting field in mysql table. could this? thanks, nick you can useragent javascript via navigator.useragent in uploadify there should js similar following: in example server file uploadify.php, can pass values in other url. $(function() { $('#file_upload').uploadify({ 'swf' : 'uploadify.swf', 'uploader' : 'upl...

c# - Delayed double click for editing textblock WPF -

i trying make textblock turns editable delayed double click. similar functionality in windows explorer when delayed double click edit file , folder names. possible? what seeing in windows explorer single-click on selected/focused item initiating rename operation. first click you're seeing selects/focuses item , second click initiates rename operation. can verify using keyboard select different item , single-clicking on newly selected item. it appears there short duration (e.g. half second) between click on selected/focused item , ui going rename mode. so... if item clicked on has focus, you'll need starting timer. if item still has focus when timer expires, enter renaming mode. from there matter of applying correct template whichever trigger/flag logic care implement. edit : search on wpf in-place editing , should find code examples. note : f2 key tends initiate rename operations on selected items if want wire in well.

asp.net mvc - Web API: HTTP verb 'OPTIONS' -

is there support in asp.net mvc 4 web api beta http verb 'options'? framework not automatically send response. think have yourselve. there method like: getverbsforurl("http://server.com/api/values"); ? there feature called apiexplorer can provide web api descriptions. can see more details here: introducing iapiexplorer/apiexplorer generating web api page using apiexplorer

apache - Beautifying the Url using .htaccess -

i have link http://xxxx.com/yyyy/index.php?class=applications&function=create and want make this http://xxxx.com/yyyy/create i know have use the rewriteengine on rewriterule .................. but since i'm new @ it, don't know how format it.. directoryindex index.php order deny,allow options +followsymlinks -multiviews rewriteengine on rewritebase / rewriterule ^(xxxxxxxx)/(aaaa)/?$ $1/index.php?class=applications&function=$2 [l,nc,qsa] rewriterule ^(xxxxxxxx)/(bbbb)/?$ $1/index.php?class=applications&function=$2 [l,nc,qsa] rewriterule ^(xxxxxxxx)/(cccc)/?$ $1/index.php?class=applications&function=$2 [l,nc,qsa] rewriterule ^(xxxxxxxx)/(dddd)/?$ $1/index.php?class= test&function=$2 [l,nc,qsa] rewriterule ^(yyyy)/index\.php$ $1 [l,nc] #this 1 not working... enable mod_rewrite , .htaccess through httpd.conf , put code in .htaccess under document_root directory: options +followsymlinks -multiviews # turn mod_rewrite on r...

java - Android Methods calling tracking -

i halfway of changing code print log message each time enter , exit method. when thought there feature or plugin eclipse can track me , show me. after all, information java compiler has @ hand. what need see order in each method called , returns. it should print method name , stack above it, can know called. optionally , if prints time of enter , return , difference, info profiling. i remember trying traceview in past, don't know if answr, remember there information there , not clear picture of going on. if knows how use info need, great too. update: having hard time using traceview , companion dmtracedump. did wasn't supposed do, searched dmtracedump code source , it. code producing error message getting. tracedata data1; datakeys* datakeys = parsedatakeys(&data1, goptions.tracefilename, &sumthreadtime); if (datakeys == null) { fprintf(stderr, "cannot read trace.\n"); exit(1); } but don't kn...

c# - Why does System.Threading.Timer callback successfully update UI? -

i have several system.threading.timers on form application callbacks update ui...successfully - i.e. without throwing errors. i had built these earlier, before knew ui should not updated on thread other ui thread. now confused why not throw cross-thread exceptions when updating ui on these separate threading.timer threads? i changing these callbacks ui updates invoked on ui thread, curious why works. edit: application winforms application. i changing these callbacks ui updates invoked on ui thread, curious why works. if windows forms, works purely luck. updating ui on background thread doesn't consistently work, not throw. in particular, if checkforillegalcrossthreadcalls false, "work", , never throw - though behavior wrong. controls not check every property, items "work" though they're not working correctly, typically introduces bugs can difficult diagnose , correct later. on side note: if wpf, change value of item bound ui...

bash - Eclipse CDT: pkg-config indexing -

i`m developing application using gtkmm eclipse. while have setup gtkmm include paths , linking options manually, decided let pkg-config work because of huge number of referenced projects. quite easy adding appropriate pkg-config command compiler invocation worked fine because 1 can use `...` shell substitution since eclipse generate makefile executed. setting indexer right isnt easy though. instead of executing shell script in interpreter, eclipse executes compiler directly , pass command line arguments directly without substituting them before. how can 1 execute shell script when executing indexer? the solution execute bash interpreter -c flag directly instead of executing g++. scenario described in question configurations followed: compiler invocation command bash compiler invocation arguements -c "g++ `pkg-config gtkmm-2.4 --cflags` -e -p -v -dd ${plugin_state_location}/specs.cpp"

python - Saving Image to Django, the correct way ? -

what best practice set upload path in django 1.4? have model def upload_image(instance, filename): return os.path.join(instance.slug, filename) class book(models.model): ... ... image = models.imagefield(upload_to=upload_image) def admin_image(self): return "<img src='%s' />" % self.image .... with settings.py project_dir = os.path.dirname(os.path.realpath(__file__)) root_dir = project_dir.rsplit(os.sep, 1)[0] media_root = os.path.join(root_dir, 'books', 'static', 'books') media_url = '/media/' static_root = '' static_url = '/static/' and admin.py class bookadmin(admin.modeladmin): list_display = ('title', 'admin_image') so, in end, got image correctly saved /root-of-project/books/static/books/programming-java/wall.jpg, however, saved path in database "programming-java/wall.jpg" , have concat prefix '/static/books/' ever...

android - Remove shortcut pointing to my app from stock launcher in ics -

i need remove 1 particular (better) or shortcuts (worst case) pointing app stock launcher. unable use uninstall_shortcut broadcast, seems dont work (simillar problem this . my app signed system certificate (it installed in /system/app) have ideas, how remove shortcuts. is there working way use uninstall_shortcut in ics? i have seen stock launcher removes links pointing app when uninstall it. there way simulate uninstalling (or send package_removed broadcast, having system privileges)? maybe write part of package manager? if 2 not possible there way can cause package manager send package_removed broadcast, reinstallation/upgrading app? (i can install/upgrade apps silently, because have system privileges install_packages permission). i believe have way start app besides shortcut. to not show on app drawer, remove <intent-filter> <action android:name="android.intent.action.main" /> <category android:name=...

GWT is making an unexpected event call -

my code below: seeing on running app loadwidget method gets invoked when adminlink not clicked. not want want, i'm not sure causing issue. please advise public class loginmodule implements entrypoint { loginpopup loginpopup; private class loginpopup extends popuppanel { public loginpopup() { super(true); } public void loadwidget(){ system.out.println("i called 1"); commonui cui = new commonui(); //#342 moved code common area formpanel loginform = cui.getloginformui(); setwidget(loginform); } } @override public void onmoduleload() { //#251 improved login popup ui. final anchor adminlink = new anchor("user login"); // final label adminlink = new label("user login"); adminlink.addclickhandler(new clickhandler() { public voi...

ios - SmallSocket causing app to crash on iPhone -

i trying use smallsockets library create tcp socket connection. currently, i'm using button test connection server iphone. here code looks like: -(ibaction)btnconnect:(id)sender { bool loopconnection = true; while(loopconnection == true) { socket *socket; int port = 11005; nsstring *host = @"199.5.83.63"; socket = [socket socket]; @try { nsmutabledata *data; [socket connecttohostname:host port:port]; [socket readdata:data]; // [socket writestring:@"hello world!"]; //** connection successful **// [socket retain]; // must retain if want use out of action block. } @catch (nsexception* exception) { nsstring *errmsg = [nsstring stringwithformat:@"%@",[exception reason]]; nslog(errmsg); socket = nil; } } } when press button, app freezes. free...

Grails button to call controller within a page -

my gsp has button , not submitting form. when clicking button, want call n action in controller , @ same time have jquery code attached button. after calling action in controller, hope stays in same view(not redirected page related action). any suggestion button? g:link, input button not seem fit. action want call "myaction" , controller has 'myaction' "mycontroller". in advance. g:remotelink best solution problem dude, call call jquery or javascript function upon success of action, here addedcart javascript function ,after action gets executed successfully <g:remotelink action="remotecart" onsuccess="addedcart()" id="${product.id}"> <img src="<g:resource dir="images" file="cart.gif"/> " rel="#mies1"/> </g:remotelink> ref : grails doc

eclipse - How do I reference an specific hard drive on Windows? -

i'm trying configure egit on portable eclipse app. needed install portablegit on usb drive well. after i'm trying reference system setting eclipse's preferences. way can manage set 'g:\programs\portablegit-1.7.10-preview20120409\etc\gitconfig' the problem when use on different system usb might not in g:. perhaps there way determine windows' drives names uuid or else, know it? alternatively use relative path. assuming eclipse in 'g:\programs\eclipse-sdk-3.7.2-win32\eclipse\eclipse.exe' should work '..\..\portablegit-1.7.10-preview20120409\etc\gitconfig', right? turns out doesn't. sets full path. i'm pretty lost here. why not simple /media/usbdrive? you launch eclipse drive using script sets path git executable in it. eclipse find git on startup , deduce $prefix that.

Strange error with text file editing in Python -

i'm using text file store weight of neural network i'm making, i'm having serious trouble editing weights stored in text field. essentially, making file regular format: word + \t + weight + \n, use follow code run through text file , grab parts: with open(neuron_file, 'r+') original_neurons: neuron in original_neurons: word_stem = re.sub(r'^([a-z-]*)([\t]?)([0-9.]*)(\n)$', r'\1', neuron) weight = float(re.sub(r'^([a-z-]*)([\t]?)([0-9.]*)(\n)$', r'\3', neuron)) which working, able change value of weight, , write same text file in same place. have managed create new file modified in way like, having strange problem writing original file. using below code it: def replace(new_file, old_file): line in open(new_file): open(old_file, 'w').write(str(line)) but reason function breaks @ point in file. first 80% transfers fine, cuts file off @ seemingly random point in m...

java - SWT How to print contents of a scrolledComposite? -

Image
does know how print contents of scrolled composite? whenver print onto gc copy viewable area of scrolled composite. want able copy entire contents of scrolled composite. for instance, code below makes huge button, inside of little window. whenver print gc below, output small viewable area of scrolled composite. possible print in scrolled composite? shell shell = new shell(getdisplay()); shell.setlayout(new filllayout()); shell.setsize(200, 200); shell.setlocation(20, 20); scrolledcomposite sc = new scrolledcomposite(shell, swt.h_scroll| swt.v_scroll); sc.setminsize(availwidth, availheight + 30); button b = new button(sc, swt.push); b.settext("button"); b.setsize(availwidth, availheight); sc.setcontent(b); image image = new image(getdisplay(), availwidth, availheight); gc imagegc = new gc(image); sc.print(imagegc); note >>> see @cryptdemon comments below. though solution known work on windows 7 , eclipse 3.7.x release. yes possible. prob...

iphone - check if UIView is in UIScrollView visible state -

what easiest , elegant way check if uiview visible on current uiscrollview's contentview? there 2 ways this, 1 involving contentoffset.y position of uiscrollview , other way convert rect area? if you're trying work out if view has been scrolled on screen, try this: cgrect theposition = myview.frame; cgrect container = cgrectmake(scrollview.contentoffset.x, scrollview.contentoffset.y, scrollview.frame.size.width, scrollview.frame.size.height); if(cgrectintersectsrect(theposition, container)) { // view has been scrolled on screen }

git installation needed on remote server which is access via ssh only -

i'm trying access remote machine server machine not contain git installation. question is: server machine need git installation in kind (i assume needs) work client via ssh git? yes need git on server without git on server, can't push/pull remote. protocol use act remotely on git repo, doesn't change this. poor mans git you can if need/want rsync .git directory remote server. because files in .git/objects directory based on hash, won't collisions. that mean in principle: # git push rsync -rv .git server:repo.git # git pull rsync -rv server:repo.git .git git reset head --hard # here lies problem technique.

c# - Multiple Filters not working in DataGrid WPF -

my databinding works fine in datagrid, when try collectionview collectionviewsource, null, , filter in datagrid not work. here code: <window.resources> <collectionviewsource x:key="jobitemviewsource" d:designsource="{d:designinstance my:jobitem, createlist=true}"/> </window.resources> <grid visibility="visible" showgridlines="false" uselayoutrounding="true" datacontext="{staticresource jobitemviewsource}"> <datagrid grid.row="4" grid.columnspan="6" loadingrow="jobitemdatagrid_loadingrow" itemssource="{binding}" name="jobitemdatagrid" rowdetailsvisibilitymode="visiblewhenselected" isreadonly="true" issynchronizedwithcurrentitem="true" autogeneratecolumns="false" grid.rowspan="2"> <datagrid.columns> <datagridtextcolumn x:name="work...

swing - Java GUI programmming -

code gives error of nullpointer exception.....wat do? import java.awt.event.*; import javax.swing.*; public class gui implements actionlistener{ jbutton button; public gui(){ jframe frame=new jframe(); jbutton button =new jbutton("click me!"); button.addactionlistener(this); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().add(button); frame.setsize(270,300); frame.setvisible(true); } public static void main(string[] args){ new gui(); } public void actionperformed(actionevent e){ button.settext("i've been clicked"); } } jbutton button =new jbutton this creates local variable. button field still null .

Cannot read property 'style' of null - in Chrome's Javascript Console -

i checking js console out , helped me fix few minor issues, know if warning worry about? this code gives error: <script type="text/javascript" src="https://www.safaviehhome.com/product_images/locations/js/jqgalscroll.js"></script> <script src="https://www.safaviehhome.com/product_images/mainnav/stuhover.js" type="text/javascript"></script> <script> function layersetup(id,visibility){ if(document.getelementbyid){ this.obj = document.getelementbyid(id).style; uncaught typeerror: cannot read property 'style' of null uncaught typeerror: cannot read property 'style' of null <!--includes many more of same "cannot read property 'style' of null messages --> this.obj.visibility = visibility; return this.obj;} else if(document.all){ this.obj = document.all[id].style; this.obj.visibility = visibility; return this.obj;} else if(document.layers){ this.obj = document.layers[i...

multithreading - ruby: waiting for a thread to release a resource -

i'm using ruby 1.9.3. have long-lived thread picks jobs queue. thread uses mutex protect critical section thread processing job. let's job data contains field item_id . the main thread receives job details external source, including item_id , , enqueues jobs onto queue. it's possible main thread receive same item_id multiple times in different jobs. the main thread has access thread's mutex , current job's item_id . my goal prevent main thread enqueuing job item_id on queue, or being processed thread. if situation happens, main thread should block until item_id processed. main thread should block in situation, or when waiting external jobs. want avoid busy-waiting. i tried using conditionvariable , doesn't work because main thread may call wait after worker calls signal upon concluding processing. causes deadlock because signal never called on conditionvariable again. edit: i'm going simplify problem. care if incoming item_id being hand...

delphi - Get list of required BPLs for a given DLL, EXE or BPL -

i'm wondering if knows of elegant way of determining bpls required given ( compiled ) dll, exe or bpl. i'm not sure if possible shy of scanning binary text references .bpl filenames ( which prone possible false-positives ). ideally i'd return tstringlist or comma-separated string containing names of required .bpl files. for packages can use requires section of packageinfo resource - see tjclpepackageinfo.

php - HTTP-Authentication with .htpasswd file -

php offers possibility use http-authentication . however, difficult use .htpasswd-files. there scripts check .htpasswd file within php (for example this one ). however, these scripts quite complex , of them don't support relevant encryption types (like md5 default used program htpasswd ). with standard .htaccess file easier (just authuserfile <.htpasswd-file> needed). however, avoid explicit .htaccess file , use php instead. is there easy way check .htpasswd-file using php? can php perhaps "ask" apache if access should granted? i doubt there direct way ask apache authenticating user, there few workarounds it: implement missing algos yourself: apr1-md5 , sha use shell_exec("htpasswd -nb $user $password") generate hash , check in .htpasswd file setup virtual server on internal interface uses .htpasswd file authenticate , perform curl call (with user credentials) it, checking response header (200 authorized, 4xx not authorized) ...

php - PHPExcel gets wrong timezone even after setting date_default_timezone_set -

i'm using http://phpexcel.codeplex.com in 1 of project, , have come issue. want write time() value inside cell, doing : function writetimeline($objactivesheet, &$linenumber, $timestart, $timeend, $duration, $category, $client, $date, $comment) { $objactivesheet->setcellvalue('a'.$linenumber, phpexcel_shared_date::phptoexcel( $timestart )); $objactivesheet->getstyle('a'.$linenumber)->getnumberformat()->setformatcode(phpexcel_style_numberformat::format_date_time4); } the $objactivesheet refers $objphpexcel->getactivesheet() and result in excel is: 20:27:39 when in real on computer i'm testing it's 16:27:39 so it's issue timezone (i'm living in eastern america -4). however, i'm including phpexcel files after setting default timezone with date_default_timezone_set('america/new_york'); and echo of time() see correct hour (16:27:39). is bug of phpexcel or doing wrong here? thanks help. ...

ruby - irb not starting -

i'm running ruby 1.9.2 w/ rbenv. moved users directory different drive. ruby , irb show using which . $ ruby /volumes/pig/users/arrow/.rbenv/shims/ruby $ irb /volumes/pig/users/arrow/.rbenv/shims/irb however, running irb hangs indefinitely. i've been running ruby files under current config executing $ ruby -v hangs. rbenv rehash can solve these sort of problems. anytime modify ruby installation need rerun command let rbenv rebuilt soft-links. from command-line output: rehash rehash rbenv shims (run after installing binaries) you might need tell rbenv binaries again, i.e., rbenv global 1.9.2... , let adjust things. remember, rbenv assumed binaries on different volume might have gotten confused , needed straighten out. the other issue ruby bound files on other volume @ compile time (because that's rbenv does, compiles ruby you) when files couldn't found apps crashed. reinstalling rbenv fix that, telling reinstall particular ruby sho...

delphi - if else statement not executing right -

i have funny behaviour of if else statement. @ start memo empty , attempted deletion triggers message. if write in memo , try delete, again right message comes up. then, after last deletion (memo empty) if click once again delete second message , not first (nothing delete. messing if else statements ?? right way here ? procedure tform1.advglowbutton2click(sender: tobject); begin if advmemo1.isempty showmessage('nothing delete !') else begin if messagedlg('delete everything?', mtconfirmation, [mbyes, mbno], 0) = mryes begin advmemo1.lines.clear; advmemo1.lines.savetofile(extractfilepath(application.exename)+ '\memo.txt'); end; end; end; there nothing wrong code showed, isempty must returning false after last delete instead of returning true, suggests either 1) not deleted thought, or 2) isempty buggy.

JavaScript array sort-function for both numeric and alphanumeric string -

i need sort array looks this: var array = new array();<br /> array[0]="201206031245 firstitem";<br /> array[1]="201206020800 seconditem";<br /> array[2]="201206040604 itemthree";<br /> array[3]="201206031345 lastitem";<br /> how sort numerically , descending? thanks in advance! although .sort() default alphanumeric sort, data work numerically because array elements start numbers follow strict date/time format same number of digits. .sort() sort ascending though. provide own comparison function sort descending , or reverse results: array.sort().reverse() for more information how .sort() works, e.g., provide own comparison function, have @ the documentation .

mysql - PHP get data from database, and use it outside while loop -

<?php $q=select * students (dynamic user searching) $qry=mysql_fetch_array($q); while($row=mysql_fetch_array()) { **// not need data here?** } ?> < table> < tr>< td><?php echo **$row[?][?];** ?>< /td>< td><?php echo **$row[?][?];** ?>< /td>...< /tr> < tr>< td><?php echo **$row[?][?];** ?>< /td>< td><?php echo **$row[?][?];** ?>< /td>...< /tr> .... < /table> in need generate dynamic report in html table format html table rows , columns static results cant use echo in while loop have access out side while loop have idea of selecting single row single column each cell of table separatly time consuming , length alternative or solution? you don't have use while loop. can fetch data need it. $row1 = mysql_fetch_array($qry); $row2 = mysql_fetch_array($qry); i don't doing though because have keep track of resource ...

osx - svn: XML data was not well-formed -

i've been having bit of problem subversion on mac running lion. anytime try checkout repository error: svn: xml data not well-formed any advice? thanks in advance! p.s. have close none experience subversion. yes have faced lot of problem due strange error. seems when svn has conflicting auth data in existing .ssh folder gets error.

Cannot allocate memory error in Rails (when creating folder locally) -

i have rails app gives me error once in while: errno::enomem error coming function: def create_folder new_dir = self.id.to_s working_dir = '/home/user/files/' # line causing error: %x[cd #{working_dir} && mkdir #{new_dir}] working_dir = working_dir + new_dir + '/' self.working_dir = working_dir self.save! this error happening controller, upon creation of model calls above mentioned function... would grateful if points out how deal it.. i cannot see pattern in why happens or when.. just record. error went away moment started using ruby's dir. so %x[mkdir nnn] # bad dir.mkdir("bbb") # good.

graphics - how to read in a texture picture into opengl -

what easiest format read texture opengl? there tutorials -good tutorials, loading image formats jpg, png, or raw array can used texture mapping (preferably without use of library libpng)? opengl not knows nothing common image formats (other natively supported s3tc/dxt compressed , alikes, different story). need expand source images rgba arrays. number of formats , combinations supported. need choose 1 suits you, e.g. gl_alpha4 masks, gl_rgb5_a1 1bit transparency, gl_bgra/gl_rgba fullcolor, etc. for me easiest (not fastest) way pngs, lossless compression , full alpha support. read png , write rgba values array hand on opengl texture creation. if don't need alpha may accept jpg or bmp. pipeline common source -> expanded rgba array -> opengl texture.

java - Where to start in building an app/system that compresses and decompresses a file -

i'm developing application in java/android allows user compress , decompress files. @ first, started study file size such as: 1byte = 8bits 1kb = 1024byte 1mb = 1024kb 1gb = 1024mb 1tb = 1024gb 1pb = 1024tb 1eb = 1024pb 1zb = 1024eb 1yb = 1024zb after studied this, studied , read articles on net , found out there 2 types of file compression (correct me if i'm wrong): lossless , lossy. lossless compression means file compressed smaller bit without losing single file while lossy compression means important files being removed while compressing file. i read compression(run-length coding method) this: aaabbccdffffeeeeh to this: 3a2b2cd4f4eh which gives me idea on how compressing/decompressing works on file. i searched net there api compressing file on java(also applicable on android) is java.util.zip i tried codes on compressing , decompressing file various helpful websites/forum/etc (including stackoverflow.com) gives me experience study. i read algorit...

Getting the admin site to work in Django Project -

i trying admin site work django project. following tutorial https://docs.djangoproject.com/en/1.4/intro/tutorial02/ , using django 1.4. urls.py: from django.conf.urls import patterns, include, url # uncomment next 2 lines enable admin: django.contrib import admin admin.autodiscover() urlpatterns = patterns('', (r'^$', include('polls.urls')), # examples: # url(r'^$', 'blog.views.home', name='home'), # url(r'^blog/', include('blog.foo.urls')), # uncomment admin/doc line below enable admin documentation: #url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # uncomment next line enable admin: url(r'^admin/', include(admin.site.urls)), ) the settings.py is: databases = { 'default': { 'engine': 'django.db.backends.sqlite3', # add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle...

twitter bootstrap - How can I avoid using too many classes in CSS? -

i using bootstrap css framework. want create table has many styles. code this: <table id="mytable" class="table table-bordered table-striped table-condensed"> .... </table> how can avoid using many classes (table table-bordered table-striped table-condensed) here? can css oo extend? mean define class named mytable , can have many predefined styles. dummy code: table.mytable{ have_class: table table-bordered table-striped table-condensed; } i'm not quite sure mean. want use classes when have to, , target element first. if it's not possible .class element add class. remember, can target more putting space , adding class/id/element. more add, more specific becomes. examples table #mytable tr #mytable tr.first #mytable .odd a also, if problem pre-defined twitter bootstrap classes, problem using grid/styled boilerplate. it's not lightweight or lean stretch of imagination. twitter bootstrap getting things quick...

how should i reference a php file from an external javascript file -

so general question: if have file structure have index page in root folder along scripts folder, , in scripts folder there 2 scripts 1 js referenced in index page, , other php referenced js script: root-folder: --> index.html --> scripts/ -----> myscript.js -----> myscript.php how should access php script js script using relative url? would be: ./myscript.php or ./scripts/myscript.php in other words relative url index file or js file. thanks! since javascript operating in scope of page, not physical location, url php include /scripts/ in path name.

magento - google analytic prolem with event and customvar -

i have problem google analytic . here code : <script> function trackregister() { if(dataform.validator.validate()) { _gaq.push(["_setcustomvar",4,"type","besogende-med-konto",1]); _gaq.push(['_trackevent', 'activatevisitorprofiletracking', 'activatevisitorprofiletracking']); _gaq.push(['_trackevent', 'konto-oprettet', 'engage', 'personlig-konto-oprettet']); } } i call trackregister function when click submit button page redirect result page ,but receive activatevisitorprofiletracking event on google analytic report. don't know why .anyone can me? thank :d based on description of how calling it, sounds maybe page being redirected before 2nd _trackevent call has chance execute. try wrapping redirect in settimeout , or wrapping ga code code detect status of ga calls , redirect when returns complete

python - SQLAlchemy declarative property from join (single attribute, not whole object) -

i wish create mapped attribute of object populated table. using sqlalchemy documentation example, wish make user_name field exist on address class such can both queried , accessed (without second round trip database) for example, wish able query , filter user_name address.query.filter(address.user_name == 'wcdolphin').first() , access user_name attribute of address objects, without performance penalty, , have persist writes expected of attribute in __tablename__ class user(base): __tablename__ = 'users' id = column(integer, primary_key=true) name = column(string(50)) addresses = relation("address", backref="user") class address(base): __tablename__ = 'addresses' id = column(integer, primary_key=true) email = column(string(50)) user_name = column(integer, foreignkey('users.name'))#this line wrong how do this? i found documentation relatively difficult understand, did not seem conform ...

Mysql transactions issue -

in straight mysql script i'd transactions this: start transaction; select @a:=sum(salary) table1 type=1; update table2 set summary=@a type=1; commit; i'm little confused how transactions work in pdo. looks there begintransaction() , commit() methods - i'm not sure these convenience wrappers around staright sql? or doing more job behind doors? in other words - these examples below same? example 1: $dbh->exec( 'start transaction' ); //...do db work here... $dbh->exec( "commit" ); example 2: $dbh->begintransaction(); //...do db work here... $dbh->commit(); functionality wise both same, begintransaction() , commit() pdo functions ensures compatibility database , there might database may give error @ start transaction pdo methods work.

How do I sync content types, taxonomy, menus among in a drupal multisite environment? -

i have drupal 7 multisite setup. example have site1.com , site2.com. manually created new content type site1.com (let's call 'books') , sync/share site2.com without having manually recreate 'books' in site2.com. how achieve this? thank feedback. use features , exports content type code can export between sites.

facebook - Canvas demo (runwithfriends) always redirects to main page under my own GAE -

Image
i'm using runwithfriends example app learn canvas programming , gae. can upload sample code gae without errors. here config.py , app.yaml files: conf.py: # facebook application id , secret. facebook_app_id = '' facebook_app_secret = '' # canvas page name. facebook_canvas_name = 'blah' # random token use real-time api. facebook_realtime_verify_token = 'random token' # external url application available @ real-time api # send it's pings. external_href = 'http://blah.appspot.com' # facebook user ids of admins. poor mans admin system. admin_user_ids = [''] app.yaml application: blah version: 1 runtime: python api_version: 1 handlers: - url: /(.*\.(html|css|js|gif|jpg|png|ico)) static_files: static/\1 upload: static/.* expiration: "1d" - url: .* script: main.py - url: /task/.* script: main.py login: admin accessing demo app on gae works fine. when take exact same code , except changes need ru...

c++ - Rcpp: neat way to compare strings derived from an R data frame? -

having headaches in rcpp handling strings, have looked @ "how test rcpp::charactervector elements equality" situation bit more complex that. to illustrate, suppose have 200-row data frame of names , marks, generated randomly: df = data.frame(name = paste("person", sample(letters[1:10],200,rep=true),sep=""), mark = pmax(pmin(round(rnorm(200,60,15)),100),0), stringsasfactors=false) i found following inline code (using rcpp) correctly works out sum of marks rows person named first person given in data frame (i.e. df$name[1] in r, or equivalently name[0] in rcpp code): library(inline) fastfunc_good1 <- cxxfunction( signature(dfin = "data.frame"), plugin = "rcpp", body = ' rcpp::dataframe df(dfin); rcpp::charactervector name = df["name"]; rcpp::integervector mark = df["mark"]; rcpp::charactervecto...

Magento Admin > System > Configuration > Advanced > System - Fatal Error -

i error when try access system > configuration > advanced > system fatal error: call member function tooptionarray() on non-object in /home/server/public_html/store/app/code/core/mage/adminhtml/block/system/config/form.php on line 421 i found answer: fatal error: call member function tooptionarray() however, code needs replaced according answer different code in file (form.php): if ($method) { if ($fieldtype == 'multiselect') { $optionarray = $sourcemodel->$method(); } else { $optionarray = array(); foreach ($sourcemodel->$method() $value => $label) { $optionarray[] = array('label' => $label, 'value' => $value); } } } else { $optionarray = $sourcemodel->tooptionarray($fieldtype == 'multiselect'); } $field-...

How to Tell iOS Paypal Mobile Payment Library Version? -

i'm referencing demo against library have , there seem differences. want make sure i'm not working deprecated or outdated. the header file each in paypal.h says: // // paypal.h // // mpl library - developer interface // // created paypal 2010 // modified by: // dizoglio, james(jdizoglio) on 5/10/11. // // copyright 2011 paypal. rights reserved. // // in particular, i'm noticing library has: +(paypal*)getinstance; while demo has: +(paypal*)getpaypalinst; i guess question paypal, , in particular james dizoglio, appreciate has integrated ios app can offer. thanks. you magic of cocoa's " respondstoselector: " method see if paypal library responds " getinstance " or " getpaypalinst " api's. and in meantime, file bug or send message developer support @ paypal see if can them resolve confusion.

How to display the images from server asynchronously in Android? -

i displaying image server in android. have gone through tutorial android load image url example . helpful. taking 5 minutes display image server. want display image asynchronously. how can that? try example's link in lazy loading .

sql server 2005 - Inserting Column From Into Another Table Trough Query -

Image
how update range field of of table below (don't mind '1' values range above, it's supposed null ) with range values of table below when inner join table other on equipmentcode values doubled this: this query used: select c.*, r.range rangefromothertable equipmentcalibrationref c inner join range r on r.equipmentcode = c.equipmentcode as start, can use following statement pseudo 1 1 match select ecr.*, r.[range] equipmentcalibrationref ecr inner join ( select refno = row_number() on (partition equipmentcode order [range]), * [range] r ) r on r.refno = ecr.refno , r.equipmentcode = c.equipmentcode

java - Eclipse Helios 3.6.1 debug view evaluate expression is not available -

Image
i debugging junit test , @ point expression evaluation ( ctrl+shift+i ) became unavailable. i starting debug session using java perspective -> package explorer view r. click on project root , choosing "debug -> junit". in debug view when try ctrl+shift+i on variable or expression getting following message: the variables view shows values properly. ctrl+shift+i , display view react same error. log file in workspace metadata directory not show related errors (all messages there outd-dated relative current debug session). i using eclipse helios 3.6.1. restaring ide did not situation. any idea how fix annoying problem? i not know 1 helped fix issue in case posting below voodoo things have done fix problem. hopefully, find 1 of them useful. ‘clean’ eclipse project: go project > clean in eclipse refresh project folder (right click on project > refresh) re-build project clean builds (if using ant or maven – clean builds) ‘switch’ worksp...

asp.net - Jquery Datepicker is not working after page load -

i'm using datepicker plugin 2 textboxes on aspx page. when click on submit, data saved in database, if again try update date, datepicker don't work after page load. i'm using following code this. <asp:textbox id="txtmovingdate" runat="server" cssclass="textbox datepicker" tabindex="19"></asp:textbox> jquery(function() { jquery(".datepicker").datepicker( { dateformat: 'mm/dd/yy', timeformat: ' hh:ii:ss', changemonth: true, changeyear: true }); please me. thank you. var prm = sys.webforms.pagerequestmanager.getinstance(); prm.add_endrequest(function() { //you need duplicate jquery datapicker function here //in order use after post });

audio - Notification sound not playing in J2ME -

i working on j2me application. using nokia 6131 nfc phone. using netbeans ide. have 4 forms , playing notification sounds user while filling form. the problem sound goes off after 3 4 min , solution exit application , again open it. my code public void playsoundok() { try { inputstream = getclass().getresourceasstream("/ok.wav"); player player = manager.createplayer(is,"audio/x-wav"); player.realize(); player.prefetch(); player.start(); } catch(exception e) { e.printstacktrace(); } } exception at com.nokia.mid.impl.isa.mmedia.audio.audiooutimpl.opensession(audiooutimpl.java:206) @ com.nokia.mid.impl.isa.mmedia.mediaout.opendatasession(mediaout.java:282) @ com.nokia.mid.impl.isa.mmedia.mediaplayer.doprefetch(mediaplayer.java:155) @ com.nokia.mid.impl.isa.amms.audio.advancedsampledplayer.doprefetch(+4) @ com.nokia.mid.impl.isa.mm...

java - Multiple ArrayList with 10 records using iterator and ArrayList -

mutliple arraylist<> 10 records. have used limiting upto 10 results , how next 10 results , on. try { arraylist<calanderqueryoutput> results = new arraylist<calanderqueryoutput>(); list<?> eventstoday = (list<?>) filter.filter(calendar.getcomponents(component.vevent)); calanderqueryoutput caldavoutput = new calanderqueryoutput(); (iterator<?> = eventstoday.iterator(); i.hasnext();) { if(limit < rslimit){ results.add(caldavoutput); limit++; } } } first of need other data strcuture store multiple arraylists, can use list of list list<list<calanderqueryoutput>> resultlist = new arraylist<list<calanderqueryoutput>>(); list<calanderqueryoutput> results = new arraylist<calanderqueryoutput>(); (iterator<?> = eventstoday.iterator(); i.hasnext();) { if(limit < rslimit){ results.add(caldavoutput); limit++; }else{ resultlist.add(results); limit = 0; ...

utf 8 - Delphi XE, Firebird and UTF8 -

i'm upgrading d7 program xe, , under delphi 7 had code this... parambyname ('somefield').asstring:=someutf8rawbytestring; under xe if someutf8rawbytestring contains unicode characters such cyrillic script, appear ???? in db. i see someutf8rawbytestring 8 characters long, 4 character string, correct. in db there 4 characters. i'm using firebird 2 through tibquery xe , updating varchar field character type 'none'. so looks utf8 being detected , converted somehow unicode data points, , failing string conversion db. i've tried setting varchar field utf8 encoding same result. so how should handled? edit: can use database tool , edit db field have non-ascii data , when read comes utf8 encoded string can use utf8decode on , it's correct. writing data field seems impossible without getting bunch of ???? in db. i've tried parambyname ('somefield').asstring:=somewidestring; , parambyname ('somefield').aswidestring:=somewidest...