w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Fancybox - apply a function to several elements
Well, while Cristiano G. Carvalho's answer works, I think it is overdoing things. The array() + the .each() method will have a(n) (arguable) high cost in terms of memory and performance, much more if you have several images in your galleries. I don't see any reason to iterate through every element and build the fancybox gallery (again) inside an array if a simple fancybox code and manual event handlers can tackle the issue. But that is entirely my personal opinion. So for instance, if you have an html like this : <h3>gallery one</h3> <div id="gallery_one"> <a rel="galleryone" class="fancybox" href="http://fancyapps.com/fancybox/demo/1_b.jpg"><img src="http://fancyapps.com/fancybox/demo/1_s.jpg" alt=""/></a> <a rel="galleryone" class="fancyb

Categories : Jquery

Apply a function on all elements in a Dataframe
Here's a worked example of how you could apply specific functions to specific columns: Example data: test <- data.frame(a=1:3,b=4:6) test a b 1 1 4 2 2 5 3 3 6 Define functions as columnname+"fun" afun <- function(x) {exp(x)} bfun <- function(x) {log(x)} Apply afun to col a and bfun to col b and so on... data.frame( mapply( function(x,y) do.call(y,list(x)), test, paste(names(test),"fun",sep=""), SIMPLIFY=FALSE ) ) Result # exp(a) log(b) as defined by afun and bfun a b 1 2.718282 1.386294 2 7.389056 1.609438 3 20.085537 1.791759

Categories : R

apply a function on two lists with different number of elements
using mapply will be inherently slow since this will require iterating over each item and performing each operation over and over. A much faster option would be do flatten the lists and use vectorized operations. Flatten the lists. # Convert list1 to a vector L1 <- as.vector(unlist(list1)) # Convert list2 to a matrix L2 <- as.matrix(rbindlist(list2)) results <- (rowSums(L1 >= L2) + 1) / (ncol(L2)+1) ## Add names if needed names(results) <- names(list2) results Compare fun <- function(x, y) (sum( x[[1]] >= y) + 1) / (length(y) + 1) results.m <- mapply(fun, list1, list2) identical(results, results.m) Much faster than mapply library(microbenchmark) microbenchmark(MatrixStyle=(rowSums(L1 >= L2) + 1) / (ncol(L2)+1), MapplyStyle=mapp

Categories : R

D3.js - Conditional apply nest.key() function to array elements
Do you want to have multiple keys? Seems like in your desired format you have just one key. In case you don't want multiple keys, you should remove your functions that define the keys, OR In case you do want multiple keys, i would recommend having an if clause before you use your function for generating the key. And checking for empty string as d.level1 === "" should help.

Categories : Javascript

jQuery animation function to apply to elements randomly
This first part is to add the function shuffle to the javascript Array object Array.prototype.shuffle = function() { var i = this.length, j, temp; if ( i == 0 ) return this; while ( --i ) { j = Math.floor( Math.random() * ( i + 1 ) ); temp = this[i]; this[i] = this[j]; this[j] = temp; } return this; } Then var array = [1,2,3,4,5,6].shuffle(); var counter = 0 function drop_points(){ $('.c'+array[counter]).animate({top :'+=400'}, 700, 'easeOutBounce',function(){ counter++; if(counter<array.length-1)drop_points(); }); }

Categories : Javascript

Apply a function to elements inside a list of lists
You could try this: object Container1 { implicit class RichList1(l: List[List[Int]]) { def xxx(f: (Int) => String): List[List[String]] = { l.map(l => l.map(n => f(n))) } } } object Container2 { implicit class RichList2(l: List[Int]) { def xxx(f: (Int) => String): List[String] = { l.map(n => f(n)) } } } object Mapping extends App { def f(i: Int): String = i.toString val source1: List[List[Int]] = List(List(1, 2), List(3, 4)) val source2: List[Int] = List(1, 2) import Container1._ val result1a: List[List[String]] = source1.xxx(f) println(result1a) import Container2._ val result2a: List[String] = source2.xxx(f) println(result2a) }

Categories : Scala

How do I apply a JQuery function to elements with the same class that have a specific number of children?
Well just glancing at your code I see the if the condition is met then the class "mynewclass" will be applied to EVERY element with ul.menu_container. For you code to work you would need to formate it like this: if( $('ul.menu_container > li').length >= 3 ){ $(this).attr('class','mynewclass');} But I am fairly certain that this will not work either because it will only evaluate the first matching set. You will need to write your code using a .each() function.

Categories : Jquery

Use index of a list of data.frames to apply a function in certain elements of a data frame
Leveraging data.table here is helpful since you can easily subset your data using .( ) syntax and extremely fast, especially with large data compared to working with, say subset library(data.table) # convert to data.table, setting the key to the column `A` DT <- data.table(df, key="A") p.col.names <- paste0("P", 1:6) results <- lapply(list.1, function(ll) DT[.(ll)][, lapply(.SD, Fisher.test), .SDcols=p.col.names] ) results side note You might want to fix the names of list.1 so that the results form lapply are properly named # fix the names, helpful for the lapply names(list.1) <- lapply(list.1, names) results: $AA P1 P2 P3 P4 P5 P6 1: 0.04770305 0.1624142 0.2899578 0.029753 0.1070376 0.17549 $BB P1

Categories : R

Spark Standalone Mode: How to compress spark output written to HDFS
The method saveAsTextFile takes an additional optional parameter of the codec class to use. So for your example it should be something like this to use gzip: someMap.saveAsTextFile("hdfs://HOST:PORT/out", classOf[GzipCodec]) UPDATE Since you're using 0.7.2 you might be able to port the compression code via configuration options that you set at startup. I'm not sure if this will work exactly, but you need to go from this: conf.setCompressMapOutput(true) conf.set("mapred.output.compress", "true") conf.setMapOutputCompressorClass(c) conf.set("mapred.output.compression.codec", c.getCanonicalName) conf.set("mapred.output.compression.type", CompressionType.BLOCK.toString) to something like this: System.setProperty("spark.hadoop.mapred.output.compress", "true") System.setProperty("spark.h

Categories : Scala

R: apply on all matrix elements
From ?apply: MARGIN: a vector giving the subscripts which the function will be applied over. E.g., for a matrix ‘1’ indicates rows, ‘2’ indicates columns, ‘c(1, 2)’ indicates rows and columns. Where ‘X’ has named dimnames, it can be a character vector selecting dimension names. So you want: ndat<-matrix(c(1:100), ncol=10) apply(ndat, 1:2, cat)

Categories : R

Apply different css for different elements in a same class
I don't really know why you want to do things this way. You could simply use the id selectors: #city { background-color: red; } #state { background-color: green; } #zipcode { background-color: blue; } If you want to specify by class then assuming your <li> has a class of className you can use a number of pseudo-selectors to access the children DEMO: http://jsfiddle.net/8qAvb/ HTML <li class="className"> <div id="city">city</div> <div id="state">state</div> <div id="other1">other1</div> <div id="other2">other2</div> <div id="other3">other3</div> <div id="other4">other4</div> <div id="zipcode">zipcode</div> </li> CSS .className > div { bac

Categories : CSS

Apply Padding to Elements with Certain Class after

If you need your solution to work for more than two occurences of .specialInstructionsNotes and you want the padding also on the first element if there is no other, then a js-solution would come in handy, even though it's not preferred by you ;) JS $('h1').each(function() { $(this).nextAll('.specialInstructionsNotes:last').addClass('last-note'); }); Then it's easy to tackle the problem in CSS: CSS .specialInstructionsNotes.last-note { padding: 0 0 30px; } See the exemplary Fiddle

Categories : CSS

apply different functions to different elements of a vector in R
You must use this instead: x.trans <- c(log10,exp,log10,function(x)x^2,function(x)1/x) Then this: mapply(function(f, x) f(x), x.trans, x.val)

Categories : R

Is it possible to apply treatement to all elements in XML jaxb
You could use the CollapsedStringAdapter to clean up your strings (or create your own). If you want it applied to all String field/properties within a package you can specify this XmlAdapter using @XmlJavaTypeAdapter at the package level. package-info @XmlJavaTypeAdapter(value=CollapsedStringAdapter.class, type=String.class) package forum17484029; import javax.xml.bind.annotation.adapters.*; Demo import java.io.File; import javax.xml.bind.*; public class Demo { public static void main(String[] args) throws Exception { JAXBContext jc = JAXBContext.newInstance(Root.class); Unmarshaller unmarshaller = jc.createUnmarshaller(); File xml = new File("src/forum17484029/input.xml"); Root root = (Root) unmarshaller.unmarshal(xml); Marshaller mar

Categories : Java

How to apply some styles to first and last elements on a print page?
Try first-child and last-child. For Instance, p {font-size: 20px;} p:first-child {...} /* Add your desired style here */ p:last-child {...} /* Add your desired style here */

Categories : Javascript

How to apply (and change) classes to an SVG elements that already exist
To color half of the circles blue: svg.selectAll("circle") .attr("fill", function(d, i){ return i < 190 ? 'blue' : 'red'; }) If you're just trying to show different vote totals, number of men v. women, or another proportion, just change the 190. To change the color of the circles based on different datasets in a more complicated way: I would suggest combining the datasets together into an array of object where each entry represents a single legislator. Bind that data to your circles and you can change easily adjust the circle's size, position, and color based on the legislator's properties.

Categories : Javascript

How to apply styles to neighboring elements in a list
You shouldn't have much trouble just so long as the item display is just for show (i.e., I doubt it can be clickable) and can be placed as a child of the element triggering the event. JS Fiddle demo HTML: <div class='container'> <ul class='mylist1'> <li id='item1'> item1 <div class='dynamic-content' style='background:blue;'> Some content. </div> </li> <li id='item2'> item2 <div class='dynamic-content' style='background:green;'> Some content. </div> </li> <li id='item3'> item3 <div class='dynamic-content' style='background:red;'>

Categories : HTML

Apply jQuery plugin to hidden elements
The elements with display:none are present in DOM, but when you apply gallery plugin for them, it probably calculates height/width of those element to be used for gallery dimantions, and since element is not displayed it takes 0. jquery's .width() or .height() will return 0 for elements with display:none If that's the case then possible solutions would be: 1) init gallery only after the 'hidden' div becomes visible first time 2) temporarily set element display:block, but with visiblility:hidden before gallery initialization - this will allow to take correct height/width of the element Example for 2nd: $('.tn3-gallery') .css({'display':'block','visibility':'hidden'}) .tn3({ //your tn3 options init:function(){ //turn element back to display

Categories : Jquery

delete function become show function when i apply my custom layout to the pay in rals4
it's because you're not including jquery (or some other compatible js lib) in your custom layout as opposed to the default layout. the data parameters inside the link are processed by javascript unobtrusively. if not, then you just get a plain old link to your post which will end up in the show action. try adding <%= javascript_include_tag :application %> to the top of your custom layout file (or whatever is in the default layout file). you may need csrf_meta_tags as well, not sure

Categories : Ruby On Rails

CSS will not apply to dynamically created elements in jQuery mobile
You should add all items to the list, then refresh the listview : $('#sortedList').append('<li><h3>Success</h3></li>').listview('refresh'); Here's a JSFiddle. As a sidenote: you don't have to spell out jQuery every time, to use jQuery. The $ symbol is another name for the jQuery object, so jQuery('#mySelector') is equivalent to $('#mySelector')

Categories : Jquery

Apply actions from loop to series of elements, once per element
Try var label = $(".formFieldLabel"); label.contents().filter(function(){ return this.nodeType == 3 && $.trim($(this).text()).length > 0 ; }).wrap('<label />') Demo: Fiddle If you want to wrap the text and the * with the label then $(".formFieldLabel").wrapInner('<label />') Demo: Fiddle

Categories : Javascript

firefox doesn't apply css transitions to child elements
Turns out that since overflow isn't a transitionable property, changing .divisions a:hover to overflow:visible was breaking the transitions for all the child elements (but not for the a itself, strangely enough). Removing that property was enough to make everything work properly in Firefox: http://jsfiddle.net/mblase75/f5FKU/17/ .divisions a:hover { height: 270px; padding: 10px 0; /* overflow: visible; */ } See also this question.

Categories : CSS

Which approach is better: function.apply(, args) or having a function to accept as argument?
apply is going to use someParams as an array of arguments; call would actually do the same thing: functionA.call(someObject, someParams); There are no benefits except for style. Passing someObject as an argument is probably going to make more sense in most cases, but it’s really up to you and which one you like best.

Categories : Javascript

function executed by .apply() works with array, but does not the original function
Your function only accepts one argument (numArray), not three—this is why your call to getMaxOfArray is failing. If you are writing a one-liner, you should use call instead of apply for a series of parameters rather than an array, as so: Math.max.apply(null, [1, 3, 9]); Math.max.call(null, 1, 3, 9); For a function, you can use the arguments object for a variable number of parameters, if you do not want the user to pass an array. Here's how you would go about doing it this way. (Note that I still call apply here, because I store all of the arguments called by the user into an array.) function getMaxOfArguments() { var parameters = 1 <= arguments.length ? [].slice.call(arguments, 0) : []; return Math.max.apply(null, parameters); } Now, your second function call should wo

Categories : Javascript

Pre-apply parameter to unityscript function and use that as an object to send into another function
In plain JavaScript you can bind parameters to a function like this: var multiply = function(x,y) { return x*y }; var doubleIt = multiply.bind(null, 2); So calling doubleIt(3) now returns 6. (The null sets the context of the function, in this case we don't care about that, so we use null). You can read more on this topic here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind In your case I would call ComplexFunction with FunctionA like so: ComplexFunction(FunctionA.bind(null, AValueFromEnumX));

Categories : Unity3d

Apply XSLT stylesheet to it's own output (Filtering out empty elements)
You could add checks in your XSLT that only creates elements if the source is not empty. For example for the field carrier you could do: <xsl:if test="not(//transport/transportservice/carriername='')"> <field name="carrier"> <xsl:value-of select="//transport/transportservice/carriername" /> </field> </xsl:if> If you do that you would not get empty fields in your output. Best regards, Peter EDIT: If you want to check the output there is a very efficient way to do that using the identity-rule: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:output method="xml" indent="yes"/> <xsl:template match="@*|node()"> <xsl:copy> <xsl:appl

Categories : Xml

Apply jQuery functions to appended Infinite Scroll elements
The answer to your question is: no, $(window).load() doesn't fire when elements are appended, but only when the window object's onload event fires, i.e., at completion of initial page load. The suggestion of event delegation is well founded, and that of passing a callback when instantiating the infinite scroller, even more so. Assuming you're using this jQuery infinite scroll plugin, you might do something like: $(window).load(function() { // [...] $('#infinite-scroll-element') .infinitescroll({ /* options */ }, // callback to handle binding events on newly added elements function(newElements) { // iterate across the elements just added for (var i = 0; i < newElement

Categories : Jquery

How can I apply mathematical calculation for every Elements of a Cell Array ( like in Excel)
If I understand you correctly, you want to do collision detection and compute the densities of individual objects. Believe it or not, the collision detection is a lot easier to do than the volume calculation. This is mostly due to how your data is organized. Here's what I arrived at: % [Body] [Weight] [warranty] Bodies = {... 'A1' 3.5 2 'A2' 6.2 3 'B1' 7.1 1 'B2' 3.9 4 'B3' 4.2 5 'C1' 1.3 7 }; % [Object] [x_min] [x_max] [y_min] [y_max] [Volume] Objects = {... 'A1-a1' 5.7 7.3 8.9 4.3 5.1 'A1-a2' 2.6 5.6 9.3 5.7 5.2 'A1-a3' 3.6 7.3 5.3 7.3 5.8 'A2-a1' 8.2 5.8 2.7 5.3 6.3 'A2-a2' 8.4 6.3 8.5

Categories : Excel

Issue to apply hover with jquery when elements share the same class
Revised jsFiddle The jQuery code, as you wrote it, selects all elements of class "btn" and turns them all blue. You need to select only the element that is triggering the hover event and turn that one blue. Therefore, Change this: $('.btn').css({background: "blue"}); to this: $(this).css({background: "blue"});

Categories : Jquery

Copying remaining elements not present in xslt apply template
<xsl:template match="Employee"> <xsl:copy> <xsl:apply-templates select="@*" /> <xsl:apply-templates select="Qualification"/> <xsl:apply-templates select="Salary" /> <xsl:apply-templates select="Background"/> <xsl:apply-templates select="node()[ not(self::Qualification | self::Salary | self::Background)]" /> </xsl:copy> </xsl:template> This will first copy the attributes, then the specific elements you're interested in in the fixed order, and finally everything else except those three elements. Leave out the first apply-templates (the @* one) if you want to copy the Employee tag without its attributes. Edit: you say in your comment that you want to keep any comment above the element t

Categories : Xml

How to structure cascading properties - apply to parent element only or all child elements?
In option 1, what happens when the parent folder with the moderator--user relation is removed? Do the child folders move one level up? How often does a user perform an action where you need to determine if he/she is a mod for that folder? The extra relations created in option 2 might be useful only if there are several moderators and thousands of child folders to compute for the performance you want this to have. Also worth considering, instead of replicating the moderator-folder relationship down the tree in option 2, you could do Option 3: maintain the 'child folder to moderated parent folder' relationship. That way, you can verify the user having mod access in two queries - 1) to the table that holds the child_folder_mod_parent relations and then 2) to check if the user is the mod for

Categories : Performance

Sorting elements accessed via apply-templates based on the real XML tag name in XSLT
I think you need to put the xsl:sort in the apply-templates for the ref instead. This seems to work... <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink"> <xsl:output method="text" indent="yes"/> <xsl:strip-space elements="*" /> <xsl:param name="code" /> <xsl:key name='mykeys' match='/root/section2/*' use='concat("#", @xml:id)'/> <xsl:template match="/" > <xsl:apply-templates select='/root/section1/a/ref'> <xsl:sort select="local-name(key('mykeys', @xlink:href))" order="descending"/> </xsl:apply-templates> </xsl:template> <xsl:template match="ref"> <xsl:apply-templates select=

Categories : Xml

Hexbin: apply function for every bin
You can determine the number of class 1 and class 2 points in each bin by library(hexbin) library(plyr) x=rnorm(10000) y=rnorm(10000) #generate hexbin object with IDs=TRUE #the object includes then a slot with a vector cID #cID maps point (x[i],y[i]) to cell number cID[i] HexObj=hexbin(x,y,IDs = TRUE) #find count statistics for first 2000 points (class 1) and the rest (class 2) CountDF=merge(count(HexObj@cID[1:2000]), count(HexObj@cID[2001:length(x)]), by="x", all=TRUE ) #replace NAs by 0 CountDF[is.na(CountDF)]=0 #check if all points are included sum(CountDF$freq.x)+sum(CountDF$freq.y) But printing them is another story. For instance, what if there are no class 2 points in one bin? The fraction is not defined then. In addition, as

Categories : R

apply() / call() vs [function]() in jquery
Unless you're manipulating contexts, there's no reason to use call or apply or the equivalent jQuery helpers. Also, you don't need to use jQuery to test if a function exists. function foo() { alert('foo') } if (foo && typeof foo === 'function') { foo(); } Fiddle

Categories : Javascript

Using a 'complex' function within the apply family
You're using the wrong function. You probably want something more like this: lapply(split(mydata,mydata$Years),function(x) aov(width ~ Factors,data = x)) or you could use the plyr package and do something like this: dlply(mydata,.(Years),function(x) aov(width ~ Factors,data = x)) tapply is for working with vectors, typically, so for more complex objects you'll want a different tool. To address your comment, perhaps something like this: aov_fun <- function(x,vars){ out <- vector("list",length(vars)) names(out) <- vars f <- paste0(vars,"~Factors") for (i in seq_along(vars)){ out[[i]] <- aov(as.formula(f[i]),data = x) } out } lapply(split(mydata,mydata$Years),aov_fun,vars = c('width','height'))

Categories : R

Understanding Function.prototype.apply
The answer to both of your questions is that this inside of construct() is set based on how you call it. If you write Function.prototype.construct(), this will be Function.prototype, and it will break. When you write MyConstructor.construct(), this is MyConstructor, so the code will work. As a side note, this code can be greatly simplified in supporting browsers: Function.prototype.construct = function (args) { return new (this.bind.apply(this, [null].concat(args)))(); };

Categories : Javascript

Incorporating external function in R's apply
I wouldn't use an apply here. Since the addition + operator is vectorized, you can get the sum using > process.xz(dat$x, dat$z, Coeff) [1] 16 18 To write this in your data.frame, don't use cbind, just assign it directly: dat$result <- process.xz(dat$x, dat$z, Coeff)

Categories : R

Apply an already defined function to all dataframes at once
Try something like: lapply(mget(ls(pattern="dat")),func) Some details: The pattern argument in ls will limit which object names it lists (e.g., I assume you have other objects including your function in the global environment). mget retrieves those objects from the environment and turns them into a list, which you can then lapply your function over.

Categories : R

How to apply a function on each item in a list
parser() never returns anything, so it defaults to returning None, hence why storage2 contains a list of Nones. Perhaps you want to look at what's in storage1?

Categories : Python

Apply function to several variables with same name pattern
Just use grepl to match the column names you want to operate on returning a logical vector, inside the [ operator to subset the dataframe. Because log10 is vectorised you can just do this.... df[ , grepl( "htotal_" , names( df ) ) ] <- -log10( df[ , grepl( "htotal_" , names( df ) ) ] ) Vectorised example # Set up the data df <- data.frame( matrix( sample( c(1,10,1000) , 16 , repl = TRUE ) , 4 , 4 ) ) names( df ) <- c("htotal_1" , "htotal_2" , "not1" , "not2" ) # htotal_1 htotal_2 not1 not2 #1 10 10 10 1000 #2 10 10 1 10 #3 1000 1 1 1000 #4 10 1000 10 1000 df[ , grepl( "htotal_" , names( df ) ) ] <- -log10( df[ , grepl( "htotal_" , names( df ) ) ] ) # htotal_1 htotal_2 not1 not2 #1 -1 -1 10 1000 #2

Categories : R



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.