Posts

Showing posts from July, 2013

simulation - R code for simulating an SIR model -

recently learning write r without using packages. , found 1 example similar research doing. however, not know how insert values. tell me how so? set.seed(18746) simulations<- 1000 nsteps<- 100 s<- 25 i<- 1 r<- 0 alpha<- 0.8 beta<- 0.6 a<- 2 singlesim <- function(alpha,beta,s,i,r){ a<- (alpha/(s+i+r))*s*i b<- beta*i d<- runif(1) ran <- max(a*d,beta*i*d) z<-c(s,i,r) j<- ifelse(c(ran>a&ran<=a+b, ran>a&ran<=a+b,ran>a&ran<=a+b),c (s,i-1,r+1),z) l<- ifelse(c(ran<=a,ran<=a,ran<=a),c(s-1,i+1,r),z) x<- ifelse(c(ran<=a,ran<=a,ran<=a),l,j) q<- ifelse(j==z&l==z,z,x) g<- ifelse(c(ran==0,ran==0,ran==0),z,q) g} onecompsim <- function(nsteps,s,i,r,alpha,beta){ p<- array(0,c(nsteps,3)) z<- array(0,c(nsteps,3)) y<- array(0,c(nsteps,3)) p[1,]<-c(s,i,r) for(i in 2:nsteps){ p[i,]<- singlesim(alpha,beta,p[i-1,1],p[i-1,2],p[i-1,3])} p} fisim<- function(simulations,nsteps,s

bitmap - Android: image rotation not desire to resize -

i have code rotate imageview, , good. problem size of image change in rotate process , desire not happen. the xml code of image <imageview android:id="@+id/imgballesta" android:layout_width="100dp" android:layout_height="100dp" android:layout_alignparentleft="true" android:layout_centervertical="true" android:src="@drawable/imgballesta" android:contentdescription="@string/imagestring" /> the code creates bitmap, put code in declaration of class bitmap bmap = bitmapfactory.decoderesource(getresources(), r.drawable.imgobjectimage); and code rotate image, code inluded , ontouchevent matrix mat = new matrix(); matrix.postrotate((float) (angle*180/math.pi), image.getwidth(),image.getheight()); bitmap bmaprotate = bitmap.createbitmap(bmap, 0, 0, bmap.getwidth(), bmap.getheight(), matrix, true); image.setimagebitmap(bmaprotate); thanks

Linked in xml response to php variables -

this question has answer here: how parse , process html/xml in php? 27 answers i getting result linked in connect script, <person> <email-address>xzenia1@gmail.com</email-address> <picture-url>http://m3.licdn.com/mpr/mprx/0_uihhf6sif4yuberhukfufkshfpomuirhmbpbf5iy4soyk7fecl4xtlxtdael42axsho9hgzdtrbl</picture-url> </person> this php call $xml_response = $linkedin->getprofile("~:(email-address,picture-url)"); how make them assign separate php variable. you can load xml string simplexml_load_string , loop in data $xml = simplexml_load_string($xml_response); foreach($xml $key => $val) { echo "$key=>$val<br>" . "\n"; } this output email-address=>xzenia1@gmail.com picture-url=>http://m3.licdn.com/mpr/mprx/0_uihhf6sif4yuberhukfufkshfpomuirhmbpbf5iy4soyk7fec

php - Jquery ToastMessage - only show close for specific toast types? -

not sure if correct place ask.. here goes. i use jquery plug in : http://akquinet.github.io/jquery-toastmessage-plugin/ it works well.. close gif appear sticky messages, not messages fade away. does know how ? many :) sorry looks posted :( changing : i=c("<div></div>").addclass("toast-item-close").prependto(d).html(g.closetext).click(function(){c().toastmessage("removetoast",d,g) }); to this: if (g.sticky) {i=c("<div></div>").addclass("toast-item-close").prependto(d).html(g.closetext).click(function(){c().toastmessage("removetoast",d,g) }); } seems have worked..

asp.net mvc - What the parameters for Html.BeginForm do in ASP.MVC4? -

i trying understand this: html.beginform("login", "account", formmethod.post, new { returnurl = viewbag.returnurl } can explain me or point me page can find information on parameters for? you dont have go anywhere find this. f12 in vs public static mvcform beginform(this htmlhelper htmlhelper, string actionname, string controllername, formmethod method, idictionary<string, object> htmlattributes); summary: writes opening tag response. when user submits form, request processed action method. parameters: htmlhelper: html helper instance method extends. actionname: name of action method. controllername: name of controller. method: http method processing form, either or post. htmlattributes: object contains html attributes set element.

LinkedIn Job API with OAuth authentication using C# -

we've develop new project of posting jobs directly linkedin using job posting api within our web application. our web application developed in c#. there sample code available in linkedin developers posting of jobs in c# here i replaced sample "api_key" or "api_secret" original key or secret. when execute code give me error : remote server returned error: (403) forbidden think in order post jobs, linkedin uses oauth signed calls. oauth-based authentication new me. can not understand reason of error. how can resolve it? bunch of valuable help...!!

Adding /etc/hosts entry to host machine on vagrant up -

is possible 1 modify files on host machine during vagrant up process? example, adding entry host machine's /etc/hosts file avoid having manually? the solution use vagrant-hostsupdater vagrant plugin install vagrant-hostsupdater this plugin adds entry /etc/hosts file on host system. on , reload commands, tries add information, if not existant in hosts file. if needs added, asked administrator password, since uses sudo edit file. on halt, suspend , destroy, entries removed again.

.net - How do submit a form without clicking submit button BUT with code in (C# web browser control) -

Image
hi there way submit form without clicking submit button? keep in mind inside webbrowser1 control in c# . if click button in c# application should automatically submit form. you can inject javascript code submits form page: // on form load. htmlelement head = webbrowser1.document.getelementsbytagname("head")[0]; htmlelement scriptel = webbrowser1.document.createelement("script"); ihtmlscriptelement element = (ihtmlscriptelement)scriptel.domelement; element.text = "function submitform() { document.getelementbyid('formid').submit(); }"; head.appendchild(scriptel); then invoke on button click: // in button click handler webbrowser1.document.invokescript("submitform");

Android - how to draw in a multiple view layout -

i have draw ball inside view (or else task). i have followed tutorial matter, every tutorial have found uses 1 view (that shown on screen without use of layout). in activity use layout, composed many views, , want draw on 1 of them. here little mockup ! anybody knows way it? view wrong container it? thanks advance! bye ... you should extend view inherits viewgroup . kind of view lets handle view contains other views. that, can control drawing, measures , layout of each of it's children separately

java - how to detect connection leak in jdbc using weblogic? -

is there way detect connection leaks in project without going load testing. using weblogic server , there way detect using weblogic? i've never used myself, think capability has been in weblogic since 8.x. series of posts starting one appear detail steps. here post shows how use profile connection leak functionality. the name , location of weblogic's profile connection leak functionality differ version version, first in connection pool page/tab advanced settings.

mysql - php pass value to multiple select queries -

i'm having trouble passing variable between mysql queries on same page. maybe can advise i'm doing wrong. i'm new php/mysql, answer seems easy, don't see it. here have: 1. mysql: table a: id | gene_id | protein_id | disease_id | etc ---------------------------------------------- 1 | 672 | p12803 | 091312 2 | 817 | p99613 | 020346 3 | 411 | p52021 | 055823 2. search result page. displays list of results. reaults identified [$id] , <a href> link passes [$id] page result details. works perfectly. 3. details page. query result search results page , display related information table, identified [$id]. works fine. <?php $sql = "select * table_a id=" . $_get["id"]; $rs_result = mysql_query ($sql,$connect); while ($row = mysql_fetch_assoc($rs_result)) { ?> <table class="table"> <tr><td>gene: </td><td><?

java - How to save the text file in a path given by JFileChooser? -

i need save text file created in particular path given jfilechooser. save is: public void actionperformed(actionevent e) { jfilechooser chooser = new jfilechooser(); int status = chooser.showsavedialog(null); if (status == jfilechooser.approve_option) { system.out.print(chooser.getcurrentdirectory()); // don't know how } how save text file in path given jfilechooser ? you want add following after if statement: file file = chooser.getselectedfile(); filewriter fw = new filewriter(file); fw.write(foo); where foo content. edit: as want write text file, i'd recommend following: printwriter out = new printwriter(file); bufferedreader in = new bufferedreader(new filereader(original)); while (true) { string line = in.nextline(); if (line == null) break; out.println(line); } out.close(); where original file containing data want write.

Does matlab build-in max-flow algorithm support undirected graph? -

i using matlab build-in max-flow algorithm undirected graph. every edge replaced 2 directed edge same capacity 1. however, encounters error: "reciprocal edges not allowed in maxflow algorithms". matlab build-in max-flow algorithm support undirected graph?

html - Why is my JavaScript code not calling my function? -

i new javascript , made basic choose own adventure game switch statement. when attempt call function using button unsuccessful. javascript alone this. function choosegame(){ var troll = prompt("you walking through forest on way gamestop. come across troll guarding bridge there, says if pay him let by. pay, kill, or challenge him game of chess?").touppercase(); switch(troll){ case'pay': var money = prompt("do have money").touppercase(); var amount = prompt("is $50?").touppercase(); if (money && amount === "yes"){ console.log("you pay him , steal game wanted, caught, , go prison."); }else{ console.log("he broke legs , stole shoes, not you'd needing them."); } break; case'kill': var weapon = prompt("do have weapon?").touppercase(); var friend = prompt("do have friends you?").touppercase(); if (weapon || friend === "yes"){ console.log("you br

image - How can i resolve same bug with jQuery scripts to center a DIV with percentage? -

this code <style> .classname{ width:55%; height:auto; margin:0 auto; } body{ text-align:center; } </style> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(window).resize(function(){ $('.classname').css({ position:'absolute', left: ($(window).width() - $('.classname').outerwidth())/2, top: ($(window).height() - $('.classname').outerheight())/2 }); }); // run function: $(window).resize(); }); </script> when open page see div not centred, when reduce , reopen in full mod window of browser, div centred, plz me i'm going crazy try change this <script> $(document).ready(function(){ $(window).resize(function(){ $('.classname').css({ position:'absolute', left: ($(window).width() - $('.classname').outerwidth())/2, top: ($(window).height() - $('.classname').outerheight())/2 });

python - Can I use an identity hasher for testing? -

i have tests need create fully-functional test users. subclassing testcase in tests, , initializing test database in setup method. however, in order create functional users, need give them useful passwords calling make_password this sufficiently computationally intensive cause development server (a raspberry pi) take multiple seconds each test. my question is: can force django not hash password during tests? improve performance of test suite, , give me benefits come along that. perhaps you're looking for: https://docs.djangoproject.com/en/dev/topics/auth/passwords/ basically, create subclass of django.contrib.auth.hashers.pbkdf2passwordhasher , add new hasher first entry in password_hashers in settings.

iOS parse html after server side javascript is run -

i trying parse website ios application... parsing html tags works fine hpple, want parse site after java scripts , other server side scripts run... how go doing this? this java script run on site launch... need one, $('h1').html(sd.number); $(document).ready(function() { var names = ""; var today = new date(); $.getjson('space.json', function(sd) { $('h1').html(sd.number); $.each(sd.people, function(key, val) { var launch = new date(val.launchdate); var diff = new date(today - launch); var days = math.floor(diff/1000/60/60/24); names += ('<a href="' + val.bio + '" target="_blank"><div class="item cf"><div class="person-name"><h2>' + val.name + '</h2><div class="flag '+ val.country +'"></div><h3>' + val.title + '</h3></div><div class="person-days"><h4>' + days + '

java - Authentication required window popping up after 7u21 update -

Image
i've been working on project last 6 months. project have glassfish server instance webservice deployed. @ client side, i'm using javafx2.2 rest requests jersey (xml requests/responses, no json) basic authentication. when user starts program (jws/jnlp), enter credentials in own made login window, press login button , start working. since 7u21 however, got java "authentication required" pop-up reason (probably because of changed security in 7u21). to sure had nothing compatibility issues between java versions, updated server 7u21, so: client: updated java 7u17 7u21 server: updated java 7u09 7u21, adjusted glassfish asenv.bat file use new jdk if hit cancel button in "authentication required" window shown above, program start thou, not run stable when doing requests: java.io.ioexception: stream closed file:/d:/netbeansprojects/mit_20130516/cl_kenom/dist/cl_kenom.jar!/gui/cow/listcow.fxml @ com.sun.jersey.api.client.clientresponse.close(clien

how to make query with substr in eloquent (laravel 4)? -

i have query: select substr(id,1,4) id meteo.a2012 group substr(id,1,4) i want take first 4 numbers id row, i'm trying in eloquent, how do? thanks. you need use raw expressions can use special functions that. model::select(db::raw('substr(id, 1, 4) id'))->groupby(db::raw('substr(id, 1, 4)'))->get(); where model eloquent model want run query on.

c# - How can I extend DataAnnotationsModelMetadata -

i have custom dataannotationsmodelmetadataprovider , i'd return object derived modelmetadata can have properties in razor templates. so far custom provider overrides createmetadata function: protected override modelmetadata createmetadata(ienumerable<attribute> attributes, type containertype, func<object> modelaccessor, type modeltype, string propertyname) { var modelmetadata = base.createmetadata(attributes, containertype, modelaccessor, modeltype, propertyname); modelmetadataattribute mma; foreach (attribute in attributes) { mma = modelmetadataattribute; if (mma != null) mma.process(modelmetadata); } return modelmetadata; } so every attribute derived modelmetadataattribute can custom actions (actually adds additionalvalues ) but since of attributes add attributes html elements generate in razor template, i'd modelmetadata in view contain dictionnary of attrib

Wordpress get attachment of post doesn't work -

i'm trying retrieve attachment of specific post, doesn't work moment. here code : $args = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $id ); $attachments = get_posts($args); where id id of post. i've tried new wp_query() didn't worked neither. both ways return empty result. does have idea i'm doing wrong here ? thanks edit ok, think know what's going wront. when using arguments get_posts function, return images uploaded through "add media" button in specific post. so basically, let's on first post, i've uploaded images need future post. if apply request on first post, retrieve images, 1 don't use in post. if apply function post, because didn't uploaded file in post, function retrieve empty array. does have idea how can retrieve images used in specific post ? not uploaded, integrated post or added custom fie

Duplication in results using php mysql and inner join -

i have 3 drop list contain retrieved values database 3 different tables governorate: governosrate_id governorate_name district: district_id district_name village: id village_name memebrs: user_id user_name governorate district village want when user select one of 3 or of them drop list system must display result related selected 1 but problem when user select governorate work fine when select governorate , district duplicate result related selected value , if user choose governorate district , village result become triples anyone can me ???? i show code of 3 types and if have complaint try not beat me code: by governorate //**********search locationn***************************************// if(isset($_post['listbyq'])) { //********************by governorate**************************************// if($_post['listbyq']=="by_gov") { $bygov = $_post['governorate']; $sql = mysql_quer

javascript - jQuery Tabs activate on Carousel with Mobify -

i need able have tab menu above carousel, when clicked on move carousel associated package within carousel. also when carousel swiped tabs move accordingly package swipe to. active tab change if swipe , vise-versa. i have put demo, working apart linking tabs , carousel. totally lost @ how this. my demo code , example: - http://jsfiddle.net/jnys7/ <ul id="navlist"> <li>basic</li> <li class="activestep">standard</li> <li>super</li> <li>antoher</li> </ul> plugin using: http://www.mobify.com/mobifyjs/modules/carousel-examples/ hope can out. thanks an example: http://jsfiddle.net/jnys7/3/ what did move #navlist inside of .m-carousel , added <a> data-slide='number_here' attribute <a> , making pagination. changed activestep class name m-active . now need style it. update http://jsfiddle.net/jnys7/10/ change margin-right here define distance b

javascript - How to play ogg file in HTML in IPAD safari? -

i want play ogg file in ipad safari. ogg file have contain in html file. in mac os safari, ogg file play normally. but, in ipad safari, ogg file didn't play. how solve issue? <body> <div class="gm4html5_div_class" id="gm4html5_div_id"> <!-- create canvas element game draws --> <canvas id="canvas" width="640" height="480"> <p>your browser doesn't support html5 canvas.</p> </canvas> </div> <!-- run game code --> <script type="text/javascript" src="sndtest/index.js?fplyb=1677165635"></script> <audio preload="auto" networkstate="0"><source src="sndtest/sound0.ogg" type="audio/ogg" codecs="vorbis"></audio> <audio preload="auto" networkstate="0"><source src="sndtest/sound1.ogg" ty

Eclipse DisplayMessageActivity error -

i have question error in eclipse. eclipse says "the nested type displaymessageactivity cannot hide enclosing type" this script: package com.example.warzonegaming; public class displaymessageactivity { public class displaymessageactivity extends activity { @suppresslint("newapi") @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // message intent intent intent = getintent(); string message = intent.getstringextra(mainactivity.extra_message); // create text view textview textview = new textview(this); textview.settextsize(40); textview.settext(message); // set text view activity layout setcontentview(textview); // make sure we're running on honeycomb or higher use actionbar apis if (build.version.sdk_int >= build.version_codes.honeycomb) { // show button in action bar.

ruby on rails - passenger don't run on app path 'Could not find passenger' -

running passenger on app path (e.g /home/my_app/rails) such: rvmsudo passenger start raising error dependency.rb:247:in `to_specs': not find passenger ... the problem caused conflict project gems. should run command outside of app, giving passenger app path handle. cd ~ rvmsudo passenger start my_app/rails

jQuery, only fire if li is clicked on and NOT an a tag -

i have following setup <ul> <li><a href="http://www.example.com">example</a></li> <li><a href="http://www.example2.com">example2</a></li> </ul> the li's have width set css 400px; i'm trying write jquery fires if li clicked, not tag. suggestions? when event in click handler, @ event.target / event.originaltarget this should give indication element caused event , can either process or ignore it. function clickhanlder (e) { if (e.target.tagname != "a") { return; } }

node.js - Grunt-contrib-watch error when compiling less files -

not sure why keep getting these errors when running watch task. grunt watch task # watch task watch: options: nospawn: true livereload: true server_coffee: files: ['server/**/*.coffee'] tasks: ['coffee:changed'] server_copy: files: ['server/**/*.!(coffee)'] tasks: ['copy:changed'] client_coffee: files: ['client/**/*.coffee'] tasks: ['coffee:changed'] client_copy: files: ['client/**/*.!(coffee)'] tasks: ['copy:changed'] grunt event # watch changed files grunt.event.on 'watch', (action, filepath) -> # determine server or client folder path = if filepath.indexof('client') isnt -1 'client' else 'server' cwd = "#{path}/" filepath = filepath.replace(cwd,'') # minimatch coffee files if minimatch filepath, '**/*.coffee' # compile changed file grunt.config.set('coffee', changed: expand: true cwd:

java - Bitmap to Mat gives wrong colors back -

Image
so make bitmap blob next code: byte[] blob = contact.getmp(); bytearrayinputstream inputstream = new bytearrayinputstream(blob); bitmap bitmap = bitmapfactory.decodestream(inputstream); bitmap scalen = bitmap.createscaledbitmap(bitmap, 320, 240, false); and gives next output, good then following make bitmap mat, colors change... //mat imagemat = new mat(); mat imagemat = new mat(320, 240, cvtype.cv_32f); utils.bitmaptomat(scalen, imagemat); i have no idea why, nor way make bitmap mat. wrong? the format of color channels in android bitmap bgr in opencv mat, channels rgb default. so when utils.bitmaptomat(), [b,g,r] values stored in [r,g,b] channels. red , blue channels interchanged. one possible solution apply cvtcolor on opencv mat got below: imgproc.cvtcolor(imagemat, imagemat, imgproc.color_bgr2rgb); it worked me.

Sorting lists in python issue -

i started learning python few days ago (with no prior programming experience nor knowledge) , stuck following thing not understand: let' have unsorted list "b" , want sort list "c" looks list "b": b = [4,3,1,2] c=b c.sort() print b print c what discovered both b , c sorted: [1,2,3,4] [1,2,3,4] why so? it seems solution works when create copy of "b" list: b = [4,3,1,2] c=b[:] c.sort() print b print c results in: [4,3,1,2] [1,2,3,4] but why first solution not work? thank you. in first sample, copying b c reference, means whenever change (sorting, example) made on b , applied on c , because both point same object. in second sample, copying array by value , not by reference , create entirely new object in memory. therefore, changes made on 1 of them not applied on other one.

Linux kernel: sequence of events/paths before process coredump happens -

when there segmentation fault , process coredump generated sequence of events happening in kernel , user space (w.r.t linux) ? linux support sigsegv handler. how signal handler gets called , on return coredump generated ? i'm looking sequence of events , pointers linux kernel function names (w.r.t latest kernel). figure rest function names, i'do understand can make out rest code. when sigsegv generated, kernel checks if there handler it. if there is, call it, other signal. if there handler, no core generated. happens in get_signal_to_deliver: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/kernel/signal.c#n2192 if gets default action sigsegv, generate coredump , exit. coredump generated do_coredump in fs/coredump.c: https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/fs/coredump.c#n485

Parallelize function on dictionary in IPython -

up till now, have parallelized functions mapping them on lists distributed out various clusters using function map_sync(function, list) . now, need run function on each entry of dictionary. map_sync not seem work on dictionaries. have tried scatter dictionary , use decorators run function in parallel. however, dictionaries dont seem lend scattering either. is there other way parallelize functions on dictionaries without having convert lists? these attempts far: from ipython.parallel import client rc = client() dview = rc[:] test_dict = {'43':"lion", '34':"tiger", '343':"duck"} dview.scatter("test",test) dview["test"] # yields [['343'], ['43'], ['34'], []] on 4 clusters # suggests dictionary can't scattered? needless say, when run function itself, error: @dview.parallel(block=true) def run(): d,v in test.iteritems(): print d,v run() attributeerror trac

php - codeigniter login form is not displaying is i post -

this users controller function login(){ $data['error']=0; if($_post){ $this->load->model('user'); $username=$this->input->post('username', true); $password=$this->input->post('password', true); $type=$this->input->post('user_type', true); $user=$this->user->login($username,$password,$type); if(!$user){ $data['error']=1; } else { $this->session->set_userdata('userid', $user['userid']); $this->session->set_userdata('user_type', $user['user_type']); redirect(base_url(). 'posts'); } $this->load->view('header'); $this->load->view('login',$data); $this->load->view('footer'); } } this user model function login($username,$password){ $w

Android build failing with build.xml:479: SDK does not have any Build Tools installed -

Image
why build fail error? {android-sdk}/tools/ant/build.xml:479: sdk not have build tools installed it started showing after updating sdk tools 22 try run android update sdk -u in terminal. you see logs on screen installing archives: preparing install archives downloading android sdk platform-tools, revision 17 installing android sdk platform-tools, revision 17 stopping adb server succeeded. installed android sdk platform-tools, revision 1799%) downloading android sdk build-tools, revision 17 installing android sdk build-tools, revision 17 installed android sdk build-tools, revision 1799%) downloading arm eabi v7a system image, android api 17, revision 2 (71%, 775 kib/s, 41 seconds left)) after android sdk updated, make sure build tools installed.

sql - Select a timestamp when I have only a date? -

i have table has 2 columns of timestamp datatype, start_time , end_time . format '2013-5-19 09:00:00' . when user enter date, 2013-5-19 . how largest value date user has entered? select max(end_time) appointment ... you should max(end_time) , records within given date. here's working sql fiddle . or can try this: create table appointment(start_time date, end_time date); insert appointment(start_time, end_time) values (to_date('2013-5-19 09:00:00', 'yyyy-mm-dd hh24:mi:ss'), to_date('2013-5-19 11:00:00', 'yyyy-mm-dd hh24:mi:ss')); select start_time, end_time appointment; select max(end_time) appointment to_char(end_time,'yyyy-mm-dd')= to_char(to_date('2013-5-19', 'yyyy-mm-dd'),'yyyy-mm-dd');

android - Getting screen coordinate of action bar menu item for creating introduction screen -

Image
i wondering, there possible of getting screen coordinate position of action bar menu item? create introduction screen, draw arrow pointing desire action bar menu item, user knows start. here's how did it: @override public boolean onoptionsitemselected(menuitem item) { if(item.getitemid().equals(r.id.my_menu_item)) { view menuview = findviewbyid(r.id.menu_item_search); int[] location = new int[2]; view.getlocationonscreen(location); int locationx = location[0]; int locationy = location[1]; } }

php - how to get all data from array in a variable? -

i have dynamic array array ( [company_name] => [address] => b [country_id] => 1 [email] => c@c.com [currency_id] => 1 ) and want create index variable like: `$var = "company_name,address,country_id,email,currency_id";` and value variable like: $value = "a,b,1,c@c.com,1"; remember array index , value not fixed. in advance. you can try this. $var = implode(',', array_keys($myarray)); $value = implode(',', array_values($myarray)); where $myarray array showed in question.

Error 404 using asp.net web api -

i've got 2 projects: core , web. core project has api controllers, models, etc. web project has html pages only. i'm loading data api using jquery. when core project (created view), ok. when web project, i've got error 404, fiddler shows ok. why so? what's problem? i found answer. because it's cross domain application. , it's necessary implement cors support. can done 2 ways. first. add section of web.config file next: <httpprotocol> <customheaders> <add name="access-control-allow-origin" value="*" /> <add name="access-control-allow-headers" value="content-type" /> <add name="access-control-allow-methods" value="get, post, put, delete, options" /> </customheaders> </httpprotocol> second. create custom messagehandler. in this post

entity framework 5 - How do I construct a delegate and pass it as a parameter to be used in a lambda expression -

i refactoring code original statement was var deletelist = new list<filterparameter>(); foreach (filterparameter param in filterparameters) { if (memlist.all(x => x.parametername != param.parametername)) { deletelist.add(param); } } now want var deletelist = ufs.filterparameters.where(param => memlist.all(rule2)).tolist(); i unsure how construct , pass in delegate i'm not entirely sure understand you, asking how pass predicate in .where() , because work like: func<filterparameter, bool> predicate = param => memlist.all(x => x.parametername != param.parametername); list<filterparameter> deletelist = filterparameters.where(predicate).tolist(); is you're asking ?

context menu in vb.net -

i have dynamically populated list in windows forms application. want add context menu such when select item, context menu appear when right click on selected item, , not appear on right-click on other blank areas of form. using code. lv.columns.add("button text", 300, horizontalalignment.left) lv.columns.add("pid", 50, horizontalalignment.left) lv.columns.add("process path", 300, horizontalalignment.left) lv.columns.add("hide icon permanently", 150, horizontalalignment.left) dim things list(of traybutton) = trayhelper.tray.gettraybuttons() each b traybutton in things if b.icon isnot nothing il.images.add(b.trayindex.tostring, b.icon) else ' when can't find icon, listview display form's one. ' try grab icon process path suppose. il.images.add(b.trayindex.tostring, me.icon) end if dim lvi new listviewitem(b.text) lvi.subitems.add(b.processidentifier.tostring) lvi.subite

For Loops in Python to read Long URL from shortened URL -

i'm python beginner , struggling loop function. if run code receive long url last entry. ideas? thanks import urllib2 beautifulsoup import beautifulsoup x in ('civ8jguveh','isrohi98ag','taz38yubob'): shorturl = 'http://t.co/' + str(x) output = urllib2.urlopen(shorturl) print output.url you reassigning variable every time before opening or printing url. need indent code assigning , printing output variable done within loop: import urllib2 beautifulsoup import beautifulsoup x in ('civ8jguveh','isrohi98ag','taz38yubob'): shorturl = 'http://t.co/' + str(x) output = urllib2.urlopen(shorturl) print output.url

wxpython ctrl+x shortcut does not work -

i'm running wxpython app in windows 7. reason when press ctrl+x on keyboard, frame not close. however if change binding text='quit\tctrl+x' text='quit\tctrl+q' or other character x , frame closes. does ctrl+x have special significance in wxpython preventing frame being closed? import os import wx class mainme(wx.frame): def __init__(self): wx.frame.__init__(self, parent=none, size=(300, 300), title = 'test frame') wx.textctrl(parent=self, style =wx.te_multiline | wx.te_no_vscroll) self.createstatusbar() filemenu = wx.menu() exitid, aboutid = wx.newid(), wx.newid() menuabout = filemenu.append(id=aboutid, text='about\tctrl+a', help='more information') menuexit = filemenu.append(id=exitid, text='quit\tctrl+x', help="close") menubar = wx.menubar() menubar.append(filemenu, title='file') self.setmenubar(menubar) s

c# - using some types in multiple classes -

i have class like: public class soru { public void sorukaydet(){...} private static void soruetiketkaydet(guid soruid, etiket etiket, dbmanager db){...} public guid? soruid { get; set; } public guid? soranid { get; set; } public int? bakilmasayisi { get; set; } public string htmlgovde { get; set; } public string markdowngovde { get; set; } public string baslik { get; set; } public int? kategoriid { get; set; } public datetime olusturulmatarihi { get; set; } public list<etiket> etiketler { get; set; } } i need class should contain of variables in class "soru". have 2 scenario this. the first scenario: public class sorusayfa { public static list<sorusayfa> sorusayfagetir(){...} public guid? soruid { get; set; } public guid? soranid { get; set; } public int? bakilmasayisi { get; set; } public string baslik { get; set; } public int? kategoriid { get; set; } public int d

Mysql selecting with sum() and group by from multiple tables -

table 1 --------------------------------------- | id | item | mu | quantity | file_id | --------------------------------------- | 1 |item1 | oz | 3.5 | 003 | | 2 |item2 | kg | 1.1 | 001 | | 3 |item1 | oz | 0.2 | 001 | | 3 |item1 | kg | 3 | 001 | table 2 ---------------------------- | id | date | file_id | ---------------------------- | 1 |timestamp1 | 001 | | 2 |timestamp2 | 002 | | 3 |timestamp3 | 003 | what i'm trying select sum of quantity each group of items have same mu. manage query. $query = "select item,sum(quantity) table1 group item,mu"; great result, wanted ---------------------------------- | id | item | mu | sum(quantity) | ---------------------------------- | 1 |item1 | oz | 3.7 | | 2 |item2 | kg | 1.1 | | 3 |item1 | kg | 3 | but now, how only rows file_id date between 2 timestamps ? you can manage achieve using left join , joining

python - Pyplot bar chart does not match table columns position with all bars -

Image
i'm building bar graph table using code example . everything looks when have 10 columns, above 10 columns bars shifted left , not match position of table columns. happens odd number of columns/bars (e.g. 11 , 13, not 12 , 14 looks good). looks x-axis columns 11 , 13 keeps space columns 12 , 14. i've enclosed code changes i've made above example in order reproduce problem with. i've been struggling long , did not find on web, appreciate help. the modified contents example: data = [[ 66386, 174296, 75131, 577908, 32015, 66386, 174296, 75131, 577908, 32015, 100000, 75131, 174296], [ 58230, 381139, 78045, 99308, 160454, 58230, 381139, 78045, 99308, 160454, 100000, 75131, 174296], [ 89135, 80552, 152558, 497981, 603535, 89135, 80552, 152558, 497981, 603535, 100000, 75131, 174296], [ 78415, 81858, 150656, 193263, 69638, 78415, 81858, 150656, 193263, 69638, 100000, 75131, 174

html - div float left bug in google chrome -

Image
i`ve got structure of menu in html: <div id="menu_box"> <a title="" class="menu_item_rfc" href="/main/menu/1"> <div class="menu_item"> bla bla bla </div> </a> <a title="" class="menu_item_rfc" href="/main/menu/2"> <div class="menu_item"> bla bla bla </div> </a> <a title="" class="menu_item_rfc" href="/main/menu/3"> <div class="menu_item"> bla bla bla </div> </a> <div id="search_box"> <form id="search_form" action="" method="post"> <div style="float:left;padding:4px 0 0 0;&quo

authentication - How to check User Online Status with Spring Security in Grails? -

we use grails spring security in our application perform user authentication. if user loggs in our application, rememberme cookie saved. means, user remain logend in between browser sessions. how can check users online? read can retrieve information session using sessionregistryimpl or httpsessionlistener have no idea how implement that. found post not sure how transform grails: online users spring security any idea? i built dating application relies on online users. created grails' service keeps track of online users. have create service keeps concurrent hash map, service singleton 1 instance whole web application. when user log-in first time, set user id, , future time in hash map. example: key = userid value = + 30min so when user logs in, increment log-in time 30min , insert in hash map. every request user sends, update value of hash map looking expiry time using user id. if user closes browser, not going update expiry , online status going invalid. can h

validation - How can I get the HTML5 validity state of an input text box? -

how can retrieve html 5 'validity' status of text box? for instance, have text input type="email" . when user enters wrong value, text box shows red border (in firefox browser). how can check 'validity-state' of input box? you can use validity property: var isvalid = document.getelementbyid('email').validity.valid; or checkvalidity() method: var isvalid = document.getelementbyid('email').checkvalidity(); demo | reference .

locking - Android get Lock Timeout Programmatically -

i writing app show activity on lock screen when phone locked , screen off. when user leave activity, keyguard should shown. common way detect whether phone locked by receiver , action.screen_off. works if user press lock button lock , screen off phone. however, after ics, phone may not locked phone screen off. so, how can lock event or how can value of automatically lock picture below? i know inkeyguardrestrictedinputmode() way check if phone locked. cannot report automatically when phone locked receiver. the screenshot setting in android 4.1.2 you can timeout value following code: mresolver = this.getcontentresolver(); long timeout = settings.secure.getint(mresolver, "lock_screen_lock_after_timeout", 0);

SASS variables inter-files scope -

in order use @include box-shadow(0 0 10px black); you have include "library": @import "compass/css3"; later in file, including other scss: @import "sidebar/main"; and in sidebar/_main.scss, when call same: @include box-shadow(0 0 10px black); compass breaks error: < ... undefined mixin 'box-shadow'.> does mean i'll have abstract libraries in own library file, , include file in each , every other scss??? rename sidebar/main.scss sidebar/ _main .scss - no other code changes needed. this instructs sass compiler not compile sidebar/main.scss file separate css file, include in main scss file. the process works this: sass compiles main scss file inclusions , generates css (no errors here, since compass included @ top) sass compiles other scss files don't begin _, since these don't have compass included, throws error.

iphone - Supporting ios 5 in monotouch applications -

i have application monotouch ios (iphone/ipad application). in project option target ios 6. now when want download application device run ios 5 itune not allow. if change target version 5, app supports ios 6 , 6.1 yet? do need change codes support both of them? if target ios 5 in monotouch, app work on both ios 5 , ios 6 devices. in general, nothing special should done support both ios 5 , ios 6. keep in mind though, apis ios 6 only, such deep facebook integration. don't worry code, make sure test app on devices different ios versions.

c# - Prepare enum list and find an enum value from List<enum> -

i decided write below code access control list permission check. my database return record employeedetfeature , create , edit i parse create , add feature acl enum list. also need find later. public enum acl { create, delete, edit, update, execute } public class feature { public int id { get; set; } public string name { get; set; } public list<acl> aclitems { get; set; } } public static class permissionhelper { public static bool checkpermission(role role, string featurename, acl acl) { feature feature = role.features.find(f =>f.name == featurename); if (feature != null) { //find acl enum , if exists return true return true; } return false; } } how make enum collection preparation , find same later checking permission. find acl enum , if exists return true something this? bool b= enum.getvalues(typeof(acl)).cast<acl>().any(e

java - Binary Search output issue? -

this first using binary search me, i've run small issue (hopefully!) first program, allows user type in random number, , if number matches book outputs title. class b { string book1, book2; b () { book1 = "wicked awesome title"; book2 = "how read book"; public static book getbook(book [] a, int left, int right, string booktitle) { int middle; book found = null; /**your average joe binary search...*/ while (found == null && left <= right) { //if middle item == 0, returns true middle = (left + right)/2; int compare = a[middle].sametitle(booktitle); if (compare == 0) { found = a[middle]; } else { if (compare >0) { right = middle -1; } else { left = middle + 1;

Second form submit capture issue - PHP -

hi can 1 give me clue why "form 2 here" message not displaying in following code? have written lengthy code in following structure. help <doctype html> <html> <head><title></title> </head> <body> <div id="one" style="width:300px; background:gray;"> <form method="post" action="<?= $_server['php_self'] ?>"> <input type="text" name="txt1" id="txt1"> <input type="submit" name="sendone" id="sendone" value="one"> </form> </div> <div id="two" style="width:300px; background:yellow;"> <?php if(isset($_post['sendone'])) {echo "<input type='submit' name='sendtwo' id='sendtwo' value='two'>";} if(isset($_post['sendtwo'])) {echo "form 2 here!"; return;} ?> </div> </body&