Search Results

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

Page 21/90 | < Previous Page | 17 18 19 20 21 22 23 24 25 26 27 28  | Next Page >

  • POSTing JSON data to WCF REST

    - by Randall Sexton
    I'm trying to send data from a client application using jQuery to a REST WCF service based on the WCF REST starter kit. Here's what I have so far. Service Definition: [WebHelp(Comment = "Save PropertyValues to the database")] [WebInvoke(Method = "POST", UriTemplate = "PropertyValues_Save", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] [OperationContract] public bool PropertyValues_Save(Guid assetId, Dictionary<Guid, string> newValues) { ... } Call from the client: $.ajax({ url:SVC_PROPERTYVALUES_SAVE, type: "POST", contentType: "application/json; charset=utf-8", data: jsonData, dataType: "json", error: function(XMLHttpRequest, textStatus, errorThrown) { alert(textStatus + ' ' + errorThrown); }, success: function(data) { if (data) { alert('Values saved'); $("#confirmSubmit").dialog('close'); } else { alert('Values failed to save'); $("#confirmSubmit").dialog('close'); } } }); Example of the JSON being passed: { "assetId": "d70714c3-e403-4cc5-b8a9-9713d05b2ee0", "newValues": [ { "key": "bd01aa88-b48d-47c7-8d3f-eadf47a46680", "value": "0e9fdf34-2d12-4639-8d70-19b88e753ab1" }, { "key": "06e8eda2-a004-450e-90ab-64df357013cf", "value": "1d490aec-f40e-47d5-865c-07fe9624f955" } ] } I'm using Windows Authentication on the virtual directory. When I call operations that are GETs, everything is fine. This code is prompting the browser to log in. When I enter my credentials, I simply get an alert in my browser which says "error undefined". Even if you can't help my specific error, do you see anything that looks wrong from glancing? I've been beating my head on this nearly all day. Thanks in advance.

    Read the article

  • XElement vs Dcitionary

    - by user135498
    Hi All, I need advice. I have application that imports 10,000 rows containing name & address from a text file into XElements that are subsequently added to a synchronized queue. When the import is complete the app spawns worker threads that process the XElements by deenqueuing them, making a database call, inserting the database output into the request document and inserting the processed document into an output queue. When all requests have been processed the output queue is written to disk as an XML doc. I used XElements for the requests because I needed the flexibility to add fields to the request during processing. i.e. Depending on the job type the app might require that it add phone number, date of birth or email address to a request based on a name/address match against a public record database. My questions is; The XElements seems to use quite a bit of memory and I know there is a lot of parsing as the document makes its way through the processing methods. I’m considering replacing the XElements with a Dictionary object but I’m skeptical the gain will be worth the effort. In essence it will accomplish the same thing. Thoughts?

    Read the article

  • Python Multiword Index

    - by Manab Chetia
    index = {'Michael': [['mj.com',1], ['Nine.com',9],['i.com', 34]], / 'Jackson': [['One.com',4],['mj.com', 2],['Nine.com', 10], ['i.com', 45]], / 'Thriller' : [['Seven.com', 7], ['Ten.com',10], ['One.com', 5], ['mj.com',3]} # In this dictionary (index), for eg: 'KEYWORD': # [['THE LINK in which KEYWORD is present,'POSITION # of KEYWORD in the page specified by link']] eg: Michael is present in MJ.com, NINE.com, and i.com at positions 1, 9, 34 of respective pages. Please help me with a python procedure which takes index and KEYWORDS as input. When i enter 'MICHAEL'. The result should be: >>['mj.com', 'nine.com', 'i.com'] When I enter 'MICHAEL JACKSON'. The result should be : >>['mj.com', 'Nine.com'] as 'Michael' and 'Jackson' are present at 'mj.com' and 'nine.com' consecutively i.e. in positions (1,2) & (9,10) respectively. The result should not show 'i.com' even though it contains both KEYWORDS but they are not placed consecutively. When I enter 'MICHAEL JACKSON THRILLER', the result should be ['mj.com'] as the 3 words 'MICHAEL', 'JACKSON', 'THRILLER' are placed consecutively in 'mj.com' ie positions (1, 2, 3) respectively. If I enter 'THRILLER JACKSON' or 'THRILLER FEDERER', the result should be NONE.

    Read the article

  • How do I create a list or set object in a class in Python?

    - by Az
    For my project, the role of the Lecturer (defined as a class) is to offer projects to students. Project itself is also a class. I have some global dictionaries, keyed by the unique numeric id's for lecturers and projects that map to objects. Thus for the "lecturers" dictionary (currently): lecturer[id] = Lecturer(lec_name, lec_id, max_students) I'm currently reading in a white-space delimited text file that has been generated from a database. I have no direct access to the database so I haven't much say on how the file is formatted. Here's a fictionalised snippet that shows how the text file is structured. Please pardon the cheesiness. 0001 001 "Miyamoto, S." "Even Newer Super Mario Bros" 0002 001 "Miyamoto, S." "Legend of Zelda: Skies of Hyrule" 0003 002 "Molyneux, P." "Project Milo" 0004 002 "Molyneux, P." "Fable III" 0005 003 "Blow, J." "Ponytail" The structure of each line is basically proj_id, lec_id, lec_name, proj_name. Now, I'm currently reading the relevant data into the relevant objects. Thus, proj_id is stored in class Project whereas lec_name is a class Lecturer object, et al. The Lecturer and Project classes are not currently related. However, as I read in each line from the text file, for that line, I wish to read in the project offered by the lecturer into the Lecturer class; I'm already reading the proj_id into the Project class. I'd like to create an object in Lecturer called offered_proj which should be a set or list of the projects offered by that lecturer. Thus whenever, for a line, I read in a new project under the same lec_id, offered_proj will be updated with that project. If I wanted to get display a list of projects offered by a lecturer I'd ideally just want to use print lecturers[lec_id].offered_proj. My Python isn't great and I'd appreciate it if someone could show me a way to do that. I'm not sure if it's better as a set or a list, as well. Update After the advice from Alex Martelli and Oddthinking I went back and made some changes and tried to print the results. Here's the code snippet: for line in csv_file: proj_id = int(line[0]) lec_id = int(line[1]) lec_name = line[2] proj_name = line[3] projects[proj_id] = Project(proj_id, proj_name) lecturers[lec_id] = Lecturer(lec_id, lec_name) if lec_id in lecturers.keys(): lecturers[lec_id].offered_proj.add(proj_id) print lec_id, lecturers[lec_id].offered_proj The print lecturers[lec_id].offered_proj line prints the following output: 001 set([0001]) 001 set([0002]) 002 set([0003]) 002 set([0004]) 003 set([0005]) It basically feels like the set is being over-written or somesuch. So if I try to print for a specific lecturer print lec_id, lecturers[001].offered_proj all I get is the last the proj_id that has been read in.

    Read the article

  • Display XML diferent in JSF (using XSLT or some another suggestion)

    - by Milan
    Hello everybody! At runtime I receive xml document and I want to display it somehow different in JSF. For example: This: <invoker.ArrayOfDictionary> <dictionary> <invoker.Dictionary> <id>gcide</id> <name>The Collaborative International Dictionary of English v.0.48</name> </invoker.Dictionary> <invoker.Dictionary> <id>wn</id> <name>WordNet (r) 2.0</name> </invoker.Dictionary> <invoker.Dictionary> <id>moby-thes</id> <name>Moby Thesaurus II by Grady Ward, 1.0</name> </invoker.Dictionary> in this: invoker.ArrayOfDictionary: dictionary: invoker.Dictionary: id:gcide name:The Collaborative International Dictionary of English v.0.48 invoker.Dictionary: id:wn name:WordNet (r) 2.0 invoker.Dictionary: id:moby-thes name:Moby Thesaurus II by Grady Ward, 1.0 I was thinking to do this with XSLT transformation. Some guidelines how to start with xslt? Or maybe you have another idea for this?

    Read the article

  • C#/.NET Fundamentals: Choosing the Right Collection Class

    - by James Michael Hare
    The .NET Base Class Library (BCL) has a wide array of collection classes at your disposal which make it easy to manage collections of objects. While it's great to have so many classes available, it can be daunting to choose the right collection to use for any given situation. As hard as it may be, choosing the right collection can be absolutely key to the performance and maintainability of your application! This post will look at breaking down any confusion between each collection and the situations in which they excel. We will be spending most of our time looking at the System.Collections.Generic namespace, which is the recommended set of collections. The Generic Collections: System.Collections.Generic namespace The generic collections were introduced in .NET 2.0 in the System.Collections.Generic namespace. This is the main body of collections you should tend to focus on first, as they will tend to suit 99% of your needs right up front. It is important to note that the generic collections are unsynchronized. This decision was made for performance reasons because depending on how you are using the collections its completely possible that synchronization may not be required or may be needed on a higher level than simple method-level synchronization. Furthermore, concurrent read access (all writes done at beginning and never again) is always safe, but for concurrent mixed access you should either synchronize the collection or use one of the concurrent collections. So let's look at each of the collections in turn and its various pros and cons, at the end we'll summarize with a table to help make it easier to compare and contrast the different collections. The Associative Collection Classes Associative collections store a value in the collection by providing a key that is used to add/remove/lookup the item. Hence, the container associates the value with the key. These collections are most useful when you need to lookup/manipulate a collection using a key value. For example, if you wanted to look up an order in a collection of orders by an order id, you might have an associative collection where they key is the order id and the value is the order. The Dictionary<TKey,TVale> is probably the most used associative container class. The Dictionary<TKey,TValue> is the fastest class for associative lookups/inserts/deletes because it uses a hash table under the covers. Because the keys are hashed, the key type should correctly implement GetHashCode() and Equals() appropriately or you should provide an external IEqualityComparer to the dictionary on construction. The insert/delete/lookup time of items in the dictionary is amortized constant time - O(1) - which means no matter how big the dictionary gets, the time it takes to find something remains relatively constant. This is highly desirable for high-speed lookups. The only downside is that the dictionary, by nature of using a hash table, is unordered, so you cannot easily traverse the items in a Dictionary in order. The SortedDictionary<TKey,TValue> is similar to the Dictionary<TKey,TValue> in usage but very different in implementation. The SortedDictionary<TKey,TValye> uses a binary tree under the covers to maintain the items in order by the key. As a consequence of sorting, the type used for the key must correctly implement IComparable<TKey> so that the keys can be correctly sorted. The sorted dictionary trades a little bit of lookup time for the ability to maintain the items in order, thus insert/delete/lookup times in a sorted dictionary are logarithmic - O(log n). Generally speaking, with logarithmic time, you can double the size of the collection and it only has to perform one extra comparison to find the item. Use the SortedDictionary<TKey,TValue> when you want fast lookups but also want to be able to maintain the collection in order by the key. The SortedList<TKey,TValue> is the other ordered associative container class in the generic containers. Once again SortedList<TKey,TValue>, like SortedDictionary<TKey,TValue>, uses a key to sort key-value pairs. Unlike SortedDictionary, however, items in a SortedList are stored as an ordered array of items. This means that insertions and deletions are linear - O(n) - because deleting or adding an item may involve shifting all items up or down in the list. Lookup time, however is O(log n) because the SortedList can use a binary search to find any item in the list by its key. So why would you ever want to do this? Well, the answer is that if you are going to load the SortedList up-front, the insertions will be slower, but because array indexing is faster than following object links, lookups are marginally faster than a SortedDictionary. Once again I'd use this in situations where you want fast lookups and want to maintain the collection in order by the key, and where insertions and deletions are rare. The Non-Associative Containers The other container classes are non-associative. They don't use keys to manipulate the collection but rely on the object itself being stored or some other means (such as index) to manipulate the collection. The List<T> is a basic contiguous storage container. Some people may call this a vector or dynamic array. Essentially it is an array of items that grow once its current capacity is exceeded. Because the items are stored contiguously as an array, you can access items in the List<T> by index very quickly. However inserting and removing in the beginning or middle of the List<T> are very costly because you must shift all the items up or down as you delete or insert respectively. However, adding and removing at the end of a List<T> is an amortized constant operation - O(1). Typically List<T> is the standard go-to collection when you don't have any other constraints, and typically we favor a List<T> even over arrays unless we are sure the size will remain absolutely fixed. The LinkedList<T> is a basic implementation of a doubly-linked list. This means that you can add or remove items in the middle of a linked list very quickly (because there's no items to move up or down in contiguous memory), but you also lose the ability to index items by position quickly. Most of the time we tend to favor List<T> over LinkedList<T> unless you are doing a lot of adding and removing from the collection, in which case a LinkedList<T> may make more sense. The HashSet<T> is an unordered collection of unique items. This means that the collection cannot have duplicates and no order is maintained. Logically, this is very similar to having a Dictionary<TKey,TValue> where the TKey and TValue both refer to the same object. This collection is very useful for maintaining a collection of items you wish to check membership against. For example, if you receive an order for a given vendor code, you may want to check to make sure the vendor code belongs to the set of vendor codes you handle. In these cases a HashSet<T> is useful for super-quick lookups where order is not important. Once again, like in Dictionary, the type T should have a valid implementation of GetHashCode() and Equals(), or you should provide an appropriate IEqualityComparer<T> to the HashSet<T> on construction. The SortedSet<T> is to HashSet<T> what the SortedDictionary<TKey,TValue> is to Dictionary<TKey,TValue>. That is, the SortedSet<T> is a binary tree where the key and value are the same object. This once again means that adding/removing/lookups are logarithmic - O(log n) - but you gain the ability to iterate over the items in order. For this collection to be effective, type T must implement IComparable<T> or you need to supply an external IComparer<T>. Finally, the Stack<T> and Queue<T> are two very specific collections that allow you to handle a sequential collection of objects in very specific ways. The Stack<T> is a last-in-first-out (LIFO) container where items are added and removed from the top of the stack. Typically this is useful in situations where you want to stack actions and then be able to undo those actions in reverse order as needed. The Queue<T> on the other hand is a first-in-first-out container which adds items at the end of the queue and removes items from the front. This is useful for situations where you need to process items in the order in which they came, such as a print spooler or waiting lines. So that's the basic collections. Let's summarize what we've learned in a quick reference table.  Collection Ordered? Contiguous Storage? Direct Access? Lookup Efficiency Manipulate Efficiency Notes Dictionary No Yes Via Key Key: O(1) O(1) Best for high performance lookups. SortedDictionary Yes No Via Key Key: O(log n) O(log n) Compromise of Dictionary speed and ordering, uses binary search tree. SortedList Yes Yes Via Key Key: O(log n) O(n) Very similar to SortedDictionary, except tree is implemented in an array, so has faster lookup on preloaded data, but slower loads. List No Yes Via Index Index: O(1) Value: O(n) O(n) Best for smaller lists where direct access required and no ordering. LinkedList No No No Value: O(n) O(1) Best for lists where inserting/deleting in middle is common and no direct access required. HashSet No Yes Via Key Key: O(1) O(1) Unique unordered collection, like a Dictionary except key and value are same object. SortedSet Yes No Via Key Key: O(log n) O(log n) Unique ordered collection, like SortedDictionary except key and value are same object. Stack No Yes Only Top Top: O(1) O(1)* Essentially same as List<T> except only process as LIFO Queue No Yes Only Front Front: O(1) O(1) Essentially same as List<T> except only process as FIFO   The Original Collections: System.Collections namespace The original collection classes are largely considered deprecated by developers and by Microsoft itself. In fact they indicate that for the most part you should always favor the generic or concurrent collections, and only use the original collections when you are dealing with legacy .NET code. Because these collections are out of vogue, let's just briefly mention the original collection and their generic equivalents: ArrayList A dynamic, contiguous collection of objects. Favor the generic collection List<T> instead. Hashtable Associative, unordered collection of key-value pairs of objects. Favor the generic collection Dictionary<TKey,TValue> instead. Queue First-in-first-out (FIFO) collection of objects. Favor the generic collection Queue<T> instead. SortedList Associative, ordered collection of key-value pairs of objects. Favor the generic collection SortedList<T> instead. Stack Last-in-first-out (LIFO) collection of objects. Favor the generic collection Stack<T> instead. In general, the older collections are non-type-safe and in some cases less performant than their generic counterparts. Once again, the only reason you should fall back on these older collections is for backward compatibility with legacy code and libraries only. The Concurrent Collections: System.Collections.Concurrent namespace The concurrent collections are new as of .NET 4.0 and are included in the System.Collections.Concurrent namespace. These collections are optimized for use in situations where multi-threaded read and write access of a collection is desired. The concurrent queue, stack, and dictionary work much as you'd expect. The bag and blocking collection are more unique. Below is the summary of each with a link to a blog post I did on each of them. ConcurrentQueue Thread-safe version of a queue (FIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentStack Thread-safe version of a stack (LIFO). For more information see: C#/.NET Little Wonders: The ConcurrentStack and ConcurrentQueue ConcurrentBag Thread-safe unordered collection of objects. Optimized for situations where a thread may be bother reader and writer. For more information see: C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection ConcurrentDictionary Thread-safe version of a dictionary. Optimized for multiple readers (allows multiple readers under same lock). For more information see C#/.NET Little Wonders: The ConcurrentDictionary BlockingCollection Wrapper collection that implement producers & consumers paradigm. Readers can block until items are available to read. Writers can block until space is available to write (if bounded). For more information see C#/.NET Little Wonders: The ConcurrentBag and BlockingCollection Summary The .NET BCL has lots of collections built in to help you store and manipulate collections of data. Understanding how these collections work and knowing in which situations each container is best is one of the key skills necessary to build more performant code. Choosing the wrong collection for the job can make your code much slower or even harder to maintain if you choose one that doesn’t perform as well or otherwise doesn’t exactly fit the situation. Remember to avoid the original collections and stick with the generic collections.  If you need concurrent access, you can use the generic collections if the data is read-only, or consider the concurrent collections for mixed-access if you are running on .NET 4.0 or higher.   Tweet Technorati Tags: C#,.NET,Collecitons,Generic,Concurrent,Dictionary,List,Stack,Queue,SortedList,SortedDictionary,HashSet,SortedSet

    Read the article

  • C# Ordered dictionary index

    - by Martijn
    I am considering of using the OrderedDictionary. As a key I want to use a long value (id) and the value will be a custom object. I use the OrderedDictionary because I want to get an object by it's Id and I want to get an object by it's 'collection' index. I want to use the OrderedDictionary like this: public void AddObject(MyObject obj) { _dict.Add(obj.Id, obj); // dict is declared as OrderedDictionary _dict = new OrderedDictionary(); } Somewhere else in my code I have something similar like this: public MyObject GetNextObject() { /* In my code keep track of the current index */ _currentIndex++; // check _currentindex doesn't exceed the _questions bounds return _dict[_currentIndex] as MyObject; } Now my question is. In the last method I've used an index. Imagine _currentIndex is set to 10, but I have also an object with an id of 10. I've set the Id as a key. The Id of MyObject is of type long?. Does this goes wrong?

    Read the article

  • The model item passed into the dictionary is of type ‘mvc.Models.ModelA’ but this dictionary require

    - by Malcolm Frexner
    I have this annoying mistake in some of my builds. There is no error in the project, because if I build again, then the problem disappears. The message only appears, when the site is deployed to a Windows 2008 Server. I first thought that it might be an issue with temporary files, but thats not the case. I deployed the build to a different web and the error still appears. The error appears on random actions of the site. Most of the time builds are ok, but each 3rd or 4th build produces runtime errors. I build using a WebdeploymentProject in release mode. Views are precompiled. It's not http://stackoverflow.com/questions/178194/in-asp-net-mvc-i-encounter-an-incorrect-type-error-when-rendering-a-page-with-the, because views have totally different names. How I can debug this problem or how I can get help for this? Here is my WebDeploymentProject <!-- Microsoft Visual Studio 2008 Web Deployment Project http://go.microsoft.com/fwlink/?LinkID=104956 --> <Project ToolsVersion="3.5" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <PropertyGroup> <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> <ProductVersion>9.0.21022</ProductVersion> <SchemaVersion>2.0</SchemaVersion> <ProjectGuid>{E5E14CEB-0BCD-4203-9A5A-34ABA9C717EA}</ProjectGuid> <SourceWebPhysicalPath>..\B2CWeb</SourceWebPhysicalPath> <SourceWebProject>{3E632DB6-6DB3-4BD0-8CCA-12DE67165B48}|B2CWeb\B2CWeb.csproj</SourceWebProject> <SourceWebVirtualPath>/B2CWeb.csproj</SourceWebVirtualPath> <TargetFrameworkVersion>v3.5</TargetFrameworkVersion> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <DebugSymbols>true</DebugSymbols> <OutputPath>.\Debug</OutputPath> <EnableUpdateable>false</EnableUpdateable> <UseMerge>true</UseMerge> <SingleAssemblyName>B2CWeb_Build</SingleAssemblyName> </PropertyGroup> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> <DebugSymbols>false</DebugSymbols> <OutputPath>..\B2CWeb_Deploy\</OutputPath> <EnableUpdateable>false</EnableUpdateable> <UseMerge>true</UseMerge> <SingleAssemblyName>B2C_Web</SingleAssemblyName> <ContentAssemblyName> </ContentAssemblyName> <DeleteAppCodeCompiledFiles>false</DeleteAppCodeCompiledFiles> </PropertyGroup> <ItemGroup> </ItemGroup> <Import Project="$(MSBuildExtensionsPath)\Microsoft\WebDeployment\v9.0\Microsoft.WebDeployment.targets" /> <!-- To modify your build process, add your task inside one of the targets below and uncomment it. Other similar extension points exist, see Microsoft.WebDeployment.targets. <Target Name="BeforeBuild"> </Target> <Target Name="BeforeMerge"> </Target> <Target Name="AfterMerge"> </Target> <Target Name="AfterBuild"> </Target> --> </Project>

    Read the article

  • converting JSON to an object / dictionary / dynamic

    - by benpage
    I'm currently using jqGrid to display data. Part of jqGrid's interface will give you search options, posting back the search details in a JSON string, for example: {"groupOp":"AND","rules":[{"field":"PersonID","op":"eq","data":"123"},{"field":"LastName","op":"eq","data":"Smith"}]} (meaning i'm searching for personID = 123, and LastName = 'Smith') so what i'm hoping to do is somehow convert that back into something i can use server-side. Does anyone have a solution for this that may convert it back into an object of some kind? My current solution would be to convert into xml, parse with linq and create instances of my own 'search' class with a 'rules' collection.

    Read the article

  • Filtering documents against a dictionary key in MongoDB

    - by Thomas
    I have a collection of articles in MongoDB that has the following structure: { 'category': 'Legislature', 'updated': datetime.datetime(2010, 3, 19, 15, 32, 22, 107000), 'byline': None, 'tags': { 'party': ['Peter Hoekstra', 'Virg Bernero', 'Alma Smith', 'Mike Bouchard', 'Tom George', 'Rick Snyder'], 'geography': ['Michigan', 'United States', 'North America'] }, 'headline': '2 Mich. gubernatorial candidates speak to students', 'text': [ 'BEVERLY HILLS, Mich. (AP) \u2014 Two Democratic and Republican gubernatorial candidates found common ground while speaking to private school students in suburban Detroit', "Democratic House Speaker state Rep. Andy Dillon and Republican U.S. Rep. Pete Hoekstra said Friday a more business-friendly government can help reduce Michigan's nation-leading unemployment rate.", "The candidates were invited to Detroit Country Day Upper School in Beverly Hills to offer ideas for Michigan's future.", 'Besides Dillon, the Democratic field includes Lansing Mayor Virg Bernero and state Rep. Alma Wheeler Smith. Other Republicans running are Oakland County Sheriff Mike Bouchard, Attorney General Mike Cox, state Sen. Tom George and Ann Arbor business leader Rick Snyder.', 'Former Republican U.S. Rep. Joe Schwarz is considering running as an independent.' ], 'dateline': 'BEVERLY HILLS, Mich.', 'published': datetime.datetime(2010, 3, 19, 8, 0, 31), 'keywords': "Governor's Race", '_id': ObjectId('4ba39721e0e16cb25fadbb40'), 'article_id': 'urn:publicid:ap.org:0611e36fb084458aa620c0187999db7e', 'slug': "BC-MI--Governor's Race,2nd Ld-Writethr" } If I wanted to write a query that looked for all articles that had at least 1 geography tag, how would I do that? I have tried writing db.articles.find( {'tags': 'geography'} ), but that doesn't appear to work. I've also thought about changing the search parameter to 'tags.geography', but am having a devil of a time figuring out what the search predicate would be.

    Read the article

  • extract data from Plist to array and dictionary

    - by Boaz
    Hi I made a plist that looks like that: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList 1.0.dtd"> <plist version="1.0"> <array> <array> <dict> <key>Company</key> <string>xxx</string> <key>Title</key> <string>VP Marketing</string> <key>Name</key> <string>Alon ddfr</string> </dict> <dict> <key>Name</key> <string>Adam Ben Shushan</string> <key>Title</key> <string>CEO</string> <key>Company</key> <string>Shushan ltd.</string> </dict> </array> <array> <dict> <key>Company</key> <string>xxx</string> <key>Title</key> <string>CTO</string> <key>Name</key> <string>Boaz frf</string> </dict> </array> </array> </plist> Now I want to extract the data like that (all the 'A' for key "Name" to one section and all the 'B' "Name" to other one): NSString *plistpath = [[NSBundle mainBundle] pathForResource:@"PeopleData" ofType:@"plist"]; NSMutableArray *attendees = [[NSMutableArray alloc] initWithContentsOfFile:plistpath]; listOfPeople = [[NSMutableArray alloc] init];//Add items NSDictionary *indexADict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:0] objectForKey:@"Name"] forKey:@"Profiles"]; NSDictionary *indexBDict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:1] objectForKey:@"Name"] forKey:@"Profiles"]; [listOfPeople addObject:indexADict]; [listOfPeople addObject:indexBDict]; This in order to view them in sectioned tableView. I know that the problem is here: NSDictionary *indexADict = [NSDictionary dictionaryWithObject:[[attendees objectAtIndex:0] objectForKey:@"Name"] forKey:@"Profiles"]; But I just can't figure how to do it right. Thanks.

    Read the article

  • Problem in populating a dictionary using Enumerable.Range()

    - by Newbie
    If I do for (int i = 0; i < appSettings.Count; i++) { string key = appSettings.Keys[i]; euFileDictionary.Add(key, appSettings[i]); } It is working fine. When I am trying the same thing using Enumerable.Range(0, appSettings.Count).Select(i => { string Key = appSettings.Keys[i]; string Value = appSettings[i]; euFileDictionary.Add(Key, Value); }).ToDictionary<string,string>(); I am getting a compile time error The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly. Any idea? Using C#3.0 Thanks

    Read the article

  • Generic Dictionary and generating a hashcode for multi-part key

    - by Andrew
    I have an object that has a multi-part key and I am struggling to find a suitable way override GetHashCode. An example of what the class looks like is. public class wibble{ public int keypart1 {get; set;} public int keypart2 {get; set;} public int keypart3 {get; set;} public int keypart4 {get; set;} public int keypart5 {get; set;} public int keypart6 {get; set;} public int keypart7 {get; set;} public single value {get; set;} } Note in just about every instance of the class no more than 2 or 3 of the keyparts would have a value greater than 0. Any ideas on how best to generate a unique hashcode in this situation? I have also been playing around with creating a key that is not unique, but spreads the objects evenly between the dictionaries buckets and then storing objects with matched hashes in a List< or LinkedList< or SortedList<. Any thoughts on this?

    Read the article

  • Use a resource dictionary as theme in Silverlight

    - by SaphuA
    Hello, I have developed an application which allows the user to switch between themes. I'm doing this by including the xaml file as a resource in my project and using the following code: MainTheme.ThemeUri = new Uri("SilverlightApplication1;component/Themes/[ThemeName]/Theme.xaml", UriKind.Relative); This worked well, untill I found these themes: http://timheuer.com/blog/archive/2010/05/17/silverlight-4-tools-released-and-new-application-templates.aspx The difference is that these themes consist of multiple files. So I made a Theme.xaml file that only includes MergedDictionaries so I could still use the code above. This is the Theme.xaml file for the Cosmopolitan theme. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="CoreStyles.xaml"/> <ResourceDictionary Source="SDKStyles.xaml"/> <ResourceDictionary Source="Styles.xaml"/> <ResourceDictionary Source="ToolkitStyles.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> However, when I run the c# code above I get the following exception: System.Windows.Markup.XamlParseException: Failed to assign to property 'System.Windows.ResourceDictionary.Source'. Just to be clear, using the MergedDictionaries method does work when I set it in my App.xaml: <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Themes/Cosmopolitan/Theme.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> What am I doing wrong? Thanks!

    Read the article

  • .net dictionary and lookup add / update

    - by freddy smith
    I am sick of doing blocks of code like this for various bits of code I have: if (dict.ContainsKey[key]) { dict[key] = value; } else { dict.Add(key,value); } and for lookups (i.e. key - list of value) if (lookup.ContainsKey[key]) { lookup[key].Add(value); } else { lookup.Add(new List<valuetype>); lookup[key].Add(value); } Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are? e.g. dict.AddOrUpdate(key,value) lookup.AddOrUpdate(key,value)

    Read the article

  • .net 4.0 concurrent queue dictionary

    - by freddy smith
    I would like to use the new concurrent collections in .NET 4.0 to solve the following problem. The basic data structure I want to have is a producer consumer queue, there will be a single consumer and multiple producers. There are items of type A,B,C,D,E that will be added to this queue. Items of type A,B,C are added to the queue in the normal manner and processed in order. However items of type D or E can only exist in the queue zero or once. If one of these is to be added and there already exists another of the same type that has not yet been processed then this should update that other one in-place in the queue. The queue position would not change (i.e. would not go to the back of the queue) after the update. Which .NET 4.0 classes would be best for this?

    Read the article

  • How to create Dictionary object in AppDelegate to access objectkey in another ViewController

    - by TechFusion
    Hello, I have created Window Based application and tab bar controller as root controller. My objective is to store Text Field data values in one tab bar VC and will be accessible and editable by other VC and also retrievable when application start. I am looking to use NSDictionary class in AppDelegate so that I can access stroed Data Values with keys. //TestAppDelegate.h @interface { ..... .... NSDictionary *Data; } @property (nonatomic, retain) NSDictionary *Data; //TestAppDelegate.m #import "TestAppDelegate.h" NSString *kNamekey =@"Namekey"; NSString *kUserIDkey =@"UserIDkey"; NSString *kPasswordkey =@"Passwordkey"; @implemetation TestAppDelegate @synthesize Data; -(void)applicationDidFinishLaunching:(UIApplication)application { NSString *NameDefault; NSString *UserIDdefault; NSString *Passworddefault; NSString *testvalue = [[NSUserDefaults standardUserDefaults] stringForKey: kNamekey]; if(testvalue == nil) { NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys: NameDefault, kNamekey, UserIdefault kUserIDkey, Passwordefault kPasswordkey, nil]; self.Data = appDefaults; [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults]; [[NSUserDefaults standardUserDefaults] synchronize]; } else { } } Here ViewController is ViewController of Navigation Controller which is attached with one tab bar.. I have attached xib file with ViewController //ViewController.h @interface IBOutlet UITextField *Name; IBOutlet UITextField *UserId; IBOutlet UITextField *Password; } @property(retain,nonatomic) IBOutlet UITextField *Name @property(retain,nonatomic) IBOutlet UITextField *UserId; @property(retain,nonatomic) IBOutlet UITextField *Password; -(IBAction)Save:(id)sender; @end Here in ViewController.m I want to store Text Field input data with key which are defined in AppDelegate. I have linked Save Barbutton with action. Here I am not getting how to access NSDictionary class with object and keys in ViewController. //ViewController.m -(IBAction)Save:(id)sender{ TestAppDelegate *appDelegate = (TestAppDelegate*)[[UIApplication sharedApplication] delegate]; //Here how to access knamekey here to set object(Name.test) value with key } Please guide me about this. Thanks,

    Read the article

  • Using a dictionary file with sed

    - by Winston
    I have a blacklist.txt file that contains keywords I want to remove using sed. Here's what the blacklist.txt file contain winston@linux ] $ cat blacklist.txt obscure keywords here ... And here's what I have so far, but currently doesn't work. blacklist=$(cat blacklist.txt); output="filtered_file.txt" for i in $blacklist; do cat $input | sed 's/$i//g' >> $output done

    Read the article

  • Parsing dictionary entries with regex

    - by Brandon
    I'm trying to pull data from Jim Breen's WWWJDIC. The raw data returned has a lot of information delimited in several different formats. The data pulled in the example below is from here: http://www.csse.monash.edu.au/~jwb/cgi-bin/wwwjdic.cgi?1ZUJ%E5%85%88%E7%94%9F ?? [????] /(n) (1) teacher/master/doctor/(suf) (2) with names of teachers, etc. as an honorific/(P)/ Should I use a regex?

    Read the article

  • The dictionary need to add every word in SpellingMistakes and the line number but it only adds the l

    - by Will Boomsight
    modules import sys import string Importing and reading the files form the Command Prompt Document = open(sys.argv[1],"r") Document = open('Wc.txt', 'r') Document = Document.read().lower() Dictionary = open(sys.argv[2],"r") Dictionary = open('Dict.txt', 'r') Dictionary = Dictionary.read() def Format(Infile): for ch in string.punctuation: Infile = Infile.replace(ch, "") for no in string.digits: Infile = Infile.replace(no, " ") Infile = Infile.lower() return(Infile) def Corrections(Infile, DictWords): Misspelled = set([]) Infile = Infile.split() DictWords = DictWords.splitlines() for word in Infile: if word not in DictWords: Misspelled.add(word) Misspelled = sorted(Misspelled) return (Misspelled) def Linecheck(Infile,ErrorWords): Infile = Infile.split() lineno = 0 Noset = list() for line in Infile: lineno += 1 line = line.split() for word in line: if word == ErrorWords: Noset.append(lineno) sorted(Noset) return(Noset) def addkey(error,linenum): Nodict = {} for line in linenum: Nodict.setdefault(error,[]).append(linenum) return Nodict FormatDoc = Format(Document) SpellingMistakes = Corrections(FormatDoc,Dictionary) alp = str(SpellingMistakes) for word in SpellingMistakes: nSet = str(Linecheck(FormatDoc,word)) nSet = nSet.split() linelist = addkey(word, nSet) print(linelist) # # for word in Nodict.keys(): # Nodict[word].append(line) Prints each incorrect word on a new line

    Read the article

  • Free en-GB dictionary for spell check in Silverlight

    - by Craig Shearer
    I'm trying to use the Vectorlight spell checker for Silverlight. The demo code comes with the en-US.dic file, but I'm trying to find a compatible one for British English. I have found one here but it doesn't work. The format seems similar to the en-US one, but it just doesn't work (i.e. it doesn't suggest any words).

    Read the article

  • C# dictionary and lookup add / update

    - by freddy smith
    I am sick of doing blocks of code like this for various bits of code I have: if (dict.ContainsKey[key]) { dict[key] = value; } else { dict.Add(key,value); } and for lookups (i.e. key - list of value) if (lookup.ContainsKey[key]) { lookup[key].Add(value); } else { lookup.Add(new List); lookup[key].Add(value); } Is there another collections lib or extension method I should use to do this in one line of code no matter what the key and value types are? e.g. dict.AddOrUpdate(key,value) lookup.AddOrUpdate(key,value)

    Read the article

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