Posts

Showing posts from June, 2012

javascript - for loop to print out multiple arrays with similar names -

i've got multiple arrays, so: bugnames0 = ["wasp", "roach", "stinkbug", "mantis"]; bugnames1 = ["hornet", "beetle", "ant", "termite"]; bugnames2 = ["gnat", "fly", "grub", "chigger"]; bugnames3 = ["flea", "bed-bug","maggots", "cricket"]; next have loop: function bugloop() { (var i=0; < 4 ; i++){ console.log(bugnames0[i]); } } that print first array console, or each individually if manually update number in array's name. but there way more this? following code bit doesn't work, hope explains trying do: for (var i=0, j=0; < 4; i++) { console.log(bugnames(i)[j]); } } here represents bugname#, update through 0 - 3 loop runs, printing out first option of each array represented j. goal outcome printed console be: "wasp", "hornet", "gnat", "flea...

MatLab - Importing CSV text file that contains commas not meant to separate -

uh! have received delivery of large text files comma separated value format. need build struct each file data analysis. piece of cake! have done before. wrote code build structs. eventually, discovered there can case data has comma the real data, not meant separate data. caught before leaving work. working home now, hoping derive solution or have recommended solution posting here. (below code , data file example). appreciate help, comments, solutions, and/or feedback. thanks data file example(line 5 problem begins, 'bubba1, ttr1' should not separated): chan, date, time, signalname, mode#, lat, long, 01, 12/12/12, 01:01:20.234, off, 0, 39.185, -106.85, 01, 12/12/12, 01:01:20.345, off, 0, 39.185, -106.85, 01, 12/12/12, 01:01:20.445, off, 0, 39.185, -106.85, 01, 12/12/12, 01:01:20.545, bubba1, ttr1, 1, 39.185, -106.85, 01, 12/12/12, 01:01:20.645, bubba1, ttr1, 1, 39.185, -106.85, 01, 12/12/12, 01:01:20.745, bubba1, ttr1, 1, 39.185, -106.85, 01, 12/12/12, 01...

How do I access a microSD card connected to my RFduino, via Bluetooth on my Android App? -

i creating device connect mobile app via ble. device using rfduino microcontroller microsd shield. mobile app can connect rfduino via ble. can tx, rssi, , send value phone app rfduino. having trouble accessing microsd card root path through mobile app. able display file explorer. have basics file explorer, displaying dot on screen. this have far. know need point path, i'm not sure how. import android.app.alertdialog; import android.app.listactivity; import android.content.dialoginterface; import android.os.bundle; import android.view.view; import android.widget.arrayadapter; import android.widget.listview; import android.widget.textview; import java.io.file; import java.util.arraylist; import java.util.arrays; import java.util.list; public class androidexplorer extends listactivity { private list<string> item = null; private list<string> path = null; private string root="/"; private textview mypath; /** called when activity fi...

c - Dynamic Character Array - Stack -

general background i had need character array contained dynamic number of character arrays based on number of files located in specific folder. able accomplish initializing char (*fullpathnames)[max_filename_and_pathname_length] , using fullpathnames = malloc( sizeof(*fullpathnames) * numoffiles * max_filename_and_pathname_length ) ) after know how many files function discovered( not provided). process works flawlessly. technical limitations i can use ansi c; using labwindows cvi 8.1, compile code. cannot use other compiler. general supporting code char (*fullpathnames)[max_filename_and_pathname_length]; size_t size; numoffiles = numberofuserfiles(“*.txt”, “c:\\programdata” ); fullpathnames = malloc( sizeof(*fullpathnames) * numoffiles * max_filename_and_pathname_length ) ); size = sizeof(*fullpathnames) * numoffiles; memset(fullpathnames,0,size); quick explaination the above code doing want. can fill array enough following code: strcpy(fullpathnames[0],”test...

wordpress - Removing script and styles version query string with .htaccess -

how change this: example.com/css/style.css?ver=3.5.3 examle.com/css/settings.css?ver=4.6.9 in this: example.com/css/style.css example.com/css/settings.css i have code on .htaccess file: <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewritecond %{request_filename} !-f rewritecond %{request_filename} !-d rewriterule ^(.+)\.(.+)\.(js|css)$ $1.$3 [l] </ifmodule> this code not functioning. suggestions appreciated. you can try in .htaccess in document root if want way. let me know how works you. <ifmodule mod_rewrite.c> rewriteengine on rewritebase / rewritecond %{query_string} ^ver=(.+) rewriterule ^css/(style|settings)(\.css)$ /css/$1$2? [l] </ifmodule>

css3 - W3C CSS validation error using calc() and vendor extensions -

after finishing new html5/css3 template proceeded w3c validation. the result html: "this document checked html5!" the result css: "sorry! found following errors (1)" and problem around height: calc(100vh - 80px); it told me: 36 property -ms-transform unknown vendor extension 37 property -webkit-transform unknown vendor extension 112 property -webkit-transition unknown vendor extension 113 property -moz-transition unknown vendor extension 249 property -webkit-background-size unknown vendor extension 292 property -webkit-background-size unknown vendor extension so in case shall 100% css3 valid? don't worry vendor extensions. don't recall why flagged way not errors on part. don't recall reasoning it. iirc, there checkbox ignore these warnings. the explanation may lie in this article states: vendor-specific extensions (mostly) adhere css 2.1 grammar, since not defined in css 2.1 specification, in...

.net - pdb file ( visual studio ) -

i want send debug executable client replicate crash loading pdb file. purpose, created debug build. should send both executable , pdb client . please advise if client going re-compile/compile @ end , run code no, that's not needed. since generated debug build; once @ client side run application in debug mode; same pdb file generated. else, yes; have send pdb file along exe . but pdb file have .net application related debug info. so, if crash due other environmental issue has captured separately.

swing - Java Fitting JPanel into Modal JDialog -

i have class returns jpanel: public static jpanel program(string csvname) { jpanel f = new jpanel(); try { string path = system.getproperty("user.dir"); string datafile = path+"/files/logic/"+csvname+".csv"; filereader fin = new filereader(datafile); defaulttablemodel m = createtablemodel(fin, null); jtable table = new jtable(m); jscrollpane stable = new jscrollpane (table); stable.setverticalscrollbarpolicy(jscrollpane.vertical_scrollbar_as_needed); stable.sethorizontalscrollbarpolicy(jscrollpane.horizontal_scrollbar_as_needed); table.setautoresizemode(jtable.auto_resize_off); f.add(stable); f.setminimumsize(new dimension(900,500)); jframe desktopframe = new jframe(); desktopframe.add(f); desktopframe.setsize(900, 500); desktopframe.setvisible(...

facebook - Azure Web app - Could not resolve the hostname into a valid IP address -

Image
i'm having problem using facebook object debugger ( https://developers.facebook.com/tools/debug/og/object/ ) scrape information page , i'm getting error "could not resolve hostname valid ip address." can see bellow this website hosted in azure, web app. everything looks ok on domain registrar, have record pointing public ip , cname pointing xxx.azurewebsites.net. you may want try removing record , redirecting root www.

php - db_result D6 query conversion to db_select D7 -

i trying convert d6 code query drupal 7 foreach ($order->products $product) { if (db_result(db_query("select nid {the_table} fid = 'string' , nid = %d", $product->nid))) { $nid[] = $product->nid; } } i changed query: if (db_result(db_query('select nid {the_table} fid = 'string' , nid = :nid', array(':nid' => $product->nid)))) { and dynamic query came out written thought foreach ($order->products $product) { $query = db_select('{the_table}', ''); $query->fields('nid', array('')); $query->condition('fid', 'string'); $query->condition('nid', ':nid'); $query->execute(); $result = $query->fetchassoc(); foreach ($result $record) { $product->nid; $nid [] = $product->nid; } } i tried "->fetchfield();" statement in ...

JavaScript function that produces an array that multiplies x number of times based on previous integer -

so i've got function , needs produce array multiplies x number of times based on previous integer. function take 2 integers arguments so: function powerof(x, n) { } for example: powerof(3, 4) produce [3, 9, 81, 6561]. can point me in right direction? this function you've been looking for: function test(a,b){ // declarin array result var res = [a]; // going through array , adding multiplied numbers for(var = 1; i<b;i++){ res[i] = res[i-1]*res[i-1]; } // returning result return res; } console.log(test(3,4)); // result : [3, 9, 81, 6561] first decalare array server result.first entry in array first number (a). rest of array (b-1), need multiply last entry in array self.

ruby on rails - Display nested attributes together in view or index.html.erb -

i have product model of attributes , has_many relationship through product_images model. of updates, edits etc work charm i'm having difficulty bringing data through front end bootstrap theme. what i'm trying have last 5 products , there default images come through can have product image , associated product attributes together. @ present have attributes , of images in 2 separate arrays. i have looked @ group_by cant work out how have attributes + images grouped 2 arrays product_id. have no idea how go this. app/controller/home_controller.html.erb class homecontroller < applicationcontroller def index @products = product.last(5) @product_ids = @products.map(&:id) @product_images = productimage.where(:product_id => @product_ids, :default_image => true ) end end the below dumps 2 arrays not together.image / attributes per product_id app/views/home/index.html.erb <% @products.each |pd| %> <%= pd.product_name %...

Python: difficulty converting ascii to unicode -

my goal: page source url , count instances of keyword within page source how doing it: getting pagesource via urllib2, looping through each char of page source , comparing keyword my problem: keyword encoded in utf-8 while page source in ascii... running errors whenever try conversions. getting page source: import urllib2 response = urllib2.urlopen(myurl) return response.read() comparing page source , keyword: pagesource[i] == keyword[j] i need convert 1 of these strings other's encoding. intuitively felt ascii (the page source) utf-8 (the key word) best , easiest, so: pagesource = unicode(pagesource) unicodedecodeerror: 'ascii' codec can't decode byte __ in position __: ordinal not in range(128) i'll assume remote "source page" contains more ascii otherwise comparison work (ascii subset of utf-8. i.e. in ascii 0x41, same utf-8). you may find python requests library easier automatically decode remote content unicode stri...

android - Toolbar as self-managed ActionBar vs Toolbar as framework managed ActionBar -

alright, trying understand lose if use toolbar self-managed actionbar , not use setsupportactionbar . afaik, actionbar is, provide placeholders logo, navigation , menu items , let fragments add/customize menu items. the same functionality achieved using toolbar.setlogo() , toolbar.setnavigationicon() , toolbar.setnavigationonclicklistener() , toolbar.inflatemenu() apis. of course, directing menu handling logic fragments might lost think not big of deal if activity knows fragment on top , changes menu items accordingly. i trying make sure : if can achieve every actionbar capability using toolbar , menuitems (and not using setsupportactionbar() ). is ok not have exhaustive knowledge of actionbar apis. of actionbar apis confusing. using sethomeasup api show hamburger icon, icon etc., doesn't feel right. if starts learning android today, need understand framework's actionbar apis? update : in article android design support library under section co...

jena - sparql to retrieve the value of a min constraint -

Image
how can retrieve min constraint on class' attribute using sparql? have value min 1000 decimal , , 1000 in hypothetical world have such statement: class: x subclassof: hasobjectproperty min 1 y if write sparql query as: select * { ?s rdfs:subclassof ?o. } you must extract refs:subclassof axioms. however, if need precise , know ones have cardinality restrictions, need go further: prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> prefix : <http://example.com#> select * { ?s rdfs:subclassof ?o. ?o ?x ?y. filter(?s = :x) } among others, can see following result: as can see, there 2 relevant items, 1 y , 1 number presented non-negative integer. therefore, 1 way each item put filter ?x in sparql query , each 1 one 1 out. example, filter owl:onclass give ?y : prefix : <http://example.com#> select * { ?s rdfs:subclassof ?o. ?o owl:onclass ?y. filter(?s = :x)

c# - Store Text to String[] Arrays? -

this question has answer here: how read text file line line windows rt? 3 answers how can store data text string or array in windows store using c#? tried method did not work: string[] phparay ={@"f:\designe- video\projects\phpgonehelp\phpgonehelp\phpcode\php1.txt"}; i thought execute data text file, unfortunately prints text path. i think you'r looking this: string[] lines = system.io.file.readalllines(@"f:\designe- video\projects\phpgonehelp\phpgonehelp\phpcode\php1.txt"); this taken https://msdn.microsoft.com/en-us/library/ezwyzy7b.aspx

c# - Pass parameters in Html.BeginForm that don't come from <input> -

i using html.beginform("details", "controllername", formmethod.post) send parameters controller . working fine. however, works <input> tags within html. there way post value of other tags? example <span> or else? @ end in actionresult details() , receive values within <span> ? thank you no, can't. input , select , textarea controls values posted server. can set in background hidden input control span value can't expect span automatically posted.

ssl - How to import javascript code from external website with different protocol -

this question has answer here: how allow http content within iframe on https site 8 answers i use advertisement system (popup) on website, have installed ssl certificate on , visitors redirect https mode, javascript code doesn't load in https.. js code: <script type="text/javascript">var popupsky_user_id = xxxx;</script> <script type="text/javascript" src="http://xxxxxxx/website/js"></script> how can use js code on website? possible? thanks http://xxxxxxx/website/js will blocked on https website need reference https instead i.e. https://xxxxxxx/website/js

Show image as byte[] from database as graphic image in JSF page -

i have image content byte[] database. private byte[] image; how can show byte array real graphic image in jsf page? this not directly possible <h:graphicimage> . can point url, not byte[] nor inputstream . basically, need make sure bytes directly available http response on given url, can use in <h:graphicimage> (or plain html <img> ). provided you're identifying image id so: <h:graphicimage value="/image/#{somebean.imageid}" /> here's kickoff example of such servlet: @webservlet("/image/*") public class imageservlet extends httpservlet { @ejb private imageservice service; @override protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { long id = long.valueof(request.getpathinfo().substring(1)); image image = service.find(id); response.setcontenttype(getservletcontext().getmimetype(image.getname())); ...

Mule avoid downloading file after db select statement -

<flow name="testflow1" doc:name="testflow1"> <http:inbound-endpoint exchange-pattern="request-response" host="${hostname}" port="${port}" path="dbtest" doc:name="http"/> <db:select config-ref="postgresql" doc:name="database"> <db:parameterized-query><![cdata[select id, name, int_status test]]></db:parameterized-query> </db:select> <!--line 6 --> <!-- <set-payload value="==no downlaod=#[payload]" doc:name="set payload"/>--> </flow> when run application url: host:port/dbtest, getting file downloaded. how can avoid downloading file? if enable line 6, don't file downloaded, instead displays in browser. since have used http inbound 'exchange-pattern' request-response . when enable setpayload(line 6) returning brower. if dont want that, make http exchange-...

ruby on rails - Single Table Inheritance or Type Table -

i facing design decision cannot solve. in application user have ability create campaign set of different campaign types available them. originally, implemented creating campaign , campaigntype model campaign has campaign_type_id attribute know type of campaign was. i seeded database possible campaigntype models. allows me fetch campaigntype's , display them options users when creating campaign. i looking refactor because in solution stuck using switch or if/else blocks check type campaign before performing logic (no subclasses). the alternative rid of campaigntype table , use simple type attribute on campaign model. allows me create subclasses of campaign , rid of switch , if/else blocks. the problem approach still need able list available campaign types users. means need iterate campaign.subclasses classes. works except means need add bunch of attributes each subclass methods displaying in ui. original campaigntype.create! :fa_icon => "fa-line-chart...

javascript - Fiber Error with npm package serial-port with meteor -

i'm using serialport npm package meteor. i've used wrapasync list serial ports don't know how serialport.on method. i've error when want inser datas in cars collection : meteor code must run within fiber. try wrapping callbacks pass non-meteor libraries meteor.bindenvironment. code : meteor.startup(function () { serialport = meteor.npmrequire('serialport'); // wrap method serialport.list call synchronously listserialports = function(callback) { serialport.list(function (err, ports) { callback(null, ports); }); } // reset cars collection }); meteor.methods({ serialportsrefresh: function () { // todo : problem when several arduinos ? config.remove({key:'serialports'}); // call serialport.list var asynclistserialports = meteor.wrapasync(listserialports); var resultslistserialports = asynclistserialports(); // insert results in database var configserialports = {key: "serialport...

Convert SQLite ROWID to primary key -

i have large table without primary key. instead, i've been using built-in rowid one. problem: can't vacuum database, because: the vacuum command may change rowids of entries in tables not have explicit integer primary key. how can convert rowid integer primary key , preserving existing rowids , behavior (or otherwise vacuum not mess rowids )?

python - Why does upsert a record using update_one raise ValueError? -

i want add record collection if key doesn't exist. understand [mongodb][1] offers upsert for did db.collection.update({"_id":"key1"},{"_id":"key1"},true) this seems work. however in pymongo documentation says update deprecated , use update_one() . but: db.collection.update_one({"_id":"key1"},{"_id":"key1"},true) gives: raise valueerror('update works $ operators') valueerror: update works $ operators i don't understand why update_one different , why need use $ operator. can help? this because didn't specify update operator . example $set id value use: db.collection.update_one({"_id":"key1"}, {"$set": {"id":"key1"}}, upsert=true) note in mongo shell, replace document new document.

java - What is the easiest way to hide HTML code from users eye? -

i working jsp pages , know easiest way comment html/java code being able see when open source on web. now, used use <%-- html/java code --%> however, later on screw highlighting of jsp file. maybe there way of commenting multiple lines without possibility see them in html source on web. look: <%-- comment --%> - commenting out html <% /*java code*/ %> - commenting out java code <!-- comment --> - html comment, ignored browser

ios - Resizing for iPhone 4 from an iPhone 5 without using autolayout or making a new xib -

my app works iphone5 , 6, 6+, not iphone4 (not ipad, that's not necessary @ moment). wrote storyboard being dimensions of iphone 5 screen, that's problem arises. collision, pixels,outlines, etc have been fitted 5. scales correctly when going 6, when goes down 4, 20% of right side gets cut off. told use autolayout messes integrity of collision, because made without using (will used next app). while it's simple game, still take while redo , can't imagine same. there sort of reliable code can use "quick fix" resizes correctly 4 same relative dimensions? i saw somewhere test bounds , have program scale screen accordingly, possible? the best thing right take hit convert code not use hard coded numbers. said built work on 4" devices tells me did things x = 160; instead of x = view.bounds.width/2. need go through code , anywhere use hard coded number 160, consider code trying (160 vs center of screen). you not need use auto layout accomplish ...

java - Jersey REST Client - Treat Custom MediaType as MediaType.APPLICATION_JSON -

i'm writing rest client using jersey with jacksonfeature enabled webservice forces me specify custom-named content type, though it's regular json. in other words, when this: request request = buildmysamplerequestpojo(); response response = requestbuilder.post( entity.entity(request, mediatype.application_json) ); the service complains i'm using invalid content type. can around specifying custom-named media type in place of mediatype.application_json constant: response response = requestbuilder.post( entity.entity(request, "vnd.stupidnamethatreallyisjustjson+json") ); however, when that, get: *severe: messagebodywriter not found media type=stupidnamethatreallyisjustjson* is there way can have jersey treat customized media type name if regular json without writing customized messagebodywriter? i think use both this (jax-rs entity providers) , this (use jackson jersey) , in order achieve want. in nutshell, register messageb...

jpa - Self referencing @OneToMany -

i have following class @entity public class comment extends base { @manytoone(cascade = cascadetype.all, fetch = fetchtype.eager) private comment inreplyto; @onetomany(mappedby = "inreplyto", cascade = cascadetype.all, fetch = fetchtype.eager) private collection<comment> replies; public comment() { } public collection<comment> getreplies() { return replies; } public void setreplies(collection<comment> comments) { this.replies = comments; } public comment getinreplyto() { return inreplyto; } public void setinreplyto(comment inreplyto) { this.inreplyto = inreplyto; } } adding new comment , setting inreplyto works , comment saved db. inreplyto comment has replies field null. also doing c.setreplies(new arraylist<comment>()); c.getreplies().add(x); repo.save(c); results in error org.datanucleus.store.types.incompatiblefieldtypeexception: incompatible type requested field "comment.replies" : java.util.collec...

c# - 'type' does not contain a definition for 'member' and no extension method 'name' accepting a first argument of type 'type' could be found -

i'm pretty new using related graphics in programs , i'm stumped because it's giving me error 'type' not contain definition 'member' , no extension method 'name' accepting first argument of type 'type' found . i've instantiated object , it's still giving me issues , i'm trying call auto generated code visual studio made windows panel. here code main: namespace testerproject { public class program { static void main(string[] args) { loginout person = new loginout(); display visualizer = new display(); visualizer.display(); person.login(); } } } and here class i'm trying call (display): namespace testerproject { public partial class display : form { public display() { initializecomponent(); } any guys can provide awesome, thanks! this constructor: public display() { initializecomponent(); } so when call ...

jquery - Javascript function to select images only works on first image -

here function i'm using select photos. become selected being added array , having green check mark placed on them. when clicked again, should removed array, , check mark should removed well. this works fine, except if select, unselect photo, not let select again after that. exception first photo in list (top left) , i'm not sure why is. can select , unselect many times , works fine. photos behave this. here code: var selectedphotos = new array(); function selectvehicle(photoid) { if ( selectedphotos.indexof(photoid) > -1 ) { $('#check'+photoid).css('z-index', '-1'); selectedphotos.splice(photoid, 1); } else { selectedphotos.push(photoid); $('#check'+photoid).css('z-index', '1'); } } you can view page in action here: http://lindseymotors.com/unassignedphotos.php you need pass index of element remove in splice index @ start changing array var index = selectedpho...

javascript - Can someone help me dissect what is wrong with my Rails PUT ajax request? -

Image
i don't have experience ajax other few 1 shots on rails app , post requests i'm having serious problems on how make ajax request put method. i'm having problems passing in rail's @variables controller through ajax. i have view code below: - if logged_in? && @account.stacks.count > 0 - @account.stacks.each |stack| - haml_tag :div, stack.title = check_box_tag 'stacked', 0, false, { stack: stack.id, project: @project.id } this creates html tags pictured below: this .js code below: $(document).ready(function() { // grab checked value 0 unchecked, 1 checked var check_value = $("input[name='stacked']").val(); $("input[name='stacked']").click(function() { if (check_value == 0) { //grab id of stack object var stack_id = $("input[name='stacked']").attr("stack"); //change unchecked value checked check_value = 1; //make reque...

jquery - Javascript format array with regex youtube video ids -

apologies in advance know there many answers question have not been successful implementing of given answers. being said, let's issue. i have table containing text inputs user enters youtube video ids onsubmit javascript create array containing these youtube video ids if user enters youtube url, array breaks quick solution if can me regex validation work user alerted , correct input start ideal solution i'm not fond of alerting users , making them change they've entered bad user experience if feeling helpful today , show me how take enter , strip out url bits , push youtube video id array super wonderful :) example: if user entered ["https://www.youtube.com/watch?v=k1cscqoj1da", "https://youtu.be/wij1sfrgmds", "iiszg-spuuo"] the code format inputs , final usersongs array be: ["k1cscqoj1da", "wij1sfrgmds", "iiszg-spuuo"] here fiddle http://jsfiddle.net/1qlr9n2j/ as can see, alert says no ...

excel - search for multiple values - loop -

i think can done in vba. tried vlookup, no luck. i want search whole sheet values. these values come row in sheet. once each value found, looks top row , pulls value. i might need loop through each value in row , search sheet there? my thought/example: sheet1!a:a 1234 5325 6346 6342 look in sheet 2 1234. lets found in cell g5, @ value in g1 , input cell a1 on sheet 2. i'm sorry making confusing. here's have starting out: sub findvalues() dim searchrow string dim searchrange range, cl range dim firstfound string dim sh worksheet ' set search value searchrow = sheets("sheet2").range("b:b") getting error on last line. run-time error '13': type mismatch you need set range object . cannot assign string unless looking property string address property . dim searchrow string dim searchrange range searchrow = sheets("sheet2").range("b:b").address set searchrange = sheets("sheet2").range(...

wpf - why is it displaying class name instead of property? -

i have following combobox in xaml: <combobox x:name="cmbcharacters1" horizontalalignment="left" margin="18,21,0,0" verticalalignment="top" width="136" selectedindex="0" height="32" rendertransformorigin="1.53,-1.281" itemssource="{binding characterentity}" selecteditem="{binding name}" selectedvalue="{binding tag}"/> and following class , binding code public class characterentity { public string name { get; set; } public string tag { get; set; } } .... cmbcharacters1.itemssource = characters;//it list<characterentity> when run displays class name instead of content of name property, doing wrong? i think forgot use this: displaymemberpath="tag" or "name" whatever wish display!

python - Why does `mylist[:] = reversed(mylist)` work? -

the following reverses list "in-place" , works in python 2 , 3: >>> mylist = [1, 2, 3, 4, 5] >>> mylist[:] = reversed(mylist) >>> mylist [5, 4, 3, 2, 1] why/how? since reversed gives me iterator , doesn't copy list beforehand, , since [:]= replaces "in-place", surprised. , following, using reversed , breaks expected: >>> mylist = [1, 2, 3, 4, 5] >>> i, item in enumerate(reversed(mylist)): mylist[i] = item >>> mylist [5, 4, 3, 4, 5] why doesn't [:] = fail that? and yes, know mylist.reverse() . cpython list slice assigment convert iterable list first calling pysequence_fast . source: https://hg.python.org/cpython/file/7556df35b913/objects/listobject.c#l611 v_as_sf = pysequence_fast(v, "can assign iterable"); even pypy similar : def setslice__list_any_any_any(space, w_list, w_start, w_stop, w_iterable): length = w_list.length() start, stop = normal...

php - fb login button has to be hit twice -

is there way make login users don't have click login button twice? when click on login goes index (my redirect uri) doesn't login. have click button again login. i have login script inside if ( isset( $session ) ) statement. facebooksession::setdefaultapplication(appnumber, appsecret); $helper = new facebookredirectloginhelper('my_url'); $permissions = array( 'email', 'user_birthday', 'user_location' ); try { if ( isset( $_session['access_token'] ) ) { // check if access token has been set. $session = new facebooksession( $_session['access_token'] ); } else { // access token code parameter in url. $session = $helper->getsessionfromredirect(); } if ( isset( $session ) ) { // retrieve & store access token in session. $_session['access_token'] = $session->gettoken(); // log in code here } }

powershell - Show the previous and after N lines each for the matched lines? -

the following command show lines match pattern. cat file.txt | select-string -pattern "..." how show previous , after 3 lines each matched lines? (like -c3 parameter of grep.) possible print out line number? btw, command slower comparing grep? specify filename in -path parameter of select-string , , use -context switch specify number of lines before , after include. select-string -path file.txt -pattern "..." -context 1,3 the file name , line number included in output

clr - C# System.Object being the ultimate base class -

Image
in msdn spec, notice system.object ultimate base class in .net. system.valuetype abstract class inheriting system.object , overrides methods equals , compare etc... value types bool , int etc.. inherit system.valuetype other .net objects inherits system.object . i have 2 questions on this. what need of system.object? why wasn't interface preferred on here? am assuming has 2 direct children(ignoring can create more) system.valuetype , system.referencetype both having entirely different implementations. **edit:**there no system.referencetype. there sytem.object , sytem.valuetype (overriding base class). apologies here. system.object may needed handle basic clr functionalities object creation using new(), enforcing default constructor, gc etc ? when de-compile sytem dll, , see implementation of bool, see struct. class (say exception) don't see inheritance system.referencetype or system.object. how inheritance handled ? infact, common type system doing m...

methods - Why should we use a List of a particular type in Java -

i going through lesson in java, , lesson covers passing arraylist object through static method. in first static method, see arraylist had declared arraylist , , name it. first static method displays of elements in array. second static method changes elements of arraylist . when declaring arraylist in method, must declared arraylist<integer> modification purposes. why way, , why make difference? thank willing shed light on this. import java.util.arraylist; public class chap11part5 { public static void main(string[] args) { arraylist<integer> numbers = new arraylist<integer>(); //for-loop create elements arraylist (int = 1; < 11; ++i) numbers.add(i); display(numbers); //display elements change(numbers, 5); //change elements (see "change" method) display(numbers); //display new results } //loop display elements of arraylist static void display(arraylist arr) { ...

javascript - Modal popup with cookie.js -

so trying implement modal popup on homepage displays on first page visit , expires after set amount of time. using cookie.js , have jsfiddle (here: https://jsfiddle.net/yalsdahk/68/ ) works perfection. however, when try copy code on homepage, doesn't seem work. can offer assistance? here's html markup , script: <div id="init-modal-wrapper"> <div class="opening-modal-title"> little heads up... </div> <div class="close_box_6"> <div class="icon-font-25 alignment" data-icon="&#xe0ab"></div> </div> <div id="horizontal_bar" class="alignment"> </div> <div id="popupfoot" class="alignment"> <div id="typeface" class="init-modal-text">stuff!</div> </div> </div> <div class="init-modal-overlay"></div> $(document).ready(function() { if ($.cookie('init...

plsql - How do we make sure the record is being locked? -

in oracle ebs, when doing data conversions , interfaces, loading data oracle system, how make sure record being locked? how make sure no other person updating our records? oracle ebs seeded api's take care locking. don't insert data ebs base tables directly, validate data , insert interface tables later run oracle standard programs import interface tables data base tables. these oracle standard programs use oracle seeded api insert data multiple base tables. how make sure no other person updating our records? developers use own custom staging tables import data ebs. when data upload staging tables interface table maintain each interface data source different, other persons don't update other interfaces records, can't track if updated database backend tools sql developer or toad. can track transaction last updated column if update applications if have specific issue related locking let know

collapsible lists in lightswitch html client with external data source -

i have been searching plugin/extension/code me generate collapsible list. though visual studio provides plugin same, developer specifies plugin can used screens intrinsic(created in lightswitch) data sources lscollapsiblelist i have tried using jquery mobile theme same , able zip file. the main problem not know files use , reference them. any on topic welcome. thank in advance have tried following this: http://lightswitchhelpwebsite.com/blog/tabid/61/entryid/3246/creating-advanced-lightswitch-html-screen-templates.aspx this website great things this, , theres downloadable version of project can see how works: http://silverlight.adefwebserver.com/files/lightswitch/lscollapsiblelist.zip before referencing them, best way drag css file content folder (within visual studio environment), , js file scripts folder. means visual studio knows files there within specific project. finally, reference both css file , js files in default.htm file located html client s...

tomcat - How to extract war files at specific location through command prompt or using java? -

hi in search of logic extract war files. in tomcat extract war in - meta-inf - web-inf -resources i have gone through link where jar -xvf -c abc.war outputdirectory doesn't work.let me know if there clue.

javascript - Using underscore _.extend to avoid overwriting nested objects? -

var obj = { customerinfo: { fname: "tom", lname: "smith", age: 23, height: 160 }, car: { color: "red", numwheels: 4 } }; i modify object into: var obj = { customerinfo: { fname: "sally", lname: "adams", mname: "tully", age: 23, height: 160 }, car: { color: "red", numwheels: 4 } }; however, if do _.extend(obj, { customerinfo: { fname: "sally", lname: "adams", mname: "tully" } }); the object becomes { customerinfo: { fname: "sally", lname: "adams", mname: "tully" }, car: { color: "red", numwheels: 4 } }; and age , height have been wiped out. what need preserve data that's nested? and updating more complex objects? http://jsfiddle.net/j4l18p7k/2/#share there better ways of achieving deep merge behavior...

java - Eclipse RCP and RAP customizable table control -

i looking table control customizable , works both on rcp , rap, single source. by customizable mean this: a cell table can splitted again in rows , columns. or should possible cell renderer draw cell table it should possible have group of columns fixed left side (but not necessary, because think workaround possible) should possible have columngroups maybe of can me such control, maybe names can research on. rap 3.0 (to released june 2015 eclipse mars) contains implementation of nebula grid . widget supports column groups. rap trees , tables support number of columns fixed left edge via setdata(rwt.fixed_colums, boolean.true) . feature not yet available grid, chances can added. splitting cells not yet supported in rap, however, using support html markup simulated.

utf 8 - echo HINDI language word stored in an array in PHP script -

i trying echo hindi script words stored in array. output getting displayed when use print_r() not when use echo . code below. changes need make? <meta http-equiv="content-type" content="text/html;charset=utf-8"> <?php $base_arr=array("सूर्योदय","कँगन","ख गोल","गँगरी","घंटाघर","चंचल","छूईमुई","जिज्ञासा","झंकार","टिकट","ठंढाई","डांटना","तौलिया","थकान","दंगल","धुँधला","निंदनीय","पँखुडी","फाइल","बाँटना","भँवर","मंजीरा","यंत्रक","रुकावट","लेकिन","वंचित","शांतनु","षडयंत्र","सँजोग","हिंदुस्तान","अजय","आँकड़े","इंकार","ईखराज","उँगली","ऊगना","एजेंसी","ऐंठना","ओवन","औलाद...

this - Javascript call method -

why following code output 1 ? function func(){ alert(this) } var = 1; func.call(i); definition function.prototype.call(this,arg1,arg2,...); thus, when call func.call , first argument pass in bound this variable. in function func , this variable replaced first argument 1 . to play further you can extend more arguments func , call further arguments , see happen: function func(a,b){ alert(this + a*b); } func.call(1,2,3); recall definition, first argument or func.call refers this variable of func . you'll end running alert( 1 + 2*3 ); ** ref: ** https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/function/call ** further reading ** function.prototype.call has close sibling function.prototype.apply . first argument of both functions refers this variable. difference function.prototype.apply accepts arguments of such function in array. so instead of func.call(1,2,3); you call by func.apply...

notify iOS & Android on data change on server -

i'm creating mobile application ios , android. problem when data has changed on server, cannot notify mobile devices. i have found 3 solutions, each have minus , pluses. use push notifications. since ios shows notification user not solution @ all. cannot know if notification go device or when will. for every x seconds ask server if change exists. don't want that, because creating many http connections , closing them not idea think. if data changed right after device asks, info change on device occur late. use web socket. application's 1 time usage expectation ~2 minutes. web socket looks choice, because app terminated or go background state , battery consume won't much. server side data changes come device in time. don't know web socket. opinion acceptable? how many concurrent connections can done server. question too. here solutions. please guys. thank you. the document suggest assumption 1. above incorrect. if read the notification payload...

javascript - How can I toggle a radio button's checked state with jQuery? -

as can seen here , i've got html: <input type="radio" id="radbtnemp" >rad btn</input> ...and jquery: $('#radbtnemp').click(function () { alert("radbtnemp clicked"); }); the alert does display when click radio button; however, clicking radio button second time not toggle state unchecked. how can in jquery? i want able respond state (or similar): if ($('#radbtnemp').attr('checked', true)) { // stuff } else { // other stuff } ...but if radiobutton never checked/false, doesn't work. the radio buttons cannot checked , unchecked.. for need use checkboxes: html: <input type = "checkbox" id = "mycheckbox">i checkbox</input> jquery: $('#mycheckbox').on('click', function() { if ($('#mycheckbox').is(':checked')) { // code } else { // code } }) hope helps

php - How can I separate a string of urls and print each link? -

how can separate each link string: $field = "www.link1.com www.link2.com"; and output them (expected output): link1 title www.link1.com link2 title www.link2.com my current code looks this: <?php $field = "www.link1.com www.link2.com"; if ($field == "link1"); { $output="link1 title</br>".$field ; } echo $output; ?> but outputs (current output): link1 title www.link1.com www.link2.com so how can change/modify code urls separated , print them shown above? this should work you: here first explode() string array, have each url array element. then loop through each link , print them. grab name between www. , next dot preg_replace() . $arr = array_map("trim", explode(php_eol, $field)); foreach($arr $v) { echo $v . " title<br>"; echo preg_replace("/^www\.([^\.]*)(.*?)$/", "$1", $v) . "<br><br...

ruby - Unzip a file an upload all its content to S3 using Rails on Heroku -

i building api in rails, , 1 of calls zip file containing static html site, upload s3, , return public url. what's best way approach this? i'm thinking of unzipping file in heroku's tmp directory , using s3_uploader upload content on s3. is worth using carrierwave ? nobody answered, i'll explain how approached issue. i'm using carrierwave upload zip file s3, , i'm calling unzip method asynchronously delayed_job gem. pretty explained on heroku's dev center page . the unzip method downloads , extracts s3 zip file on heroku's tmp folder, uploads s3 using s3_uploader gem. works quite nicely, thing have sort out @ point deleting unzipped folder when model entity gets deleted.

Java OpenCSV How to edit specific cells from csv file -

i have csv file looks this: http://gyazo.com/5dcfb8eca4e133cbeac87f514099e320.png i need figure out how can read specific cells , update them in file. this code using: import java.util.list; import java.io.filereader; import java.io.filewriter; import java.io.ioexception; import com.opencsv.*; public class readcsv { private static final char separator = ';'; public static void updatecsv(string input, string output, string replace, int row, int col) throws ioexception { csvreader reader = new csvreader(new filereader(input),separator); list<string[]> csvbody = reader.readall(); csvbody.get(row)[col]=replace; reader.close(); csvwriter writer = new csvwriter(new filewriter(output),separator,' '); writer.writeall(csvbody); writer.flush(); writer.close(); } public static void main(string[] args) throws ioexception { string source ...