Search Results

Search found 2235 results on 90 pages for 'dictionary'.

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

  • C# Dictionary Performance

    - by derek
    I am using a Dictionary to store data, and will be caching it. I would like to avoid server memory issues, and have good performance by limiting the size of the Dictionary<, either in size or number of entries. What is the best method of doing this? Is there another class I should be considering other than a Dictionary?

    Read the article

  • How to share a dictionary between multiple processes in python without locking

    - by RandomVector
    I need to share a huge dictionary (around 1 gb in size) between multiple processs, however since all processes will always read from it. I dont need locking. Is there any way to share a dictionary without locking? The multiprocessing module in python provides an Array class which allows sharing without locking by setting lock=false however There is no such option for Dictionary provided by manager in multiprocessing module.

    Read the article

  • How to Get Spelling Autocorrect Across All Applications on Your System

    - by Erez Zukerman
    Spelling auto-correction can be a very handy feature, whether it is for tricky words (“emmitted” vs. “emitted”), typical typos (“desing” vs. “design”) or other common errors. Microsoft Word has it, but why not implement it across your system using a free, customizable and easy-to-use AutoHotkey script? Read on to see how. The script we’re going to be using goes by the shockingly original name AutoCorrect. For starters, simply click the link and save it somewhere handy. It’s a vintage script, last updated on 2007, but it still works very well – we’ve been using it daily for months. Latest Features How-To Geek ETC How to Get Amazing Color from Photos in Photoshop, GIMP, and Paint.NET Learn To Adjust Contrast Like a Pro in Photoshop, GIMP, and Paint.NET Have You Ever Wondered How Your Operating System Got Its Name? Should You Delete Windows 7 Service Pack Backup Files to Save Space? What Can Super Mario Teach Us About Graphics Technology? Windows 7 Service Pack 1 is Released: But Should You Install It? Peaceful Alpine River on a Sunny Day [Wallpaper] Fast Society Creates Mini and Mobile Temporary Social Networks Page Zipper Unpacks Multi-Page Articles for Single-Page Display Minty Bug: Build an FM Bug Inside a Mint Container Get the MakeUseOf eBook Guide to Hacker Proofing Your PC Sync Your Windows Computer with Your Ubuntu One Account [Desktop Client]

    Read the article

  • Map, Set use cases in a general web app

    - by user2541902
    I am currently working on my own Java web app (to be shown in interview to get a Java job). So I've not worked on Java in professional environment, so no guidance. I have database, entity classes, JPA relationships. Use cases are like, user has albums, album has pics, user has locations, location has co-ordinates etc. I used List (ArrayList) everywhere. I can do anything with List and DB, get some entry, find etc. For example, I will keep the list of users in List, then use queries to get some entry (why would I keep them in Map with id/email as key?). I know very well the working and features, implementing classes of Map, Set. I can use them for solving some algorithm, processing some data etc. In interviews, I get asked have you worked with these, where have you used them etc. So, Please tell me cases where they should be used (DB or any popular real use case).

    Read the article

  • How to install Oxford Advanced Learners' 8 in ubuntu 12.04 LTS 64bit

    - by ioweyou
    I have bought Oxford Advanced Learners' 8 which come along with installation CD. In the cd they have linux installation option. But i can't install that in my ubuntu. When i run setup.sh from my terminal i get the following error message: The setup program seems to have failed on amd64/unknown Fatal error, no tech support email configured in this setup Does anyone have idea about installing OALD 8 in ubuntu 64 bit os?

    Read the article

  • Creating a dynamic, extensible C# Expando Object

    - by Rick Strahl
    I love dynamic functionality in a strongly typed language because it offers us the best of both worlds. In C# (or any of the main .NET languages) we now have the dynamic type that provides a host of dynamic features for the static C# language. One place where I've found dynamic to be incredibly useful is in building extensible types or types that expose traditionally non-object data (like dictionaries) in easier to use and more readable syntax. I wrote about a couple of these for accessing old school ADO.NET DataRows and DataReaders more easily for example. These classes are dynamic wrappers that provide easier syntax and auto-type conversions which greatly simplifies code clutter and increases clarity in existing code. ExpandoObject in .NET 4.0 Another great use case for dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically. The .NET 4.0 framework actually includes an ExpandoObject class which provides a very dynamic object that allows you to add properties and methods on the fly and then access them again. For example with ExpandoObject you can do stuff like this:dynamic expand = new ExpandoObject(); expand.Name = "Rick"; expand.HelloWorld = (Func<string, string>) ((string name) => { return "Hello " + name; }); Console.WriteLine(expand.Name); Console.WriteLine(expand.HelloWorld("Dufus")); Internally ExpandoObject uses a Dictionary like structure and interface to store properties and methods and then allows you to add and access properties and methods easily. As cool as ExpandoObject is it has a few shortcomings too: It's a sealed type so you can't use it as a base class It only works off 'properties' in the internal Dictionary - you can't expose existing type data It doesn't serialize to XML or with DataContractSerializer/DataContractJsonSerializer Expando - A truly extensible Object ExpandoObject is nice if you just need a dynamic container for a dictionary like structure. However, if you want to build an extensible object that starts out with a set of strongly typed properties and then allows you to extend it, ExpandoObject does not work because it's a sealed class that can't be inherited. I started thinking about this very scenario for one of my applications I'm building for a customer. In this system we are connecting to various different user stores. Each user store has the same basic requirements for username, password, name etc. But then each store also has a number of extended properties that is available to each application. In the real world scenario the data is loaded from the database in a data reader and the known properties are assigned from the known fields in the database. All unknown fields are then 'added' to the expando object dynamically. In the past I've done this very thing with a separate property - Properties - just like I do for this class. But the property and dictionary syntax is not ideal and tedious to work with. I started thinking about how to represent these extra property structures. One way certainly would be to add a Dictionary, or an ExpandoObject to hold all those extra properties. But wouldn't it be nice if the application could actually extend an existing object that looks something like this as you can with the Expando object:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } } and then simply start extending the properties of this object dynamically? Using the Expando object I describe later you can now do the following:[TestMethod] public void UserExampleTest() { var user = new User(); // Set strongly typed properties user.Email = "[email protected]"; user.Password = "nonya123"; user.Name = "Rickochet"; user.Active = true; // Now add dynamic properties dynamic duser = user; duser.Entered = DateTime.Now; duser.Accesses = 1; // you can also add dynamic props via indexer user["NickName"] = "AntiSocialX"; duser["WebSite"] = "http://www.west-wind.com/weblog"; // Access strong type through dynamic ref Assert.AreEqual(user.Name,duser.Name); // Access strong type through indexer Assert.AreEqual(user.Password,user["Password"]); // access dyanmically added value through indexer Assert.AreEqual(duser.Entered,user["Entered"]); // access index added value through dynamic Assert.AreEqual(user["NickName"],duser.NickName); // loop through all properties dynamic AND strong type properties (true) foreach (var prop in user.GetProperties(true)) { object val = prop.Value; if (val == null) val = "null"; Console.WriteLine(prop.Key + ": " + val.ToString()); } } As you can see this code somewhat blurs the line between a static and dynamic type. You start with a strongly typed object that has a fixed set of properties. You can then cast the object to dynamic (as I discussed in my last post) and add additional properties to the object. You can also use an indexer to add dynamic properties to the object. To access the strongly typed properties you can use either the strongly typed instance, the indexer or the dynamic cast of the object. Personally I think it's kinda cool to have an easy way to access strongly typed properties by string which can make some data scenarios much easier. To access the 'dynamically added' properties you can use either the indexer on the strongly typed object, or property syntax on the dynamic cast. Using the dynamic type allows all three modes to work on both strongly typed and dynamic properties. Finally you can iterate over all properties, both dynamic and strongly typed if you chose. Lots of flexibility. Note also that by default the Expando object works against the (this) instance meaning it extends the current object. You can also pass in a separate instance to the constructor in which case that object will be used to iterate over to find properties rather than this. Using this approach provides some really interesting functionality when use the dynamic type. To use this we have to add an explicit constructor to the Expando subclass:public class User : Westwind.Utilities.Dynamic.Expando { public string Email { get; set; } public string Password { get; set; } public string Name { get; set; } public bool Active { get; set; } public DateTime? ExpiresOn { get; set; } public User() : base() { } // only required if you want to mix in seperate instance public User(object instance) : base(instance) { } } to allow the instance to be passed. When you do you can now do:[TestMethod] public void ExpandoMixinTest() { // have Expando work on Addresses var user = new User( new Address() ); // cast to dynamicAccessToPropertyTest dynamic duser = user; // Set strongly typed properties duser.Email = "[email protected]"; user.Password = "nonya123"; // Set properties on address object duser.Address = "32 Kaiea"; //duser.Phone = "808-123-2131"; // set dynamic properties duser.NonExistantProperty = "This works too"; // shows default value Address.Phone value Console.WriteLine(duser.Phone); } Using the dynamic cast in this case allows you to access *three* different 'objects': The strong type properties, the dynamically added properties in the dictionary and the properties of the instance passed in! Effectively this gives you a way to simulate multiple inheritance (which is scary - so be very careful with this, but you can do it). How Expando works Behind the scenes Expando is a DynamicObject subclass as I discussed in my last post. By implementing a few of DynamicObject's methods you can basically create a type that can trap 'property missing' and 'method missing' operations. When you access a non-existant property a known method is fired that our code can intercept and provide a value for. Internally Expando uses a custom dictionary implementation to hold the dynamic properties you might add to your expandable object. Let's look at code first. The code for the Expando type is straight forward and given what it provides relatively short. Here it is.using System; using System.Collections.Generic; using System.Linq; using System.Dynamic; using System.Reflection; namespace Westwind.Utilities.Dynamic { /// <summary> /// Class that provides extensible properties and methods. This /// dynamic object stores 'extra' properties in a dictionary or /// checks the actual properties of the instance. /// /// This means you can subclass this expando and retrieve either /// native properties or properties from values in the dictionary. /// /// This type allows you three ways to access its properties: /// /// Directly: any explicitly declared properties are accessible /// Dynamic: dynamic cast allows access to dictionary and native properties/methods /// Dictionary: Any of the extended properties are accessible via IDictionary interface /// </summary> [Serializable] public class Expando : DynamicObject, IDynamicMetaObjectProvider { /// <summary> /// Instance of object passed in /// </summary> object Instance; /// <summary> /// Cached type of the instance /// </summary> Type InstanceType; PropertyInfo[] InstancePropertyInfo { get { if (_InstancePropertyInfo == null && Instance != null) _InstancePropertyInfo = Instance.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly); return _InstancePropertyInfo; } } PropertyInfo[] _InstancePropertyInfo; /// <summary> /// String Dictionary that contains the extra dynamic values /// stored on this object/instance /// </summary> /// <remarks>Using PropertyBag to support XML Serialization of the dictionary</remarks> public PropertyBag Properties = new PropertyBag(); //public Dictionary<string,object> Properties = new Dictionary<string, object>(); /// <summary> /// This constructor just works off the internal dictionary and any /// public properties of this object. /// /// Note you can subclass Expando. /// </summary> public Expando() { Initialize(this); } /// <summary> /// Allows passing in an existing instance variable to 'extend'. /// </summary> /// <remarks> /// You can pass in null here if you don't want to /// check native properties and only check the Dictionary! /// </remarks> /// <param name="instance"></param> public Expando(object instance) { Initialize(instance); } protected virtual void Initialize(object instance) { Instance = instance; if (instance != null) InstanceType = instance.GetType(); } /// <summary> /// Try to retrieve a member by name first from instance properties /// followed by the collection entries. /// </summary> /// <param name="binder"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryGetMember(GetMemberBinder binder, out object result) { result = null; // first check the Properties collection for member if (Properties.Keys.Contains(binder.Name)) { result = Properties[binder.Name]; return true; } // Next check for Public properties via Reflection if (Instance != null) { try { return GetProperty(Instance, binder.Name, out result); } catch { } } // failed to retrieve a property result = null; return false; } /// <summary> /// Property setter implementation tries to retrieve value from instance /// first then into this object /// </summary> /// <param name="binder"></param> /// <param name="value"></param> /// <returns></returns> public override bool TrySetMember(SetMemberBinder binder, object value) { // first check to see if there's a native property to set if (Instance != null) { try { bool result = SetProperty(Instance, binder.Name, value); if (result) return true; } catch { } } // no match - set or add to dictionary Properties[binder.Name] = value; return true; } /// <summary> /// Dynamic invocation method. Currently allows only for Reflection based /// operation (no ability to add methods dynamically). /// </summary> /// <param name="binder"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (Instance != null) { try { // check instance passed in for methods to invoke if (InvokeMethod(Instance, binder.Name, args, out result)) return true; } catch { } } result = null; return false; } /// <summary> /// Reflection Helper method to retrieve a property /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="result"></param> /// <returns></returns> protected bool GetProperty(object instance, string name, out object result) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.GetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { result = ((PropertyInfo)mi).GetValue(instance,null); return true; } } result = null; return false; } /// <summary> /// Reflection helper method to set a property value /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="value"></param> /// <returns></returns> protected bool SetProperty(object instance, string name, object value) { if (instance == null) instance = this; var miArray = InstanceType.GetMember(name, BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0]; if (mi.MemberType == MemberTypes.Property) { ((PropertyInfo)mi).SetValue(Instance, value, null); return true; } } return false; } /// <summary> /// Reflection helper method to invoke a method /// </summary> /// <param name="instance"></param> /// <param name="name"></param> /// <param name="args"></param> /// <param name="result"></param> /// <returns></returns> protected bool InvokeMethod(object instance, string name, object[] args, out object result) { if (instance == null) instance = this; // Look at the instanceType var miArray = InstanceType.GetMember(name, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance); if (miArray != null && miArray.Length > 0) { var mi = miArray[0] as MethodInfo; result = mi.Invoke(Instance, args); return true; } result = null; return false; } /// <summary> /// Convenience method that provides a string Indexer /// to the Properties collection AND the strongly typed /// properties of the object by name. /// /// // dynamic /// exp["Address"] = "112 nowhere lane"; /// // strong /// var name = exp["StronglyTypedProperty"] as string; /// </summary> /// <remarks> /// The getter checks the Properties dictionary first /// then looks in PropertyInfo for properties. /// The setter checks the instance properties before /// checking the Properties dictionary. /// </remarks> /// <param name="key"></param> /// /// <returns></returns> public object this[string key] { get { try { // try to get from properties collection first return Properties[key]; } catch (KeyNotFoundException ex) { // try reflection on instanceType object result = null; if (GetProperty(Instance, key, out result)) return result; // nope doesn't exist throw; } } set { if (Properties.ContainsKey(key)) { Properties[key] = value; return; } // check instance for existance of type first var miArray = InstanceType.GetMember(key, BindingFlags.Public | BindingFlags.GetProperty); if (miArray != null && miArray.Length > 0) SetProperty(Instance, key, value); else Properties[key] = value; } } /// <summary> /// Returns and the properties of /// </summary> /// <param name="includeProperties"></param> /// <returns></returns> public IEnumerable<KeyValuePair<string,object>> GetProperties(bool includeInstanceProperties = false) { if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) yield return new KeyValuePair<string, object>(prop.Name, prop.GetValue(Instance, null)); } foreach (var key in this.Properties.Keys) yield return new KeyValuePair<string, object>(key, this.Properties[key]); } /// <summary> /// Checks whether a property exists in the Property collection /// or as a property on the instance /// </summary> /// <param name="item"></param> /// <returns></returns> public bool Contains(KeyValuePair<string, object> item, bool includeInstanceProperties = false) { bool res = Properties.ContainsKey(item.Key); if (res) return true; if (includeInstanceProperties && Instance != null) { foreach (var prop in this.InstancePropertyInfo) { if (prop.Name == item.Key) return true; } } return false; } } } Although the Expando class supports an indexer, it doesn't actually implement IDictionary or even IEnumerable. It only provides the indexer and Contains() and GetProperties() methods, that work against the Properties dictionary AND the internal instance. The reason for not implementing IDictionary is that a) it doesn't add much value since you can access the Properties dictionary directly and that b) I wanted to keep the interface to class very lean so that it can serve as an entity type if desired. Implementing these IDictionary (or even IEnumerable) causes LINQ extension methods to pop up on the type which obscures the property interface and would only confuse the purpose of the type. IDictionary and IEnumerable are also problematic for XML and JSON Serialization - the XML Serializer doesn't serialize IDictionary<string,object>, nor does the DataContractSerializer. The JavaScriptSerializer does serialize, but it treats the entire object like a dictionary and doesn't serialize the strongly typed properties of the type, only the dictionary values which is also not desirable. Hence the decision to stick with only implementing the indexer to support the user["CustomProperty"] functionality and leaving iteration functions to the publicly exposed Properties dictionary. Note that the Dictionary used here is a custom PropertyBag class I created to allow for serialization to work. One important aspect for my apps is that whatever custom properties get added they have to be accessible to AJAX clients since the particular app I'm working on is a SIngle Page Web app where most of the Web access is through JSON AJAX calls. PropertyBag can serialize to XML and one way serialize to JSON using the JavaScript serializer (not the DCS serializers though). The key components that make Expando work in this code are the Properties Dictionary and the TryGetMember() and TrySetMember() methods. The Properties collection is public so if you choose you can explicitly access the collection to get better performance or to manipulate the members in internal code (like loading up dynamic values form a database). Notice that TryGetMember() and TrySetMember() both work against the dictionary AND the internal instance to retrieve and set properties. This means that user["Name"] works against native properties of the object as does user["Name"] = "RogaDugDog". What's your Use Case? This is still an early prototype but I've plugged it into one of my customer's applications and so far it's working very well. The key features for me were the ability to easily extend the type with values coming from a database and exposing those values in a nice and easy to use manner. I'm also finding that using this type of object for ViewModels works very well to add custom properties to view models. I suspect there will be lots of uses for this - I've been using the extra dictionary approach to extensibility for years - using a dynamic type to make the syntax cleaner is just a bonus here. What can you think of to use this for? Resources Source Code and Tests (GitHub) Also integrated in Westwind.Utilities of the West Wind Web Toolkit West Wind Utilities NuGet© Rick Strahl, West Wind Technologies, 2005-2012Posted in CSharp  .NET  Dynamic Types   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • python: what are efficient techniques to deal with deeply nested data in a flexible manner?

    - by AlexandreS
    My question is not about a specific code snippet but more general, so please bear with me: How should I organize the data I'm analyzing, and which tools should I use to manage it? I'm using python and numpy to analyse data. Because the python documentation indicates that dictionaries are very optimized in python, and also due to the fact that the data itself is very structured, I stored it in a deeply nested dictionary. Here is a skeleton of the dictionary: the position in the hierarchy defines the nature of the element, and each new line defines the contents of a key in the precedent level: [AS091209M02] [AS091209M01] [AS090901M06] ... [100113] [100211] [100128] [100121] [R16] [R17] [R03] [R15] [R05] [R04] [R07] ... [1263399103] ... [ImageSize] [FilePath] [Trials] [Depth] [Frames] [Responses] ... [N01] [N04] ... [Sequential] [Randomized] [Ch1] [Ch2] Edit: To explain a bit better my data set: [individual] ex: [AS091209M02] [imaging session (date string)] ex: [100113] [Region imaged] ex: [R16] [timestamp of file] ex [1263399103] [properties of file] ex: [Responses] [regions of interest in image ] ex [N01] [format of data] ex [Sequential] [channel of acquisition: this key indexes an array of values] ex [Ch1] The type of operations I perform is for instance to compute properties of the arrays (listed under Ch1, Ch2), pick up arrays to make a new collection, for instance analyze responses of N01 from region 16 (R16) of a given individual at different time points, etc. This structure works well for me and is very fast, as promised. I can analyze the full data set pretty quickly (and the dictionary is far too small to fill up my computer's ram : half a gig). My problem comes from the cumbersome manner in which I need to program the operations of the dictionary. I often have stretches of code that go like this: for mk in dic.keys(): for rgk in dic[mk].keys(): for nk in dic[mk][rgk].keys(): for ik in dic[mk][rgk][nk].keys(): for ek in dic[mk][rgk][nk][ik].keys(): #do something which is ugly, cumbersome, non reusable, and brittle (need to recode it for any variant of the dictionary). I tried using recursive functions, but apart from the simplest applications, I ran into some very nasty bugs and bizarre behaviors that caused a big waste of time (it does not help that I don't manage to debug with pdb in ipython when I'm dealing with deeply nested recursive functions). In the end the only recursive function I use regularly is the following: def dicExplorer(dic, depth = -1, stp = 0): '''prints the hierarchy of a dictionary. if depth not specified, will explore all the dictionary ''' if depth - stp == 0: return try : list_keys = dic.keys() except AttributeError: return stp += 1 for key in list_keys: else: print '+%s> [\'%s\']' %(stp * '---', key) dicExplorer(dic[key], depth, stp) I know I'm doing this wrong, because my code is long, noodly and non-reusable. I need to either use better techniques to flexibly manipulate the dictionaries, or to put the data in some database format (sqlite?). My problem is that since I'm (badly) self-taught in regards to programming, I lack practical experience and background knowledge to appreciate the options available. I'm ready to learn new tools (SQL, object oriented programming), whatever it takes to get the job done, but I am reluctant to invest my time and efforts into something that will be a dead end for my needs. So what are your suggestions to tackle this issue, and be able to code my tools in a more brief, flexible and re-usable manner?

    Read the article

  • C# Array of Dictionaries

    - by Nave
    I want to create an array of Dictionaries. But the array size is unknown. For integer, i used List to obtain the integer array of unknown size. But in the case of Dictionary, am not able to create a list of Dictionary. Is thr any wayz by which this can be done? Dictionary(int, String) paramList=null;I am want to create the array of paramList(above). I am using C Sharp.

    Read the article

  • Declaring the datatype dynamically reading from an xml string

    - by NLV
    Hello I've this strange issue. I've an xml string which looks like below - <key><int>5</int></key><value><int>10</int> The above xml is obtained after serializing a Dictionary using Paul's Code. Now i want to convert the xml back to the dictionary. How can i get the type "int" from the xml and declare the dictionary as follows? Dictionary<int, int> Any clues?

    Read the article

  • How to Declare an Array of Generic Dictionaries in C#?

    - by Nave
    I want to create an array of Dictionaries. But the array size is unknown. For integer, i used List to obtain the integer array of unknown size. But in the case of Dictionary, am not able to create a list of Dictionary. Is thr any wayz by which this can be done? Dictionary(int, String) paramList=null;I am want to create the array of paramList(above). I am using C Sharp.

    Read the article

  • Loading a DB table into nested dictionaries in Python

    - by Hossein
    Hi, I have a table in MySql DB which I want to load it to a dictionary in python. the table columns is as follows: id,url,tag,tagCount tagCount is the number of times that a tag has been repeated for a certain url. So in that case I need a nested dictionary, in other words a dictionary of dictionary, to load this table. Because each url have several tags for which there are different tagCounts.the code that I used is this:( the whole table is about 22,000 records ) cursor.execute( ''' SELECT url,tag,tagCount FROM wtp ''') urlTagCount = cursor.fetchall() d = defaultdict(defaultdict) for url,tag,tagCount in urlTagCount: d[url][tag]=tagCount print d first of all I want to know if this is correct.. and if it is why it takes so much time? Is there any faster solutions? I am loading this table into memory to have fast access to get rid of the hassle of slow database operations, but with this slow speed it has become a bottleneck itself, it is even much slower than DB access. and anyone help? thanks

    Read the article

  • KeyNotFound Exception in CSsharp

    - by C Patton
    I'm about ready to bang my head against the wall I have a class called Map which has a dictionary called tiles. class Map { public Dictionary<Location, Tile> tiles = new Dictionary<Location, Tile>(); public Size mapSize; public Map(Size size) { this.mapSize = size; } //etc... I fill this dictionary temporarily to test some things.. public void FillTemp(Dictionary<int, Item> itemInfo) { Random r = new Random(); for(int i =0; i < mapSize.Width; i++) { for(int j=0; j<mapSize.Height; j++) { Location temp = new Location(i, j, 0); int rint = r.Next(0, (itemInfo.Count - 1)); Tile t = new Tile(new Item(rint, rint)); tiles[temp] = t; } } } and in my main program code Map m = new Map(10, 10); m.FillTemp(iInfo); Tile t = m.GetTile(new Location(2, 2, 0)); //The problem line now, if I add a breakpoint in my code, I can clearly see that my instance (m) of the map class is filled with pairs via the function above, but when I try to access a value with the GetTile function: public Tile GetTile(Location location) { if(this.tiles.ContainsKey(location)) { return this.tiles[location]; } else { return null; } } it ALWAYS returns null. Again, if I view inside the Map object and find the Location key where x=2,y=2,z=0 , I clearly see the value being a Tile that FillTemp generated.. Why is it doing this? I've had no problems with a Dictionary such as this so far. I have no idea why it's returning null. and again, when debugging, I can CLEARLY see that the Map instance contains the Location key it says it does not... very frustrating. Any clues? Need any more info? Help would be greatly appreciated :)

    Read the article

  • How much RAM used by Python dict or list?

    - by Who8MyLunch
    My problem: I am writing a simple Python tool to help me visualize my data as a function of many parameters. Each change in parameters involves a non-trivial amount of time, so I would like to cache each step's resulting imagery and supporting data in a dictionary. But then I worry that this dictionary could grow too large over time. Most of my data is in the form of Numpy arrays. My question: How would one go about computing the total number of bytes used by a Python dictionary. The dictionary itself may contain lists and other dictionaries, each of which contain data stored in Numpy arrays. Ideas?

    Read the article

  • Firefox 3.6/4: modify/ tweak spell-check dictionary?

    - by studiohack
    I edit frequently on Super User, and it is a pain to edit for capitalization or words that are shortened, i.e. Win7 instead of Windows 7, or windows versus Windows. Using Firefox 3.6 and/or 4, Is there a way (using an extension or configure settings) I can configure the dictionary to automatically recognize words that may not be capitalized or are shortened (while editing a post)? Say, have the dictionary see Win7 and underline it so that I can right-click on it, and select Windows 7? I would want it to be configurable, so I can tell it what to look for, etc... Ideas or recommendations?

    Read the article

  • Why is Dictionary.First() so slow?

    - by Rotsor
    Not a real question because I already found out the answer, but still interesting thing. I always thought that hash table is the fastest associative container if you hash properly. However, the following code is terribly slow. It executes only about 1 million iterations and takes more than 2 minutes of time on a Core 2 CPU. The code does the following: it maintains the collection todo of items it needs to process. At each iteration it takes an item from this collection (doesn't matter which item), deletes it, processes it if it wasn't processed (possibly adding more items to process), and repeats this until there are no items to process. The culprit seems to be the Dictionary.Keys.First() operation. The question is why is it slow? Stopwatch watch = new Stopwatch(); watch.Start(); HashSet<int> processed = new HashSet<int>(); Dictionary<int, int> todo = new Dictionary<int, int>(); todo.Add(1, 1); int iterations = 0; int limit = 500000; while (todo.Count > 0) { iterations++; var key = todo.Keys.First(); var value = todo[key]; todo.Remove(key); if (!processed.Contains(key)) { processed.Add(key); // process item here if (key < limit) { todo[key + 13] = value + 1; todo[key + 7] = value + 1; } // doesn't matter much how } } Console.WriteLine("Iterations: {0}; Time: {1}.", iterations, watch.Elapsed); This results in: Iterations: 923007; Time: 00:02:09.8414388. Simply changing Dictionary to SortedDictionary yields: Iterations: 499976; Time: 00:00:00.4451514. 300 times faster while having only 2 times less iterations. The same happens in java. Used HashMap instead of Dictionary and keySet().iterator().next() instead of Keys.First().

    Read the article

  • "Dictionary problem." Error with VMPlayer

    - by George Mauer
    I'm pretty new to using vmware virtualization (been a virtualbox user) so I'm hoping you guys can help me out. I recently got an external usb disk containing a vm for a client, downloaded vmplayer, set it up with "Open a Virtual Machine", ran it, easy as pie. After working with it a bit this morning, I shut the VM down and now trying to start it back up again I get this: I tried removing the vm from my library, now it happens whenever I try to add it back in. In the meantime, I can still access other virtual machines so it seems like the problem might be with the virtual disk. So two questions: This is obviously not a very helpful error message. Where can I go to get more information? My Application EventLog doesn't contain anything from VMWare. What steps can I take to fix the problem? Edit: A couple more pieces of information. I did not take any snapshots. I don't think VM Player even has that ability. I have a zip file of (what I assume) is the state of the VM when it was sent to me. I cannot unzip it as it is huge and simply requires more HD space than I have available but I did extract the vmx file and examine it. Other than the UUIDs and the fact that mine reads cleanShutdown = "FALSE" they are identical. The log contains the following lines Jun 23 10:11:18.080: vmx| SNAPSHOT: SnapshotConfigInfoRead: Unable to load dict from 'E:....\MachineName.vmsd'. Jun 23 10:11:18.080: vmx| SNAPSHOT: SnapshotConfigInfoRead failed for file 'E:....\MachineName.vmx': Dictionary problem (6) Jun 23 10:11:18.082: vmx| SNAPSHOT: Snapshot_TimeStampTiers failed: Dictionary problem (6)

    Read the article

  • "Dictionary problem." Error with VMPlayer

    - by George Mauer
    I'm pretty new to using vmware virtualization (been a virtualbox user) so I'm hoping you guys can help me out. I recently got an external usb disk containing a vm for a client, downloaded vmplayer, set it up with "Open a Virtual Machine", ran it, easy as pie. After working with it a bit this morning, I shut the VM down and now trying to start it back up again I get this: I tried removing the vm from my library, now it happens whenever I try to add it back in. In the meantime, I can still access other virtual machines so it seems like the problem might be with the virtual disk. So two questions: This is obviously not a very helpful error message. Where can I go to get more information? My Application EventLog doesn't contain anything from VMWare. What steps can I take to fix the problem? Edit: A couple more pieces of information. I did not take any snapshots. I don't think VM Player even has that ability. I have a zip file of (what I assume) is the state of the VM when it was sent to me. I cannot unzip it as it is huge and simply requires more HD space than I have available but I did extract the vmx file and examine it. Other than the UUIDs and the fact that mine reads cleanShutdown = "FALSE" they are identical. The log contains the following lines Jun 23 10:11:18.080: vmx| SNAPSHOT: SnapshotConfigInfoRead: Unable to load dict from 'E:....\MachineName.vmsd'. Jun 23 10:11:18.080: vmx| SNAPSHOT: SnapshotConfigInfoRead failed for file 'E:....\MachineName.vmx': Dictionary problem (6) Jun 23 10:11:18.082: vmx| SNAPSHOT: Snapshot_TimeStampTiers failed: Dictionary problem (6)

    Read the article

  • problem disposing class in Dictionary it is Still in the heap memory although using GC.Collect

    - by Bahgat Mashaly
    Hello i have a problem disposing class in Dictionary this is my code private Dictionary<string, MyProcessor> Processors = new Dictionary<string, MyProcessor>(); private void button1_Click(object sender, EventArgs e) { if (!Processors.ContainsKey(textBox1.Text)) { Processors.Add(textBox1.Text, new MyProcessor()); } } private void button2_Click(object sender, EventArgs e) { MyProcessor currnt_processor = Processors[textBox1.Text]; Processors.Remove(textBox2.Text); currnt_processor.Dispose(); currnt_processor = null; GC.Collect(); } public class MyProcessor: IDisposable { private bool isDisposed = false; string x = ""; public MyProcessor() { for (int i = 0; i < 20000; i++) { //this line only to increase the memory usage to know if the class is dispose or not x = x + "gggggggggggg"; } this.Dispose(); GC.SuppressFinalize(this); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } public void Dispose(bool disposing) { if (!this.isDisposed) { isDisposed = true; this.Dispose(); } } ~MyProcessor() { Dispose(false); } } i use "ANTS Memory Profiler" to monitor heap memory the disposing work only when i remove all keys from dictionary how can i destroy the class from heap memory ? thanks in advance

    Read the article

  • MVC Form and Dictionary Type

    - by Brian Schmitt
    I am attempting to use a property on my model that is of type Dictionary<string, string>. This dictionary is one of several other properties on the model, and I am using the dictionary as a key/value store to produce a 'dynamic' form. E.G.: User Name Settings A B I want to be able to submit and save any changes to settings A and B. I can submit the form and get my posted values in all my other fields, however the dictionary gets set to null. <%=Html.LabelFor(m => m.Name)%> <%=Html.DisplayFor(m => m.Name)%> <%=Html.LabelFor(m => m.Settings["A"])%> <%=Html.TextBoxFor(m => m.Settings["A"])%> <%=Html.LabelFor(m => m.Settings["B"])%> <%=Html.TextBoxFor(m => m.Settings["B"])%> Is there a better way to produce the dynamic form with a key/value pair? The actual code will be using partials (there several hundred variations), and the above is only a contrived example.

    Read the article

  • How to make Fluent NHibernate ignore Dictionary properties

    - by Matt Winckler
    I'm trying to make Fluent NHibernate's automapping ignore a Dictionary property on one of my classes, but Fluent is ignoring me instead. Ignoring other types of properties seems to work fine, but even after following the documentation and adding an override for the Dictionary, I still get the following exception when BuildSessionFactory is called: The type or method has 2 generic parameter(s), but 1 generic argument(s) were provided. A generic argument must be provided for each generic parameter. I've tried overriding by property name: .Override<MyClass>(map => { map.IgnoreProperty(x => x.MyDictionaryProperty); }) and also tried implementing ignores using a custom attribute, both of which result in the same exception from BuildSessionFactory. The only thing so far that makes this exception go away is removing the Dictionary property entirely. My question seems to be identical to this one which was never answered (though I'll expand the scope by stating it doesn't matter whether the dictionary is on an abstract base class; the problem always happens for me regardless of what class the property is on). Any takers this time around?

    Read the article

  • ASP.net MVC 2 EditorFor Dictionary Bind

    - by user307540
    Hi! I try this, but don't work. bemutatkozas@Modify = null all the time. public class Iroda { public Dictionary<int,string> bemutatkozas { get; set; } } public ActionResult Index() { var dct = new Dictionary<int, string>(); dct.Add(1, "magyar"); dct.Add(2, "angol"); dct.Add(3, "olasz"); return View(new Iroda { bemutatkozas = dct }); } [HttpPost] public ActionResult Modify(Dictionary<int,string> bemutatkozas) { return View(); } <% using (Html.BeginForm("Modify","Iroda")) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <%= Html.EditorFor(o=>o.bemutatkozas,"MultiLanguageEditor") %> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Dictionary<int, string>>" %> <% int i = 0; %> <% foreach (var s in Model) { %> <%= Html.Hidden(Html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix+"["+i+"].key", s.Key) %> <%= Html.TextBox(Html.ViewContext.ViewData.TemplateInfo.HtmlFieldPrefix+"["+i+"].value",s.Value) %> <% i++; %> <% }%> Whats the solution? Thx!

    Read the article

  • Create a dictionary property list programmatically

    - by jovany
    I want to programatically create a dictionary which feeds data to my UITableView but I'm having a hard time with it. I want to create a dictionary that resembles this property list (image) give or take a couple of items. I've looked at "Property List Programming Guide: Creating Property Lists Programmatically" and I came up with a small sample of my own: //keys NSArray *Childs = [NSArray arrayWithObjects:@"testerbet", nil]; NSArray *Children = [NSArray arrayWithObjects:@"Children", nil]; NSArray *Keys = [NSArray arrayWithObjects:@"Rows", nil]; NSArray *Title = [NSArray arrayWithObjects:@"Title", nil]; //strings NSString *Titles = @"mmm training"; //dictionary NSDictionary *item1 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title]; NSDictionary *item2 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title]; NSDictionary *item3 = [NSDictionary dictionaryWithObject:Childs, Titles forKey:Children , Title]; NSArray *Rows = [NSArray arrayWithObjects: item1, item2, item3, nil]; NSDictionary *Root = [NSDictionary dictionaryWithObject:Rows forKey:Keys]; // NSDictionary *tempDict = [[NSDictionary alloc] //initWithContentsOfFile:DataPath]; NSDictionary *tempDict = [[NSDictionary alloc] initWithDictionary: Root]; I'm trying to use this data of hierachy for my table views. I'm actually using this article as an example. So I was wondering how can I can create my property list (dictionary) programmatically so that I can fill it with my own arrays. I'm still new with iPhone development so bear with me. ;)

    Read the article

  • Approaches to create a nested tree structure of NSDictionaries?

    - by d11wtq
    I'm parsing some input which produces a tree structure containing NSDictionary instances on the branches and NSString instance at the nodes. After parsing, the whole structure should be immutable. I feel like I'm jumping through hoops to create the structure and then make sure it's immutable when it's returned from my method. We can probably all relate to the input I'm parsing, since it's a query string from a URL. In a string like this: a=foo&b=bar&a=zip We expect a structure like this: NSDictionary { "a" => NSDictionary { 0 => "foo", 1 => "zip" }, "b" => "bar" } I'm keeping it just two-dimensional in this example for brevity, though in the real-world we sometimes see var[key1][key2]=value&var[key1][key3]=value2 type structures. The code hasn't evolved that far just yet. Currently I do this: - (NSDictionary *)parseQuery:(NSString *)queryString { NSMutableDictionary *params = [NSMutableDictionary dictionary]; NSArray *pairs = [queryString componentsSeparatedByString:@"&"]; for (NSString *pair in pairs) { NSRange eqRange = [pair rangeOfString:@"="]; NSString *key; id value; // If the parameter is a key without a specified value if (eqRange.location == NSNotFound) { key = [pair stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; value = @""; } else { // Else determine both key and value key = [[pair substringToIndex:eqRange.location] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; if ([pair length] > eqRange.location + 1) { value = [[pair substringFromIndex:eqRange.location + 1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; } else { value = @""; } } // Parameter already exists, it must be a dictionary if (nil != [params objectForKey:key]) { id existingValue = [params objectForKey:key]; if (![existingValue isKindOfClass:[NSDictionary class]]) { value = [NSDictionary dictionaryWithObjectsAndKeys:existingValue, [NSNumber numberWithInt:0], value, [NSNumber numberWithInt:1], nil]; } else { // FIXME: There must be a more elegant way to build a nested dictionary where the end result is immutable? NSMutableDictionary *newValue = [NSMutableDictionary dictionaryWithDictionary:existingValue]; [newValue setObject:value forKey:[NSNumber numberWithInt:[newValue count]]]; value = [NSDictionary dictionaryWithDictionary:newValue]; } } [params setObject:value forKey:key]; } return [NSDictionary dictionaryWithDictionary:params]; } If you look at the bit where I've added FIXME it feels awfully clumsy, pulling out the existing dictionary, creating an immutable version of it, adding the new value, then creating an immutable dictionary from that to set back in place. Expensive and unnecessary? I'm not sure if there are any Cocoa-specific design patterns I can follow here?

    Read the article

  • Problem with fetching dictionary objects in array from plist iphone sdk

    - by neha
    Hi all, What is the datatype you use to fetch items whose type is dictionary in plist i.e. nsmutabledictionary or nsdictionary? Because I'm using following code to retrieve dictionary objects from an array of dictionaries in plist. NSMutableDictionary *_myDict = [contentArray objectAtIndex:0]; NSLog(@"MYDICT : %@",_myDict); NSString *myKey = (NSString *)[_myDict valueForKey:@"Contents"] ; [[cell lblFeed] setText:[NSString stringWithFormat:@"%@",myKey]]; Here, on first line it's showing me objc_msgsend. ContentArray is an nsarray and it's contents are showing 2 objects that are there in plist. In plist they are dictionary objects. Then why this error? Can anybody please help? Thanx in advance.

    Read the article

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