Why some jquery operations work with all elements within a selector result and others work only with the first element in the match?
For example $(".selector").click function assigns an event to all elements within a selector result, but $('.selector]').offset().top returns the value only of the first element in the result set.
How can I know what is the behavior for each operation?
Some jquery functions can accept the multiple dom elements while the others can work with single one only. $(".selector") is an object, when you call some function for it the all elements from the object or only the first one will be passed to the function.
offset() function description:
Get the current coordinates of the first element, or set the
coordinates of every element, in the set of matched elements, relative
to the document.
So if you call offset() without parameters it will return position of the first element; offset({ top: y, left: x }) will set the same top and left properties for the all elements of the jquery object.
To see how a function works read its documentation.
Related
I have an issue rearding the passing of more than one array parameter. I was able to do a "for each" cycle to execute my array parameter "SPPATH", but unfortunately I can pass only one, here is my code:
{"SPPATH":"#{item()}","SPFOLPATH":"#{pipeline().parameters.SPFOLPATH}","updsppath":"#{pipeline().parameters.updsppath}","Storageacct":"#{pipeline().parameters.Storageacct}","sapath":"#{pipeline().parameters.sapath}","saoppath":"#{pipeline().parameters.saoppath}"}
I want to pass "updsppath" also in the array because my output is on different locations, is it possible to do that, if so, how?
thanks in advance
I have reproduced the above and able to iterate multiple arrays inside ForEach.
For this the length of the all arrays should be same.
Use another array for indexes of these.
For Sample I have two array parameters like below.
I have created another array for index like below.
#range(0,length(pipeline().parameters.arr1))
Give this index_array to ForEach.
Create a res array variable in pipeline and inside ForEach, use append variable with the below dynamic content.
#json(concat('{"arr1":"',pipeline().parameters.arr1[item()],'","SPFOLPATH":"',pipeline().parameters.arr2[item()],'"}'))
After ForEach if you look at variable result (for showing here I have assigned to another variable), it will give you the desired JSON.
Result:
You can use this procedure to generate the desired array of objects and pass it to the logic apps as per your requirement.
I have an array as shown here. Here Bandit is a class that I created.
bandits = [Bandit(m1),Bandit(m2),Bandit(m3)];
Now, I want to do the following. Following is Python code which immediately gives me the maxarg of the value of the mean of each of these objects.
j = np.argmax([b.mean for b in bandits])
How can I do the same in MATLAB? To give more clarity, every bandit object has an attribute mean_value. I.e. if b1 is a bandit object, then I can get that value using dot operator (b1.mean_value). I want to find which among b1, b2, b3 has maximum mean_val and need to get the index for it. (See the python code above. If b2 has the highest mean_val, then finally, j will contain index 2.)
arrayfun applies a function to each element of an array. It results in a new array with the results of the operation. To this result you can then apply max as usual:
[~,arg] = max(arrayfun(#mean,bandits));
Note that this might not work if you have overloaded the subsref or size methods for the Bandit class.
Edit:
So now I understand that mean was not a function but an attribute. The operation x.mean can be expressed as the function call subsref(x,substruct('.','mean')). Thus, it is possible to change the solution above to call this function on each array element:
op = #(x)subsref(x,substruct('.','mean'))
[~,arg] = max(arrayfun(op,bandits));
That is, instead of calling the function mean, we call the function subsref to index the attribute mean.
If bandits is a simple struct array, then the following will work also:
[~,arg] = max([bandits.mean]);
Here, bandits.mean will extract the mean value for each element of the struct array, yielding a comma-separated list. This list is captured with the square brackets to form a vector. This vector is again input into the max function as usual.
I'm not sure if this latter solution works also for custom classes. I don't have your Bandit class to test. Please let me know if this latter solution works, so I can update the post with correct information.
I'm using Scala, and have a ResultSet with an unknown number of elements. I'd like to loop through the set, processing each row, and end up with an array of the processed elements. The function rs.next() moves the pointer to the next element and returns true if that element is a meaningful row and false if that element is not (either after the last row, or the return was empty to begin with). So even though the following won't work, I'd like something structured like:
while (rs.next()) yield new foo(rs)
I tried the answer for this question, like so:
if (rs.next()) Iterator.continually(new foo(rs)).takeWhile(rs.next())
But this doesn't work because the element is created before the condition is checked, behaving as a do-while which has to process the first bad element. As written, it will create a foo using the last element of the resultset but not return it and requires the initial rs.next() to get started.
I have multiple other ways to approach this problem: another query to count the number of elements and then using take, using a boolean var that's set equal to rs.next() and then used to return a null element if false and also used for the takeWhile, a mutable collection that is added to in a while loop, and so on.
But I feel like I must be missing something, because some part of each of those solutions feels inelegant. Is there a simple functional construction that will repeatedly check a condition, creating an element to add to an iterator so long as the condition is true?
I'm learning Scala now, and I have a scenario where I have to compare an element (say num) with all the elements in a list.
Assume,
val MyList = List(1, 2, 3, 4)
If num is equal to anyone the elements in the list, I need to return true. I know to do it recursively using the head and tail functions, but is there a simpler way to it (I think I'll be able to do it using foreach, but I'm not sure how to implement it exactly)?
There is number of possibilities:
val x = 3
MyList.contains(x)
!MyList.forall(y => y != x) // early exit, basically the same as .contains
If you plan to do it frequently, you may consider to convert your list to Set, cause every .contains lookup on list in worst case is proportional to number of elements, whereas on Set it is effectively constant
val mySet = MyList.toSet
mySet.contains(x)
or simply:
mySet(x)
A contains method is pretty standard for lists in any language. Scala's List has it too:
http://www.scala-lang.org/api/current/scala/collection/immutable/List.html
As others have answered, the contains method on the list will do exactly this, and it's the most understandable/performant way.
Looking at your closing comments though, you wouldn't be able to do it (in an elegant fashion) with foreach, since that returns Unit. Foreach "does" something for each element, but you don't get any result back. It's useful for logging/println statements, but it doesn't act as a transformation.
If you want to run a function on every element individually, you would use map, which returns a List of the results of applying the function. So assuming num = 3, then MyList.map(_ == num) would return List(false, false, true, false). Since you're looking for a single result, and not a list of results, then this is not what you're after.
In order to collapse a sequence of things into a single result, you would use a fold over the data. Folding involves a function that takes two arguments (the result so far, and the current thing in the list) and returns the new running result. So that this can work on the very first element, you also need to provide the initial value to use for the ongoing result (usually some sort of zero).
In your particular case, then, you want a Boolean answer at the end - "was an element found that was equal to num". So the running result would be "have I seen an element so far that was equal to num". Which means the initial value is false. And the function itself should return true if an element has already been seen, or if the current element is equal to num.
Putting this together, it would look like this:
MyList.foldLeft(false) { case (runningResult, listElem) =>
// return true if runningResult is true, or if listElem is the target number
runningResult || listElem == num
}
This doesn't have the nice aspect of stopping as soon as the target value has been found - and it's nowhere near as concise as calling MyList.contains. But as an instructional example, this is how you could implement this yourself from the primitive functional operations on a list.
List has a method for that:
val found = MyList.contains(num)
If I have an ArrayList<Double> dblList and a Predicate<Double> IS_EVEN I am able to remove all even elements from dblList using:
Collections2.filter(dblList, IS_EVEN).clear()
if dblList however is a result of a transformation like
dblList = Lists.transform(intList, TO_DOUBLE)
this does not work any more as the transformed list is immutable :-)
Any solution?
Lists.transform() accepts a List and helpfully returns a result that is RandomAccess list. Iterables.transform() only accepts an Iterable, and the result is not RandomAccess. Finally, Iterables.removeIf (and as far as I see, this is the only one in Iterables) has an optimization in case that the given argument is RandomAccess, the point of which is to make the algorithm linear instead of quadratic, e.g. think what would happen if you had a big ArrayList (and not an ArrayDeque - that should be more popular) and kept removing elements from its start till its empty.
But the optimization depends not on iterator remove(), but on List.set(), which is cannot be possibly supported in a transformed list. If this were to be fixed, we would need another marker interface, to denote that "the optional set() actually works".
So the options you have are:
Call Iterables.removeIf() version, and run a quadratic algorithm (it won't matter if your list is small or you remove few elements)
Copy the List into another List that supports all optional operations, then call Iterables.removeIf().
The following approach should work, though I haven't tried it yet.
Collection<Double> dblCollection =
Collections.checkedCollection(dblList, Double.class);
Collections2.filter(dblCollection, IS_EVEN).clear();
The checkCollection() method generates a view of the list that doesn't implement List. [It would be cleaner, but more verbose, to create a ForwardingCollection instead.] Then Collections2.filter() won't call the unsupported set() method.
The library code could be made more robust. Iterables.removeIf() could generate a composed Predicate, as Michael D suggested, when passed a transformed list. However, we previously decided not to complicate the code by adding special-case logic of that sort.
Maybe:
Collection<Double> odds = Collections2.filter(dblList, Predicates.not(IS_EVEN));
or
dblList = Lists.newArrayList(Lists.transform(intList, TO_DOUBLE));
Collections2.filter(dblList, IS_EVEN).clear();
As long as you have no need for the intermediate collection, then you can just use Predicates.compose() to create a predicate that first transforms the item, then evaluates a predicate on the transformed item.
For example, suppose I have a List<Double> from which I want to remove all items where the Integer part is even. I already have a Function<Double,Integer> that gives me the Integer part, and a Predicate<Integer> that tells me if it is even.
I can use these to get a new predicate, INTEGER_PART_IS_EVEN
Predicate<Double> INTEGER_PART_IS_EVEN = Predicates.compose(IS_EVEN, DOUBLE_TO_INTEGER);
Collections2.filter(dblList, INTEGER_PART_IS_EVEN).clear();
After some tries, I think I've found it :)
final ArrayList<Integer> ints = Lists.newArrayList(1, 2, 3, 4, 5);
Iterables.removeIf(Iterables.transform(ints, intoDouble()), even());
System.out.println(ints);
[1,3,5]
I don't have a solution, instead I found some kind of a problem with Iterables.removeIf() in combination with Lists.TransformingRandomAccessList.
The transformed list implements RandomAccess, thus Iterables.removeIf() delegates to Iterables.removeIfFromRandomAccessList() which depends on an unsupported List.set() operation.
Calling Iterators.removeIf() however would be successful, as the remove() operation IS supported by Lists.TransformingRandomAccessList.
see: Iterables: 147
Conclusion: instanceof RandomAccess does not guarantee List.set().
Addition:
In special situations calling removeIfFromRandomAccessList() even works:
if and only if the elements to erase form a compact group at the tail of the List or all elements are covered by the Predicate.