w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Take difference between two vectors
A useful command is %in%. This will return TRUE or FALSE, for every element of a vector a, whether that element is in vector b. You can then negate this using !. So: a[!(a %in% b)]

Categories : R

Difference in behavior of conj on vectors and lists in Clojure
The conj procedure adds new elements "at different 'places' depending on the concrete type". In particular, conj is adding new elements at the most efficient place for the given data structure. In a single-linked list, the cheapest place to insert a new element is at the head - there's no need to traverse the list to find the insertion point, just connect the new element with the list's first element. In a vector, the cheapest place is at the end - there's no need to shift or move the rest of the elements to make room for the new element, and if the vector was created with extra free space with actual size greater than its current length (as is the case with transient vectors and conj!, but not with persistent vectors), it's a simple matter of adding the new element at the first free pos

Categories : List

Searching Multiple Vectors
If the elements need to match at the same location, it seems that a std::find() or std::find_if() combined with a check for the other vectors at the position is a reasonable approach: std::vector<A> a(...); std::vector<B> b(...); std::vector<C> c(...); std::vector<D> d(...); std::size_t match(0); for (auto it = a.begin(), end = a.end(); it != end; ) { it = std::find_if(it, end, conditionA)); if (it != end) { if (conditionB[it - a.begin()] && conditionC[it - a.begin()] && conditionD[it - a.begin()]) { ++match; } ++it; } }

Categories : C++

Matching multiple vectors in R
The merge() function should be what you're looking for. Ex: > merge(df1,df2,all.x=T) c1 c2 c4 1 a 1 10 2 b 2 9 3 c 3 8 4 d 4 7 5 e 5 6 6 f 6 5 7 g 7 4 8 h 8 3 9 i 9 2 10 j 10 1 > merge(df1,df2,all.y=T) c1 c2 c4 1 a 1 10 2 b 2 9 3 c 4 NA 4 x 4 NA

Categories : R

convert vector of multiple vectors of int to array of int
It's not 100% clear what you want, but making the most of what you've said, I would do something like this: std::vector<std::vector<int>> v; // input, assume it's already filled std::size_t size = 0; for (std::vector<std::vector<int>>::const_iterator i = v.begin(); i != v.end(); ++i) { size += i->size(); } boost::scoped_array<int> array; if (size != 0) { array.reset(new int[size]); std::size_t offset = 0; for (std::vector<std::vector<int>>::const_iterator i = v.begin(); i != v.end(); ++i) { std::copy_n(&(*i)[0], i->size(), array + offset); offset += i->size(); } } // ...use array... If you want to make array unique, you could do: std::sort(array.get(), array.get() + size); std::size_t newSi

Categories : C++

Subtracting multiple vectors from each row of an array (super broadcasting)
The core of this problem is to compute a distance matrix D of size m x 3 that contains the pairwise distances between all data points in X and all data points in C. The Euclidean distance between the i-th vector x_i in X and the j-th vector c_j in C can be rewritten as: |x_i-c_j|^2 = |x_i|^2 - 2<x_i, c_j> + |c_j|^2 where <,> refers to inner product. The right-hand side of this equation can be easily vectorized, because the inner product of all pairs is just X * C' which is BLAS3 operation. This way of computing the distance matrix is known as dist2 function in the book Pattern Recognition and Machine Learning by Christopher Bishop. I copy the function below with a little modification. function D = dist2(X, C) tempx = full(sum(X.^2, 2)); tempc = full(sum(C.^2, 2

Categories : Matlab

How can I sort two vectors in the same way, with criteria that uses only one of the vectors in C++?
Implement operator< for ExampleStruct bool operator<(ExampleStruct const& es1, ExampleStruct const& es2) { return es1.i < es2.i; } Then just use std::sort for vectorC. std::sort(vectorC.begin(), vectorC.end());

Categories : C++

Should I be worried about having too many levels of vectors in vectors?
Use references instead. This doesn't copy an object but just makes an alias to make it more usable, so performance is not touched. Block& b = rawSheets[pos.a].countries[pos.b].cities[pos.c].blocks[pos.d]; (watch the ampersand). When you use b you will be working with the original vector. But as @delnan notes you should be worried more about your code structure - I'm sure you could rewrite it in a more appropriate and maintable way.

Categories : C++

Freeing vectors of vectors after use
To free the contents of a vector, just let it go out of scope or be destroyed along with the class instance it belongs to (depending on your exact situation). If you can't wait that long, you can always use the good old swap-with-empty idiom to ensure the memory is actually freed: std::vector<std::array<double,640>>().swap(A); // or, nicer version using C++11's decltype, which avoids typing the exact type: decltype(A)().swap(A);

Categories : C++

Sum multiple time difference on a particular day
select x.employee_index, max(case when x.entry_type_index = 1 then x.entry_datetime else null end) as in_time, max(case when x.entry_type_index = 2 then x.entry_datetime else null end) as out_time, sum(case when x.entry_type_index = 6 then y.entry_datetime-x.entry_datetime else 0 end as break from (select @rn:=@rn+1 as rn, a.* from table1 a, (select @rn := 0) b order by entry_datetime) x left join (select @rn1:=@rn1+1 as rn1, a.* from table1 a, (select @rn1 := -1) b order by entry_datetime) y on x.rn = y.rn1 group by x.employee_index

Categories : PHP

Understanding the difference between ON with multiple conditions and WHERE in a JOIN
A LEFT JOIN brings back every record from the 'LEFT' table, unless you limit it, as you did with your WHERE criteria. When you change it to be part of the JOIN criteria it's not limiting the results, just limiting which records have non NULL values from the right table.

Categories : SQL

Difference between multiple IF else condition and logical OR operation
They're the same. The second one is definitely easier to read, and readability is incredibly important in programming. The rule I like to go by is that if multiple branches of an if-else statement produce the same behavior, I combine them. (Be sure that they're the EXACT same behavior)

Categories : Java

Will it make a difference in performance to have multiple ques across different nodes?
Firstly, if you're mirroring queues and using persistent messages, you're going to be harming performance. See my article on the performance of RabbitMQ HA for details. You're right though to consider more queues in order to improve throughput - each RabbitMQ is a single Erlang process so will only ever use one core. There's other Erlang processes of course that will help, but you are indeed bottlenecked by the single queue. The answer is the consistent hash exchange type which will evenly distribute messages to each queue connected to it. YMMV but I'd imagine you'd want one queue per core of each server.

Categories : Java

What is the difference between running multiple python scripts and multiprocessing
Martijn Pieters' comment hits the nail on the head, I think. If each of your processes only consumes a small amount of memory (so that you can easily have all four running in parallel without running out of RAM) and if your processes do not need to communicate with each other, it is easiest to start all four processes independently, from the shell, as you suggested. The python multiprocessing module is very useful if you have slightly more complex requirements. You might, for instance, have a program that needs to run in serial at startup, then spawn several copies for the more computationally intensive section, and finally do some post-processing in serial. multiprocessing would be invaluable for this sort of synchronization. Alternatively, your program might require a large amount of m

Categories : Python

Calculate average time difference between multiple unix timestamps
The most straight forward way it to do it like you described. $res =0; for($x = 1, $num = count($array); $x < $num; $x++){ $res =+ $array[$x] - $array[$x-1]; } echo $res/($num-1);

Categories : PHP

difference between sqlite ramdrive 1m row single file vs multiple files
One million row is not that much. SQLite supports databases up to 140 terabytes. See the detailed description of the SQLite limits. How much memory does the table with one million rows consume? It should be easily handled on any modern machine.

Categories : Database

Calculate the average difference between two date columns for multiple rows
Use DATEDIFF() and AVG() select avg(datediff(view_date, sent_date)) from mails

Categories : PHP

C++ For loops through Vectors of Structs (containing more vectors of structs)
Your struct does not contain a vector, it just has a typedef: typedef vector<pAccount> Accounts; If you want Accounts to be a data member, remove the typedef. vector<pAccount> Accounts; Furthermore, you should seriously consider not using the same name for the items in both levels of the nested loop: for (auto& user : users) { for (auto& account : user.Accounts) { Also, note that you do not need to use typedef to declare a struct. In typedef struct Foo {};, the typedef is ignored. It just adds clutter to the code. Finally, at a glance there seems to be no reason for the usage of pointers in your code. It would be greatly simplified if you stored values instead.

Categories : C++

mysql select all calculate difference bewteen multiple rows to on result from pivot
I am assuming that the data is coming in the concatenated form -- not that you are created it. You can unconcatenate it using substring_index() and reverse(), along with a table that generates numbers. The following query undoes the concatenate, then groups the results back together: select t.*, sum(HOUR(TIMEDIFF(STR_TO_DATE(Arbeitsbeginn, '%d.%m.%Y %H:%i:%s'), STR_TO_DATE(Arbeitsende, '%d.%m.%Y %H:%i:%s')))) AS ARBEITSZEIT, sum(HOUR(TIMEDIFF(STR_TO_DATE(Projektbeginn, '%d.%m.%Y %H:%i:%s'), STR_TO_DATE(Projektbeginn, '%d.%m.%Y %H:%i:%s')))) AS Projektzeit FROM (select DriverName, (case when n.n = 1 then substring_index(arbeitsbeginn, ',', 1) else reverse(substring_index(REVERSE(substring_index(arbeitsbeginn, ',', 2)), ',', 1)) end) as ar

Categories : Mysql

Why does adding extra check in loop make big difference on some machines, and small difference on others?
One big difference between CPUs is the pipeline optimization The CPU can execute in parallel several instructions until reaches a conditional branch. From this point instead of waiting until all the instructions are executed, the CPU can continue with a branch in parallel until the condition is available and ready to be evaluated. If the assumption was correct, then we have a gain. Otherwise the CPU will go with the other branch. So the tricky part for a CPU is to find the best assumptions and to execute as many instructions in parallel as possible.

Categories : C++

What do blue-difference and red-difference chroma components mean in YCbCr color space?
The Cb and Cr components of the YCbCr, or YCC, color space are not immediately physically intuitive. Cb and Cr respectively represent the blue-difference and red-difference chroma signals as you noted. Chromaticity represents the perceptual deviation from the neutral, i.e. grayscale, so the greater the deviation, the higher the intensity of chroma. An image with low chroma is less colorful, and conversely. And so, Cb and Cr are one representation of changes in blue and red "colorfulness", respectively. Each colorspace has different advantages, mostly related to how sensitive channels to changes. For example, YCbCR is widely popular for its compressibility in the Cb and Cr channels by subsampling. Or, when doing things in computer vision like image matching using color-based methods, it is

Categories : Image

Find difference between rows of same column (difference between time data)
Try: DATEDIFF (mi, CAST(mc.login AS DATETIME), CAST(mp.login AS DATETIME)) as diff This will get difference in minutes SQLFiddle DEMO

Categories : Asp Net

Does columns order in multiple columns unique constraint make any difference? Is it justifiable to have duplicate indexes?
Your question is: Would it be justified, in certain situations, to create two indexes? One, multiple column index, on (index_id, index_date) and second, single column index, on (index_date)? The answer is "yes". The first index will be used to satisfy queries with conditions like: filtering on index_id in the where clause filtering on index_id and index_date in the where clause filtering on index_id in the where clause and the ordering by index_date The second index would not be used in these circumstance. It would be used for: filtering on index_date in the where clause And the first index would not be used in this case. The ordering of columns in indexes is important. They are used from the left to the right. So, these two indexes are useful. However, a third ind

Categories : SQL

Postgres sql 8.4 Use of Time Difference and Date Difference Separately
Here is the SQLFiddel Demo Below is the query which you can try select EmpHrs.ID_EMP, EmpHrs.Name, ( (EmpHrs.NOOFHRS*20)- (EmpHrs.NOOFHRS* JuneSuspension.MONTHSUSPENSION) ) as "June-2013", ( (EmpHrs.NOOFHRS*20)- (EmpHrs.NOOFHRS* JulySuspension.MONTHSUSPENSION) ) as "July-2013" from ( select ID_EMP,NAME, Extract(Hours from time_end-time_initial)+ Extract(Minutes from time_end-time_initial)/60 as NoOfHrs from schedule ) EmpHrs Left join (select ID_EMP,to_char(to_timestamp (Extract(Month from suspension_initial)::text, 'MM'),'Mon') as MonthIni,(suspension_end::date - suspension_initial::date)+1 MonthSuspension from suspension where Extract(Month from suspension_initial) = 6) JuneSusp

Categories : SQL

Difference in VTBL in single inheritance and multiple inheritance
If you have to base class A and B of your multiply inherited object D, these have their own vtable layout and D needs to provide vtables which match the vtables of both A and B. Further, if another class derives from D and possibly from another similarly multiple inherited class, the same thing happens again, i.e., there are multiple vtables needed. They can't just simply be merged. As a result, multiply inherited objects typically have multiple vtables around and the compiler inserts code to first determine the function's correct vtable and then call it. I think the code determining the correct vtable based on a pointer to an object with multiple bases is just a simple addition or subtraction if the virtual function is not in a virtual base class and a look-up of the location of the virtu

Categories : C++

A difference-in-difference boxplot-like plot in Matlab
How about something along the lines of: x = rand(2, 1); % ? maybe just leave out? y = rand(2, 1); % [mean(Apre), mean(Apost)] e = rand(2, 1)*.2; % ? is this maybe [std(Apre), std(Apost)] errorbar(x, y, e, 'o-'); % You can leave off the x here if you don't need it hold all %Now repeat for B x = rand(2, 1); y = rand(2, 1); e = rand(2, 1)*.2; errorbar(x, y, e, '^-'); legend({'First series', 'Second Series'})

Categories : Matlab

FDR of comparing two vectors
if you have one sample for each condition there is no way to have a pvalue,because this is the probability that the difference between samples drawn for one population are statistically different. But, if you have no replicates, no mean, no variance for each gene, as I understood, we can't estimate the sampling error, and therefore there is no how to differentiate the value you see from a random value, for a conventional test of small samples, as t-test. Look this, it may help: http://en.wikipedia.org/wiki/P-value http://www-stat.stanford.edu/~tibs/SAM/ What you can do, is a MA plot http://en.wikipedia.org/wiki/MA_plot and see for the distribution of your data which are the big differences, and select those. But, this is not in the statistical framework of a false discovery rate analy

Categories : R

initialising 2d vectors in c++
Is it possible to declare the 'length' of the first vector whilst declaring the variable without declaring the othe? Kind of, assuming that by "first vector" you mean the outer one. You can do this: std::vector < std::vector <TYPE> > VARIABLE(2); so VARIABLE will consist of two empty std::vectors<TYPE>. There is no such thing as "unknown length" in this context.

Categories : C++

c++ vectors and push_back
This is a case of MVP (Most Vexing Parse): vector<vector<float> > points(); This is actually a function declaration, change it to: vector<vector<float> > points; With the first version, C++ thinks you're declaring a function called points which takes no arguments and returns a vector of vector of floats. That's why it's complaining about it being a non-class type.

Categories : C++

C++ Vectors initialization
It's not clear which compiler you are using, but versions of Microsoft's Visual Studio before the 2013 preview do not support the uniform initialisation syntax {} If you are using gcc you need to tell it to use C++11: -std=c++0x

Categories : C++

Iterating through vectors
Lengths that are 2+ or 7- that sounds like a weird condition. Most likely your conditional should be: if((*itr).length() >= 2 && (*itr).length() <= 7) As a side note, you're better off reading words like this: string word; while(in >> word) { cout << word << endl; //push in selected words based on num of chars words.push_back(word); }

Categories : C++

SHA-256 test vectors
That's because echo appends a newline to the string. Use echo -n instead: $ echo "abc" | shasum -a 256 edeaaff3f1774ad2888673770c6d64097e391bc362d7d6fb34982ddf0efd18cb - $ echo -n "abc" | shasum -a 256 ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad -

Categories : Linux

Calculate average using SSE with STL vectors
You're mixing float & double unnecessarily, especially as you don't let your accumulator be double your precision is totally destroyed and won't be close to satisfactory for larger series. As the arithmetic is super light weight what's destroying your performance here is most likely memory access, read up on memory cache lines and how they work. Basically what you need to do here is probe ahead, some processors have explicit instructions for pulling stuff into your cache, otherwise you can perform a load at a memory location ahead of time. Create another level of nesting in your loop and at regular intervals prime the cache with data you know you will get to in a few iterations. What people do to maximize performance is that they spend a lot of time actually designing their data lay

Categories : C++

LINQ: Combining vectors
This is how you could do it. Result = a.Zip(b, (x, y) => new { x, y }).Select((a,i) => { remainder[i] = 0; if (a.y > a.x) { remainder[i] = a.y - a.x; return 0; } else { return a.x- a.y; } }).ToArray(); It uses the indexed overload of IEnumerable.Select.

Categories : Linq

Remove maximum value of two vectors in R
You can do this for each vector individually: v1[-which(v1==max(v1))] a1[-which(v1==max(v1))] But it probably makes more sense to bind them together so you don't have to repeat commands, like: cbind(v1,a1)[-which(v1==max(v1)),] The process would be the same for v2 and a2: cbind(v2,a2)[-which(v2==max(v2)),] I should also add that it's possible to do this without which with slightly different syntax: cbind(v1,a1)[!v1==max(v1),] cbind(v2,a2)[!v2==max(v2),]

Categories : R

C++ vector of vectors in class
jf and m_content have the same type, you can't push jf as an element of m_content. Try change m_content.push_back(jf); To: m_content = jf; If you want to have a vector of vector of double type, you need to declare m_content as: std::vector<std::vector<double> > m_content;

Categories : C++

simulate vectors as 2D arrays
I know that we can't have multi dimensional vectors You can have 2D vectors like: vector< vector<char> > SeperateBitsBands; Please note :While declaring a vector of vectors, be careful not to put two > together as follows: vector<vector<char>> SeperateBitsBands; as this >> would be mistaken for a right shift operator by the compiler.

Categories : C++

Randomizing one patient per bed using vectors
The general principle when doing "randomly distribute items of vector V to slots in container C" is something like this: Pick a random number in the range 0..C.size()-1 into R Check if slot C[R] is available. If not repeat step 1. Pick the next available item in V, and insert into C[R]. If not all V done, go back to 1.

Categories : C++

Using Parameter Vectors of Different Lengths in R
You are using dbinom with a range of x values and then summing. Instead using pbinom, which calculates then probability of P(x <=q) (or P(x >q) if lower.tail = FALSE). Thus you can calculate P(x >6) + P(q <= 1) (which is what you appear to want to calculate) pbinom(q = 6, p = p ,size = n, lower.tail = FALSE) + pbinom(q = 1, p = p, size = n)

Categories : R

Why am I unable to include vectors?
If you are talking about underlined vector with red color - that's a famous NetBeans problem which I suffer as well. One solution is to click project context menu -> code assistance -> reparse project . The code itself (after your edit) is a valid C++ code and compiler will treat it absolutely fine if you try to compile it.

Categories : C++



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