w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
R- all pairwise combinations of elements from two lists
Life is made easier if you put your models and data frames into lists. modlst <- list(model.1, model.2, ....) datlst <- list(data.1, data.2, ....) out <- lapply(modlst, function(mod) { lapply(datlst, function(dat) predict(mod, dat)) })

Categories : R

pairwise combinations of coefficient and correlation p.value?
You can use the combn function to generate all combinations of column comparisons and then apply across this matrix using cor.test on the combinations of columns of A (this assumes A is available in your global environment): # All combinations of pairwise comparisons cols <- t( combn(1:4,2) ) apply( cols , 1 , function(x) cor.test( A[,x[1] ] , A[ , x[2] ] )$p.value ) #[1] 0.9893876 0.9844555 0.5461623 0.7987615 0.7414658 0.1061751 The pairwise combinations of columns generated by the combn function is: [,1] [,2] [1,] 1 2 [2,] 1 3 [3,] 1 4 [4,] 2 3 [5,] 2 4 [6,] 3 4 Your apply(Y=A,2,allCorr.p,X=A) did not work as expected because (disregarding that you do not need to use Y=A) you pass the whole matrix as the second argument to your function,

Categories : R

Iterate over all pairwise combinations of numpy array columns
If you don't want to use recursion you should generally be using itertools.combinations. There is no specific reason (afaik) why this should cause your code to run slower. The computationally-intensive parts are still being handled by numpy. Itertools also has the advantage of readability.

Categories : Python

Idiom for pairwise iteration through a sorted collection
Iterator<Thing> thingerator = coll.iterator(); if (thingerator.hasNext()) { Thing thing1 = thingerator.next(); while (thingerator.hasNext()) { final Thing thing2 = thingerator.next(); doStuffToThings(thing1, thing2); thing1 = thing2; } }

Categories : Java

Clojure functions that yield "internal cartesian products" in a collection
I would do it in the following way. It uses destructuring along with mapcat to simplify the expression: (mapcat (fn [[a b]] (map #(vector a %) b)) theList) In general mapcat (or flatmap/collect/selectmany in other languages) is good for dealing with nested collections you want to flatten while transforming them.

Categories : Clojure

Python - all lottery combinations - no duplicates, in order
Use itertools.combinations: >>> from itertools import combinations >>> for comb in combinations(range(1,50), 6): ... print comb #Hit Enter at your own risk For printing the combinations to the text file: with open('combinations.txt', 'w') as f: for comb in combination: f.write(str(comb) + ' ')

Categories : Python

Order by ignoring second criteria
If you want a combination of the two you should create a column consisting of the combined (possibly weighed by an extra factor) sum of both like DATEDIFF(content_time,NOW())+views. By using DATEDIFF you will make sure that content_time is a numeric type and can be added to views. By using DATEDIFF()with the arguments in the shown order you will be getting a negative number for any content_times in the past which will reduce the combined value with views accordingly. So your query should end in something like this .. ... ORDER BY DATEDIFF(viewsitem_info.content_time,NOW())+viewsitem_info.views desc DATEDIFF() gives the difference in days. Maybe you want to be a bit more precise. In that case you might want to use TIMESTAMPDIFF(MINUTE,viewsitem_info.content_time,NOW()) instead. @Aaron:

Categories : Mysql

Optimal algorithm for generating all combinations (order of letter matters) of a word
One can generate permutations (excluding the duplicate constraint) by, for each character, swapping that character with the first character and recursing by excluding the first character. Now if we want to exclude duplicates, we simply need to make sure we don't put the same character in the first position twice. Doing this can be done by sorting the characters (so the duplicate characters are next to one another) and skipping over any character that's the same as the one before it or the same as the character at the target position. Java code: (derived from a basic permutation generator) import java.util.Arrays; import java.util.Scanner; public class NewMain { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the

Categories : Algorithm

SQL Server Multiple DDLs Ignoring Order And in a Single Transaction
Organize the files in the correct order, test the procedure on a test environment, have a validation and acceptance test, then run it in production. While running DDL in a transaction may seem possible, in practice is not. There are many DDL statements that don't mix well with transactions. You must put the application offline, take a database backup (or create a snapshot) before the schema changes, run the tested and verified upgrade procedure (your scripts), validate the result with acceptance tests and then turn the application back online. If something fails, revert to the backup created initially (with all the implications vis-a-vis any downstream log consumer like replication, log shipping or mirroring). This is the correct way, and as far as I'm concerned the only way. I know you

Categories : SQL

ORDER BY on multiple fields at the same time while ignoring specific value in MySQL
here's a trick using LEAST() and GREATEST() ORDER BY LEAST(IF(SalePrice = 0, GREATEST(SalePrice, SpecialPrice, UsedPrice) + 1, SalePrice), IF(SpecialPrice = 0, GREATEST(SalePrice, SpecialPrice, UsedPrice) + 1, SpecialPrice), IF(UsedPrice = 0, GREATEST(SalePrice, SpecialPrice, UsedPrice) + 1, UsedPrice)) ASC SQLFiddle Demo

Categories : Mysql

Do we need to set the index on the collection for the order by fields also?
I think so. Refer: http://docs.mongodb.org/manual/tutorial/sort-results-with-indexes/ It says: In MongoDB sort operations that sort documents based on an indexed field provide the greatest performance. Indexes in MongoDB, as in other databases, have an order: as a result, using an index to access documents returns in the same order as the index.

Categories : Mongodb

Using AngularJS how could I randomize the order of a collection?
orderBy can take a function parameter, just like array.sort so you can use your HTML above and define a function random on the scope like: $scope.random = function(){ return 0.5 - Math.random(); }; This will return a random value sometimes negative, sometimes positive, sometimes 0, which will randomly sort the array.

Categories : Sorting

Order of Files collection in FileSystemObject
If you want to get the files in a folder in a specific order, you'll have to do it yourself. If you don't like the ADO recordset or using a sortable .NET collection, you can shell out (.Run, .Exec) and process the output of dir /A:-D /B /O:D /T:C (no folders, bare format (no header/summary), order:date, timefield:creation). Update: While I surely can show examples where the .Files collection delivered its elements ordered by name, Mr. Gates explicitly says: INFO: Limitations of the FileSystemObject ... Cannot sort file names from the files collection - you can iterate through the File objects in the Files collection to obtain a list of the files in a folder. However, the File objects are not sorted. You need to use a sort routine to sort the File objects in the Files collect

Categories : Vbscript

Order By in many-to-many association
The following worked as expected. The alias locList was used in select instead of o.locationList SELECT locList FROM Order o join o.locationList locList where o.orderId = 1 order by locList.city desc

Categories : Java

Order the result of query by collection size in HQL
In this case it's pretty much standard SQL as I see it, so "from Parent p left join p.children as pc group by p order by count(pc)" is what I needed, however this gave an error due to it now returning tuples with an extra column, the number of children. This was fixed by specifying in the select clause that I wanted to return only the parent part of the joined table. I'm not exactly sure what was going on under the hood here but this works and make a nice logical and readable query. "select p from Parent p left join p.children as pc group by p order by count(pc)" simples.

Categories : Java

Order DataTable using LINQ based on a Class Collection
As far as I understood your question, you have collection which has data including ids and stored procedure that returns DataTable containing only one of its component. The simplest way is to iterate through list of data rows and match respective value from the full list and order after that: List<Foo> sc = new List<Foo>(); sc.Add(new Foo() { ID = 0, Name = "Michael" }); sc.Add(new Foo() { ID = 2, Name = "Natasha" }); sc.Add(new Foo() { ID = 1, Name = "Casandra" }); List<string> dt = new List<string>(); //For testing replaced just by string. dt.Add("Michael"); dt.Add("Natasha"); dt.Add("Casandra"); var ordered = dt.Select(i => sc.First(c => c.Name == i)).OrderBy(i => i.ID); Demo (sorry for awful formatting).

Categories : C#

Magento: How to filter a collection (sales/order) by a certain category?
Here's one (perhaps) not so elegant approach to doing so... First grab all products in the category you want $category_id = 44; $category = Mage::getModel("catalog/category")->load($category_id); $products = Mage::getModel("catalog/product")->getCollection() ->addCategoryFilter($category); Next I collect just the product ids so I can use them $product_ids = array(); foreach ($products as $product) $product_ids[] = $product->getId(); Grab all order items where the product id is one of the products from our category $items = Mage::getModel("sales/order_item")->getCollection() ->addFieldToFilter("product_id", array("in" => $product_ids)); Now fetch all the unique orders referenced by the items $orders = array(); foreach ($items as $item) { $order_id = $

Categories : Magento

Lamda Expression to order (sort) my list collection
You can add another property. class mymodel { public string Name{ get; set; } public string AMPM{ get; set; } public int AMPM_Sort { get { if (AMPM == "AM") return 1; if (AMPM == "PM") return 2; if (AMPM == "MIX") return 3; if (AMPM == "--") return 4; return 9; } } } List<mymodel> mylist; var sorted = mylist.OrderBy(x => x.AMPM_Sort);

Categories : C#

Ensuring that Collection._ensureIndex passes fields in the right order
Do not worry about this, this should work fine. You can easily see whether it worked by checking which indexes there are on the MongoDB shell too: mongo yourdb db.collectionName.getIndexes();

Categories : Javascript

Add timestamp and sort order fields on collection add() Backbone.js
I would just set up the model so that whenever it is created, you give it a timestamp. So I would add the following to your model: var modelMessage = Backbone.Model.extend({ defaults: function() { return { addedon: new Date().getTime() }; }, // ... the rest of your code }); Then change the Messages.listenTo call to the following as well: Messages.listenTo(Messages, "add", function (model) { model.set({levelcode: model.levelToInt()}); $('#output').append('<div>added model:' + JSON.stringify(model.toJSON()) + '</div>'); }); Here is a fiddle: http://jsfiddle.net/xUyak/ Or as Andrew mentioned the following would work as well: var modelMessage = Backbone.Model.extend({ initialize: function() { this.set({ addedon: new Date().getTime(),

Categories : Javascript

How to aggregate in R ignoring some rows for some fields, and not ignoring them for others?
Use aggregate, with both the arguments na.action=na.pass and na.rm=TRUE. The former tells aggregate not to remove rows where NAs are present; and the latter is the action that the aggregating function should take. aggregate(cbind(qA, qB, qC) ~ city, df, mean, na.action=na.pass, na.rm=TRUE)

Categories : R

How to pass an existing collection to a controller in order to render a page
link_to("Show", object) will normally produce a URL like /illustrations/:id. A show route. You're trying to render a collection. Generally, I think you're trying to just show your search results in a different way, no? At least that's what I gather from your examples. If that's the case, render a different view. def search # search stuff... (you should try ElasticSearch/Tire) # # Now, use a different template if the 'thumbs' param is present return render :search_thumbs unless params[:thumbs].nil? end In the view: = link_to "View Thumbs", search_path(search: params[:search], thumbs: true)

Categories : Ruby On Rails

Clean method in order to update collection in entity framework
But i'm unconfortable with this, because in my mind, entity framework should be able to do the work for me ! In fact, EF does the Work for you. Using the data context SaveChanges method EF should be able to save all your changes at once: DbContext.SaveChanges() For your convinience you can still override this method. Internally you should use something like this: public override int SaveChanges() { var changeSet = ChangeTracker.Entries<IAuditable>(); if (changeSet != null) { foreach (var entry in changeSet.Where(c => c.State != EntityState.Unchanged)) { entry.Entity.ModifiedDate = DateProvider.GetCurrentDate(); entry.Entity.ModifiedBy = UserName; } } return base.SaveChanges(); }

Categories : C#

How to make tree implemented in Scala useful with higher-order collection functions?
Let's rename FactType to something that looks more like a type parameter. I think naming it just T helps indicate it is a type parameter versus a meaningful class in your code: sealed abstract class FactsQueryAst[T] extends Traversable[T] So FactQueryAst contains things of type T and we want to be able to traverse the tree to do something for each t:T. The method to implement is: def foreach[U](f: T => U): Unit So replacing all FactType in your code with T and modifying the signature of T, I end up with: object FactsQueryAst { case class AndNode[T](subqueries: Seq[FactsQueryAst[T]]) extends FactsQueryAst[T] { def foreach[U](f: T => U) { subqueries foreach { _.foreach(f) } } } case class OrNode[T](subqueries: Seq[FactsQueryAst[T]]) extends FactsQueryAst[T] { def f

Categories : Scala

java garbage collection does a <(major collection:mark and sweep> every time it does a
I would try removing all the settings you have so that you have the absolute minimum and you are less likely to get a strange interaction between settings Try just -Xmx16g -XX:+UseConcMarkSweepGC and monitor it using jstat

Categories : Java

Taking 3 or more combinations using `combinations`
I'm not good at math, but if the question is "How would I then sum each of the triples I get in v?" then the answer is: sv = map(sum, v) where sv will contain a list (an iterator actually) of sums of triples from v

Categories : Python

Splitting a pairwise matrix in R
m <- structure(c(0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0), .Dim = c(4L, 6L), .Dimnames = list(c("GENE1", "GENE2", "GENE3", "GENE4"), c("A-B", "A-C", "A-D", "B-C", "B-D", "C-D"))) gene <- matrix(NA, ncol=4, nrow=4) # empty, template matrix gene[upper.tri(gene)] <- m[1,] gene[lower.tri(gene)] <- rev(m[1,]) ## gene now contains the interaction matrix for GENE1.

Categories : R

R - How to combine 2 pairwise vectors into a matrix
df <- read.table(textConnection('col1 col2 col3 row1 "A" "A" "1.0" row2 "A" "B" "0.9" row3 "A" "C" "0.4" row4 "B" "A" "0.9" row5 "B" "B" "1.0" row6 "B" "C" "0.2" row7 "C" "A" "0.4" row8 "C" "B" "0.2" row9 "C" "C" "1.0"'), header=T) ## fetch row/column indices rows <- match(df$col1, LETTERS) cols <- match(df$col2, LETTERS) ## create matrix m <- matrix(0, nrow=max(rows), ncol=max(cols)) ## fill matrix m[cbind(rows, cols)] <- df$col3 m # [,1] [,2] [,3] #[1,] 1.0 0.9 0.4 #[2,] 0.9 1.0 0.2 #[3,] 0.4 0.2 1.0

Categories : R

How to do pairwise replacement of strings efficiently
The function that worked for me was replace.pairwise=function(listofstrings,...){ ss=c(unlist(listofstrings)) pairs=list(...) for(s in 1:length(ss)){ for(p in 1:length(pairs)){ ss[s]=gsub(names(pairs)[p],pairs[p],ss[s]) } } ss } I am sure it is not the most efficient way, but it works. I wonder whether I have again just programmed something that is already hidden in one of the many packages in R...

Categories : R

sort pairwise shortest distance
If I understand you correctly, you want to reorder some vertices such that all the lines drawn between subsequent points form a closed, non-overlapping contour. This can be accomplished by re-ordering your vertices in a (counter)clockwise fashion about the centre of mass of all the points. In 2D, this can most easily be accomplished by sorting the output of atan2: %// Compute centre of mass r_COM = sum([X, Y]) / numel(X); %// Sort all vertices by angle [~, I] = sort(atan2(Y - r_COM(2), X - r_COM(1))); %// Plot the new contour hold on, plot(X([I; I(1)]),Y([I; I(1)]), '.-k', 'linewidth', 2); Results:

Categories : Matlab

calculate pairwise simhash "distances"
According to the documentation, only metrics from scipy.spatial.distance are allowed, or a callable from: In [26]: sklearn.metrics.pairwise.pairwise_distance_functions Out[26]: {'cityblock': <function sklearn.metrics.pairwise.manhattan_distances>, 'euclidean': <function sklearn.metrics.pairwise.euclidean_distances>, 'l1': <function sklearn.metrics.pairwise.manhattan_distances>, 'l2': <function sklearn.metrics.pairwise.euclidean_distances>, 'manhattan': <function sklearn.metrics.pairwise.manhattan_distances>} One issue is that if metric is callable then sklearn.metrics.pairwise.check_pairwise_arrays tries to convert the input to float, (scipy.spatial.distance.pdist does something similar, so you're out of luck there) thus your error. Even if you could p

Categories : Python

Determine parent, children from pairwise data
Have you looked into using a dictionary with a list store in it. a dictionary is basically a hash table and you can store a key (the begging and end point ex, AD) and a value (the segments it needs to go through [AB, BC, CD])

Categories : Algorithm

make asymmetric pairwise comparisons in a matrix
What do you want to do with the entries > 0.7? Set them to NA? Remove them? Regardless, this should get you going in the right direction: #Assumes your data is named x > which(x > 0.7, arr.ind = TRUE) #---- row col A 1 1 E 5 1 B 2 2 D 4 2 ... #Set values = NA x[which(x>0.7, arr.ind = TRUE)] <- NA #--- A B C D E A NA 0.7 NA NA NA B 0.2 NA 0.2 NA 0.3 C 0.3 0.4 NA 0.5 0.6 D 0.4 NA NA NA 0.4 E NA 0.2 NA NA NA

Categories : R

Finding positions of milestones given their pairwise distances
Ok. I will give my idea , which could reduce the number of permutations. Finding n, is simple, you could even run a Reverse factorial http://math.stackexchange.com/questions/171882/is-there-a-way-to-reverse-factorials Assumption: Currently I have no idea of how to find the numbers. But I assume you have found out the numbers somehow. After finding n and elements we could apply this for partial reduction of computation. Consider a problem like, |<--3-->|<--6-->|<--1-->|<--7-->| A B C D E Now as you said, the sum they will give (in random order too) 3,9,10,17,6,7,14,1,8,7. But you could take any combination (mostly it will be wrong ), 6-3-1-7. (say this is our taken combination) Now, 6+3 -> 9 There, so Yes //Checking in the lis

Categories : Algorithm

Find pairwise overlaps of intervals (segments)
The intervals package seems to provide a solution here: require("intervals") A=rbind(A1=c(1,7), A2=c(2,5), A3=c(4, 16)) B=rbind(B1=c(2,3), B2=c(2,20)) # here you can also define if it is an closed or open interval Aint<-Intervals(A) Bint<-Intervals(B) # that should be what you are looking for interval_overlap(Aint, Bint) see for a nice demonstration: Demo hth

Categories : R

Create a collection of sub collection from a given Collection (Group By) in Java
Probably this is what you need until java 8 closures comes HashMap<Integer, DateTileGrid> dataGridMap = new HashMap<>(); for (Date date: dateList) { int year = date.getYear(); //Deprecated.. use something better DateTileGrid dataGrid = dataGridMap.get(year); if(dataGrid == null){ dataGrid = new DateTileGrid(); dataGrid.setCurrentYear(year); dataGrid.setDateTiles(new ArrayList<Date>()); dataGridMap.put(year, dataGrid); } dataGrid.getDateTiles().add(date); } //Here is your result ArrayList<DateTileGrid> result = new ArrayList<>(dataGridMap.values());

Categories : Java

Matlab euclidean pairwise square distance function
Simply put yes, the pdist method is hungry for your memory and your computer cannot feed it. For example, even with a 6000 by 300 matrix X, I get the following variable sizes for X and Y using whos X Y: >> whos X Y Name Size Bytes Class Attributes X 6000x300 14400000 double Y 1x17997000 143976000 double Now my my memory states (on a 32 bit machine): >> memory Maximum possible array: 677 MB (7.101e+008 bytes) * So I am really pushing the memory limits with the computation Y = pdist(X) as this produces an array of roughly 1.44 *10^8 bytes whereas the maximum possible array size is roughly of order 5 times that. Any bigger with the matrix and your s

Categories : Matlab

Fast algorithms for finding pairwise Euclidean distance
Computers are not infinitely large, or infinitely fast. People think that they have a lot of memory, a fast CPU, so they just create larger and larger problems, and then eventually wonder why their problem runs slowly. The fact is, this is NOT computational inefficiency. It is JUST an overloaded CPU. As Oli points out in a comment, there are something like 2e9 values to compute, even assuming you only compute the upper or lower half of the distance matrix. (6e4^2/2 is approximately 2e9.) This will require roughly 16 gigabytes of RAM to store, assuming that only ONE copy of the array is created in memory. If your code is sloppy, you might easily double or triple that. As soon as you go into virtual memory, things get much slower. Wanting a big problem to run fast is not enough. To really

Categories : Matlab

MySQL Calculating sum over pairwise time differences of log file
I think the easiest way to structure this type of query is using correlated subqueries (and, to be honest, I generally don't like correlated subqueries, but this is an exception). Your query would probably work with the right group by clause. Here is an alternative method: select TIMEDIFF(action_created, LogoutTS) from (select ual.*, (select ual2.user_activity_log from user_activity_log ual2 where ual2.user_id = ual.user_id and ual2.action_type = 2 and ual2.action_created > ual.action_created order by ual2.action_created desc limit 1 ) as LogoutTS from user_activity_log ual where ual.user_id = 6 and ual.action_type = 1 ) ual To get t

Categories : Mysql

Is there any standard algorithm for doing pairwise comparison of Vector Elements?
How big are the vectors? Something like: template <typename T> bool unorderedEqual( std::vector<T> const& v1, std::vector<T> const& v2 ) { return v1.size() == v2.size() && std::find_if( v1.begin(), v1.end(), [&v2]( T const& elem ) { return std::find( v2.begin(), v2.end(), elem ) == v2.end(); } ) == v1.end(); } might do the trick, but it's O(n^2) (which means it's only good for very small vectors), and it won't work if the vectors contain duplicate elements. (Note too that I've not tested it, so it probably contains typos and other errors. But it should be close enough to give the general idea.) Otherwise, I think you'll have to sort; even if the objects don't support less than

Categories : C++



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