Search Results

Search found 4755 results on 191 pages for 'scripting dictionary'.

Page 19/191 | < Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >

  • How do I sum values from two dictionaries in C#?

    - by George Stocker
    I have two dictionaries with the same structure: Dictionary<string, int> foo = new Dictionary<string, int>() { {"Table", 5 }, {"Chair", 3 }, {"Couch", 1 } }; Dictionary<string, int> bar = new Dictionary<string, int>() { {"Table", 4 }, {"Chair", 7 }, {"Couch", 8 } }; I'd like to sum the values of the dictionaries together and return a third dictionaries with the keys, and the total values for each key: Table, 9 Chair, 10 Couch, 9 My current solution is to loop through the dictionary and pull them out that way, but I know that solution isn't the most performant or most readable. However, I'm hitting a brick wall trying to come up with a solution in LINQ.

    Read the article

  • How can I make this Dictionary TryGetValue code more readable?

    - by mafutrct
    I'd like to test if an id was not yet known or, if it is known, if the associated value has changed. I'm currently using code similar to this, but it is hard to understand for those not familiar with the pattern. Can you think of a way to make it more readable while keeping it short in LOC? string id; string actual; string stored; if (!someDictionary.TryGetValue (id, out stored) || stored != actual) { // id not known yet or associated value changed. }

    Read the article

  • Dictionary/Hashmap......... what on earth is happening?

    - by Tom
    else if (!registryData.ContainsKey(kyInvolved)) { keyInvolved = new RegistryKy(kyInvolved); lock (registryDataLock) { registryData.Add(kyInvolved, keyInvolved); } processInvolved = new Proces(procInvolved); keyInvolved.addProcessToDict(processInvolved); } kyInvolved is a String which represents a registry key. keyInvolved is the actual registry key object. I'm being told that im adding a key which already exists, yet i have already checked to see whether it is in there or not???

    Read the article

  • smarter "reverse" of a dictionary in python (acc for some of values being the same)?

    - by mrkafk
    def revert_dict(d): rd = {} for key in d: val = d[key] if val in rd: rd[val].append(key) else: rd[val] = [key] return rd >>> revert_dict({'srvc3': '1', 'srvc2': '1', 'srvc1': '2'}) {'1': ['srvc3', 'srvc2'], '2': ['srvc1']} This obviously isn't simple exchange of keys with values: this would overwrite some values (as new keys) which is NOT what I'm after. If 2 or more values are the same for different keys, keys are supposed to be grouped in a list. The above function works, but I wonder if there is a smarter / faster way?

    Read the article

  • Generating a .CSV with Several Columns - Use a Dictionary?

    - by Qanthelas
    I am writing a script that looks through my inventory, compares it with a master list of all possible inventory items, and tells me what items I am missing. My goal is a .csv file where the first column contains a unique key integer and then the remaining several columns would have data related to that key. For example, a three row snippet of my end-goal .csv file might look like this: 100001,apple,fruit,medium,12,red 100002,carrot,vegetable,medium,10,orange 100005,radish,vegetable,small,10,red The data for this is being drawn from a couple sources. 1st, a query to an API server gives me a list of keys for items that are in inventory. 2nd, I read in a .csv file into a dict that matches keys with item name for all possible keys. A snippet of the first 5 rows of this .csv file might look like this: 100001,apple 100002,carrot 100003,pear 100004,banana 100005,radish Note how any key in my list of inventory will be found in this two column .csv file that gives all keys and their corresponding item name and this list minus my inventory on hand yields what I'm looking for (which is the inventory I need to get). So far I can get a .csv file that contains just the keys and item names for the items that I don't have in inventory. Give a list of inventory on hand like this: 100003,100004 A snippet of my resulting .csv file looks like this: 100001,apple 100002,carrot 100005,radish This means that I have pear and banana in inventory (so they are not in this .csv file.) To get this I have a function to get an item name when given an item id that looks like this: def getNames(id_to_name, ids): return [id_to_name[id] for id in ids] Then a function which gives a list of keys as integers from my inventory server API call that returns a list and I've run this function like this: invlist = ServerApiCallFunction(AppropriateInfo) A third function takes this invlist as its input and returns a dict of keys (the item id) and names for the items I don't have. It also writes the information of this dict to a .csv file. I am using the set1 - set2 method to do this. It looks like this: def InventoryNumbers(inventory): with open(csvfile,'w') as c: c.write('InvName' + ',InvID' + '\n') missinginvnames = [] with open("KeyAndItemNameTwoColumns.csv","rb") as fp: reader = csv.reader(fp, skipinitialspace=True) fp.readline() # skip header invidsandnames = {int(id): str.upper(name) for id, name in reader} invids = set(invidsandnames.keys()) invnames = set(invidsandnames.values()) invonhandset = set(inventory) missinginvidsset = invids - invonhandset missinginvids = list(missinginvidsset) missinginvnames = getNames(invidsandnames, missinginvids) missinginvnameswithids = dict(zip(missinginvnames, missinginvids)) print missinginvnameswithids with open(csvfile,'a') as c: for invname, invid in missinginvnameswithids.iteritems(): c.write(invname + ',' + str(invid) + '\n') return missinginvnameswithids Which I then call like this: InventoryNumbers(invlist) With that explanation, now on to my question here. I want to expand the data in this output .csv file by adding in additional columns. The data for this would be drawn from another .csv file, a snippet of which would look like this: 100001,fruit,medium,12,red 100002,vegetable,medium,10,orange 100003,fruit,medium,14,green 100004,fruit,medium,12,yellow 100005,vegetable,small,10,red Note how this does not contain the item name (so I have to pull that from a different .csv file that just has the two columns of key and item name) but it does use the same keys. I am looking for a way to bring in this extra information so that my final .csv file will not just tell me the keys (which are item ids) and item names for the items I don't have in stock but it will also have columns for type, size, number, and color. One option I've looked at is the defaultdict piece from collections, but I'm not sure if this is the best way to go about what I want to do. If I did use this method I'm not sure exactly how I'd call it to achieve my desired result. If some other method would be easier I'm certainly willing to try that, too. How can I take my dict of keys and corresponding item names for items that I don't have in inventory and add to it this extra information in such a way that I could output it all to a .csv file? EDIT: As I typed this up it occurred to me that I might make things easier on myself by creating a new single .csv file that would have date in the form key,item name,type,size,number,color (basically just copying in the column for item name into the .csv that already has the other information for each key.) This way I would only need to draw from one .csv file rather than from two. Even if I did this, though, how would I go about making my desired .csv file based on only those keys for items not in inventory?

    Read the article

  • C# 4: The Curious ConcurrentDictionary

    - by James Michael Hare
    In my previous post (here) I did a comparison of the new ConcurrentQueue versus the old standard of a System.Collections.Generic Queue with simple locking.  The results were exactly what I would have hoped, that the ConcurrentQueue was faster with multi-threading for most all situations.  In addition, concurrent collections have the added benefit that you can enumerate them even if they're being modified. So I set out to see what the improvements would be for the ConcurrentDictionary, would it have the same performance benefits as the ConcurrentQueue did?  Well, after running some tests and multiple tweaks and tunes, I have good and bad news. But first, let's look at the tests.  Obviously there's many things we can do with a dictionary.  One of the most notable uses, of course, in a multi-threaded environment is for a small, local in-memory cache.  So I set about to do a very simple simulation of a cache where I would create a test class that I'll just call an Accessor.  This accessor will attempt to look up a key in the dictionary, and if the key exists, it stops (i.e. a cache "hit").  However, if the lookup fails, it will then try to add the key and value to the dictionary (i.e. a cache "miss").  So here's the Accessor that will run the tests: 1: internal class Accessor 2: { 3: public int Hits { get; set; } 4: public int Misses { get; set; } 5: public Func<int, string> GetDelegate { get; set; } 6: public Action<int, string> AddDelegate { get; set; } 7: public int Iterations { get; set; } 8: public int MaxRange { get; set; } 9: public int Seed { get; set; } 10:  11: public void Access() 12: { 13: var randomGenerator = new Random(Seed); 14:  15: for (int i=0; i<Iterations; i++) 16: { 17: // give a wide spread so will have some duplicates and some unique 18: var target = randomGenerator.Next(1, MaxRange); 19:  20: // attempt to grab the item from the cache 21: var result = GetDelegate(target); 22:  23: // if the item doesn't exist, add it 24: if(result == null) 25: { 26: AddDelegate(target, target.ToString()); 27: Misses++; 28: } 29: else 30: { 31: Hits++; 32: } 33: } 34: } 35: } Note that so I could test different implementations, I defined a GetDelegate and AddDelegate that will call the appropriate dictionary methods to add or retrieve items in the cache using various techniques. So let's examine the three techniques I decided to test: Dictionary with mutex - Just your standard generic Dictionary with a simple lock construct on an internal object. Dictionary with ReaderWriterLockSlim - Same Dictionary, but now using a lock designed to let multiple readers access simultaneously and then locked when a writer needs access. ConcurrentDictionary - The new ConcurrentDictionary from System.Collections.Concurrent that is supposed to be optimized to allow multiple threads to access safely. So the approach to each of these is also fairly straight-forward.  Let's look at the GetDelegate and AddDelegate implementations for the Dictionary with mutex lock: 1: var addDelegate = (key,val) => 2: { 3: lock (_mutex) 4: { 5: _dictionary[key] = val; 6: } 7: }; 8: var getDelegate = (key) => 9: { 10: lock (_mutex) 11: { 12: string val; 13: return _dictionary.TryGetValue(key, out val) ? val : null; 14: } 15: }; Nothing new or fancy here, just your basic lock on a private object and then query/insert into the Dictionary. Now, for the Dictionary with ReadWriteLockSlim it's a little more complex: 1: var addDelegate = (key,val) => 2: { 3: _readerWriterLock.EnterWriteLock(); 4: _dictionary[key] = val; 5: _readerWriterLock.ExitWriteLock(); 6: }; 7: var getDelegate = (key) => 8: { 9: string val; 10: _readerWriterLock.EnterReadLock(); 11: if(!_dictionary.TryGetValue(key, out val)) 12: { 13: val = null; 14: } 15: _readerWriterLock.ExitReadLock(); 16: return val; 17: }; And finally, the ConcurrentDictionary, which since it does all it's own concurrency control, is remarkably elegant and simple: 1: var addDelegate = (key,val) => 2: { 3: _concurrentDictionary[key] = val; 4: }; 5: var getDelegate = (key) => 6: { 7: string s; 8: return _concurrentDictionary.TryGetValue(key, out s) ? s : null; 9: };                    Then, I set up a test harness that would simply ask the user for the number of concurrent Accessors to attempt to Access the cache (as specified in Accessor.Access() above) and then let them fly and see how long it took them all to complete.  Each of these tests was run with 10,000,000 cache accesses divided among the available Accessor instances.  All times are in milliseconds. 1: Dictionary with Mutex Locking 2: --------------------------------------------------- 3: Accessors Mostly Misses Mostly Hits 4: 1 7916 3285 5: 10 8293 3481 6: 100 8799 3532 7: 1000 8815 3584 8:  9:  10: Dictionary with ReaderWriterLockSlim Locking 11: --------------------------------------------------- 12: Accessors Mostly Misses Mostly Hits 13: 1 8445 3624 14: 10 11002 4119 15: 100 11076 3992 16: 1000 14794 4861 17:  18:  19: Concurrent Dictionary 20: --------------------------------------------------- 21: Accessors Mostly Misses Mostly Hits 22: 1 17443 3726 23: 10 14181 1897 24: 100 15141 1994 25: 1000 17209 2128 The first test I did across the board is the Mostly Misses category.  The mostly misses (more adds because data requested was not in the dictionary) shows an interesting trend.  In both cases the Dictionary with the simple mutex lock is much faster, and the ConcurrentDictionary is the slowest solution.  But this got me thinking, and a little research seemed to confirm it, maybe the ConcurrentDictionary is more optimized to concurrent "gets" than "adds".  So since the ratio of misses to hits were 2 to 1, I decided to reverse that and see the results. So I tweaked the data so that the number of keys were much smaller than the number of iterations to give me about a 2 to 1 ration of hits to misses (twice as likely to already find the item in the cache than to need to add it).  And yes, indeed here we see that the ConcurrentDictionary is indeed faster than the standard Dictionary here.  I have a strong feeling that as the ration of hits-to-misses gets higher and higher these number gets even better as well.  This makes sense since the ConcurrentDictionary is read-optimized. Also note that I tried the tests with capacity and concurrency hints on the ConcurrentDictionary but saw very little improvement, I think this is largely because on the 10,000,000 hit test it quickly ramped up to the correct capacity and concurrency and thus the impact was limited to the first few milliseconds of the run. So what does this tell us?  Well, as in all things, ConcurrentDictionary is not a panacea.  It won't solve all your woes and it shouldn't be the only Dictionary you ever use.  So when should we use each? Use System.Collections.Generic.Dictionary when: You need a single-threaded Dictionary (no locking needed). You need a multi-threaded Dictionary that is loaded only once at creation and never modified (no locking needed). You need a multi-threaded Dictionary to store items where writes are far more prevalent than reads (locking needed). And use System.Collections.Concurrent.ConcurrentDictionary when: You need a multi-threaded Dictionary where the writes are far more prevalent than reads. You need to be able to iterate over the collection without locking it even if its being modified. Both Dictionaries have their strong suits, I have a feeling this is just one where you need to know from design what you hope to use it for and make your decision based on that criteria.

    Read the article

  • Loading data from a dictionary of dictionaries into an array in Objective C for an iphone app

    - by Kat
    I have a UINavigationController consisting of a tableview I want to load some data into. I have a dictionary plist containing Dictionaries for each Train Line which in turn have dictionaries for each station with the relevant information along with one string lineName. I need to collect the station Names keys and add them to an array to populate my table (This is working). The line names are stored as a string in my lines dictionary with the key being "lineName" Root->| | |->TrainLine1(Dictionary)->| | |-> lineName (String) | |-> Station1 (Dictionary) | |-> Station2 (Dictionary) | | |->TrainLine2(Dictionary)->| | |-> lineName (String) | |-> Station1 (Dictionary) | |-> Station2 (Dictionary) Am I going about this the wrong way? Should I reorganise my plist? The code below crashes the app. - (void)viewDidLoad { self.title = @"Train Lines"; NSString *path = [[NSBundle mainBundle] pathForResource:@"lineDetails" ofType:@"plist"]; NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:path]; NSMutableArray *array = [[NSMutableArray alloc] init]; NSMutableArray *lineNameArray = [[NSMutableArray alloc] init]; NSString *key; for (key in dictionary) { NSMutableDictionary *secondDictionary = [NSDictionary dictionaryWithDictionary:[dictionary valueForKey:key]]; [lineNameArray addObject:key]; NSLog(@"Adding this in array:%@", key); [array addObject:[secondDictionary objectForKey:kLineNameKey]]; } self.trainLines = array; self.trainLineKeys = lineNameArray; NSLog(@"Array contents:%@", self.trainLineKeys); [lineNameArray release]; [array release]; [dictionary release]; [super viewDidLoad]; }

    Read the article

  • Remove English - United States language from Firefox

    - by Paul
    How do I remove the English (United States) dictionary from Firefox? It's not an add-on so I'm guessing it's built into Firefox by default. Maybe that makes it unremovable? I noticed whilst typing a Hotmail email in Firefox that the default language seems to be English/United States. As I am from the UK I thought I would add in the English/United Kingdom dictionary, which I have. This is now the default language and I don't need the US dictionary. Firefox 3.6.2 on Windows 7 Home Premium 32 bit.

    Read the article

  • Take all fields in a database table and put them straight into a text file

    - by DalexL
    I have an database file (mdb) file that contains a dictionary of words. A couple thousand of them. I just need the words (in the order they are already in) put into a text file. Currently they have ID's associated with them (e.g. 1, 2, 3) but I don't need it. I just need the words. What is the best way to do this? Actually, if somebody is able to find a dictionary of English words (something along the lines of a scrabble dictionary) that is free online, I'll accept that too. I just can't seem to find any good ones online.

    Read the article

  • When to use Bash, when Python/Perl/Ruby? [closed]

    - by futlib
    What's your rationale for when to write a Bash script and when to use a more powerful scripting language (Python, Perl, Ruby, ...)? I'm finding that very simple scripts are nicer with Bash, but many of those get quite fancy over time, and it never seems like a good idea to rewrite the whole thing. That's why I'm leaning towards always using Python for all scripting. But since Bash seems to be the the lingua franca of Linux scripting, is that something a responsible system administrator would do?

    Read the article

  • What should the name of this class be?

    - by Tim Murphy
    Naming classes is sometimes hard. What do you think name of the class should be? I originally created the class to use as a cache but can see its may have other uses. Example code to use the class. Dim cache = New NamePendingDictionary(Of String, Sample) Dim value = cache("a", Function() New Sample()) And here is the class that needs a name. ''' <summary> ''' Enhancement of <see cref="System.Collections.Generic.Dictionary"/>. See the Item property ''' for more details. ''' </summary> ''' <typeparam name="TKey">The type of the keys in the dictionary.</typeparam> ''' <typeparam name="TValue">The type of the values in the dictionary.</typeparam> Public Class NamePendingDictionary(Of TKey, TValue) Inherits Dictionary(Of TKey, TValue) Delegate Function DefaultValue() As TValue ''' <summary> ''' Gets or sets the value associated with the specified key. If the specified key does not exist ''' then <paramref name="createDefaultValue"/> is invoked and added to the dictionary. The created ''' value is then returned. ''' </summary> ''' <param name="key">The key of the value to get.</param> ''' <param name="createDefaultValue"> ''' The delegate to invoke if <paramref name="key"/> does not exist in the dictionary. ''' </param> ''' <exception cref="T:System.ArgumentNullException"><paramref name="key" /> is null.</exception> Default Public Overloads ReadOnly Property Item(ByVal key As TKey, ByVal createDefaultValue As DefaultValue) As TValue Get Dim value As TValue If createDefaultValue Is Nothing Then Throw New ArgumentNullException("createValue") End If If Not Me.TryGetValue(key, value) Then value = createDefaultValue.Invoke() Me.Add(key, value) End If Return value End Get End Property End Class

    Read the article

  • Ruby vs Lua as scripting language for C++

    - by bl00dshooter
    I am currently building a game server (not an engine), and I want it to be extendable, like a plugin system. The solution I found is to use a scripting language. So far, so good. I'm not sure if I should use Ruby or Lua. Lua is easier to embed, but Ruby has a larger library, and better syntax (in my opinion). The problem is, there is no easy way I found to use Ruby as scripting language with C++, whereas it's very easy with Lua. Toughs about this? Suggestions for using Ruby as scripting language (I tried SWIG, but it isn't nearly as neat as using Lua)? Thanks.

    Read the article

  • (PHP vs Python vs Perl) vs Ruby [closed]

    - by Dr.Kameleon
    OK, here's what : I've programmed in over 20 different languages and now, because of a large project I'm currently working on for Mac OS X (in Objective-C/Cocoa), I need to make a final decision on which language to use for my background scripting + plugin functionality. Definitely, one factor that'll ultimately influence my decision is which one I'm most familiar with, which is PHP (one of the ugliest languages around, which I however adore... lol), then Python / Perl (the "proven values"... )... and then Ruby (which, to me, is almost confusing and I've only played with it for some time.) Now, here's my considerations : (As previously mentioned) Being familiar with it (anyway, if X is better in my case, I really don't mind studying it from scratch...) Speed Good interaction with the Shell + ease of integration with my Cocoa application Btw, some of the reasons that made me wonder if Ruby would be a good choice is : The hype around it (although, I still don't get why; but that's probably just me...) My major competitor (we're actually talking about the same type of software here) is using Ruby for its backend scripting almost exclusively (ok, along with some BASH). Isn't Ruby considered slower e.g. than Perl? Why did he choose that? Simply, a matter of personal taste? So... your thoughts?

    Read the article

  • How to present a stable data model in a public API that allows internal data structures to be changed without breaking the public view of the data?

    - by Max Palmer
    I am in the process of developing an application that allows users to write C# scripts. These scripts allow users to call selected methods and to access and manipulate data in a document. This works well, however, in the development version, scripts access the document's (internal) data structures directly. This means that if we were to change the internal data model/structure, there is a good chance that someone's script will no longer compile. We obviously want to prevent this breaking change from happening, but still want to allow the user to write sensible C# code (whilst not restricting how we develop our internal data model as a result). We therefore need to decouple our scripting API and its data structures from our internal methods and data structures. We've a few ideas as to how we might allow the user to access a what is effectively a stable public version of the document's internal data*, but I wanted to throw the question out there to someone who might have some real experience of this problem. NB our internal document's data structure is quite complex and it could be quite difficult to wrap. We know we want to expose as little as possible in our public API, especially as once it's out there, it's out there for good. Can anyone help? How do scripting languages / APIs decouple their public API and data structures from their internal data structures? Is there no real alternative to having to write a complex interaction layer? If we need to do this, what's a good approach or pattern for wrapping complex data structures that include nested objects, including collections? I've looked at the API facade pattern, which looks like it's trying to address these kinds of issues, but are there alternatives? *One idea is to build a data facade that is kept stable across versions of our application. The facade exposes a set of facade data objects that are used in the script code. These maintain backwards compatibility and wrap access to our internal document's data model.

    Read the article

  • Oiling the gears for the data dictionary

    Documenting the database is always a challenge, and there are many techniques you can use to help all the people on your team understand what all your tables are used for. David Poole brings us an easy way to implement a framework for documentation. The Future of SQL Server Monitoring "Being web-based, SQL Monitor 2.0 enables you to check on your servers from almost any location" Jonathan Allen.Try SQL Monitor now.

    Read the article

  • Problem with bash scripting

    - by eple
    Hi. I terrible with bash scripting, and need some help with the following: #!/bin/bash if [ -e Pretty* ];then ncftpput -R -DD -v -u xbmc -p xbmc 192.168.1.100 /home/xbmc/TV/Pretty_Little_Liars/ Pretty* else echo "No new folders" fi find -depth -type d -empty -exec rmdir {} \; Problem here is the ncftpput line.. if I just do a simple [ echo "working" ] instead, everything is OK, but when I try the ncftpput-line it just gives me [ line 5: [: too many arguments ] the ncftpput command alone works fine.. Any ideas?

    Read the article

  • LibreOffice english spelling dictionary missing

    - by rossouwap
    I've got two machines, same OS (Ubuntu 11.10 x86_64), same LibreOffice ppa's (ppa:libreoffice/ppa). One has the "English spelling dictionaries, hyphenation rules, thesaurus..." extension in the extension manager, the other doesn't. Each upgraded using the ppa from 3.5.0 to 3.5.1. Can anyone provide some insight as to how to get this extension onto the second machine? I can remove LibreOffice from the second machine and install the packages from the LibreOffice site, but would prefer to keep the ppa - as I don't then need to remember to upgrade.

    Read the article

  • SEO For A Doman Name That Is A Dictionary Work Misspell [closed]

    - by Miles
    Possible Duplicate: How should I handle search engines auto-correcting the spelling of a site's name? My domain name is radiuus.com. Since the correct spelling of the word is with one u, when I search for "radiuus" on google it thinks I'm misspelling the word, kindly lets me know, and returns results for "radius". Example: https://www.google.com/search?q=radiuus&oq=radiuus&sugexp=chrome,mod=2&sourceid=chrome&ie=UTF-8 What can I do to prevent this? And taking this one step further: what can I do to get my site to show up when someone searches for "radius" spelled the correct way? Thanks!!

    Read the article

  • Dealing with Word spell check in technical documents?

    - by Robert MacLean
    I have waste millions of hours clicking the Ignore Once button in Word, while trying to spell check a document related to development. Be that something light on terms like a proposal or something worse like technical specs. I'm beginning to think that this is a huge waste and someone may have developed a dictionary for Word with common development terms that I could add and no longer have this problem. Does such a dictionary exist or is there some other tricks to use to improve this process?

    Read the article

< Previous Page | 15 16 17 18 19 20 21 22 23 24 25 26  | Next Page >