w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Matplotlib imshow() too many objects for cmap
imshow doesn't take x, y, z as input. (pcolor and pcolormesh do, however). Either use pcolormesh(x, y, z), or use the extent kwarg to imshow. e.g. plt.imshow(Z, extent=[X.min(), X.max(), Y.min(), Y.max()], cmap='bone') or plt.pcolormesh(X, Y, Z, cmap='bone') What's happening is that imshow expects imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, **kwargs) Notice that the second argument is cmap, which explains why you're getting the error you are when you pass in an additional cmap kwarg. Hopefully that clarifies things a touch! Good luck!

Categories : Python

CMap - What will happen if we add more elements to the map than the hashtable size?
Overfilling a hash table results in collisions. The items that collide get put in a list, which must be searched. Everything still works, it just gets a bit slower. If your hash table is properly-sized and your hash function is decent, then inserts and lookups in your hash table will be constant-time. In your overfull hash table, these times will increase due to having to walk the lists that result from collisions.

Categories : C++

How to write this graph related algorithm
This is my first pass quickly thinking about this question, and if I think of a better response I'll come back and edit my answer. Someone else may be able to take what I provide and help you out more too. This is the "brute force" approach, and there may be a better way of solving this. Enumerate all origin/destination pairs (which looks to be an input.) -10,000 operations. For stations requiring more capacity than the train can provide, split these into additional origin/destination pairs. Enumeration all permutations of origin/destination pairs - 10,000! operations (n*n complexity) - inside a loop, not saving each one. For each permutation, calculate the total distance the train drives. For each pair, this will be the previous distance driven plus the train to origin + the train to t

Categories : C

Can I know the encryption algorithm used so that I could write my own sign-in code?
It's Blowfish, and isn't even a hash. If you care about security, you may want to switch login providers or even products away from Openfire and its internal user provider. Blowfish has a 64-bit block size I guess we have multiple blocks, though the password is somewhat short. From cursory examination of the length of what is apparently a hash(not encryption) it appears to have 24 hexits, hence 24 nibbles, which equals 192 bits. Unless the hash is truncated(then we don't know exactly), it should be Tiger, at the bottom of the page, for 192 bits. Edit: No match for Tiger-192,3 or Tiger-192,4. Either it's salted or not Tiger. I'll look for source. Edit: It's probably Blowfish encryption, not hashing. Seems odd, but it's there, in openfire_src_3_8_2.zip/openfire_src/src/java/or

Categories : Java

How do I write an algorithm to break the Caesar Cipher?
Since this appears to be an assignment, I'm not going to give you the answer in C#. I will explain the algorithm and give a solution in Python. The Caeser Cipher works by shifting an alphabet "N" number of spaces. If you have an alphabet set up in an array: array = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] This is an easy way to manipulate the alphabet to see what different shifts would look like. The next thing to do is to count the number of occurrences of each letter in the cipher: count = {} encrypted_string = "HVWGWGHVSPSGHQCADIHSFSLSFQWGSWVOJSSJSFS

Categories : C#

Algorithm to write two's complement integer in memory portably
If I understand correctly, you want to store 4 bytes of an int32 inside a char buffer, in a specific order(e.g. lower byte first), regardless of how int32 is represented. Let's first make clear about those assumptions: sizeof(char)=8, two's compliment, and sizeof(int32)=4. No, there is NO portable way in your code because you are trying to convert it to char instead of unsigned char. Storing a byte in char is implementation defined. But if you store it in an unsigned char array, there are portable ways. You can right shift the value each time by 8 bit, to form a byte in the resulting array, or with the bitwise and operator &: // a is unsigned 1st byte = a & 0xFF 2nd byte = a>>8 & 0xFF 3rd byte = a>>16 & 0xFF 4th byte = a>>24 & 0xFF

Categories : C

How to write an algorithm in java to evaluate an arithmetic expression with brackets
A common approach to evaluate arithmetic expressions is to develop or lookup a grammar for arithmetic expressions, see here http://www.csse.monash.edu.au/~lloyd/tildeProgLang/Grammar/Arith-Exp/ for example and then code a "recursive descent parser". Those programms have a structure very close to the grammar. Once you see one you will appreciate this approach.

Categories : Java

Rolling Hash Algorithm for Rabin-Karp Algorithm Java
You have a couple of fundamental problems in your code. The first one is here: patternHash += int_mod(patternHash * base + pattern[i], primeMod); It is duplicated on a few more places. The second one is in calculating the rowing hash: segmentHash += int_mod(segmentHash * base + text[i + pattern.length -1],primeMod); segmentHash -= int_mod(segmentHash * base + text[i-1], primeMod); Both this errors can be easily fixed. However, I will suggest you to understand better the logic behind the code instead of just copying it from somewhere. The hashing algorithm you've used is based on polynomials, so try to see what happens on that level. Maybe even write a few examples by hand -- they will be useful while debugging the code. Note also that you will have problems with integer over

Categories : Java

Algorithm analysis: Choosing the best algorithm
Actually, you are trying to solve the inequality because the algorithm is only going to be faster for a very short time, and then for any larger values of n, the algorithm will be faster. Ignore the case n <= 0, multiply by 10, and divide by n to produce: Then divide by 20 and exponentiate both sides with a base of 10: Use a numeric solver to find the zeros of on the interval [1, 40] since clearly 40 is an upper bound (because ). For instance, in Matlab: >> fzero(@(x) 10^(x/20)- x, 20) ans = 29.3531 So for any n an integer up through 29, the algorithm is faster, and for n > 29, the algorithm wins.

Categories : Algorithm

Fastest searching algorithm for 5 million records from linear search, binary search, b tree search algorithm?
Every data structure has it's value. For instance, you'd use a binary tree most likely if you had numerically sorted data because your complexity would be really low (I.e. O(logn)). You would use a linear search only if you have a few records because the complexity is O(n) or linear (go figure!). You'll have to do research on the value of various structures and the knowledge of how your data is stored to get a better feel!

Categories : Database

Why does UPDATE .WRITE() only work if I use [column].WRITE(), but not [table].[column].WRITE()?
It doesn't seem very consistent ... It is actually consistent with the rest of the SET clause: SET { column_name = { expression | DEFAULT | NULL } | { udt_column_name.{ { property_name = expression | field_name = expression } | method_name ( argument [ ,...n ] ) } } | column_name { .WRITE ( expression , @Offset , @Length ) } | @variable = expression | @variable = column = expression | column_name { += | -= | *= | /= | %= | &= | ^= | |= } expression | @variable { += | -= | *= | /= | %= | &= | ^= | |= } expression | @variable = column { += | -= | *= | /= | %= | &= | ^= | |= } expression } [ ,...n ] That is, it's never valid, in the SET

Categories : Sql Server

Relation between KMP algorithm and Z algorithm
NOTE: algorithm is wrong for i in range(0, len(s)): if lps[i] != 0: Z[i - lps[i] + 1] = lps[i] After that in Z[i] will be the maximum length of the suffix, that starts in position i and which is also a prefix of the string. EDIT As nikhil_vyas noted, the proposed algorithm does not solve your problem. What it actually does is partially filling Z array with the longest suffixes and some others. Such incomplete array can basically help you to solve several "find the longest something in the string" problems, but it does not answer your question. The easiest way to rebuild Z array having lps array that comes to my mind is to build the string, corresponding to the lps array and then build Z array for that string. But I am not sure whether it suits your definition of "some mod

Categories : String

Android: write failed: EPIPE (Broken pipe) Error on write file
EPIPE issue usually happens when you either try to execute command which needs root permissions (getRuntime().exec) in your case on the device without it or run several root commands simultaneously. If you work on the emulator and need to root it I think you you can try this while the emulator is running: adb shell mount -o rw,remount -t yaffs2 /dev/block/mtdblock03 /system adb push su /system/xbin/su adb shell chmod 06755 /system adb shell chmod 06755 /system/xbin/su Here http://abd-tech.blogspot.com/2011/05/test-root-apps-on-android-emulator.html more detail explanation.

Categories : Android

Write a single textfile multiple times with to_csv and write methods
Use the mode argument to .to_csv. In [5]: df = DataFrame({'A': ['foo', 'foo', 'foo', 'bar', 'bar'], 'B': ['one', 'two', 'three', 'one', 'two'], 'C': np.random.randn(5)}) In [6]: with open('test.txt', 'w') as f: ...: f.write('Testing ') ...: In [7]: !cat 'test.txt' Testing In [11]: df.to_csv('test.txt', mode='a') In [12]: !cat 'test.txt' Testing ,A,B,C 0,foo,one,0.42364430570326805 1,foo,two,1.1992467813307852 2,foo,three,0.4302171615562164 3,bar,one,0.6837252733791036 4,bar,two,0.16800783901724345

Categories : Python

I want to write an OCMock unit test for the button and the method below. How do I write it?
Your mock object and object created inside method is not same. Should be something like this: //This method displays the UIAlertView when Call Security button is pressed. -(void)displayAlertView:(UIAlertView *)callAlert { [callAlert show]; if([[callAlert buttonTitleAtIndex:1] isEqualToString:@"Call"]) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"telprompt://0000000000"]]; } } //This Button calls the above method. -(IBAction)callSecurityButton { UIAlertView *callAlert = [[UIAlertView alloc] initWithTitle:@"Call Security" message:@"(000)-000-0000" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Call", nil]; [self displayAlertView:callAlert]; } And test method: -(void)testDisplayAlertView { OCMockObject *UIAl

Categories : IOS

C# SerialPort.Write is taking a long time to write data
The baud rate is bits per second, not bytes per second. 420 bytes is 3360 bits, so the raw data takes 3360/9600 = 0.35 seconds to send. So, 400 ms seems very reasonable when the overhead is included.

Categories : C#

Can you write multiple IP packets in one write to the linux tun device?
Actually multiple packets were returned by the driver because it had been enhanced locally. The tun driver that comes with linux only returns one packet per read. The driver also expects only one packet per write.

Categories : Misc

How to write an Android application to do sysfs read/write.?
Firstly, make sure you have the permission to that sysfs node(Usually you don't, if you are developing a user app). Secondly, I would say usually you don't have to talk to sysfs node directly from Android app.Below app there are Android Framework and HAL levels that did all the abstraction for you. Since not sure about what you are going to do, here is an example I fetched from Android LightsService which directly talk to sysfs node, which might be helpful to you. 216 private static final String FLASHLIGHT_FILE = "/sys/class/leds/spotlight/brightness"; ... 236 try { 237 FileOutputStream fos = new FileOutputStream(FLASHLIGHT_FILE); 238 byte[] bytes = new byte[2]; 239 bytes[0] = (byte)(on ? '1' : '0'); 240 bytes[1]

Categories : Android

Automatically using the object name as file name with write.table or write.csv
The idiomatic approach is to use deparse(substitute(blah)) eg write.csv.named <- function(x, ...){ fname <- sprintf('%s.csv',deparse(substitute(x))) write.csv(x=x, file = fname, ...) }

Categories : R

Using fs.open and fs.write to write exclusively to a file
Ok so I did some testing and came up with the following code, which assumes the file doesn't exist (it will throw an exception because of the x flag if it does): var fs = require("fs"); var log = { filename: "path", flag: "ax", mode: 0444, file: null, encoding: "utf8", finalMode: 0644, write: function( string ) { if( this.file == null ) { this.file = fs.openSync(this.filename, this.flag, this.mode); } if( string instanceof String ) string = string.toString(); if( typeof string != "string" ) string = JSON.stringify( string ); var buffer = new Buffer( string, this.encoding ); fs.writeSync(this.file, buffer, 0, buffer.length); return this; }, close: function() { fs.close(this.f

Categories : Javascript

How to write copy-on-write list in .NET
Implementation is correct because reference assignment is atomic in accordance to Atomicity of variable references. I would add volatile to list.

Categories : C#

When using sys.stdout.write, "None" appears after what I write
sys.stdout.write('%') returns None. It simply prints the message and does not return anything. Just put "%" at the end instead of calling sys.stdout.write Or, you can use .format() here: print "What are his odds of hitting? {}%".format(( 25.0 / 10.0 ) * 8 + 65)

Categories : Python

mixing file.write and system calls that write to same file
You are opening the file in "write" mode which is clobbering the first echo. Instead use 'append' mode. Additionally, you're not flushing after you write "2" so it'll be out of order when you read it back. Remember, f.write doesn't append a newline, so you probably need that too. irb(main):020:0> File.open('asdf', 'a') do |f| irb(main):021:1* `echo 1 > asdf` irb(main):022:1> f.write("2 ") and f.flush irb(main):023:1> `echo 3 >> asdf` irb(main):024:1> end => "" irb(main):025:0> File.read('asdf') => "1 2 3 " irb(main):026:0> puts File.read('asdf') 1 2 3 The File.open(name, 'a') is the important part. It means append to this file instead of overwriting it. See http://www.ruby-doc.org/core-2.0/IO.html#method-c-new and What are the Ruby File.open modes

Categories : Ruby

A bug in FFT Algorithm
I can't immediately say what your problem is, but you have at least one serious bug. Here: float a = ceil(log(num)/log(base))-floor(log(num)/log(base)); if (a==0){ return 1; } Other than the fact that a valid comparison would be to 0.0f, you should not do some floating point calculation and expect the value to be a specific number. Where you expect 0.0, it may actually be something like 0.00000000132. Because that is how floating point numbers work. They always have and will work like that, unfortunately. As for your FFT calculation, I'd look more closely at the lines where you assign F[k] and F[k+M]. In those, you multiply a value by ODFT[k] and my suspicion is that ODFT[k] may be 0 there.

Categories : C++

Fox Algorithm with MPI
While not answering your original question can I just remark that MPI_Bcast and matrixmult both take tmp as a first argument in the else block, perhaps using it as a destination to store variables. Without seeing how those two functions are implemented you can't know for sure whether tmp is used unitialised. Also malloc-allocated memory can sometimes be 0 initalised though it's not behaviour I would rely on. And finally, if you're going to use the code in the slides don't cast the result of malloc.

Categories : C

RSA Algorithm Example
The message m is 42, and blinding factor r is 11, so the value provided to the authority is m' calculated as: m' = m * re mod N m' = 42 * 1111 mod 85 m' = 62 The authority will sign this by calculating s' using: s' = m'd mod N Where d is the private exponent. We must therefore calculate the private exponent which we know to be a value that satisfies the relation: e * d = 1 mod ɸ(N) Where ɸ is Euler's totient function. N is the product of two primes p and q per the definition of the RSA algorithm, and since N is small we can easily factor it to determine p = 5 and q = 17. Thus by definition of ɸ: ɸ(N) = (p-1)(q-1) ɸ(N) = (5-1)(17-1) = 64 Using the provided results, we can therefore determine: e * d = 1 mod ɸ(N) 11 * d = 1 mod 64 d = 35 So, the authority should return to us

Categories : Security

Why does this O(N^2) algorithm run so quickly?
I think the issue here is that everything is getting optimized away. Here's my reasoning: The value of x can be known without having to do any computation - your array is all 0s, so x will always take the value 0. The local variable x is unused and can be optimized away. The inner loop does nothing, so can be optimized away. The outer loop does nothing, so can be optimized away. You're left with not all that much code, which is why it probably runs so quickly! For reference, I tried this on my own machine and varied the array size by constantly multiplying it by a factor of 10 and saw absolutely no change in performance - it always finished and outputted that 0 seconds were required. This is consistent with the optimization hypothesis, which states the runtime should be O(1). EDIT:

Categories : Java

Dijkstra algorithm
The logical error in your code is that you have set the values of cost matrix by reading from the file. But other values are zero by default, so you are always getting min as zero. So the pair of of nodes which don't have path between them are considered as the shortest distance. You need to make these cost INFINITE i.e. some very large value. for(i = 0;i < n;i++) for(j = 0;j < n;j++) { if(i!=j) { if(cost[i][j]==0) { cost[i][j] = INF; } } }

Categories : Arrays

Will this algorithm always work?
It will work, but there is an even cooler way to do it with no loops. Disp "GIVE ONE NUMBER" Prompt A Disp "GIVE A SECOND NUMBER" Prompt B 1/fPart(A)->F A*F->A B*F->B 1/fPart(B)->F A*F->A B*F->B gcd(A,B)->C Disp A/C Disp B/C

Categories : Misc

What should the Kth ant do in the Ant Colony Algorithm?
The idea behind the ant colony algorithm is that 1) all edges start out with no scent 2) an ant taking an edge gives it some extra scent 3) scent decays over time 4) if an ant has multiple paths to pick from, it picks randomly - BUT - randomly with weights according to scent quantity on each path. Picture it like this. Let's says that a road with no scent has weight 1, and a road with scent units 1 has weight 2. An ant sees four paths, but the first path has one scent unit. The weights are: 2, 1, 1, 1 Total weight = 5 Chance of taking path one = 2/5 (40%) Chance of taking path two = 1/5 (same for path three, four and five) (20%, 20%, 20%) Obviously you can use whatever functions you like for how much scent is added to an edge dependent upon how much scent it has, how much scent

Categories : Algorithm

Algorithm for best fit rectangle
Here are some ideas that might help you. We can estimate if a point is on an edge or on a corner as follows: Collect the point's n neares neighbours Calculate the points' centroid Calculate the points' covariance matrix as follows: Start with Covariance = ((0, 0), (0, 0)) For each point calculate d = point - centroid Covariance += outer_product(d, d) Calculate the covariance's eigenvalues. (e.g. with SVD) Classify point: if one eigenvalue is large and the other very small, we are probably on an edge otherwise we should be on a corner Extract all corner points and do a segmentation. Choose the four segments with most entries. The centroid of those segments are candidates for the rectangle's corners. Calculate the normalized direction vectors of two opposite sides and calculate th

Categories : C

Kernighan-Lin Algorithm
Yes, K--L may create disconnected subgraphs. For example, it splits the 8-vertex star * * * |/ *-*-* /| * * into two 4-vertex subgraphs, of which one, the one not containing the center, is necessarily not connected. I don't know what you would want to happen on this example.

Categories : Algorithm

K-means++ algorithm
http://en.wikipedia.org/wiki/K-means%2B%2B 1. Choose one center uniformly at random from among the data points. 2. For each data point x, compute D(x), the distance between x and the nearest center that has already been chosen. 3. Choose one new data point at random as a new center, using a weighted probability distribution where a point x is chosen with probability proportional to D(x)2. 4. Repeat Steps 2 and 3 until k centers have been chosen. 5. Now that the initial centers have been chosen, proceed using standard k-means clustering.

Categories : Algorithm

FCFS algorithm using C++
Its simple. Just sort the processes according to their waiting time (wt). And calculate the burst time. Please provide a better input set. Your current input doesn't need any sorting. On other note, please try to understand what the algorithm says. In FCFS, the processes (P1...Pn) will be processed in a order according to their entering time in CPU. Who comes first will be served first as the name says.

Categories : C++

What is the "make -jX" algorithm
You can see precisely the algorithm that make uses by using make -d to print debugging information. For your example (I added echo commands to actually cause something to happen): $ make -r -d -j GNU Make 3.81 Copyright (C) 2006 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This program built for i386-apple-darwin11.3.0 Reading makefiles... Reading makefile `Makefile'... Updating makefiles.... Considering target file `Makefile'. Looking for an implicit rule for `Makefile'. No implicit rule found for `Makefile'. Finished prerequisites of target file `Makefile'. No need to remake target `Makefile'. Updating goal targets.... Considering target file

Categories : Algorithm

Is this algorithm of O(n^4) avoidable?
Well we can already halve the loop by changing the starting index of the second loop. for (y = 1, ...) to for (y = x + 1; ...) giving for (x = 0; x < (sizeof(slopes) / sizeof(slopes[0])) - 1; x++) for (y = x + 1; y < (sizeof(slopes) / sizeof(slopes[0])); y++) for (z = 0; z < sizeof(inter) / sizeof(inter[0]); z++) for (a = 0; a < sizeof(inter) / sizeof(inter[0]); a++) printIntersect(slopes[x], slopes[y], inter[z], inter[a]); I've also removed the equality check, even though as jxh pointed out, slopes may contain duplicate entries. Well, I did this because you can remove duplicates in O(n). Of course this doesn't change the overall time complexity of the algorithm, but it should help with the runtime.

Categories : C

Algorithm complexity
The time complexity of the algorithm is O(n). Each recursive call's complexity is actually: f(n) = 2*f(n/2) + CONST It is easy to see (by induction1) that f(n) <= CONST'*n - and thus it is O(n). The space complexity is O(logN) - because this is the maximal depth of the recursion - so you allocate O(logN) memory on the call stack. (1) If you use f(n) = 2*n*CONST - CONST you get: f(n) = 2*f(n/2) + CONST = (h.i.) 2*(2*CONST*n/2 - CONST) + CONST = = 2*n*CONST - 2CONST + CONST = 2*n*CONST - CONST (Checking the base is is left as exercise for the reader)

Categories : Algorithm

Ddrescue(GNU) algorithm
bad sectors are naturally occur in groups...if i gently hit a working drive with a hammer, the heads are most likely scratch the surface...which is rotating...so it will create a nice concentrical circle on the storage surface. trying bad blocks after bad blocks is usually time wasting...and in most cases bad drives doesn't have much hours left... after trimming the unknown range most likely has bad sectors on the edges - that's why splitting starts in the center...which is probably healthy... it seeks to the target sector by using fseek() or something like that...ddrescue is like dd on steroids...it has the ability to "know" what data have been read, it leaves out all parts of the disk which are unreadable

Categories : Algorithm

Identify AES Algorithm . Is it AES 128 or AES 256?
It's AES 256. The number is the key size. From Wikipedia: Strictly speaking, the AES standard is a variant of Rijndael where the block size is restricted to 128 bits. So the block size is always 128. I can't point you to any official documentation because (so far as I'm aware) AES-<Number> has always been an unofficial shorthand. I can point you at a Bruce Schneier Blog Post which quotes a research paper: AES is the best known and most widely used block cipher. Its three versions (AES-128, AES-192, and AES-256) differ in their key sizes (128 bits, 192 bits and 256 bits) and in their number of rounds (10, 12, and 14, respectively). In the case of ... Although your client may not like the rest of that blog post since it's Schneier recommending AES-128 over AES-256.

Categories : C#

DDA algorithm confusion......!
In order to draw a continuous line on a discreet plan (x,y), x, y integer, that algorithm, based on the slope of the line, makes either x or y the "carrier" (always incremented by one) and the other coordinate is interpolated. Reason are: the drawing should be as close as possible to the line equation there should be no "hole" in the drawn line there is no need to calculate more values than necessary (eg, having x "carrier", x+0.1, x+0.2 etc...) The document seems to be this PDF, where you can see that the continuous line, is not always in the center of the pixels it crosses. Thanks to that algorithm, a dot will have an immediate neighbor, either at x+1 or y+1 depending on the slope (the interpolated coordinate could be twice (or more) in a row the same rounded value. Eg if y is interp

Categories : Algorithm



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