Posts

Showing posts from April, 2015

php - Read a page generated with JavaScript -

this time i'm looking special. in php page, got table generated javascript, here example : example page this table racing game results. didn't write js, , can't change format of results. need parse these results variables, generate championship results giving points guys, adding points of multiple series, etc... i tried : parsing domdocument, substr, it's js generated can't work. >>this solution<< sounded doesn't work. do guys have idea exploitable array ? if not, suggest alternative solution ? i'm not able reproduce js in php function, hard. here js : click thank ! here's how you'd able parse initial array in php: $url = 'http://mxs-concept.com/liveresults/test.php'; $page = file_get_contents($url); // fetch page preg_match('/resultslines=(.+)print_race_analysis/sim', $page, $matches); // find javascript array $js = preg_replace('/,\s+\]$/', ']', $matches[1]); // fix last

java - Use of writeDouble produces nonsense -

this question extension of discussion found here . goal write 2 formatted columns of arrayed x , y data file (type double ). current attempt accomplish follows: try { fileoutputstream fos = new fileoutputstream("angle.txt"); dataoutputstream dos = new dataoutputstream(fos); (i = 0; < i_max-1; = + 1) { dos.writedouble(theta[i]); } dos.close(); } catch (ioexception error) { system.out.println("ioexception: " + error); } this code derived example found here (dataoutputstream). having limited grasp of java, expected work 1 column only; instead produced this: ?¹™™™™™Å¡?¹™™™™™Å¡?¹™™™™™Å¡?¹™™™™™Å¡?¹™™™™™Å¡?¹™™™™™Å¡?¹™™™™™Å¡?¹™... i don't understand i'm doing wrong. any insights can offer great help. my next question be: how format not 1 two columns of type double , formatted ("%1$16.6f, %2$16.6f", time[i], theta[i]) . right i'm following this discussion. however, compiler dislikes approach use of writedouble . yo

javascript - Using constructor function to add methods -

the classic way create constructor function like: var obj = function(param){ this.param = param; this.method = function(){ console.log(this.param); } } but why can't this: obj.anothermethod = function(){ //some code } (i know obj.prototype.anothermethod ). in practical usage can't understand why use string.prototype.func instead of string.func define new method. because string constructor function , it's impossible add method it? those different things. if add method constructor.prototype , available on instances of constructor . you can add methods constructor itself. however, instances won't inherit them. for example, charat method defined on string.prototype , can use both "abc".charat(1) , string.prototype.charat.call("abc", 1) . but fromcharcode defined on string , can use string.fromcharcode(65) , "abc".fromcharcode undefined.

RPN Calculator Ruby matching in arrays -

i'm making reverse polish notation calculator. wrote out gameplan , trying fill in. i'm @ part want take integers in array , move them new array (using shift remove permanently array). this should easy can't figure out. tried identifying integers-only things integer.match(x) x.class == integer but that's not working. i've tried building pull that's not in operations array, like, 1 fails: x.include?(operations) i new , not @ coding. if you'd berate me how code sloppy or posted wrong, has. i'm trying. thanks, class rpncalculator def initialize(problem) @problem = problem end def resolve array = @problem.split(" ") @array = array operations = ["+", "-", "*"] @operations = operations queue = [] @queue = queue array.map! { |x| /[0-9]/.match(x) ? x.to_i : x} array.each |x| #this i'm building & f

javascript - CKEditor AJAX request returning error 500 -

i'm using ckeditor on mvc site, using ajax edit 'bio' of sports team. i have json result in controller receives string , int. on ajax request function not called. the ajax being hit in browser, , returning 500. breakpoint in controller not being hit. failing on send function of ajax -as note, works if user bio: "hello world", teamid: 2 cshtml function updatebio() { var myurl = "/team/updatebio"; var teamtoedit = 2; ckeditor.instances.bioeditor.updateelement(); var biostring = $("#bioeditor").val().trim(); $.ajax({ url: myurl, data: { bio: biostring , teamid: teamtoedit }, type: 'post', datatype: 'json', success: function(result) { $("#post-message-content").text(result.data); $("#post-editor").text(""); $(

.htaccess - Redirect index.php with parameters to index.php to others parameters using htaccess -

i have shop has migrated version, , product catalog has changed. now, have table correspondence of product id , need create redirection htaccess this: rewriterule ^index.php?id_product=3&controller=product$ index.php id_product=101064&controller=product [r=301,l] i know the old id 3 id 101064 ... doesn't work. i tried: rewriterule ^toto.php$ index.php?id_product=101064&controller=product [r=301,l] and works, why doesn't first code snippet work? you have use %{query_string} . put code in htaccess (which has in root folder) rewriteengine on rewritecond %{query_string} ^id_product=3&controller=product$ rewriterule ^index\.php$ /index.php?id_product=101064&controller=product [r=301,l]

ios - How to provide view controllers with pointer to already-initialized singleton object? -

after initializing singleton object via -[appdelegate didfinishlaunchingwithoptions?] , how 1 pass pointer of object view controller? it helps, let's assume object stand-alone reasonably coupled ui. (for example, managing server connection thread.) prefer more "intimate" signaling via nsnotificationcenter . it depends. if object needed single view controller, initialize in viewdidload . if is needed entire app, initialize in app delegate. in case, best in app delegate since needed lifetime of application , not used 1 view controller. you can create property in app delegate , put object in it. can delegate anywhere in application this: ((appdelegate *)[uiapplication sharedapplication].delegate) so, long have #imported appdelegate.h in file accessing app delegate from, can object this: myobject *object = ((appdelegate *)[uiapplication sharedapplication].delegate).propertyname;

java - Internationalization in Spring Oauth exception messages -

is possible have spring oauth2 error messages localized? error messages invalidgrantexception , usernamenotfoundexception. maybe late, gonna leave answer here maybe else interested. as far know, there no builtin internationalization feature in spring oauth2 (please correct me if wrong). however, spring lets extends default implementations up. there 2 possible approaches i'd guess: 1. backend internationalize error messages on server , return them api. requires locale resolving (e.g. header locale resolving) 2. backend + frontend attach additional error codes response , frontend need map them localized message. the idea implement custom tokengranter , translate authenticationexception own exception (e.g. invalidgrantexception) on authenticating. example below creates different error codes different types of invalid_grant (appoache #2) : public class customtokengranter extends abstracttokengranter { private static final string error_code_key

grails - Unable to import org.apache.common.collections.list -

i using groovy grails tool suite grails project. trying use lazylist.decorate in 1 of domain classes , want import org.apache.common.collections.list within domain class. see org.apache.commons.collections_3.2.0.v2013030210310.jar available under ggts plugins folder. however, editor shows error @ import statement saying "groovy: unable resolve org.apache.common.collections.list". please help! since question missing code snippet suspect have line import org.apache.common.collections.list . should import org.apache.common.collections.list.* - or if lazylist want: import org.apache.common.collections.list.lazylist

appendChild of objects containing javascript attributes -

i have javascript function function webit(thumb){ webi = document.createelement("img"); webi.alt=thumb.id.replace("t", ""); webi.id = "w"+webi.alt; webi.classname = "web"; webi.src= thumb.src.replace("thm","web"); webi.height=233; webi.onclick='alert()'; document.body.appendchild(webi); } which supposed embed larger version of thumbnail image end of document. works fine except javascript function ( ie onxxx) stays resolutely null. seems no matter js function use , afaict thing try set to. the above example uses webi.onclick='alert()'; which fails leaving onclick null, though other statements succeed. when in javascript .onclick property expects function not string webi.onclick=function(){ alert(); }; you use addeventlistener method set event handler webi.addeventlistener("click",function(){ alert(); });

html - Distinguishing and Processing Only One Div Item with JQuery -

i creating list item folding/unfolding css , jquery. when click first item unfold it, items unfolded because names of class same. can distinguish 1 item list keeping class names same? my code below , sharing same class name. <div class="flip">unfold!</div> <div class="panel">hello<br>this first</div> <div class="flip">unfold 2!</div> <div class="panel">hello<br>this second</div> and jquery code below $(document).ready(function(){ $(".flip").click(function(){ $(".panel").slidedown("slow"); }); }); does jquery have command distinguish items? you can around source below well. http://jsfiddle.net/qmavqug6/ thanks in advance help. the .panel element want target next sibling of clicked flip , use .next() find target panel $(document).ready(function () { $(".flip").click(function () { $(this).next(".p

php - Checking a file for a specific IP address? -

what i'm trying check file named ip-addresses.php in same directory specific ip address , if ip not in file want assign value of spark here have far: $ip = if( $ip ) { $value = "spark"; } ?> so i'm trying have value $ip check php file ips , assign value of "spark" how do this? the function file() reads lines of file array, making easy check existing elements in_array() . $list = file("ip-addresses.txt", file_ignore_new_lines | file_skip_empty_lines); if (in_array($_server['remote_addr'], $list)) { $value = "spark"; }

javascript - Inputosaurus Text + jQuery UI Sortable -

i'm trying combine inputosaurus text jquery-ui sortable plugin can re-order tags , submit them in order. attaching sortable inputosaurus list works fine, can move tags around. need way inputosaurus detect they've moved. if submit form after moving tags, submitted in original order. here simple demonstration of i'm trying accomplish, need textbox have updated value of list html: <input type="text" id="tags" name="tags" value="foo,bar,baz"> javascript: $('#tags').inputosaurus(); $(".inputosaurus-container").sortable({ update: function( event, ui ) { alert( $('#tags').val() ); } }); http://jsfiddle.net/75c45jtn/1/ if me solve you'd hero! it may help. try this.. $(".inputosaurus-container").sortable({ update: function( event, ui ) { var val="",obj=null; var cnt=$('.inputosaurus-container').children('li

java - Asign int value to JCheckBox -

Image
im trying set value 5 different jcheckbox's having little trouble doing so. have set checkbox's boolean type data within main class before methods: boolean s1 = solarpanel.isselected(); boolean s2 = ducted.isselected(); boolean s3 = hometheatre.isselected(); boolean s4 = spa.isselected(); boolean s5 = swimming.isselected(); now im trying assign int value each of checkbox through function: private void options() { if (s1 == true){ s1 = 7500; } if (s2 == true){ s2 = 5000; } if (s3 == true){ s3 = 8000; } if (s4 == true){ s4 = 3500; } if (s5 == true){ s5 = 12000; } } but getting 'incompatible types' error. here calling 'options' function within function final price can calculated. in advance! consider alternate approach dealing group of objects in form of product has attributes productname & energyconsumption displayed in jlist using custom cell re

go - Golang panic crash prevention -

in golang panic without recover crash process, end putting following code snippet @ beginning of every function: defer func() { if err := recover(); err != nil { fmt.println(err) } }() just in order prevent program crashing. i'm wondering, way go? because think looks little bit strange put same code everywhere. it seems me, java way, bubbling exceptions calling function, until main function better way control exceptions/panics. understand it's go's design, advantage of crashing process go does? you should recover panic if know why. go program panic under 2 circumstances: a program logic error (such nil pointer dereference or out-of-bounds array or slice access) an intentional panic (called using panic(...) ) either code or code code calls in first case, crash appropriate because means program has entered bad state , shouldn't keep executing. in second case, should recover panic if expect it. best way explain it's extremely r

objective c - Need help incorporating "Preform Selector: WithObject: AfterDelay:" with the SKScene being paused -

i need incorporating the preformselector: withobject: afterdelay: with skscene being paused. making game there pause button pauses scene. this, not affect the preformselector: withobject: afterdelay: function calls "reload" function. without fixed user can fire shot, press pause, wait reload function called, un-pause, , shoot. makes user can continuously fire without having reload in "game time". there way fix this? you shouldn't using performselector:withobject:afterdelay: , because keeping track of timing , storing selectors , objects etc. method cumbersome. instead, make use of spritekit's +[skaction waitforduration:] action. you want following (i'm assuming code takes place somewhere in 1 of scene's methods): // replace 2.0 below long want wait, in seconds skaction *waitaction = [skaction waitforduration:2.0]; // i'm assuming "reload" method method declared in scene's // class , not other class, i

android - How to read a string array from external file in Roboium -

can 1 me how read array external file in robotium, parameterize test project. how can export result in robotium. scanner scanner = new scanner(getactivity().getresources().openrawresource(r.array.login_arr)); list<string> list = new arraylist<string-arrays>(r.array.); while (scanner.hasnext()) { string data = (scanner.next()); //read data record string [] values = data.split(","); for(int i;i<=values.length;i++){ solo.entertext(0, values[i]); }

php - How do I redirect to a specific page after inserting data in cakePHP scaffolding? -

well using scaffolding concept in cakephp first time, runs quite okay, problem facing is: after data getting inserted database page automatically redirected success page. i want redirect custom action page. can in cakephp scaffoliding? please me! no! can not add our custom redirection in scaffolding. scaffolding more non-production deployment used give initial idea framework , feasibility towards application. to precise question, have skip scaffolding particular action, write saving logic , redirect wherever want. can bake controller , create actions save time , can add redirection in that. hope help.

javascript - Class alert when section's top is equal or higher than main panel's top -

i have fixed panel content scrolled , separated divs. would, when content's div top reaches panel top, alert appear div's class. each div has class <div class="section-proceso anc1"> (both classes included on each div start section- , anc , if needed ant new class can added) live demo i have tried things no result: if ($("div[class^='anc']").offset().top >= $('.contentpanel').offset().top){ alert($(this).attr('class')); } use this: $(".contentpanel").scroll(function () { $("div[class*='anc']").each(function() { $this = $(this); var topview = $('.contentpanel').offset().top; var topelement = $this.offset().top; if (topelement <= topview && !$(this).hasclass('appear')){ $(this).addclass('appear'); alert($(this).attr('class')); } if (topelement >= topv

javascript - Using bootstrap modal to load different contents with jquery validations -

Image
i'm using bootstrap model edit table values. works perfectly. when i'm using bootstrapvalidator plugin validate modal there's problem. problem when click edit first time , load model works normally. if click edit again in same page, validation errors belongs previous 1 still shows. screen shot displays here, modal call <a data-toggle="modal" data-target="#dealmodal" onclick="ajax_get_edit_data('.$id.');"></a> validations <script type="text/javascript"> $(document).ready(function () { $('#dealform') .bootstrapvalidator({ message: 'this value not valid', fields: { deal_description: { message: 'the deal discription not valid', validators: { notempty: { message: 'the deal discription required , can\'t empty'

c++ - Selecting a valid random enum value in a general way -

let's have enumerated type e . enum class e : underlying_type_of_e { v1 = ue1, v2 = ue2, //... vn = uen }; typedef typename std::underlying_type<e>::type ue; in general, not values of ue valid values of e , because can choose relationship between them. there general way of creating random, valid (named in definition, not assignable ), values of e? this, example not work: std::mt19937 m; std::uniform_int_distribution<ue> randomue(0, std::numeric_limits<ue>::max()); e e = static_cast<e>( randomue(m) ); because: value range may not start 0 value range may not end @ std::numeric_limits::max() value range may not range @ - can select discrete values e ue, example {1, 3, 64, 272}. given of enumerated values known @ compile-time, cannot imagine reason why in way dangerous, or error-prone. as context of why want such thing - i'm working on genetic algorithm uses templated gene storage. now, use enums chromosomes , store them in std

ios - This view probably hasn't received initWithFrame: or initWithCoder: -

i using tableview , have implemented delegates , data source methods well. not new tableviews , delegates. still getting crash: terminating app due uncaught exception 'nsinternalinconsistencyexception', reason: 'requesting window of view (<uiview: 0xc8b7a00; frame = (0 0; 0 0); transform = [0, 0, 0, 0, 0, 0]; alpha = 0; opaque = no; autoresize = w; layer = (null)>) nil layer. view hasn't received initwithframe: or initwithcoder:.' i have used same code many other tableviews using 1 don't know wrong , know old or repeated question none of previous solutions worked me. here delegate , data source methods. -(nsinteger)numberofsectionsintableview:(uitableview *)tableview{ return 2; } -(nsinteger) tableview:(uitableview *)tableview numberofrowsinsection:(nsinteger)section{ int numberofrows = 0; if(section == 0){ numberofrows = [self.lotteryarray count]; }else{ numberofrows = 10; } return numberofrows; } -(

FFMPEG command issue for merging mp4 videos in android -

i using following ffmpeg command merging mp4 videos in android. video rotated 90 degree after merging. i stuck 2 days .if idea highly appriciated. thanks in advance ! complexcommand = new string[] { "ffmpeg", "-y", "-i", recordpath + "vid1.mp4", "-i", recordpath + "vid2.mp4", "-strict", "experimental", "-filter_complex", "[0:v]scale=w=640:h=480[v1]; [1:v]scale=w=640:h=480[v2]; [v1][0:a][v2][1:a] concat=n=2:v=1:a=1 [v] [a]", "-map", "[v]", "-map", "[a]", "-b", "2097k", "-vcodec", "mpeg4","-ab","64k","-ac","2","-ar","22050", recordpath + "outputn

html - How to change divs placing from horizontal to vertical using css? -

i have 3 divs in footer, divs used footer , can see them horizontally on bottom of page. <div class="footer-text footer_maindiv"> <div class="footer_leftdiv"> rights reserved </div> <div class="footer_middlediv"> <a href="url">help</a> </div> <div class="footer_rightdiv"> version 6.0 </div> </div> with css: .footer_maindiv { position: relative; width: 100%; border-top: 1px solid #eeeeee; margin: auto; } .footer_leftdiv { text-align: left; position : absolute; top: 0px; left: 20px; height: 50px; width: 33%; margin: auto; } .footer_middlediv { height: 50px; width: 33%; margin: auto; } .footer_rightdiv { text-align: right; position: absolute; top: 0px; right: 20px; height: 50px; width: 33%; margin: auto; } what way make divs horizont

java - Fire base not call onCancelled if timeout or not able to access server -

i using firebase , found , issue firebase not send error timeout or if not able connect server. in case unable provide correct information user issue is. firebase developers must handle common use-case. did encounter issue? .addlistenerforsinglevalueevent(new valueeventlistener() { @override public void ondatachange(datasnapshot data) { } @override public void oncancelled(firebaseerror arg0) { } utilize .info/connected monitor connection state. firebase works while offline , oncancelled event not going fired because still waiting connection restored message can delivered. firebase real-time sync platform. cannot keep data in sync without internet access (how local , remote reconciled?). need utilize disk persistence (in beta on ios) or @ least have initial connection things moving. check out offline capabilities details on of these topics.

geolocation - Android LocationUpdates not working -

i trying implement location update listener detect loction change in android.i have implemented following code. notification log "gps started". after onlocationchanged() function never calls. tested changing location never called. note gps enabbled. public class locationactivity extends activity implements locationlistener{ locationmanager lmanager=null; textview _textview; void initlocationservice() { { lmanager=(locationmanager)getsystemservice(context.location_service); criteria criteria=new criteria(); criteria.setaccuracy(criteria.accuracy_fine); gpsstatus.listener gpslistener=new gpsstatus.listener() { @override public void ongpsstatuschanged(int event) { if(event==gpsstatus.gps_event_stopped) { log.e("gps listener","gps stoped");

wordpress - Show attached media image if no thumbnail image detected -

i'm using if ( has_post_thumbnail() ){} to check if post have thumbnail image, echo get_attached_media('image', $post->id); display word array i need show attached image if trying 1 image in post , use thumbail, might want try one: add you're functions.php : // url of first image in post function catch_that_image() { global $post, $posts; $first_img = ''; ob_start(); ob_end_clean(); $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); $first_img = $matches [1] [0]; // no image found display default image instead if(empty($first_img)){ $first_img = "/images/default.jpg"; } return $first_img; } to call put <?php echo catch_that_image() ?> in template file within loop. i found brilliant code forum thread . saved me lot of times.

ios - Empty cells in InAppSettingsKit settings window -

i need show settings screen within app, use inappsettingskit implement this. use storyboards in app, created uitableviewcontroller iaskappsettingsviewcontroller super class. in class didn't implement other special methods except settingsviewcontrollerdidend: . problem need hide empty cells in table view (i have 2 parameters in settings, whole remaining screen full of empty cells). means remaining part of screen should empty, without empty cells, , grey background (as in settings.app). can make uiview empty frame footer view of uitableview , it's not best solution - background color of footer remains white in normal table view. what's best way limit number of cells? i set style property uitableview grouped in interface builder, , resolved problem.

css - Bootstrap responsive issues -

in bootstrap button class "navbar-toggle" in navbar appears when screen less 768px, i.e. 767px. but ipad mini has screen dimensions 768-1024px. should override bootstrap style 768px 992px, this: @media (min-width: 992px){ .navbar-toggle { display: none !important; } } you should not change bootstrap file itself, advised if need add dimensions own custom css file over-write bootstrap lib file. its ok overwrite bootstrap specify min , max width ensure catering particular edge case.

c# - typeof(interface).IsAssignableFrom(intptr) returns true -

i need go through properties implement interface, , have intptr property passes isassignablefrom condotion. is there other way check if property implements interface? this method goes through properties: protected void setowner() { ienumerable<propertyinfo> sourceproperties = this.gettype().getproperties(); foreach (propertyinfo pi in sourceproperties) { if (pi.name != "owner" && pi.declaringtype.getinterface("iownersystem") != null) //i tried too: typeof(iownersystem).isassignablefrom(pi.declaringtype)) { iownersystem systm = (iownersystem)pi.getvalue(this, null); if (systm != null) { systm.owner = this; } } } } and class: public abstract class aircraft : ownersystem { //a bunch of properties... public abstract intptr videowindow { get; } } pi.declaringtype type declares property, not type of property. in ca

java - Copy Multiple files from HDFS to local: Multithreading? -

in java application, need copy multiple files hdfs local file system. which of below 2 approaches faster ? 1. sequentially copy files one-by-one 2. run parallel threads copy each file. if have 1 physical disk part of local file system sequential approach best, parallel approach cause disk (in case of hard drive) spin , forth unnecessarily (depending on how os can or not , nature of writes), , because have 1 physical resource work @ time, 1 thread enough. if local file system has multiple physical disks, possibility of running parallel threads more performance ideal (like thread writes files going drive c, while thread b writes files going drive d).

javascript - select the file to upload before sending with jquery -

i looking select files on interface before sent server....you can see screenshot http://screencast.com/t/g2dixiysnkrm my script : <!doctype html> <html> <head> <meta charset="utf-8"> <!-- latest compiled , minified css --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <!-- optional theme --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <style > .attachmentselect { display: block; font-family: courier; font-size: 11px; width: 650px; } ption:checked { background-color: -moz-html-cellhighlight !important; color: -moz-html-cellhi

ios - Need to stop AVPlayer before playing new stream -

i have on-line radio app. located on first viewcontroller (tableview) audio streams. audio streams made table. clicking on name of stream screen opens avpalyer. problem when opening second stream, ашкые stream played simultaneously. how make played if 1 thread, , second turned down? avplayer: @interface radioviewcontroller () @end @implementation radioviewcontroller - (id)initwithnibname:(nsstring *)nibnameornil bundle:(nsbundle *)nibbundleornil { self = [super initwithnibname:nibnameornil bundle:nibbundleornil]; if (self) { // custom initialization } return self; } - (void)viewdidload { [super viewdidload]; // additional setup after loading view. nsstring *restorationid = self.restorationidentifier; nsstring *streamid = _detail.label; nsstring* identifer = [restorationid stringbyappendingstring: streamid]; nslog(@"%@", identifer); self.title = apptitle; self.streamlabel.text = _detail.label; //Определение потока nsstring *streamurl; if (_detail.label =

jquery - Javascript menu behaviour inverted if mouse is on menu when page is loading -

i'm getting crazy javascript menu. website dday.it , menu javascript pull down ajax loading. i'm trying fight issue quite annoying: if mouse on menu (accidentaly) when page loading, behaviour of menu inverted: normal state open, hover state closed. you can try live on website using chrome. i want solve myself (i'm rails developer i'm learning js) , cannot figure why behaviour change on page loading if js loaded , executed @ end of page... added code: here gist the faulty code in line 232: $navcontainer.addclass('animating').toggleclass('open'); it belongs function animatemenutoggle should receive status parameter (can passed function tooglemenu ). then, can use status parameter like: $navcontainer.addclass('animating').removeclass('open close').addclass(status);

How to add specific code for all user profile urls - rails app -

i trying sort out metatags rails app. have added tags each of main pages. there lots of 'user' pages (i.e. each user's profile page) , 'tags' pages (i.e. each tag blog posts has own page). i want add specific code (basically noindex it) apply 'user' pages, or 'tags' pages. i can't work out put code or how write it. able apply line of code urls websitename.com/users/..... , websitename.com/tags/.... e.g. <meta name="robots" content="noindex, follow"> is there way this? you can either in layout or view itself. the layout conditionally set, this: #app/views/layouts/application.html.erb <% if controller_name == "users" && action_name == "show" %> <meta name="robots" content="noindex, follow"> <% end %> -- for view, set yield block in layout , , populate view: #app/views/layouts/application.html.erb <%= yield :robots %>

javascript - how to update model's object in each loop -

i tried update each object in model within each loop i wanna add size property each object in model. but seems doesn't work. console (it didn't work after appended size property) self.model().get(i).size=123 >> 123 self.model().get(i) >> id: 1 name: "url_command_comparison" rounds: 2 team: "cvt" __proto__: object code model: function(){ return ember.a([ {id: 1, name: 'url_command_comparison', team: 'cvt' }, {id: 2, name: 'auto test', 'manualhours':20 ,'autohours': 3, .... $.each(this.model(),function(i,d){ self.model().get(i).set("size",self.perroundroi(d)*d.rounds*d.coverage) }); firstly model hook should never called ( this.model() ). it's called router when it's building context current url/transition. if want access model route after transition has completed can use this.currentmodel . if want access somew

python - Django views returning only one particular field instead of entire model -

i new django. tried write view returns fields of foreign key model associated search term. instead of whole model (foreign key) getting particular field. this view problem: @csrf_exempt @requires_csrf_token def search_haystack(request): if request.method == 'post': search_text = request.post['search'] print search_text else: search_text = '' results_list= none if str(search_text) != "": results_dish = searchqueryset().models(dish).filter(content=autoquery(request.post.get("search", ""))) result in results_dish: print result.resto print result.resto.name print result.resto.area results_list = [{'resto_id':result.resto.id , 'name' :result.resto.name, 'area' :result.resto.area} result in results_dish] else: results = none print results_list print encodetojsonhaystac

Android Layout change causes type-error -

i trying change working android app 1 column layout 2 column layout. when this, execution error on mainactivity.java, in line here: imageview picview = (imageview)findviewbyid(r.id.picture); the error states: android.widget.textview cannot cast android.widget.imageview from understand findviewbyid(r.id.picture) returns textview . make sense me. defined imageview in activity_main.xlm : <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:baselinealigned="false"> <linearlayout android:layout_width="0dp" android:layout_weight="1" android:layout_height="fill_parent" android:orientation="vertical"> <button android:id="@+id/capture_btn" android:text="@string/capture" an

python - Boolean to string with lowercase -

can str.format() method print boolean arguments without capitalized strings? i cannot use str(myvar).lower() argument of format, because want preserve case of letters when myvar not boolean. please don't post solutions conditional checks of values of variable. all interested in possibility of writing following: "bla bla bla {}".format(myvar) so output becomes "bla bla bla true" when myvar == true , "bla bla bla false" when myvar == false you use expression this str(myvar).lower() if type(myvar) bool else myvar

javascript - click event not working on new html with append , even using on -

this question has answer here: in jquery, how attach events dynamic html elements? [duplicate] 8 answers hi creating new element , child of element beforesend in ajax. later on want show child element if click on parent... $('#submit-task').on('click', function() { // variable declarations etc jquery.ajax({ // other data beforesend: function() { jquery('#' + month + ' .month-tasks-design').append( '<div class="month-task" data-id="' + next_id + '" style="width:0%;background: ' + colour + ';"><div class="task-info">name: ' + name + '<br />design hours: ' + design_hours + '<br />description: ' + description + '<br /></div></div>'); jquery(&#

php - simple upload of image in database for sign up user -

using php , pdo able make sign page out saving image $firstname = trim($_post['fn']); //at minimus clear whitespace. $lastname = trim($_post['ln']); $username = trim($_post['un']); $password = trim($_post['pw']); $confirmpassword= trim($_post['cp']); $stmt = $dbh->prepare("insert registration (fname,lname,username,password) values (?,?,?,?)"); $stmt->bindvalue(1,$firstname,pdo::param_str); $stmt->bindvalue(2,$lastname,pdo::param_str); $stmt->bindvalue(3,$username,pdo::param_str); $stmt->bindvalue(4,$password,pdo::param_str); if($stmt->execute()){ echo "your registration completed..."; } i found tutorial complicated me understand , not explained looking ideas or tutorial easy understand on how upload image..any idea appreaciated form <form method="post" action="crud.php">

java - Field not injected in Android Dagger project -

i playing dagger on android. created model userpreference , module called preferencemodule , class userpreferencetest test of preferencemodule . have below 3 java files userpreference.java package com.sigicn.preference; import javax.inject.inject; import com.sigicn.commonmodels.application; public class userpreference { public string name, weiboaccount; @inject public application[] frequentlyusedapps; } then preferencemodule.java package com.sigicn.preference; import javax.inject.singleton; import com.sigicn.commonmodels.application; import com.sigicn.utils.miscutils; import dagger.module; import dagger.provides; @module(library = true, complete = true) public class preferencemodule { @provides @singleton userpreference provideuserpreference() { userpreference userpreference = new userpreference(); userpreference.frequentlyusedapps = provideapplications(); return userpreference; } @provides @singleton application[]

Android Notification Big Picture Style and Big Text Style -

Image
i've build push notification using big picture style show here . possible mix big picture style , big text style shown in attached photo? how do it? you should able way: notification notif = new notification.builder(context) .setcontenttitle("title") .setcontenttext("content") .setsmallicon(r.drawable.ic_small) .setlargeicon(bitmap) .setstyle(new notification.bigpicturestyle() .bigpicture(bigbitmap) .setbigcontenttitle("big title")) .build(); source

objective c - Xcode Help using if statement to hide buttons -

i've got 3 buttons - when button 1 'grassleft' pressed want hide it/make fade out (and push next segue), after buttons 2 , 3 have been pressed , have disappeared first. don't want grassleft method push segue until grassmiddle , grassright have disappeared. don't think i'm using if statement properly. code: - (ibaction)grassleft:(id)sender { if ((grassrightbutton.hidden == yes)) { grassleftbutton.alpha = 0; } if ((grassmiddlebutton.hidden == yes)) { grassleftbutton.alpha = 0; } else { [uiview animatewithduration:0.3 delay:0.0 options:uiviewanimationoptioncurveeaseinout animations:^{ self.grassleftbutton.alpha = 0; } completion:^(bool finished) { self.grassleftbutton.alpha = 0.0; [grassleftshakes invalidate]; }]; } double delayinseconds = 1

javascript - Populating a table with an object with JQuery -

i have array of objects object [{date, count, city}] lets have data [{01/01/01, 10, new york}, {01/01/01, 15, london}, {01/01/01, 16, rome},{02/01/01, 40, new york},{02/01/01, 25, london}, {02/01/01, 36, rome}] i want populate html table using jquery , have following result date | new york | london | rome 01/01/01 | 10 | 15 | 16 02/01/01 | 40 | 25 | 36 is possible generate table similar jquery? this code have done far for (var = 0; < countresult.length; i++) { var html = "<table><thead><tr><th>date</th><th>city</th><th>count</th></thead><tbody>"; (var j = 0; j < countresult[i].length; j++) { html += "<tr>"; html += "<td>" + countresult[i][j].date + "</td><td>" + countresult[i][j].city + "</td><td>" + countresult[i][j].count+ "</td>";

xamarin - iBeacon ranging, Android, Minor always the same -

i've made app android detects ibeacons. it's based on 'find monkey example uses ibeacon library radius networks. the app has been working fine until morning when started recognise 1 of beacons (i have maybe 6 in office). the code loops through familiar have played ibeacons: void rangingbeaconsinregion(object sender, rangeeventargs e) { if (e.beacons.count > 0) { var beacon = e.beacons.firstordefault(); var minor = beacon.minor; console.writeline ("minor .... " + minor); switch((proximitytype)beacon.proximity) { case proximitytype.immediate: console.writeline ("beacon fired minor " + minor); showcouponmessage(); break; case proximitytype.near: updatedisplay ("you're getting warmer (near)", color.lawngreen