Search Results

Search found 3659 results on 147 pages for 'sorted hash'.

Page 12/147 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • Properly maintain sorted state of Array/Set

    - by Jeff
    I'm trying to get data out of my MOC and then create some new objects based on those objects, and put it all back together, while keeping my sort state. The securities come out of the MOC in proper order. And everything seems to be fine until I do the assignment to the game at the bottom from setWithArray. The documentation says that setWithArray removed the duplicate objects, if there are any. I'm wonder if that's messing up my data, but I don't see a good alternative. The data is ultimately being pulled out into a UITableView. When I add items to the game manually, then they stay sorted, so I don't think the breaking of the sort is beyond the scope of what I've included here. NSError *error; NSArray *allTheSecurities = [managedObjectContext executeFetchRequest:request error:&error]; if (allTheSecurities == nil) { // Handle the error. } [request release]; /**/ NSLog( @"Enumerate..." ); NSEnumerator *enumerator = [allTheSecurities objectEnumerator]; id anObject; NSMutableArray *portfolioStocks = [[NSMutableArray alloc] init]; while (anObject = [enumerator nextObject]) { NSLog( @"Iteration... %@", [anObject name] ); NSLog( @"Build a stock..." ); PortfolioStocks *this_stock = (PortfolioStocks *)[NSEntityDescription insertNewObjectForEntityForName:@"PortfolioStocks" inManagedObjectContext:context]; NSLog( @"Set a value..." ); [this_stock setSecurity:(Security *)anObject]; [this_stock setQuantity:[NSNumber numberWithInt:0]]; NSLog( @"Add to portfolioStocks..." ); [portfolioStocks addObject:this_stock]; } //Sorted properly up to here! NSLog( @"Add to portfolio..." ); [game setPortfolio:[NSSet setWithArray:portfolioStocks]]; // <-- This is where it's not sorted anymore.

    Read the article

  • The algorithm used to generate recommendations in Google News?

    - by Siddhant
    Hi everyone. I'm study recommendation engines, and I went through the paper that defines how Google News generates recommendations to users for news items which might be of their interest, based on collaborative filtering. One interesting technique that they mention is Minhashing. I went through what it does, but I'm pretty sure that what I have is a fuzzy idea and there is a strong chance that I'm wrong. The following is what I could make out of it :- Collect a set of all news items. Define a hash function for a user. This hash function returns the index of the first item from the news items which this user viewed, in the list of all news items. Collect, say "n" number of such values, and represent a user with this list of values. Based on the similarity count between these lists, we can calculate the similarity between users as the number of common items. This reduces the number of comparisons a lot. Based on these similarity measures, group users into different clusters. This is just what I think it might be. In Step 2, instead of defining a constant hash function, it might be possible that we vary the hash function in a way that it returns the index of a different element. So one hash function could return the index of the first element from the user's list, another hash function could return the index of the second element from the user's list, and so on. So the nature of the hash function satisfying the minwise independent permutations condition, this does sound like a possible approach. Could anyone please confirm if what I think is correct? Or the minhashing portion of Google News Recommendations, functions in some other way? I'm new to internal implementations of recommendations. Any help is appreciated a lot. Thanks!

    Read the article

  • Tool to compute SHA256 Tree Hash

    - by Benjamin
    I've started using AWS Glacier, and noticed that it hashes the files using an algorithm called SHA-256 Tree Hash. To my surprise, this algorithm is different from SHA-256, so I can't use the tools I'm used to, to compare hashes and verify file integrity. Do you know a Windows tool, if possible integrated in the context menu, to compute the SHA-256 Tree Hash of a file? I'd also accept a Linux command-line tool, as a second choice :-)

    Read the article

  • Algorithm for converting hierarchical flat data (w/ ParentID) into sorted flat list w/ indentation l

    - by eagle
    I have the following structure: MyClass { guid ID guid ParentID string Name } I'd like to create an array which contains the elements in the order they should be displayed in a hierarchy (e.g. according to their "left" values), as well as a hash which maps the guid to the indentation level. For example: ID Name ParentID ------------------------ 1 Cats 2 2 Animal NULL 3 Tiger 1 4 Book NULL 5 Airplane NULL This would essentially produce the following objects: // Array is an array of all the elements sorted by the way you would see them in a fully expanded tree Array[0] = "Airplane" Array[1] = "Animal" Array[2] = "Cats" Array[3] = "Tiger" Array[4] = "Book" // IndentationLevel is a hash of GUIDs to IndentationLevels. IndentationLevel["1"] = 1 IndentationLevel["2"] = 0 IndentationLevel["3"] = 2 IndentationLevel["4"] = 0 IndentationLevel["5"] = 0 For clarity, this is what the hierarchy looks like: Airplane Animal Cats Tiger Book I'd like to iterate through the items the least amount of times possible. I also don't want to create a hierarchical data structure. I'd prefer to use arrays, hashes, stacks, or queues. The two objectives are: Store a hash of the ID to the indentation level. Sort the list that holds all the objects according to their left values. When I get the list of elements, they are in no particular order. Siblings should be ordered by their Name property. Update: This may seem like I haven't tried coming up with a solution myself and simply want others to do the work for me. However, I have tried coming up with three different solutions, and I've gotten stuck on each. One reason might be that I've tried to avoid recursion (maybe wrongly so). I'm not posting the partial solutions I have so far since they are incorrect and may badly influence the solutions of others.

    Read the article

  • MySQL Hashing Function Implementation

    - by Jonas Stevens
    I know that php has md5(), sha1(), and the hash() functions, but I want to create a hash using the MySQL PASSWORD() function. So far, the only way I can think of is to just query the server, but I want a function (preferably in php or Perl) that will do the same thing without querying MySQL at all. For example: MySQL hash - 464bb2cb3cf18b66 MySQL5 hash - *01D01F5CA7CA8BA771E03F4AC55EC73C11EFA229 Thanks!

    Read the article

  • hashing password giving different results

    - by geoff
    I am taking over a system that a previous developer wrote. The system has an administrator approve a user account and when they do that the system uses the following method to hash a password and save it to the database. It sends the unhashed password to the user. When the user logs in the system uses the exact same method to hash what the user enters and compares it to the database value. We've run into a couple of times when the database entry doesn't match the user's entry whey they should. So it appears that the method isn't always hashing the value the same. Does anyone know if this method of hashing isn't reliable and how to make it reliable? Thanks. private string HashPassword(string password) { string hashedPassword = string.Empty; // Convert plain text into a byte array. byte[] plainTextBytes = Encoding.UTF8.GetBytes(password); // Allocate array, which will hold plain text and salt. byte[] plainTextWithSaltBytes = new byte[plainTextBytes.Length + SALT.Length]; // Copy plain text bytes into resulting array. for(int i = 0; i < plainTextBytes.Length; i++) plainTextWithSaltBytes[i] = plainTextBytes[i]; // Append salt bytes to the resulting array. for(int i = 0; i < SALT.Length; i++) plainTextWithSaltBytes[plainTextBytes.Length + i] = SALT[i]; // Because we support multiple hashing algorithms, we must define // hash object as a common (abstract) base class. We will specify the // actual hashing algorithm class later during object creation. HashAlgorithm hash = new SHA256Managed(); // Compute hash value of our plain text with appended salt. byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes); // Create array which will hold hash and original salt bytes. byte[] hashWithSaltBytes = new byte[hashBytes.Length + SALT.Length]; // Copy hash bytes into resulting array. for(int i = 0; i < hashBytes.Length; i++) hashWithSaltBytes[i] = hashBytes[i]; // Append salt bytes to the result. for(int i = 0; i < SALT.Length; i++) hashWithSaltBytes[hashBytes.Length + i] = SALT[i]; // Convert result into a base64-encoded string. hashedPassword = Convert.ToBase64String(hashWithSaltBytes); return hashedPassword; }

    Read the article

  • Are fragments of hashes collision-resistent?

    - by Mark
    Let me see if someone would mind clearing up this elementary point about md5 and hashing. If you only use the first 4 bytes of an md5 hash, would that mean theoretically only 1 in 255^4 chance of collision. iow is that the intention with it (and other hash algorithms) - that you only have to use a small portion of the returned hash (say the hash is of a file of some size).

    Read the article

  • Optimizing hash lookup & memory performance in Go

    - by Moishe
    As an exercise, I'm implementing HashLife in Go. In brief, HashLife works by memoizing nodes in a quadtree so that once a given node's value in the future has been calculated, it can just be looked up instead of being re-calculated. So eg. if you have a node at the 8x8 level, you remember it by its four children (each at the 2x2 level). So next time you see an 8x8 node, when you calculate the next generation, you first check if you've already seen a node with those same four children. This is extended up through all levels of the quadtree, which gives you some pretty amazing optimizations if eg. you're 10 levels above the leaves. Unsurprisingly, it looks like the perfmance crux of this is the lookup of nodes by child-node values. Currently I have a hashmap of {&upper_left_node,&upper_right_node,&lower_left_node,&lower_right_node} -> node So my lookup function is this: func FindNode(ul, ur, ll, lr *Node) *Node { var node *Node var ok bool nc := NodeChildren{ul, ur, ll, lr} node, ok = NodeMap[nc] if ok { return node } node = &Node{ul, ur, ll, lr, 0, ul.Level + 1, nil} NodeMap[nc] = node return node } What I'm trying to figure out is if the "nc := NodeChildren..." line causes a memory allocation each time the function is called. If it does, can I/should I move the declaration to the global scope and just modify the values each time this function is called? Or is there a more efficient way to do this? Any advice/feedback would be welcome. (even coding style nits; this is literally the first thing I've written in Go so I'd love any feedback)

    Read the article

  • Version hash to solve Event Sourcing problems

    - by SystematicFrank
    The basic examples I have seen about Event Sourcing do not deal with out of order events, clock offsets in different systems and late events from system partitions. I am wondering if more polished Event Sourcing implementations rely on a version stamp of modified objects? For example, assuming that the system is rendering the entity Client with version id ABCD1234. If the user modifies the entity, the system will create an event with the modified fields AND the version id reference to which version it applies. Later the event responder would detect out of order events and merge them.

    Read the article

  • How to randomize a sorted list?

    - by Faken
    Here's a strange question for you guys, I have a nice sorted list that I wish to randomize. How would i go about doing that? In my application, i have a function that returns a list of points that describe the outline of a discretized object. Due to the way the problem is solved, the function returns a nice ordered list. i have a second boundary described in math and want to determine if the two objects intersect each other. I simply itterate over the points and determine if any one point is inside the mathematical boundary. The method works well but i want to increase speed by randomizing the point data. Since it is likely that that my mathematical boundary will be overlapped by a series of points that are right beside each other, i think it would make sense to check a randomized list rather than iterating over a nice sorted one (as it only takes a single hit to declare an intersection). So, any ideas on how i would go about randomizing an ordered list?

    Read the article

  • Best data-structure to use for two ended sorted list

    - by fmark
    I need a collection data-structure that can do the following: Be sorted Allow me to quickly pop values off the front and back of the list Remain sorted after I insert a new value Allow a user-specified comparison function, as I will be storing tuples and want to sort on a particular value Thread-safety is not required Optionally allow efficient haskey() lookups (I'm happy to maintain a separate hash-table for this though) My thoughts at this stage are that I need a priority queue and a hash table, although I don't know if I can quickly pop values off both ends of a priority queue. I'm interested in performance for a moderate number of items (I would estimate less than 200,000). Another possibility is simply maintaining an OrderedDictionary and doing an insertion sort it every-time I add more data to it. Furthermore, are there any particular implementations in Python. I would really like to avoid writing this code myself.

    Read the article

  • Seaching for an element in a circular sorted array

    - by guirgis
    I wanted to share this with you, i had this problem in a google interview. we want to search for a given element in a circular sorted array in complexity not greater than O(Log n). ex: search for 13 in {5,9,13,1,3}. My idea was to convert the circular array into a regular sorted array then do a binary search on the resulting array, but my problem was the algorithm i came up was stupid that it takes O(n) in the worst case: for(i = 1; i < a.length; i++){ if (a[i] < a[i-1]){ minIndex = i; break; } } then the corresponding index of ith element will be determined from the following relation: (i + minInex - 1) % a.length it is clear that my conversion (from circular to regular) algorithm may take O(n), so we need a better one, any suggestions?

    Read the article

  • Find next lower item in a sorted list

    - by Sebastian
    Hey guys, let's say I have a sorted list of Floats. Now I'd like to get the index of the next lower item of a given value. The usual for-loop aprroach has a complexity of O(n). Since the list is sorted there must be a way to get the index with O(log n). My O(n) approach: index=0 for i,value in enumerate(mylist): if value>compareValue: index=i-1 Is there a datatype for solving that problem in O(log n)? best regards Sebastian

    Read the article

  • How to fetch managed objects sorted by calculated value

    - by Marcin Zbijowski
    Hello, I'm working on the app that uses CoreData. There is location entity that holds latitude and longitude values. I'd like to fetch those entities sorted by distance to the user's location. I tried to set sort descriptor to distance formula sqrt ((x1 - x2)^2 + (y1 - y2)^2) but it fails with exception "... keypath ... not found in entity". NSString *distanceFormula = [NSString stringWithFormat:@"sqrt(((latitude - %f) * (latitude - %f)) + ((longitude - %f) * (longitude - %f)))", location.coordinate.latitude, location.coordinate.latitude, location.coordinate.longitude, location.coordinate.longitude]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:distanceFormula ascending:YES]; [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]]; NSError *error; NSArray *result = [[self managedObjectContext] executeFetchRequest:fetchRequest error:&error]; I'd like to fetch already sorted objects rather then fetch them all and then sort in the code. Any tips appreciated.

    Read the article

  • Inserting a number into a sorted array!

    - by Jay
    I would like to write a piece of code for inserting a number into a sorted array at the appropriate position (i.e. the array should still remain sorted after insertion) My data structure doesn't allow duplicates. I am planning to do something like this: 1. Find the right index where I should be putting this element using binary search 2. Create space for this element, by moving all the elements from that index down. 3. Put this element there. Is there any other better way?

    Read the article

  • MySQL Unique hash insertion

    - by Jesse
    So, imagine a mysql table with a few simple columns, an auto increment, and a hash (varchar, UNIQUE). Is it possible to give mysql a query that will add a column, and generate a unique hash without multiple queries? Currently, the only way I can think of to achieve this is with a while, which I worry would become more and more processor intensive the more entries were in the db. Here's some pseudo-php, obviously untested, but gets the general idea across: while(!query("INSERT INTO table (hash) VALUES (".generate_hash().");")){ //found conflict, try again. } In the above example, the hash column would be UNIQUE, and so the query would fail. The problem is, say there's 500,000 entries in the db and I'm working off of a base36 hash generator, with 4 characters. The likelyhood of a conflict would be almost 1 in 3, and I definitely can't be running 160,000 queries. In fact, any more than 5 I would consider unacceptable. So, can I do this with pure SQL? I would need to generate a base62, 6 char string (like: "j8Du7X", chars a-z, A-Z, and 0-9), and either update the last_insert_id with it, or even better, generate it during the insert. I can handle basic CRUD with MySQL, but even JOINs are a little outside of my MySQL comfort zone, so excuse my ignorance if this is cake. Any ideas? I'd prefer to use either pure MySQL or PHP & MySQL, but hell, if another language can get this done cleanly, I'd build a script and AJAX it too. Thanks!

    Read the article

  • Character encoding issues when generating MD5 hash cross-platform

    - by rogueprocess
    This is a general question about character encoding when using MD5 libraries in various languages. My concern is: suppose I generate an MD5 hash using a native Python string object, like this: message = "hello world" m = md5() m.update(message) Then I take a hex version of that MD5 hash using: m.hexdigest() and send the message & MD5 hash via a network, let's say, a JMS message or a HTTP request. Now I get this message in a Java program in the form of a native Java string, along with the checksum. Then I generate an MD5 hash using Java, like this (using the Commons Codec library): String md5 = org.apache.commons.codec.digest.DigestUtils.DigestUtils.md5Hex(s) My feeling is that this is wrong because I have not specified character encodng at either end. So the original hash will be based on the bytes of the Python version of the string; the Java one will be based on the bytes of the Java version of the string , these two byte sequences will often not be the same - is that right? So really I need to specify "UTF-8" or whatever at both ends right? (I am actually getting an intermittent error in my code where the MD5 checksum fails, and I suspect this is the reason - but because it's intermittent, it's difficult to say if changing this fixes it or not. ) Thank you!

    Read the article

  • How to transform phrases and words into MD5 hash?

    - by brilliant
    Can anyone, please, explain to me how to transform a phrase like "I want to buy some milk" into MD5? I read Wikipedia article on MD5, but the explanation given there is beyond my comprehension: "MD5 processes a variable-length message into a fixed-length output of 128 bits. The input message is broken up into chunks of 512-bit blocks (sixteen 32-bit little endian integers)" "sixteen 32-bit little endian integers" is already hard for me. I checked the article on little endians and didn't understand a bit. However, the examples of some phrases and their MD5 hashes are very nice: MD5("The quick brown fox jumps over the lazy dog") = 9e107d9d372bb6826bd81d3542a419d6 MD5("The quick brown fox jumps over the lazy dog.") = e4d909c290d0fb1ca068ffaddf22cbd0 Can anyone, please, explain to me how this MD5 algorithm works on some very simple example? And also, perhaps you know some software or a code that would transform phrases into their MD5. If yes, please, let me know.

    Read the article

  • Hash Map Usage and Idea

    - by Anand
    Hi, I have been working in Java for the last 6 months and have been using Hash Maps What is the basic idea of a Hash Map ? I am using it as it easy for me to store so much data with direct key references rather than having to iterate through an arraylist ? Where is the power of Hash Map seen ? What is the scientific idea behind this data structure ?

    Read the article

  • good __eq__, __lt__, ..., __hash__ methods for image class?

    - by Marten Bauer
    I create the following class: class Image(object): def __init__(self, extension, data, urls=None, user_data=None): self._extension = extension self._data = data self._urls = urls self._user_data = user_data self._hex_digest = hashlib.sha1(self._data).hexDigest() Images should be equal when all values are equal. Therefore I wrote: def __eq__(self, other): if isinstance(other, Image) and self.__dict__ == other.__dict__: return True return False def __ne__(self, other): return not self.__eq__(other) def __lt__(self, other): return self.__dict__ < other.__dict__ ... But how should the __hash__ method look like? Equal Images should return equal hashes... def __hash__(self): # won't work !?! return hash(self.__dict__) Is the way I try to use __eq__, __ne__, __lt__, __hash__, ... recommend?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >