Posts

Showing posts from June, 2011

python - Save ascii as clear string into txt file -

my code: f = open("log.txt", "a") key = chr(event.ascii) f.write(key) f.closed if print key out. nice readable form "a" "b" "c" , on. if file python has saved ascii - that: 0013 0200 4461 i tried convert errors. knows whats wrong here? i think need f.close() not f.closed . also, putting key code in key. if want read single char, use: sys.stdin.read(1) (see: https://stackoverflow.com/a/510404/103081 ) putting together: import sys f = open("log.txt", "a") key = sys.stdin.read(1) f.write(key) f.close() this should fine homework problem or learning python on own. writing keylogger steal password , credit card numbers, though, useless because return must hit input.

Evaluating polynomials - floating point or optimization issue? -

from numerical recipes: we assume know enough never evaluate polynomial way: p=c[0]+c[1]*x+c[2]*x*x+c[3]*x*x*x+c[4]*x*x*x*x; ... obviously don't know enough... is optimization issue or floating point arithmetic issue , why? you can compute p=c[0]+c[1]*x+c[2]*x*x+c[3]*x*x*x+c[4]*x*x*x*x; as: p=c[0]+(c[1]+(c[2]+(c[3]+c[4]*x)*x)*x)*x; there fewer multiplications in second form. second form called “horner's”. is optimization issue or floating point arithmetic issue , why? it optimization issue. however, modern processors have floating-point operation multiplication , addition in single instruction without intermediate rounding multiplication, , while benefit programmers see still optimization, means result more accurate. horner's form well-adapted computation fused-multiply-add instruction . finally, should point out sake of completeness modern processors can more efficient if polynomial presented them in form more parallelism. see

java - Iterable: may iterator() returns null in case there is nothing to iterate over? -

an object implementing iterable interface must have method signature: iterator<t> iterator() o being iterable , code safe? while(o.iterator().hasnext()) { ... } in other terms, may iterator() returns null in case there nothing iterate over? edit: 1- of point out, iterator returned different each time o.iterator() executed. fair enough! must agree had forgotten point when writing question. let's line rewritten: iterator<string> = o.iterator(); .... .... while(it.hasnext() {...} 2- of point out, bad programming practice return null when documentation iterable.iterator() says: "returns iterator on set of elements of type t." however question whether returning null prevented directly or indirectly 'contract' in java api documentation. me "returns iterator on set of elements of type t" doesn't prevent returning null. may wrong. conclusion answers , additional research overall: java api has no mean if iterator valu

windows - Why won't portions of the code from this batch file execute. Please explain the GOTO function -

i playing around bit batch files , having problems. according 1 website: to exit batch script file or exit subroutine specify goto:eof transfer control end of current batch file or end of current subroutine . so, definition in mind, why won't portions of these 2 codes execute: first one: :loop echo in loop. goto:eof echo hello goto loop echo finish pause the thing prints is: in loop. nothing else prints. second one: echo hello goto loop echo finish pause :loop echo in loop goto:eof echo finish not print. why? also, can briefly state what's difference between goto use , subroutines? thanks update: while searching on google else, found this: using call labels in batch script guess answers question, i still elaboration please , such as 1) when use goto , when use call? (which suppose related question above differences between subroutines , goto) 2) first code, why sentence: "i in loop." print / echoed, when never called up

python - IDLE closing when I try to run Pygame -

idle keeps closing whenever try run code.i've uninstalled idle , installed again twice now. i've tested other python files sure isn't problem in code. i opened python command line, wrote idlelib import idle, opened python file , tried running , got this: exception in tkinter callback traceback (most recent call last): file "c:\python34\lib\tkinter\__init__.py", line 1487, in __call__ return self.func(*args) file "c:\python34\lib\idlelib\multicall.py", line 179, in handler r = l[i](event) file "c:\python34\lib\idlelib\scriptbinding.py", line 127, in run_module_event return self._run_module_event(event) file "c:\python34\lib\idlelib\scriptbinding.py", line 141, in _run_module_event code = self.checksyntax(filename) file "c:\python34\lib\idlelib\scriptbinding.py", line 102, in checksyntax return compile(source, filename, "exec") typeerror: source code string cannot contain null

c++ - Replacing IF statement (random condition) with boolean logic- execution time identical? -

(setup: win 7 64, msvc, 3rd generation core i7, 64-bit compliation, -o2 enabled) the below code has 3 functions- 1 has if statement executes different code depending on whether condition has been met. replaced if statement boolean logic. timings identical.... expecting lack of branch prediction yield faster code: #include <iostream> unsigned long long iterations = 1000000000; void test1(){ volatile int c = 0; for(int i=0; i<iterations; i++){ bool condition = __rdtsc() % 2 == 0; if(condition){ c = 4; } else{ c = 5; } } } void test2(){ volatile int c = 0; for(int i=0; i<iterations; i++){ bool condition = __rdtsc() % 2 == 0; c = (4 * condition) + (5 * !condition); } } int main(){ unsigned long long s = 0; unsigned long long f = 0; unsigned long long s2 = 0; unsigned long long f2 = 0; unsigned int x = 0; unsigned int y = 0; start = _

php - Globally accessible user object in controllers and models -

i'm building laravel api authenticates users using authentication token. routes need authentication, i'm wrapping them in auth filter: route::group(array('before' => 'auth'), function() { route::get('user/account', 'usercontroller@getaccountdetails'); }); my auth filter decrypts passed in authentication token , checks if it's valid: route::filter('auth', function() { // try catch because crypt::decrypt throws exception if it's not valid string decrypt try { $authtoken = crypt::decrypt(request::header('authorization')); // if there's user tied auth token, it's valid $user = authtoken::where('token', '=', $authtoken)->first()->user()->first(); if (!$user) { throw new \exception(); } // make user globally accessible in controllers } catch (\exception $e) { return response::json([

php - Should an object being created by a factory method accept constructor arguments? -

i'm using factory pattern create users i'm having problem constructor issue. i have following factory: class userfactory { public function factorymethod(user $user_type) { $user = new $user_type($db); return $user; } } i instantiate class follows: $user = new userfactory(); $user = $user->factorymethod(new admin()); the issue is, need pass $db parameter new admin() call can't find way of doing or if it's possible. have overlooked simple or not possible?

javascript - Rails VideoJS swf-Flash-Fallback asset_path -

i trying embed videojs in rails-app, works fine long don't have use flash-fallback, e.g. in firefox. hosting videojs locally. here have far in javascript: videojs.options.techorder = ['flash']; videojs.options.flash.swf = "#{asset_path(video-js/video-js.swf)}"; i using techorder force flash time beeing. if open page in firefox get http://localhost:3000/path/to/site/videos#{asset_path(video-js/video-js.swf)} the error message, video not supported disappears , playbutton appears. leads me belive, flashplugin not loaded (especially since think not right). hint error is, appreciated. you can try use gem js_assets in application.js //= require app_assets this directive adds method asset_path in global scope. add filter files *.swf . this, add initizlizer: # config/initializers/js_assets.rb jsassets::list.allow << '*.swf' to path file video-js.swf depending on environment videojs.options.flash.swf = asset_path("vi

javascript - How can I output the values in an array to a View in MVC with Razor? -

task output values ienumerable of simple types in view. conditions i have model, passed in controller, contains array of simple values (in case int). want output variable in javascript block in view. standards without using large foreach block , iterating on each item , figuring out commas, output values in such way similar statement seen below. example var packagesummaryviewmodel = new packagesummaryviewmodel([1,2,3,4,5,6,7]); currently happening: view.cshtml var packagesummaryviewmodel = new packagesummaryviewmodel(@sensorids); output var packagesummaryviewmodel = new packagesummaryviewmodel(system.int32[]); the way use json serializer, json.net. json stands javascript object notation, it's natural use json serializer convert c#/.net objects javascript objects. @using newtonsoft.json @model mynamespace.myobject var myproperty = @html.raw(jsonconvert.serializeobject(model.myproperty)); if model.myproperty list<int> containing inte

php - Open a hidden JavaScript form when linked from a different page -

i don't know if there answer question, i'll try explain , hope smart enough me :). all right: for school have website can log in , register etc. on index there log in , register form included, hidden javascript. pressing button you'll able login or register (one of forms appear). problem: i'm checking register form php on different page, , errors outputted in form on page. but, when go register/login page, hidden, ofcourse, , input gone user , have retype everything. <? if(isset($_post['example'])){echo htmlentities ($_post['example']);} ?> in form doesn't work anymore. putting code other page in index doesn't seem option. thanks in advance response, paul edit - i'll post code make clearer. javascript hide , toggle: '$(document).ready(function(){ $("#login").hide(); $("#registerincl").hide(); $("#loginb").click(function(){

android - How can I use OnListItemClickListener using this Search Filtering ListView -

i'm having trouble using setonitemclicklistener in listview. everytime try, causes many errors fixes makes code worse i'm intending do. this code: public class search extends activity{ // list view private listview lv; // listview adapter arrayadapter<string> adapter; // search edittext edittext inputsearch; // arraylist listview arraylist<hashmap<string, string>> productlist; @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_search); // listview data final string products[] = {"fill in blocks", "the music bee", "little paragon", "subway surfers", "cytus", "temple run", "clumsy ninja", "smash hit"}; lv = (listview) findviewbyid(r.id.list_view); inputsearch = (edittext) findviewbyid(r.id.inputsearch); // adding items listview adapter = new arrayadapter<string>(this, r.layout.list_ite

android - GreenDao is it possible to do a To-Many relation in only one direction? -

let's have ingredient entity, , recipe entity. lots of recipes might refer same ingredient. recipe 1 uses ingredients 1, 2 , 3 recipe 2 uses ingredients 1, 3 , 5 i want able load ingredients recipe, not reverse. i think need model many-to-many relation creating separate entity track recipe <-> ingredient mappings. is understanding correct, or there way make work tomany relation? i don't think using single tomany relation work, because greendao requires them have foreign key in target entity original entity (see "modelling to-many relations" in docs ). means ingredients can refer single recipe - 2 recipes reference same ingredient 1 of them lose relation. ftr, if don't set foreign key in target entity, tomany relation lost after restarting application (i.e. works current database session). tip: simulate scenario in automated tests, call daosession.clear() before loading object , asserting contains values expect. since 1 ingred

opengl - Transform feedback without a framebuffer? -

i'm interested in using vertex shader process buffer without producing rendered output. here's relevant snippet: gluseprogram(program); gluint tfoutputbuffer; glgenbuffers(1, &tfoutputbuffer); glbindbuffer(gl_array_buffer, tfoutputbuffer); glbufferdata(gl_array_buffer, sizeof(double)*4*3, null, gl_static_read); glenable(gl_rasterizer_discard_ext); glbindbufferbase(gl_transform_feedback_buffer, 0, tfoutputbuffer); glbegintransformfeedbackext(gl_triangles); glbindbuffer(gl_array_buffer, positionbuffer); glenablevertexattribarray(positionattribute); glvertexattribpointer(positionattribute, 4, gl_float, gl_false, sizeof(double)*4, 0); glbindbuffer(gl_element_array_buffer, elementbuffer); gldrawelements(gl_triangles, 1, gl_unsigned_int, 0); this works fine until gldrawelements() call, results in gl_invalid_framebuffer_operation . , glcheckframebufferstatusext(gl_framebuffer_ext); returns gl_framebuffer_undefined . i presume because gl context not have default

c# - how to update a form from a thread -

i using mod bus protocol retrieve data board. want update data in window form time. label update when click button, problem coding? private void call() { { requestdata(); //get data mod bus run(a.tostring()); } while (operation); } delegate void callmethod(string data); private void run(string data) { if (this.labelo2.invokerequired) { setrichboxcallback d = new setrichboxcallback(run); this.invoke(d, new object[] { data }); } else { labelo2.text = data; } } thread thread; private void button1_click(object sender, eventargs e) { thread = new thread(new threadstart(call)); thread.start(); } public void requestdata() { if (writeserialport(setmessage, 0, 8)) { thread.sleep(1000); (i = 0; < 19; i++) { mm[i] = (byte)serialpor

windows - ImmNotifyIME() with empty string? -

i have doubt on immnotifyime() function. immnotifyime(hwnd, ni_compositionstr, cps_cancel, 0); if created hwnd empty string. then, return? whether through error? immnotifyime takes handle input context , not hwnd. but, assuming meant himc himc = immgetcontext(hwnd); immnotifyime(immgetcontext(hwnd), ni_compositionstr, cps_cancel, 0); immreleasecontext(himc); then clear pending composition, if 1 open or not.

Google App Script - callback from Mail body -

i sending html form in body of mail button included , when button clicked saving reference in google spreadsheet. able code , not able worked.please me in fixing issue. //function send mail google app script function sendmail(e) { var subject = 'test'; var template = htmlservice.createhtmloutput('<form id = "myform" >' + '<label = "name"> name: </label>'+ '<input type = "text" id ="name" />'+ '</form>'+ '<button onclick = "submitdata()">save</button>' + '<script>' + 'function submitdata(){'+ 'var form = document.getelementbyid('+"myform"+');'+ 'google.script.run.withfailurehandler(alert).withsuccesshandler(alert).' + 'submitform(form);'+ '}'); var html = template.getcontent(); // email self recipient = session.getactiveuser().getemail

database - How can I see which button has been pressed in php? -

i'm quite new php might seem easy. have table called 'products' , each product in table want create button id of product. have no problem creating buttons can not see of buttons has been pressed. how can solve this? this code: $sql = "select id `products` subcategory = 'laptop' order id desc limit 1"; $query = mysql_query($sql); $id = mysql_result($query,0); for($i=1; $i<= $id; $i++){ $product2 = r::load('products', $i); echo "<input type='submit' name='$product2->id' value='add cart'/>"; } thank ! assign value button/input <input type="submit" name="btn" value="button1" /> <input type="submit" name="btn" value="button2" /> <input type="submit" name="btn" value="button3" /> <?php echo filter_input(input_post, 'btn'); ?> or <input type="s

Need to find Max Value in Liferay table using Service Builder -

i have built liferay portlet using service builder , has 1 table. 1 of fields holds double value called 'zvalue'. need add -localserviceimpl.java file public method return maximum value found in field 'zvalue'. hoping there liferay class similar dynamicquery instead returns single value. know can return records , cycle through them myself maximum value, i'm sure there simpler way max value. what have found in search of stackoverflow is: dynamicquery query = dynamicqueryfactoryutil.forclass(classname); query.setprojection(projectionfactoryutil.max("zvalue")); but didn't understand how return value dynamicquery returns list , not single value. in following example, query journalarticle table find articles match criteria, , newest version of each of (the max). as pankaj said, need create 2 dynamic queries. first 1 used specify need max returned: dynamicquery subquery = dynamicqueryfactoryutil.forclass(journalarticle.class, "ar

android - Why doesn't supportRequestWindowFeature() work? -

i have problem , i've been trying find mistake couple hours can't find it? my situation: don't want titlebar appears. device htc , runs android 2.3.3. tried supportrequestwindowfeature() somehow doesn't work. my code here: @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); supportrequestwindowfeature(window.feature_no_title); setcontentview(r.layout.activity_main); } also mainactivity extends actionbaractivity.

django - News feed using Celery and RabbitMQ -

i developing news feed backend multiple applications. idea user can subscribe multiple groups , receive posts groups subscribed via push. i thinking of: on creating new post have create_post_task(content) goes celery feed queue, celery workers can consume it. not sure should afterwards deliver posts clients, dynamically create new rabbitmq queue each group, , route posts respective queue, subscribed clients pushed posts queues? if so, how do after task consumed? having lot of rabbitmq/celery queues problem? suggestions on effective solution valuable.

javascript - How to make dropdown based one JSON, and selected parameter taken from another? -

so got js code, suppose make list of statuses in dropdown: $.getjson('/statuses', { ajax: 'true' }, function (data) { var html; var len = data.length; html += '<select id="status" class="form-control selectpicker" width="150" style="width: 150px">'; (var = 0; < len; i++) { html += '<option value="' + data[i].id + '">' + data[i].name + '</option>'; } html += '</select>'; $('#status').html(html); }); this part working, have make sure selected option equals other json. tried in other getjson: status += '<select id="status" class="form-control selectpicker" width="150" style="width: 150px">'; status += '<option value="' + data.status + '" selected="sele

mongodb - python mongoengine mapping to the existing collection -

i'm new mongo engine , having bit of trouble understanding how functions - documentation provided not straight forward. have collection in mongo each document has fields. mapped these fields fields in derived document class , referenced collection per alias. class imported_item(me.document): _id = me.objectidfield(required = true) _type = me.stringfield(max_length=10) _name = me.stringfield(max_length=10) def item_print(self): print ("************************************************") print self._id print self._type print self._name me.meta = { 'db_alias': 'test', 'index_background': true, 'indexes': [(_type, 1),(_name, 1)], } def main(): me.register_connection(alias="test", name=_database, host=_host, port=_port, username=_username, password=_password) print imported_item.objects({imported_item._type:'sm_tags'}) imported_item.item_p

linux - SyntaxError: invalid syntax Python 2.7 -

i newish programmer , can't seem figure 1 out. getting error on bit of code put in. note on linux (raspberry pi exact). direct = raw_input("\nplease give the directory or song ending file type \nex. /folder1/favoritesong.wav" #ftype - file type #ftype 1 - wav file #ftype 2 - mp3 file ftype11 = ".wav" in direct ftype12 = ".wav" in direct ftype21 = ".mp3" in direct ftype22 = ".mp3" in direct if ftype11 or ftype12 == true: if ftype11 == true: os.system("clear") print "does song sound fast, slow, or not playing @ all? check readme files." check1 = os.system("sudo ./pifm " + direct + " " + str(freq) + " 22050 stereo") print check1 elif ftype11 == false: if ftype12 == true: os.system("cle

bash - Linux X-Session Script -

okay, have strange issue. trying create x-session script automatically log remmina remote desktop, , return login screen when remote desktop disconnected. here script x-session calls: #! /bin/bash gnome-wm & sleep 10 exec remmina -c /home/user/.remmina/opi.remmina; logout this correctly connects requested remote desktop, when session logged out nothing happens, screen freezes, mouse works nothing active. if adjust script call firefox instead so: #! /bin/bash gnome-wm & sleep 10 exec firefox; logout it works expected. firefox loads, , when closed, returned login screen. ideas? do not use exec makes firefox take on of script: exec firefox must be: firefox

python - Converting Decimal to % -

so have looked @ post here: how show percentage in python , used solution. s = 'ftp' "{0:.0f}%".format(s.count('f') / 9 * 100) the desired output 11% , when run code using format specified "0%" instead of 11% want. push in right direction appreciated. if want show percentage, should use percent formatter directly: >>> '{:.0%}'.format(s.count('f') / 9) '11%' as others noted, python 2 use integer division if both arguments integers, can make constant float instead: >>> '{:.0%}'.format(s.count('f') / 9.) '11%'

database - Does MonetDB's code contain the X100(VectorWise) 's research? -

since x100 project has been commercialized actian/vectorwise company. wonder if it's technology remains in monetdb's code base. in paper 'monetdb: 2 decades of research in column-oriented database architectures', said both fundamental , high risk projects materialized within monetdb kernel , disseminated open source code rest of monetdb code family. mean rearch project have there code in monetdb code base? the open-source code base of monetdb disjoint action/vectorwise code base, despite fact many of x100 ideas inspired earlier versions of monetdb code base. action/vectorwise code further optimized vectorised (vulcano-style) execution , embedded in old ingres code base.

c++ - Retrieve the string “0.1” from after assignment to a double variable -

i have naive question high-precision number conversion (in c++ here). suppose user assigns 0.1 double variable x_d statement, x_d = 0.1 it known x_d obtained no more 0.1 , due inevitable machine rounding. i wonder whether still have way original highly precise string “0.1”, double variable x_d ? clearly, useless use std::to_string (x_d) here. high precision library boost::multiprecision or mpfr seem helpless. example, std::to_string(boost:cpp_dec_float_10000(x_d) ) cannot recover lost precision. so question is, can retrieve string “0.1” double x_d assigned using statement x_d = 0.1 ? let's assume during assignment, decimal number 0.1 rounded double value x not equal decimal number 0.1. now, assume other computation results in value x , without being rounded. in order distinguish two, have store origin somewhere. that, there no place in double (assuming common implementations), answer question "no".

Regex: How many strings start with letters and end with numbers? -

i'm trying write regex expression searches through text file bunch of names, phone numbers, emails, , garbage, find how many strings start letters , end numbers? line line searching. any help? know needs start believe. thanks. /^[a-z] here test using code provided 1 of you. http://i.imgur.com/frys50j.png ^[a-za-z]+.*[0-9]+$ here explanation: ^ .. @ start of paragraph [a-za-z]+ .. letter occurs @ least once, then .* .. character except line break or paragraph break occurs 0 n times [0-9]+ .. there @ least 1 number $ .. @ end of paragraph you can use online regex testing tool check if regex correct: http://www.myregextester.com/index.php and here list of regex expressions: https://help.libreoffice.org/common/list_of_regular_expressions

html - Why is the container div used in this particular way? I see it used like this all the time -

for simple use case example check out below: <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <title>a question stackflow community</title> <link rel="stylesheet" type="text/css" href="css/global.css"> </head> <body> <script src="../js/cool-awesome-jquery.min.js"></script> <div id="container"></div> <div id="call-to-action">dude need buy stuff!!</div> <div id="menu"> <button id="home">home</button> </div> <script>yada yada yada....</script> </body> </html> i know browsers offer native relationship container div, or @ least can. see use case alot in code, container div created closed. no special css

rest - Fixing broken pipe error in uWSGI with Python -

while hitting rest resource ( my_resource ) in python, uwsgi server throwing following error in log: sigpipe: writing closed pipe/socket/fd (probably client disconnected) on request my_resource (ip <my_ip>) !!! uwsgi_response_write_body_do(): broken pipe [core/writer.c line 164] ioerror: write error it seems related timeout (the client disconnected before request finish processing). what sort of timeout , how can fixed? it depends on frontend server. example nginx has uwsgi_read_timeout parameter. (generally set 60 seconds). uwsgi http router --http-timeout default 60 seconds , on. talking rest api quite doubtful requires more 60 seconds generate response, sure not have wrong response header triggering connection close frontend webserver ?

javascript - Highcharts - Reverse order of negative stacked series -

is there way reverse order of negative stacked bars? i using highcharts render stacked bar chart. when graph render stacks starts y 0-line , render them in order result in negative stacks reversed. example ( http://jsfiddle.net/moppa/6tenw/2/ ): if read graph bottom top following result series except "grapes" order joe, jane, john "grapes" series order jane, joe, john the grapes series not complying order in legend box. there way fix this? code comply stack overflow guidelines: $(function () { var chart; $(document).ready(function() { chart = new highcharts.chart({ chart: { renderto: 'container', type: 'column' }, title: { text: 'stacked column chart' }, xaxis: { categories: ['apples', 'oranges', 'pears', 'grapes', 'bananas'] },

Rounded corner listview items Background issue in android 4.0.4 -

Image
i have listview code given below <listview android:id="@+id/listview01" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/relativelayout01" android:cachecolorhint="@android:color/transparent" android:choicemode="singlechoice" > </listview> and here listview items layout <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <relativelayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:padding="5dp"

Oracle SQL Self Join advice -

this first question on forum, patient... question efficient way build query on following table: create table opentrades( accountnumber number, snapshottime date, ticket number, opentime date, tradetype varchar2(4), tradesize number, tradeitem char(6), openprice number, tradesl number, tradetp number, tradeswap number, tradeprofit number ); alter table opentrades add constraint opentrades_pk primary key (accountnumber, snapshottime, ticket) using index tablespace mynnidx;` this table populated every 15 minutes, , timestamp of insert saved in snapshottime column. sought query should group records week number (based on snapshottime), , filter records return latest (snapshottime) within same week . so far, i've tried following: select myweekno(ot1.snapshottime), max(ot2.snapshottime) opentrades ot1, opentrades ot2 myweekno(ot2.snapshottime)=myweekno(ot1.snapshottime) group myweekno(ot1.snapsho

php - Website Form do not carry any value when .htaccess File Extension Remover Code is Used -

i have code in htaccess file , works fine remove .php file extension.it allows page load without extension. # security reasons, option followsymlinks cannot overridden. #options +followsymlinks -multiviews options +symlinksifownermatch -multiviews # turn mod_rewrite on rewriteengine on rewritebase / ## hide .php extension # externally redirect /dir/foo.php /dir/foo rewritecond %{the_request} ^[a-z]{3,}\s([^.]+)\.php [nc] rewriterule ^ %1 [r,l,nc] ## internally redirect /dir/foo /dir/foo.php rewritecond %{request_filename}.php -f rewriterule ^ %{request_uri}.php [l] it works fine.the issue when use code <form action="test.php" method="post" id="myform" name="myform"> <input type="text" name="username"> <input type="submit" value="login"> </form> on test.php echo $_request['username']; empty/null. i tried remove .php form action worked.but can not remove .php

Grails Unit Test Case -

my controller contains following action def addnumber ={countrynumbercmd cmd -> def countryselected = params?.countryselected if(cmd.validate()) { println "success page" }else{ flash.cmd=cmd render(view:'hello') } } my hello.gsp page contains following code <html> <head> <title>hello</title> </head> <body> <div class="width460" id="formerrorjavascripttable"> <g:haserrors bean="${flash.cmd}"> <g:rendererrors bean="${flash.cmd}" as="list" /> </g:haserrors> </div> </body> </html> and message.properties countrynumbercmd.countryselected.nullable = country value should not null. command object validation class class countrynumbercmd { string countryselected static constraints = { coun

javascript - Two onclick event -

i have onclick 2 times on same button, button second 1 not seem work. need inorder make both of them work. <button type="submit" style="display:none;" id="done">ok</button> 1st event $(document).ready(function () { $('#done').click(function () { }); }); 2nd event $(function () { $(document).on("click", "#done", done); }); function done() { $.ajax({ }); } i believe need debug issue little bit. title of question indicates javascript (or jquery) not handling click event. may not case. $(document).ready(function () { $('#done').click(function () { console.log('first') }); }); $(function () { $(document).on("click", "#done", done); }); function done() { console.log('second') } <button type="submit" style="display:block;" id="done">ok</button> this runs fine, see jsfid

c - Evaluation of logical operand -

if have following: int = -10 && 0; then c evaluate -10 1 because -10 different 0 , make comparation between 1 && 0 0 result? or let -10 , make comparation written? instead if write: int c = 10; int b = 11; int res = c > 10 && b == 11; then c make this: c > 10 false evaluates 0 while b == 11 true evaluates 1 then expression is: 0 && 1 0 result. the operator && , || has short circuit behavior 1 . in int = -10 && 0; since left operand -10 , non-zero , hence true , therefore right operand, i.e 0 checked. in int res = c > 10 && b == 11; since left operand evaluated false , right operand not evaluated. 1 c11 6.5.13 (p4): if first operand compares equal 0 , second operand not evaluated.

gdata - Google Spreadsheet Java API - Protect Worksheet -

is possible programmatically protect worksheet in spreadsheet allow specific people edit it? i can't find decent documentation or examples on how this. things can find may relevant setrights() / getrights() , getcontributors() methods in baseentry.java , don't think good, don't know because there's no documentation. is there feed url can post to update list of contributors? thanks help. google-apps-script looks possible google-apps-script https://developers.google.com/apps-script/reference/spreadsheet/sheet#setsheetprotection(pageprotection) gdata - spreadsheet api there nothing close in spreadsheet api. basics set cell color or insert row don't exist. (there append row) it works fine data , calculation little else.

this - jQuery methods on dynamic elements -

unable use addclass method nor save instances of dom elements $(this) on dynamically loaded elements. using .on method click events on these elements not able manipulate them. $(document).on("click",".playpause",function(){ if($(this).attr('src') == 'img/play.png'){ $(this).attr('src','img/pause.png'); var songid = $(this).parent().siblings('.top_container').children('input').val(); $.post('songs.php',{songid : songid}, function(path){ if(globalsong.playstate && !($(this).hasclass('prevselection'))){ $('.prevselection').attr('src','img/play.png'); globalsong.pause(); $('.prevselection').removeclass('prevselection'); } globalsong = soundmanager.createsound({

iOS safari: sync two jquery functions -

on mobile website try this: $('.element').removeattr('style'); $(window).scrolltop(60); these 2 jquery functions fire @ same time in browsers other ios safari , causing glitchy behavior. there way force these 2 fire @ once?

angularjs - Links on mouse hover event in angular js -

i looking menu (vertical) shows sub menu on mouse hover event. sub menu should come @ right side of selected main menu list. i came main menu ng repeat following snippets. <head> <title>links on hover angularjs</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script> <script src="app.js" type="text/javascript"></script> <script src="linkscontroller.js" type="text/javascript"></script> <link rel="stylesheet" type="text/css" href="leftlinks.css"> </head> <body> <div id='content' ng-app='leftlinks' ng-controller='linkscontroller'> <ul type='none'> <li ng-repeat="link in links"><a href="#" class="leftlinks">{{link}}</a&

ios - How to show all the elements of an array in swift? -

i have array this: var array = ["chinese","italian", "japanase", "french" , "american"] and want print out seperate elements on new line. how can this? you can iterate through array , print out elements on new line: for element in array { println(element) } update for swift 2 , swift 3: for element in array { print(element) } or if want on same line: for element in array { print(element, terminator: " ") }

osx - How do I draw NSGradient to NSImage? -

i'm trying take nsgradient , save image in rubymotion, can't work. code have far: gradient = nsgradient.alloc.initwithcolors(colors, atlocations: locations.to_pointer(:double), colorspace: nscolorspace.genericrgbcolorspace ) size = size(width, height) image = nsimage.imagewithsize(size, flipped: false, drawinghandler: lambda |rect| gradient.drawinrect(rect, angle: angle) true end) data = image.tiffrepresentation data.writetofile('output.tif', atomically: false) it runs without error, file saved blank , there no image data. can point me in right direction? i don’t know rubymotion, here’s how in objective-c: nsgradient *grad = [[nsgradient alloc] initwithstartingcolor:[nscolor redcolor] endingcolor:[nscolor bluecolor]]; nsrect rect = cgrectmake(0.0, 0.0, 50.0, 50.0); nsimage *image = [[nsimage alloc] initwithsize:rect.size]; nsbezierpath *path = [nsbezierpath bezierpathwithrect:rect]; [image

c# - Button does not work after Validation -

i have 1 textbox , 2 buttons on update panel. <asp:button id="button_search" runat="server" text="search" onclick="button_search_click" validationgroup="personalinfogroup"/> <asp:button id="button_clear" runat="server" text="clear" onclick="button_clear_click" validationgroup="clear" causesvalidation="false"/> i validate textbox using compare validator. <asp:comparevalidator id="validator" runat="server" controltovalidate="textbox_trackingno" operator="datatypecheck" type="integer" errormessage="value must number" validationgroup="personalinfogroup" /> page load event; protected void page_load(object sender, eventargs e) { if (ispostback) page.validate(); loaddata(this, new eventarg

python 2.7 - Using OS.walk and paramiko to move files to ftp server causing EOFError? -

my goal walk through files in folder (and subfolders), check whether file exists on ftp. if file doesn't exist, put in in destination folder , if exist, archive old file using rename , put new file in it's place. code far follows. path = 'z:\\_magento images\\2014\\jun2014\\09jun2014' ssh = paramiko.sshclient() log_file = 'c:\\temp\\log.txt' paramiko.util.log_to_file(log_file) ssh.set_missing_host_key_policy(paramiko.autoaddpolicy()) def upload_images(): #' #in case server's key unknown,' #we adding automatically list of known hosts #ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts"))) #loads user's local known host file ssh.connect('xxxxxxxxxxxxx', port=22, username='xxxxxxxx', password='xxxxxxxxx') ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('ls /tmp') print "output", ssh_stdo

html - How to display inline blocks without breaking them on new line when shrinking parent -

i have 2 columns (inline blocks) in container (100% width). left side column has have min-width, 200px, width:25%. right side column has width:75% <style> .outer { width: 100%; border: 1px solid black; } .left, .right { display:inline-block; } .left { min-width: 200px; width: 25%; background-color: #dcc2c2; } .right { width: 75%; background-color: #d0dee8; } </style> <div class="outer"> <div class="left">left</div> <div class="right">right</div> </div> until min-width reached when resizing, columns sit side side want, once min-width kicks in, right column falls on next line. how can make right column shrink not fall on next line ? link jsfiddle add white-space:nowrap , overflow:hidden outer: .outer { width: 100%; border: 1px solid black; white-space:nowrap; overflow:hidden; } jsfiddle example

vb.net - Is there a decent way to send "Windows messages" between Adobe AIR and .NET, or do you need to use sockets? -

we have adobe air app , vb.net app running on same machine, , want these establish point-to-point communication. 1 option comes mind sockets. windows messages have been brought up. flash seems have several tutorials , such using sockets, not coming on google sort of native "windows message" communication. i haven't worked lot of windows api before, aside using .net in general, i'm not quite sure windows messages or how work. i'm not sure, instance, whether they're .net construct. either way, if adobe air supports passing windows messages , forth .net app, how done? (just 1 basic example or other resource me started.) or can through native extensions air? (that out of question, in case.) thanks. air can run external .exe file called nativeprocess . so can write external bat or simple exe job (sends specific messages) , call through air. haven't heard/seen "windows message" being available air. i haven used approach sim

s3Client for amazon web services on android -

i exploring using amazon web services storing user images viewed via android aplication. problem amazon charge me $0.12 per gig of downloads of image. cost minimal if enable caching of image urls s3 url generator file urls requires experation date part of url. means wouldn't able cache requests. is there way set s3client generate url doesn't require expiration data? anyone have experience this? i figured out.. no amazon's own documentatio scattered , out of date.. you can set permission public read so: putobjectrequest por = new putobjectrequest( constants.getpicturebucket(), constants.picture_name, resolver.openinputstream(selectedimage),metadata); por.setcannedacl(cannedaccesscontrollist.publicread); then end getting normal url: https://s3-us-west-2.amazonaws.com/[bucket]/[nameofthepicture]

fortran90 - Vim highlighting weird parts of FORTRAN -

Image
i using vim theme molokai, if makes difference. i have been learning fortran lately , when write fortran program using vim, have weird coloring depending on whitespace. for instance, if tab things on (no indenting) have purple highlight on portion of word (sometimes isn't there, notice prints , reads). if tab on looks normal: i new vim (not mention fortran) not sure what's happening, don't mind tabbing on time think looks little ridiculous if whole program wasting column of white space. if search :help fortran , you'll list of options can set. these fortran options set in own .vimrc file. (i don't work fixed-format code though) know there 1 or 2 fortran specific scripts available online, don't use them. let fortran_free_source=1 let fortran_have_tabs=1 let fortran_more_precise=1 let fortran_do_enddo=1

c# - ASP.NET Passing variable from .aspx page to UserControl -

i have usercontrol want pass value .aspx page. i've setup property in usercontrol set value need page value null. here control code in .aspx page, <tcs:submitdatadiscrepancy runat="server" id="submitdatadiscrepancy" entitynameprop='<%# bind("association_name") %>'/> the .ascx code, <div style="text-align:right;"> <asp:linkbutton id="reportlink" runat="server" text="report data discrepancy"></asp:linkbutton> <asp:panel id="reportpanel" runat="server" cssclass="modalpopup" style="width:auto;"> <div id="popheader" style="background-color: black; color: white; height: auto;"> report discrepancy <div style="float: right;"> <asp:linkbutton runat="server" id="associationcanceltextbutton" causesvalidation="false" font-underl

bluetooth lowenergy - Android BLE Out of Band data -

i have been working on ble sensor app. set sensor send oob key during pairing i'm not sure on android sdk side in order make app request oob when call create bond in code. if switch sensor keyboard capable see android requesting random pin. don't want use pin use oob. could shed light me? basically, sensor , android app have knowledge of oob secret key , bonding established based on secret key. thanks appreciate time helping me. cheers,

javascript - Building drag and drop navigation tabs -

i'm working on building new website purely learning purposes , want try , implement drag/drop sorting system. aware jquery provide sortable ui component http://jqueryui.com/sortable/ want have go @ designing , building system scratch (seen learning purposes). when comes javascript have admit novice, wondering if of offer 2 cents against current thinking of how program work: an un-ordered list sits @ top of page (navigation bar), each item assigned class 'draggable x' x current position in list an event listener bound each li element within list when on-mouse-down made on element variable set telling cell has been clicked, creates thumbnail under cursor (hides old cell) , allows user drag when mouse released list item slotted new position updating class number, whilst decrementing class numbers behind it questions: 1) main problem is, how detect when have passed li element when dragging? assume width n has been passed, each cell of variable length making