w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Producing primes in python: how is my logic wrong
Your logic was right, your blocks were not. The break should be indented (under if n % i) and the else should be unindented, so it's the else for the for loop - i.e. numbers are only added if NONE of the primes are it's factor, instead of once for EACH of the primes are it's factor. counter = 1 primes = [2] n = 3 while counter < 1000: for i in range(2, n): if n % i == 0: break else: primes.append(n) counter = counter + 1 n = n + 1 print primes You can save time by only dividing n by (the list of primes so far), instead of all numbers - simply replace range(2, n) with primes

Categories : Python

First 100 primes javascript, why do I get undefined after my array of primes?
You are logging the result of HundoPrimeNumbers: console.log(HundoPrimeNumbers()); HundoPrimeNumbers does not have a return statement. When a function doesn't have a return statement, or returns without a value, like return;, it actually ends up returning undefined. This then gets logged to the console. Solution: call it like this: HundoPrimeNumbers();

Categories : Javascript

Why is Scipy's ndimage.map_coordinates returning no values or wrong results for some arrays?
This is actually my fault in the original question. If we examine the position it is trying to interpolate twoD_interpolate(arr, 0, 1, 1400, 3200, 0.5, 1684) we get arr[ 170400, 0.1] as the value to find which will be clipped by mode='nearest' to arr[ -1 , 0.1]. Note I switched the x and y to get the positions as it would appear in an array. This corresponds to a interpolation from the values arr[-1,0] = 3.3 and arr[-1,1] = 4.7 so the interpolation looks like 3.3 * .9 + 4.7 * .1 = 3.44. The issues comes in the stride. If we take an array that goes from 50 to 250: >>> a=np.arange(50,300,50) >>> a array([ 50, 100, 150, 200, 250]) >>> stride=float(a.max()-a.min())/(a.shape[0]-1) >>> stride 50.0 >>> (75-a.min()) * stride 1250.0 #Not what we

Categories : Python

getting wrong values when javascript data tags used to manipulate dom values on AJAX success
So, if I read right you are adding and subtracting to a total each time something is removed? I find it's always better to recount everything, it's so much easier to maintain than a half dozen edit operations(add,delete,number change, qty change is a curve ball). Here is a function that can add up all input's that match a selector(Your selector would obviously be different). function add(){ var total = 0; $('input').each(function(i,domEl){ var val = $(domEl).val(); if(!isNaN(val)){ total += parseFloat(val); } }); return total; }

Categories : Javascript

Getting wrong results calculating age with PHP
$date1 = "2012-09-13"; $date2 = date("Y-m-d"); $diff = abs(strtotime($date2) - strtotime($date1)); $years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24)); $finaldate = ($years*365)+ ($months*30)+$days; $finalyear = floor($finaldate/365);

Categories : PHP

NOT of 64 bit number giving wrong results in c
Since you didn't want to make an SSCE, I made one for you: #include <stdio.h> int main(void) { unsigned long long a = 42, b = 1ULL << 33; a = a|b; if(!(a&b)) printf("!(a&b) "); else printf("(a&b) "); return 0; } and ran it at ideone. It outputs (a&b) as expected. Your problem is not in the code you are showing us.

Categories : C

mysql returns wrong results when using "like"
utf8_general_ci will sort Ö with O So maybe that's what you want. More about this here otherwise. when you want to search specific on characters like ÄËÖ you can set it to utf8_swedish_ci that will work with ö

Categories : Mysql

MS CryptoAPI giving wrong RC4 Results?
I just wanted to follow up with the answer I found in case this is useful to someone else in the future. First and foremost, the answer was to RTFM! As it turns out, by default, CryptDeriveKey adds a "salt" to 40-bit symmetric keys consisting of all 0's. When I looked at our old CryptoAPI code and saw that we weren't passing any flags into it, I assumed this meant nothing special was going on and I didn't read through the details of all possible flags on MSDN. Furthermore, since MS considers this portion of the key a salt it is not included when you export the key so that was also a dead end. I eventually found my way to http://msdn.microsoft.com/en-us/library/windows/desktop/aa387695(v=vs.85).aspx which explains the salt mechanism for 40-bit keys and the line that caught my eye was that

Categories : Misc

Why does MSVC give me 'wrong' results?
Iterators (including std::vector<Person>::iterator, which you are passing as an argument to printf()) are not guaranteed to be PODs, and arguments to a C-style variadic function can only be PODs. WTF!?! I get no warnings/errors That is because passing non-POD arguments to a C-style variadic function is undefined behavior. The compiler is not required to issue a diagnostic, although some very nice compilers do that (as correctly mentioned by Mark B in the comments).

Categories : C++

Rails activerecord returning wrong results
You don't need to call to_json on the object in this line @log_id = Log.where("bid = ?",@b_id).last.to_json Just the original object is okay. @log_id = Log.where("bid = ?",@b_id).last Because when you call render json: @obj there will be an action to convert the obj to json. No need duplication.

Categories : Ruby On Rails

MySql Procedure Producing Wrong Results
For your first question: 1) What's wrong (or missing) in this stored procedure? (Dummy table had thousands of records as well) I guess you forgot to CLOSE the CURSOR. Right after you end the LOOP, you should CLOSE the CURSOR. END LOOP claimlistloop; CLOSE claimlist; END 2) What could be the best possible way of doing this task other than creating a stored procedure? Doing that in the STORED PROCEDURE should be fine. And also using CURSOR would be fine since you will just execute the procedure once (I guess because this is a production fix). But from your question, you just want to update TableA based from the provided DummyTable. I assume that these tables have the same columns. So I think this query is better than the CURSOR: UPDATE TableA A INNER JOIN DummyTabl

Categories : Mysql

MySQL same table calculation wrong results
Change COUNT(s*) AS total_guests to COUNT(*) AS total_guests or to COUNT(s.id) AS total_guests At least that seems to be your immediate problem.

Categories : Mysql

Javascript for loop yields wrong results
The issue here is that the functions created on each iteration of your loop are going to look in the enclosing scope for the value of the name variable when the function is called. This means that every one of those functions will end up using the value of name from the final iteration. Consider the following simple example which illustrates what is going on here: var functions = []; for (var i = 0; i < 3; i++) { functions.push(function() { console.log(i); }); } functions[0](); // logs 3 So even though at a glance it looks like functions[0](); should log 0 since that was the value of i when functions[0] was created, it logs 3 because that is the value of i when the function is called. One way to fix this is to use a closure that fixes the variables to their curren

Categories : PHP

xslt not showing results. xpath or ns wrong?
This is indeed an issue with namespaces. In your XML, you have declared a default namespace meaning the root element, and all its descendants, and in this namespace. <bibdataset .xmlns="http://www.elsevier.com/xml/ani/ani" ... Now, in your XSLT, you have also declared this namespace, but without a prefix. <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.elsevier.com/xml/ani/ani" This means it only applies to the elements you are outputting, so your searchresult element gets output in this namespace <searchresult xmlns="http://www.elsevier.com/xml/ani/ani" However, it doesn't apply to the xpath expression in your XSLT, and so these are looking for elements in your input XML with no namespace. In XSLT 2.0 the solution

Categories : Xslt

Spring mvc calling controller from jsp results in wrong url
Either of this should work. You could use index method which is the default mapping. @RequestMapping(value="/", method=RequestMethod.GET) public String list(Model model) { // ... } Or instead list rename to index as follows @RequestMapping(method=RequestMethod.GET) public String index(Model model) { // ... }

Categories : Java

ChannelBuffer readInt()/writeInt() results in wrong value
haraldK is exactly right. When an integer is written out across the network (or technically, when it is serially written), the bytes are received in the opposite order. Using netty channel buffers (and groovy) this script makes it a bit easier what's going on. It starts with an int of 5 and writes to a LITTLE_ENDIAN buffer. The contents of that buffer are then copied into a BIG_ENDIAN buffer, and when read back out, present and int which os not 5. The underlying bytes of the int have been reversed. The script also prints the binary (bits) representation of the int, and, using a much more efficient transformation, Integer.reverseBytes(int), does the same thing. import org.jboss.netty.buffer.*; import java.nio.*; lBuff = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, 4); int a = 5; lBuff.w

Categories : Java

When I try to use function to "reuse" the code, it gives wrong results
Since the three parameters you are passing are just strings, javascript will pass them by value. This means that making a change to TCwind inside the function will not change TCwind outside the function. The most straight forward way to do that is to return the values in an object: var result = Intensity(65, '', ''); var TCwind = result.TCwind; var TCimage = result.TCimage; var TCIntensity = result.TCIntensity; function Intensity(TCwind, TCIntensity, TCimage) { /* snip */ return { TCwind: TCwind, TCIntensity: TCIntensity, TCimage: TCimage }; }; For more information about pass by value / pass by reference, check out some of these other questions: Is JavaScript a pass-by-reference or pass-by-value language? Does JavaScript pass by reference? Pass Va

Categories : Javascript

Wrong results appearing for date formula
Similar to your attempt: =IF(AND(ISBLANK(E2),ISBLANK(M2)),"no data",IF(ISBLANK(E2),"no est",IF(ISBLANK(M2),"no del",NETWORKDAYS(E2,M2)))) (probably could be abbreviated slightly, but relatively clear).

Categories : Excel

MD4 hashing with Crypto++ results in wrong hash?
Okay, I found the solution by myself. It doesn't work the way I posted above. Here the correct code, it may be useful for someone else: std::string value; CryptoPP::Weak1::MD4 hashmd4; CryptoPP::StringSource (password, true, new CryptoPP::HashFilter( hashmd4, new CryptoPP::HexEncoder( new CryptoPP::StringSink(value) ) ) );

Categories : C++

Values ​​of an array showing wrong values
You're prefixing the keys with 0, so they're being treated as octal numbers. e.g. $_LANG[027(octal)] is actually $_LANG[23(decimal) $_LANG[010(octal)] is actually $_LANG[8(decimal)] Either use strings: $_LANG['027'] or normal decimals: $_LANG[27]

Categories : PHP

Page Views Counter in PHP is giving the Wrong Results
Try like this <?php $thread_id = 4554; // thread_id is the unique page id $sess_key = "page_id_" . $thread_id; $sessVal = $_SESSION[$sess_key]; if (!isset($sessVal)) { $_SESSION[$sess_key] = session_id(); //Update the count in mysql table }

Categories : PHP

Quadratic Program Java returning wrong results
You should NOT use int type for your a, b, c coefficients. If you use double type, your code should work. When you use integers, then code that is using b*b or 4*a*c is likely to cause integer overflow and throw off your code logic.

Categories : Java

Why this left outer join produces wrong results?
The condition e.deptno is null needs to be in the where clause: select d.deptno as d_deptno, e.deptno as e_deptno from dept d left outer join emp e on d.deptno = e.deptno where e.deptno is null This is because the on clause uses the conditions specified as the criteria to join rows from one table to the other - so it would only link to emp records that had a null deptno, and simultaneously a deptno matching the dept record. Since these criteria are mutually exclusive, the query will never successfully link to an emp record, so the outer join ensures that nulls are returned for the emp values. The where clause is applied after the join conditions - so moving the is null condition into the where clause ensures that only dept records with no matching emp records are selected. e_d

Categories : Mysql

Wrong results in Visual Studio Performance Profiler
Thanks MikeDunlavey, your answer is accurate, time spent doing I/O, like accessing a DB, does not show up in the results. That insight made me search and find something like this pretty awesome feature of Visual Studio: TIP (Tier Interaction Profiler). It lists all my SQL queries (the exact text of the query), how often they got called, to which DB the calls were made, the time it took to execute them. And it seems to handle other I/O (like HTTP requests as well). Hats off to MS for creating this little-known (?) gem! After this rare opportunity to praise MS I have to say that the profiler crashes on my app most of the time. But that's another story, and perhaps another question.

Categories : Dotnet

mysql date compare query gives wrong results
put the item conditions between () (ítem_code = 'msft234' OR ítem_code = 'hp550x') AND transact_date>=STR_TO_DATE('06-07-2013','%d-%m-%Y') and transact_date<=STR_TO_DATE('12-07-2013','%d-%m-%Y')

Categories : PHP

Calculating an integer from its Bytes gives oddly wrong results
I've done this a hundred times. Change: char b[2] = {0xBD, 0x74}; To unsigned char b[2] = {0xBD, 0x74}; Or, better yet uint8_t b[2] = {0xBD, 0x74}; Note that char can be more than 8 bits (I worked on a system with a 32-bit char size)

Categories : C

Issue with exact match returning wrong results
The two queries are different from each other. The first one looks for a records which contains MEM04912 within column referredby, while the second one finds a records that has exact value of MEM04912. Given the set of data, referredby ============== AMEM04912 MEM04912 MEM049123 XMEM04912X when you execute your first query, it will return all records since all of them contains a part of your searched string, while your second query will only return the second record because it is the only record that exactly match on your searched string.

Categories : Mysql

Python numpy.nan and logical functions: wrong results
While evaluating logical expressions containing and, we have to evaluate the expressions that are present on both sides of the and operator. Whereas for or operator, if the first expression is True, then there is no need to check for the correctness of the second expression E.g., While evaluating the expression 2>2 and 3==3 , first we should check whether the first expression 2>2 is True or not. If this first expression is False, then there is no need to check the second expression because of the AND operator and the result of such an expression will be FALSE as the first expression is FALSE. Whereas if the expression has been 2==2 AND 3==3 , then since the first expression 2==2 is True, then we need not check the correctness of the second expression and since here the second expres

Categories : Python

OpenMP parallel for reduction delivers wrong results
Use the Kahan summation algorithm It has the same algorithmic complexity as a naive summation It will greatly increase the accuracy of a summation, without requiring you to switch data types to double. By rewriting your code to implement it: for(int row = 0; row < tan_hd.rows; row++) { float sum = 0.0, c = 0.0; #pragma omp parallel for reduction(+:sum, +:c) for(int column = 0; column < tan_hd.cols; column++) { float y = tan_hd.data[column * tan_hd.rows + row] - c; float t = sum + y; c = (t - sum) - y; sum = t; } sum = sum - c; printf("row %d: %f", row, sum); } You can additionally switch all float to double to achieve a higher precision, but since your array is a float array, there should only be differences in the number

Categories : C

sieving primes up to 10^12
You will need to use a segmented sieve. The basic idea of a segmented sieve is to choose the sieving primes less than the square root of n, choose a reasonably large segment size that nevertheless fits in memory, and then sieve each of the segments in turn, starting with the smallest. At the first segment, the smallest multiple of each sieving prime that is within the segment is calculated, then multiples of the sieving prime are marked as composite in the normal way; when all the sieving primes have been used, the remaining unmarked numbers in the segment are prime. Then, for the next segment, for each sieving prime you already know the first multiple in the current segment (it was the multiple that ended the sieving for that prime in the prior segment), so you sieve on each sieving prim

Categories : Java

DataTable Compute and Select methods giving wrong results
The issue got fixed after adding the below line of code just above .Compute. (this.DataSource as BindingSource).EndEdit(); Apparently the data in the grid cell (jobtype column here) was not committed to the underlying datasource. EndEdit did the trick.

Categories : C#

Page Views Count Function giving wrong Results
If you use url rewriting, it is possible that the browser requests additional assets (for example favicon.ico) and if that does not exist and gets rewritten to request your php file, you get another hit. Apple devices are also looking for different icons / images.

Categories : PHP

GRAILS GORM is showing wrong results while querying with Enum Types
Generally Enums are capitalized (to avoid the confusion with normal String implementations). It should work as expected if the setup is like: enum Status{ PROCESSED('processed') REJECTED('rejected') INPROGRESS('progress') private final String name Status(name){this.name=name} String value(){name} } [new Request(status: Status.INPROGRESS), new Request(status: Status.REJECTED), new Request(status: Status.PROCESSED)]*.save() assert Request.findByStatus(Status.REJECTED) instanceof Request assert Request.findByStatus(Status.REJECTED).status == Status.REJECTED assert Request.findByStatus(Status.REJECTED).status.value==Status.REJECTED.value

Categories : Grails

Can .Find method return wrong results in multi-user environment
Well the docs state that Find... Uses the primary key value to attempt to find an entity tracked by the context. If the entity is not in the context then a query will be executed and evaluated against the data in the data source, So it searches the cache first. If what's in your cache is old (or doesn't exist in the database - and maybe never will) then that's what you get. It ONLY does a query if it can't find the entity in the cache. I wouldn't say it returns the "wrong" thing because of what it's defined to do. If you need to find data that might be changed by another user or that's guaranteed to exist in the database you'll want to stick with a query.

Categories : C#

Unexpected token ILLEGAL(first 100 primes)
“ is not the same as ". Similarly, ‘ and ' are not the same. Change each occurance of “ and ‘ to " and ' respectively, and your code should work fine.

Categories : Javascript

How can I check if numbers are consecutive primes?
Try this: public int nextPrime(int start){ int next = start+1; while(!isPrime(next)){ next++; } return next; } public void arePrimeSequence(int r, int s, int a){ int firstPrime = nextPrime(r); int secondPrime = nextPrime(firstPrime); if(s == firstPrime && a == secondPrime){ System.out.println("YES"); } else{ System.out.println("NO"); } }

Categories : Java

Generating primes List in objective C?
-(NSMutableArray *)generatePrimes:(int)upperLimit { NSMutableArray *primes = [[NSMutableArray alloc]init]; bool isPrime; for (int i=2; i<upperLimit; i++) { bool prime = true; for (int j=2; j*j<=i; j++) { if (i % j == 0) { prime = false; break; } } if(prime) { [primes addObject:[NSDecimalNumber numberWithInt:i]]; } } return primes; } or -(NSMutableArray *)generatePrimes:(int)upperLimit { NSMutableArray *primes = [[NSMutableArray alloc]init]; [primes addObject:[NSDecimalNumber numberWithInt:2]]; for(int i=3; i < upperLimit; i++) { bool prime=true; for(int j=0;j<primes.count &&

Categories : Objective C

Generating Primes by 'Sieve' method
There are many problems in your code: for(i=m[s];i<=n[s];i++) prime[i] = 1; prime is an array from 0..m[s]-n[s], so i should go from 0 to m[s]-n[s]. sieves are not constructed this way, sieves are always constructed starting from 2. What you could possibly do, is find the max num in the array n; Then build a sieve, from 2..max. Now, return the primes between m[s] and n[s], as is required.

Categories : C

Sum of primes using Sieve of Eratosthenes; answer too small
for (int i = 0; i <= b.length(); i++) change it to for (int i = p+1; i <= b.length(); i++) Otherwise you're eliminating all primes smaller than 2,000,000^.5

Categories : Java

Find the sum of all the primes below two million. Project euler, C
Using float as the sum is the problem. The largest integer k such that all integers from [-k, k] are exactly representable in 32-bit float is 2^241; after that you will start losing precision in some integers. Since your sum is outside that range that, by an absurd margin, you lose precision and all bets are off. You need to change to a larger type like long (assuming it's 64-bits on your machine). Make the change, and you'll get right answer (as I did with you code): [ec2-user@ip-10-196-190-10 ~]$ cat -n euler.c 1 #include <stdio.h> 2 #include <math.h> 3 4 #define BELOW 2000000 5 6 int isaprime (int num); 7 8 int main (void) { 9 10 int i; 11 long sum = 0; 12 13 for (i = 2; i < BELOW

Categories : C



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