Search Results

Search found 361 results on 15 pages for 'dictionaries'.

Page 12/15 | < Previous Page | 8 9 10 11 12 13 14 15  | Next Page >

  • Python alignment of assignments (style)

    - by ikaros45
    I really like following style standards, as those specified in PEP 8. I have a linter that checks it automatically, and definitely my code is much better because of that. There is just one point in PEP 8, the E251 & E221 don't feel very good. Coming from a JavaScript background, I used to align the variable assignments as following: var var1 = 1234; var2 = 54; longer_name = 'hi'; var lol = { 'that' : 65, 'those' : 87, 'other_thing' : true }; And in my humble opinion, this improves readability dramatically. Problem is, this is dis-recommended by PEP 8. With dictionaries, is not that bad because spaces are allowed after the colon: dictionary = { 'something': 98, 'some_other_thing': False } I can "live" with variable assignments without alignment, but what I don't like at all is not to be able to pass named arguments in a function call, like this: some_func(length= 40, weight= 900, lol= 'troll', useless_var= True, intelligence=None) So, what I end up doing is using a dictionary, as following: specs = { 'length': 40, 'weight': 900, 'lol': 'troll', 'useless_var': True, 'intelligence': None } some_func(**specs) or just simply some_func(**{'length': 40, 'weight': 900, 'lol': 'troll', 'useless_var': True, 'intelligence': None}) But I have the feeling this work around is just worse than ignoring the PEP 8 E251 / E221. What is the best practice?

    Read the article

  • What is a faster way of merging the values of this Python structure into a single dictionary?

    - by jcoon
    I've refactored how the merged-dictionary (all_classes) below is created, but I'm wondering if it can be more efficient. I have a dictionary of dictionaries, like this: groups_and_classes = {'group_1': {'class_A': [1, 2, 3], 'class_B': [1, 3, 5, 7], 'class_c': [1, 2], # ...many more items like this }, 'group_2': {'class_A': [11, 12, 13], 'class_C': [5, 6, 7, 8, 9] }, # ...and many more items like this } A function creates a new object from groups_and_classes like this (the function to create this is called often): all_classes = {'class_A': [1, 2, 3, 11, 12, 13], 'class_B': [1, 3, 5, 7, 9], 'class_C': [1, 2, 5, 6, 7, 8, 9] } Right now, there is a loop that does this: all_classes = {} for group in groups_and_classes.values(): for c, vals in group.iteritems(): for v in vals: if all_classes.has_key(c): if v not in all_classes[c]: all_classes[c].append(v) else: all_classes[c] = [v] So far, I changed the code to use a set instead of a list since the order of the list doesn't matter and the values need to be unique: all_classes = {} for group in groups_and_classes.values(): for c, vals in group.iteritems(): try: all_classes[c].update(set(vals)) except KeyError: all_classes[c] = set(vals) This is a little nicer, and I didn't have to convert the sets to lists because of how all_classes is used in the code. Question: Is there a more efficient way of creating all_classes (aside from building it at the same time groups_and_classes is built, and changing everywhere this function is called)?

    Read the article

  • general learning methodology

    - by momo
    just wanted to hear on the different general learning paths people embark on when learning a new language/framework. the one i currently use, which is how i learned bash and am currently learning python, is: instant hacking tutorial (very short tutorial introducing the basic syntax, variable declaration, loops, data types, etc. and how they are generally used) in depth tutorial with good programming style and slightly topic-specific (e.g. Mark Pilgrim's Dive into Python), important topics for me personally are regex methods, file IO, and ways the different data types are utilized best (i wrote a very primitive bayesian spam filter using python's dictionaries to keep track of word occurrences) spaced-repition of syntax or short recipes (i use anki, with questions like 'create dictionary with filename and filesize metadata, human-readable' or simpler ones like 'match 0 - 3 occurences of the letter M in a string', or 'return/create an iterator from two sequences') the use of spaced-repitition has been invaluable, and i credit it with the ease that i can recall/create python algorithms. however, i've recently started looking into django, and i've found that spaced-repitition, at least in my case, doesn't work very well for learning a framework, it works best with short code recipes (either that or i should start looking into more basic django framework tutorials). the problem i'm encountering is that since framework programming is not only algorithms, but actually learning the API, which can be quite complex since you have to learn all the methods, modules, the places where they are stored, and the sequence of which things have to be done. for ex. in django to start a project that deals with polls (from the django tutorial), one has to create the project, edit the settings.py file, create the polls app, edit the models.py file (which requires knowing the classes that are present in the module models), edit the urls.py file, etc. i found that my spaced-repition method didn't work very well for this type of learning, so i wanted to ask you guys what method(s) you use for learning the different frameworks/APIs.

    Read the article

  • Problem with sorting NSDictionary

    - by Stas Dmitrenko
    Hello. I need to sort a NSDictionary of dictionaries. It looks like: {//dictionary RU = "110.1"; //key and value SG = "150.2"; //key and value US = "50.3"; //key and value } Result need to be like: {//dictionary SG = "150.2"; //key and value RU = "110.1"; //key and value US = "50.3"; //key and value } I am trying this: @implementation NSMutableDictionary (sorting) -(NSMutableDictionary*)sortDictionary { NSArray *allKeys = [self allKeys]; NSMutableArray *allValues = [NSMutableArray array]; NSMutableArray *sortValues= [NSMutableArray array]; NSMutableArray *sortKeys= [NSMutableArray array]; for(int i=0;i<[[self allValues] count];i++) { [allValues addObject:[NSNumber numberWithFloat:[[[self allValues] objectAtIndex:i] floatValue]]]; } [sortValues addObjectsFromArray:allValues]; [sortKeys addObjectsFromArray:[self allKeys]]; [sortValues sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:@"floatValue" ascending:NO] autorelease]]]; for(int i=0;i<[sortValues count];i++) { [sortKeys replaceObjectAtIndex:i withObject:[allKeys objectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]]]]; [allValues replaceObjectAtIndex:[allValues indexOfObject:[sortValues objectAtIndex:i]] withObject:[NSNull null]]; } NSLog(@"%@", sortKeys); NSLog(@"%@", sortValues); NSLog(@"%@", [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]); return [NSMutableDictionary dictionaryWithObjects:sortValues forKeys:sortKeys]; } @end This is the result of NSLog: 1) { SG, RU, US } 2) { 150.2, 110.1, 50.3 } 3) { RU = "110.1"; SG = "150.2"; US = "50.3"; } Why is this happening? Can you help me with this problem?

    Read the article

  • Is my objective possible using WCF (and is it the right way to do things?)

    - by David
    I'm writing some software that modifies a Windows Server's configuration (things like MS-DNS, IIS, parts of the filesystem). My design has a server process that builds an in-memory object graph of the server configuration state and a client which requests this object graph. The server would then serialize the graph, send it to the client (presumably using WCF), the server then makes changes to this graph and sends it back to the server. The server receives the graph and proceeds to make modifications to the server. However I've learned that object-graph serialisation in WCF isn't as simple as I first thought. My objects have a hierarchy and many have parametrised-constructors and immutable properties/fields. There are also numerous collections, arrays, and dictionaries. My understanding of WCF serialisation is that it requires use of either the XmlSerializer or DataContractSerializer, but DCS places restrictions on the design of my object-graph (immutable data seems right-out, it also requires parameter-less constructors). I understand XmlSerializer lets me use my own classes provided they implement ISerializable and have the de-serializer constructor. That is fine by me. I spoke to a friend of mine about this, and he advocates going for a Data Transport Object-only route, where I'd have to maintain a separate DataContract object-graph for the transport of data and re-implement my server objects on the client. Another friend of mine said that because my service only has two operations ("GetServerConfiguration" and "PutServerConfiguration") it might be worthwhile just skipping WCF entirely and implementing my own server that uses Sockets. So my questions are: Has anyone faced a similar problem before and if so, are there better approaches? Is it wise to send an entire object graph to the client for processing? Should I instead break it down so that the client requests a part of the object graph as it needs it and sends only bits that have changed (thus reducing concurrency-related risks?)? If sending the object-graph down is the right way, is WCF the right tool? And if WCF is right, what's the best way to get WCF to serialise my object graph?

    Read the article

  • Getting unpredictable data into a tabular format

    - by Acorn
    The situation: Each page I scrape has <input> elements with a title= and a value= I don't know what is going to be on the page. I want to have all my collected data in a single table at the end, with a column for each title. So basically, I need each row of data to line up with all the others, and if a row doesn't have a certain element, then it should be blank (but there must be something there to keep the alignment). eg. First page has: {animal: cat, colour: blue, fruit: lemon, day: monday} Second page has: {animal: fish, colour: green, day: saturday} Third page has: {animal: dog, number: 10, colour: yellow, fruit: mango, day: tuesday} Then my resulting table should be: animal | number | colour | fruit | day cat | none | blue | lemon | monday fish | none | green | none | saturday dog | 10 | yellow | mango | tuesday Although it would be good to keep the order of the title value pairs, which I know dictionaries wont do. So basically, I need to generate columns from all the titles (kept in order but somehow merged together) What would be the best way of going about this without knowing all the possible titles and explicitly specifying an order for the values to be put in?

    Read the article

  • Python: Access dictionary value inside of tuple and sort quickly by dict value

    - by Aquat33nfan
    I know that wasn't clear. Here's what I'm doing specifically. I have my list of dictionaries here: dict = [{int=0, value=A}, {int=1, value=B}, ... n] and I want to take them in combinations, so I used itertools and it gave me a tuple (Well, okay it gave me a memory object that I then used enumerate on so I could loop over it and enumerate gave ma tuple): for (index, tuple) in enumerate(combinations(dict, 2)): and this is where I have my problem. I want to identify which of the two items in the combination has the bigger 'int' value and which has the smaller value and assign them to variables (I'm actually using more than 2 in the combination so I can't just say if tuple[0]['int'] tuple[1]['int'] and do the assignment because I'd have to list this out a bunch of times and that's hard to manage). I was going to assign each 'int' value to a variable, sort it in a list, index the 'int' value in the list by 1, 2, 3, 4, 5 ... etc., then go back and access the dictionary I wanted by the int value and then assign the dictionary to a variable so I knew which was bigger. But I have a big list and lists and variable assignments are resource intensive and this is taking a long time (I had only a little bit of that written and it was taking forever to run). So I was hoping someone knew a fast way to do this. I actually could list out every possible combination of assignmnets using the if/thens but it's just like 5 pages of if/thens and assignments and is hard to read and manage when I want to change it. You've probably gathered this, but I"m new at programming. thx

    Read the article

  • How to save timers with connection to OrderId?

    - by Adrian Serafin
    Hi! I have a system where clients can make orders. After making order they have 60 minutes to pay fot it before it will be deleted. On the server side when order is made i create timer and set elapsed time to 60 minutes System.Timer.Timers timer = new System.Timers.Timer(1000*60*60); timer.AutoReset = false; timer.Elapsed += HandleElapsed; timer.Start(); Because I want to be able to dispose timer if client decides to pay and I want to be able to cancel order if he doesn't I keep two Dictionaries: Dictionary<int, Timer> _orderTimer; Dictionary<Timer, int> _timerOrder; Then when client pay's I can access Timer by orderId with O(1) thanks to _orderTimer dictionary and when time elapsed I can access order with O(1) thanks to _timerOrder dictionary. My question is: Is it good aproach? Assuming that max number of rows I have to keep in dictionary in one moment will be 50000? Maybe it would be better to derive from Timer class, add property called OrderId, keep it all in List and search for order/timer using linq? Or maybe you I should do this in different way?

    Read the article

  • Efficiently Serving Dynamic Content in Google App Engine

    - by awegawef
    My app on google app engine returns content items (just text) and comments on them. It works like this (pseudo-ish code): query: get keys of latest content #query to datastore for each item in content if item_dict in memcache: use item_dict else: build_item_dict(item) #by fetching from datastore store item_dict in memcache send all item_dicts to template Sorry if the code isn't understandable. I get all of the content dictionaries and send them to the template, which uses them to create the webpage. My problem is that if the memcache has expired, for each item I want to display, I have to (1) lookup item in memcache, (2) since no memcache exists I must fetch item from the datastore, and (3) store the item in memcache. These calls build up quickly. I don't set an expire time for the entries to the memcache, so this really only happens once in the morning, but the webpage takes long enough to load (~1 sec) that the browser reports it as not existing. Regularly, my webpages take about 50ms to load. This approach works decently for frequent visits, but it has its flaws as shown above. How can I remedy this? The entries are dynamic enough that I don't think it would be in my best interest to cache my initial request. Thanks in advance

    Read the article

  • Utility of List<T>.Sort() versus List<T>.OrderBy() for a member of a custom container class

    - by ccomet
    I've found myself running back through some old 3.5 framework legacy code, and found some points where there are a whole bunch of lists and dictionaries that must be updated in a synchronized fashion. I've determined that I can make this process infinitely easier to both utilize and understand by converging these into custom container classes of new custom classes. There are some points, however, where I came to concerns with organizing the contents of these new container classes by a specific inner property. For example, sorting by the ID number property of one class. As the container classes are primarily based around a generic List object, my first instinct was to write the inner classes with IComparable, and write the CompareTo method that compares the properties. This way, I can just call items.Sort() when I want to invoke the sorting. However, I've been thinking instead about using items = items.OrderBy(Func) instead. This way it is more flexible if I need to sort by any other property. Readability is better as well, since the property used for sorting will be listed in-line with the sort call rather than having to look up the IComparable code. The overall implementation feels cleaner as a result. I don't care for premature or micro optimization, but I like consistency. I find it best to stick with one kind of implementation for as many cases as it is appropriate, and use different implementations where it is necessary. Is it worth it to convert my code to use the LINQ OrderBy instead of using List.Sort? Is it a better practice to stick with the IComparable implementation for these custom containers? Are there any significant mechanical advantages offered by either path that I should be weighing the decision on? Or is their end-functionality equivalent to the point that it just becomes coder's preference?

    Read the article

  • Is it possible to create a python iterator over pre-defined mutable data?

    - by Wilduck
    I might be doing this wrong, if I am, let me know, but I'm curious if the following is possible: I have a class that holds a number of dictionaries, each of which pairs names to a different set of objects of a given class. For example: items = {"ball" : ItemInstance1, "sword" : ItemInstance2} people = {"Jerry" : PersonInstance1, "Bob" : PersonInstance2, "Jill" : PersonInstance3} My class would then hold the current items and people that are availible, and these would be subject to change as the state changes: Class State: def __init__(self, items, people): self.items = items self.people = people I would like to define a iter() and next() method such that it iterates through all of the values in its attributes. My first question is whether or not this is possible. If it is, will it be able to support a situation as follows: I define items and people as above then: state = State(items, people) for names, thing in state: print name + " is " + thing.color items[cheese] = ItemInstance3 for names, thing in state: print name + " weighs " + thing.weight While I feel like this would be usefull in the code I have, I don't know if it's either possible or the right approach. Everything I've read about user defined iterators has suggested that each instance of them is one use only.

    Read the article

  • Obj-C: Passing pointers to initialized classes in other classes

    - by FnGreg7
    Hey all. I initialized a class in my singleton called DataModel. Now, from my UIViewController, when I click a button, I have a method that is trying to access that class so that I may add an object to one of its dictionaries. My get/set method passes back the pointer to the class from my singleton, but when I am back in my UIViewController, the class passed back doesn't respond to methods. It's like it's just not there. I think it has something to do with the difference in passing pointers around classes or something. I even tried using the copy method to throw a copy back, but no luck. UIViewController: ApplicationSingleton *applicationSingleton = [[ApplicationSingleton alloc] init]; DataModel *dataModel = [applicationSingleton getDataModel]; [dataModel retrieveDataCategory:dataCategory]; Singleton: ApplicationSingleton *m_instance; DataModel *m_dataModel; - (id) init { NSLog(@"ApplicationSingleton.m initialized."); self = [super init]; if(self != nil) { if(m_instance != nil) { return m_instance; } NSLog(@"Initializing the application singleton."); m_instance = self; m_dataModel = [[DataModel alloc] init]; } NSLog(@"ApplicationSingleton init method returning."); return m_instance; } -(DataModel *)getDataModel { DataModel *dataModel_COPY = [m_dataModel copy]; return dataModel_COPY; } For the getDataModel method, I also tried this: -(DataModel *)getDataModel { return m_dataModel; } In my DataModel retrieveDataCategory method, I couldn't get anything to work. I even just tried putting a NSLog in there but it never would come onto the console. Any ideas?

    Read the article

  • How do I alter the default style of a button without WPF reverting from Aero to Classic?

    - by DanM
    I've added PresentationFramework.Aero to my App.xaml merged dictionaries, as in... <Application x:Class="TestApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/PresentationFramework.Aero;component/themes/Aero.NormalColor.xaml" /> <ResourceDictionary Source="pack://application:,,,/WPFToolkit;component/Themes/Aero.NormalColor.xaml" /> <ResourceDictionary Source="ButtonResourceDictionary.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application> I'm trying to modify the default look of buttons just slightly. I put this style in my ButtonResourceDictionary: <Style TargetType="Button"> <Setter Property="Padding" Value="3" /> <Setter Property="FontWeight" Value="Bold" /> </Style> All buttons now have the correct padding and bold text, but they look "Classic", not "Aero". How do I fix this style so my buttons all look Aero but also have these minor changes? I would prefer not to have to set the Style property for every button.

    Read the article

  • Refactoring code/consolidating functions (e.g. nested for-loop order)

    - by bmay2
    Just a little background: I'm making a program where a user inputs a skeleton text, two numbers (lower and upper limit), and a list of words. The outputs are a series of modifications on the skeleton text. Sample inputs: text = "Player # likes @." (replace # with inputted integers and @ with words in list) lower = 1 upper = 3 list = "apples, bananas, oranges" The user can choose to iterate over numbers first: Player 1 likes apples. Player 2 likes apples. Player 3 likes apples. Or words first: Player 1 likes apples. Player 1 likes bananas. Player 1 likes oranges. I chose to split these two methods of outputs by creating a different type of dictionary based on either number keys (integers inputted by the user) or word keys (from words in the inputted list) and then later iterating over the values in the dictionary. Here are the two types of dictionary creation: def numkey(dict): # {1: ['Player 1 likes apples', 'Player 1 likes...' ] } text, lower, upper, list = input_sort(dict) d = {} for num in range(lower,upper+1): l = [] for i in list: l.append(text.replace('#', str(num)).replace('@', i)) d[num] = l return d def wordkey(dict): # {'apples': ['Player 1 likes apples', 'Player 2 likes apples'..] } text, lower, upper, list = input_sort(dict) d = {} for i in list: l = [] for num in range(lower,upper+1): l.append(text.replace('#', str(num)).replace('@', i)) d[i] = l return d It's fine that I have two separate functions for creating different types of dictionaries but I see a lot of repetition between the two. Is there any way I could make one dictionary function and pass in different values to it that would change the order of the nested for loops to create the specific {key : value} pairs I'm looking for? I'm not sure how this would be done. Is there anything related to functional programming or other paradigms that might help with this? The question is a little abstract and more stylistic/design-oriented than anything.

    Read the article

  • I don't like Python functions that take two or more iterables. Is it a good idea?

    - by Xavier Ho
    This question came from looking at this question on Stackoverflow. def fringe8((px, py), (x1, y1, x2, y2)): Personally, it's been one of my pet peeves to see a function that takes two arguments with fixed-number iterables (like a tuple) or two or more dictionaries (Like in the Shotgun API). It's just hard to use, because of all the verbosity and double-bracketed enclosures. Wouldn't this be better: >>> class Point(object): ... def __init__(self, x, y): ... self.x = x ... self.y = y ... >>> class Rect(object): ... def __init__(self, x1, y1, x2, y2): ... self.x1 = x1 ... self.y1 = y1 ... self.x2 = x2 ... self.y2 = y2 ... >>> def fringe8(point, rect): ... # ... ... >>> >>> point = Point(2, 2) >>> rect = Rect(1, 1, 3, 3) >>> >>> fringe8(point, rect) Is there a situation where taking two or more iterable arguments is justified? Obviously the standard itertools Python library needs that, but I can't see it being pretty in maintainable, flexible code design.

    Read the article

  • Optimization of Function with Dictionary and Zip()

    - by eWizardII
    Hello, I have the following function: def filetxt(): word_freq = {} lvl1 = [] lvl2 = [] total_t = 0 users = 0 text = [] for l in range(0,500): # Open File if os.path.exists("C:/Twitter/json/user_" + str(l) + ".json") == True: with open("C:/Twitter/json/user_" + str(l) + ".json", "r") as f: text_f = json.load(f) users = users + 1 for i in range(len(text_f)): text.append(text_f[str(i)]['text']) total_t = total_t + 1 else: pass # Filter occ = 0 import string for i in range(len(text)): s = text[i] # Sample string a = re.findall(r'(RT)',s) b = re.findall(r'(@)',s) occ = len(a) + len(b) + occ s = s.encode('utf-8') out = s.translate(string.maketrans("",""), string.punctuation) # Create Wordlist/Dictionary word_list = text[i].lower().split(None) for word in word_list: word_freq[word] = word_freq.get(word, 0) + 1 keys = word_freq.keys() numbo = range(1,len(keys)+1) WList = ', '.join(keys) NList = str(numbo).strip('[]') WList = WList.split(", ") NList = NList.split(", ") W2N = dict(zip(WList, NList)) for k in range (0,len(word_list)): word_list[k] = W2N[word_list[k]] for i in range (0,len(word_list)-1): lvl1.append(word_list[i]) lvl2.append(word_list[i+1]) I have used the profiler to find that it seems the greatest CPU time is spent on the zip() function and the join and split parts of the code, I'm looking to see if there is any way I have overlooked that I could potentially clean up the code to make it more optimized, since the greatest lag seems to be in how I am working with the dictionaries and the zip() function. Any help would be appreciated thanks!

    Read the article

  • In what order should the Python concepts be explained to absolute beginners?

    - by Tomaž Pisanski
    I am teaching Python to undergraduate math majors. I am interested in the optimal order in which students should be introduced to various Python concepts. In my view, at each stage the students should be able to solve a non-trivial programming problem using only the tools available at that time. Each new tool should enable a simpler solution to a familiar problem. A selection of numerous concepts available in Python is essential in order to keep students focused. They should also motivated and should appreciate each newly mastered tool without too much memorization. Here are some specific questions: For instance, my predecessor introduced lists before strings. I think the opposite is a better solution. Should function definitions be introduced at the very beginning or after mastering basic structured programming ideas, such as decisions (if) and loops (while)? Should sets be introduced before dictionaries? Is it better to introduce reading and writing files early in the course or should one use input and print for most of the course? Any suggestions with explanations are most welcome.

    Read the article

  • How to specify generic method type parameters partly

    - by DNNX
    I have an extension method like below: public static T GetValueAs<T, R>(this IDictionary<string, R> dictionary, string fieldName) where T : R { R value; if (!dictionary.TryGetValue(fieldName, out value)) return default(T); return (T)value; } Currently, I can use it in the following way: var dictionary = new Dictionary<string, object(); //... var list = dictionary.GetValueAs<List<int, object("A"); // this may throw ClassCastException - this is expected behavior; It works pretty fine, but the second type parameter is really annoying. Is it possible in C# 4.0 rewrite GetValueAs is such a way that the method will still be applicable to different types of string-keyed dictionaries AND there will be no need to specify second type parameter in the calling code, i.e. use var list = dictionary.GetValueAs<List<int("A"); or at least something like var list = dictionary.GetValueAs<List<int, ?("A"); instead of var list = dictionary.GetValueAs<List<int, object("A");

    Read the article

  • Core Data object into an NSDictionary with possible nil objects

    - by Chuck
    I have a core data object that has a bunch of optional values. I'm pushing a table view controller and passing it a reference to the object so I can display its contents in a table view. Because I want the table view displayed a specific way, I am storing the values from the core data object into an array of dictionaries then using the array to populate the table view. This works great, and I got editing and saving working properly. (i'm not using a fetched results controller because I don't have anything to sort on) The issue with my current code is that if one of the items in the object is missing, then I end up trying to put nil into the dictionary, which won't work. I'm looking for a clean way to handle this, I could do the following, but I can't help but feeling like there's a better way. *passedEntry is the core data object handed to the view controller when it is pushed, lets say it contains firstName, lastName, and age, all optional. if ([passedEntry firstName] != nil) { [dictionary setObject:[passedEntry firstName] forKey:@"firstName"] } else { [dictionary setObject:@"" forKey:@"firstName"] } And so on. This works, but it feels kludgy, especially if I end up adding more items to the core data object down the road.

    Read the article

  • How to force VS to react on a changing of an attached property in design time?

    - by sedovav
    Imagine, we have a wpf class library with a window1.xaml and a resource dictionary res.xaml defined in it. I know how to use styles that defined in the res.xaml for the controls that defined into the window: <Window x:Class="...Window1"> <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="res.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> <\Window.Resources> </Window> So we can use the dictionary's styles for all elements into the window (except the window element... I don't know how to set the style from the res.xaml for the window :( ). I saw the article where describes how to create and use attached property to add resource dictionaries to a FrameworkElement.Resources.MergedDictionaries list. It's good! We can do the same as we done in the example above but we can use the window style now. It looks like this: <Window x:Class="...Window1" xmlns: resources="..." resources:SharedResources.MergedDictionaries="res.xaml"> </Window> That's good but VS2008 cannot recognize resources from res.xaml in design time. So we have a sad situation: all styles from res.xaml are available in run-time but in the design-time VS cannot display the window (it can't find the mentioned styles). Does anybody know how to fix this situation?

    Read the article

  • What is the fastest (to access) struct-like object in Python?

    - by DNS
    I'm optimizing some code whose main bottleneck is running through and accessing a very large list of struct-like objects. Currently I'm using namedtuples, for readability. But some quick benchmarking using 'timeit' shows that this is really the wrong way to go where performance is a factor: Named tuple with a, b, c: >>> timeit("z = a.c", "from __main__ import a") 0.38655471766332994 Class using __slots__, with a, b, c: >>> timeit("z = b.c", "from __main__ import b") 0.14527461047146062 Dictionary with keys a, b, c: >>> timeit("z = c['c']", "from __main__ import c") 0.11588272541098377 Tuple with three values, using a constant key: >>> timeit("z = d[2]", "from __main__ import d") 0.11106188992948773 List with three values, using a constant key: >>> timeit("z = e[2]", "from __main__ import e") 0.086038238242508669 Tuple with three values, using a local key: >>> timeit("z = d[key]", "from __main__ import d, key") 0.11187358437882722 List with three values, using a local key: >>> timeit("z = e[key]", "from __main__ import e, key") 0.088604143037173344 First of all, is there anything about these little timeit tests that would render them invalid? I ran each several times, to make sure no random system event had thrown them off, and the results were almost identical. It would appear that dictionaries offer the best balance between performance and readability, with classes coming in second. This is unfortunate, since, for my purposes, I also need the object to be sequence-like; hence my choice of namedtuple. Lists are substantially faster, but constant keys are unmaintainable; I'd have to create a bunch of index-constants, i.e. KEY_1 = 1, KEY_2 = 2, etc. which is also not ideal. Am I stuck with these choices, or is there an alternative that I've missed?

    Read the article

  • Uitableview not able to hold data

    - by pankaj
    Hi i have a uitableview, i am displaying some data of about 200 rows in it. Data will be displayed in several sections which will be determined at run time. I am able to get sections but i am not able to display data for a particular section in correct order. I have data in the form of dictionaries in an array. My Code: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { TeraGoAppDelegate *appDel = (TeraGoAppDelegate *)[[UIApplication sharedApplication] delegate]; UITableViewCell *cell = nil; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease]; cell.textLabel.text = [(NSMutableDictionary *)[appDel.arrEqp objectAtIndex:countEqpIndex] objectForKey:@"EQP_NAME"]; cell.textLabel.font = [UIFont fontWithName:@"Arial" size:14]; if(![[(NSMutableDictionary *)[appDel.arrEqp objectAtIndex:indexPath.row] objectForKey:@"select"] isEqualToString:@"0"]) { cell.accessoryType = UITableViewCellAccessoryCheckmark; } else cell.accessoryType = UITableViewCellAccessoryNone; } // Set up the cell... return cell; } I am trying to use indexPath.row but its values initialises from 0 in every section I can not get data from array in this case as i dont have index of array to get data. How will i get the index of array whose values i need to display????

    Read the article

  • Pickled my dictionary from ZODB but i got a less in size one?

    - by Someone Someoneelse
    I use ZODB and i want to copy my 'database_1.fs' file to another 'database_2.fs', so I opened the root dictionary of that 'database_1.fs' and I (pickle.dump) it in a text file. Then I (pickle.load) it in a dictionary-variable, in the end I update the root dictionary of the other 'database_2.fs' with the dictionary-variable. It works, but I wonder why the size of the 'database_1.fs' not equal to the size of the other 'database_2.fs'. They are still copies of each other. def openstorage(store): #opens the database data={} data['file']=filestorage data['db']=DB(data['file']) data['conn']=data['db'].open() data['root']=data['conn'].root() return data def getroot(dicty): return dicty['root'] def closestorage(dicty): #close the database after Saving transaction.commit() dicty['file'].close() dicty['db'].close() dicty['conn'].close() transaction.get().abort() then that's what i do:- import pickle loc1='G:\\database_1.fs' op1=openstorage(loc1) root1=getroot(op1) loc2='G:database_2.fs' op2=openstorage(loc2) root2=getroot(op2) >>> len(root1) 215 >>> len(root2) 0 pickle.dump( root1, open( "save.txt", "wb" )) item=pickle.load( open( "save.txt", "rb" ) ) #now item is a dictionary root2.update(item) closestorage(op1) closestorage(op2) #after I open both of the databases #I get the same keys in both databases #But `database_2.fs` is smaller that `database_2.fs` in size I mean. >>> len(root2)==len(root1)==215 #they have the same keys True Note: (1) there are persistent dictionaries and lists in the original database_1.fs (2) both of them have the same length and the same indexes.

    Read the article

  • Create SQL parameters programmatically

    - by Neo
    Another annoying one for me but probably something simple. I have a number of possible where clauses for a query based on user input, my question is how can I add these programmatically? For instance: wherequery = @"WHERE fieldname = @p_FieldName AND "; if (txtValue.textLength > 0){ wherequery += "fieldname2 = @p_FieldName2 AND "; } query = @"SELECT * FROM tabe" + wherequery; sql = connection.CreateCommand(); sql.CommandText = query; How would I go about doing the parameters for that? I've tried ArrayLists, Dictionaries and a few other methods but can't find a way of doing it. Ideally I'd want to do something like this: SqlParameter[] sqlparams; wherequery = @"WHERE fieldname = @p_FieldName AND "; if (txtValue.textLength > 0){ wherequery += "fieldname2 = @p_FieldName2 AND "; sqlparams.Parameters.Add("@p_FieldName2 ", SqlDbType.VarChar).Value = txtValue.text; } query = @"SELECT * FROM tabe" + wherequery; sql = connection.CreateCommand(); sql.CommandText = query; sql.Parameters.Add(sqlparams);

    Read the article

  • Empty value when iterating a dictionary with .iteritems() method

    - by ptpatil
    I am having some weird trouble with dictionaries, I am trying to iterate pairs from a dictionary to pass to another function. The loop for the iterator though for some reason always returns empty values. Here is the code: def LinktoCentral(self, linkmethod): if linkmethod == 'sim': linkworker = Linker.SimilarityLinker() matchlist = [] for k,v in self.ToBeMatchedTable.iteritems(): matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) Now if I insert a print line above the for loop: matchlist = [] print self.ToBeMatchedTable.items() for k,v in self.ToBeMatchedTable.iteritems(): matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) I get the data that is supposed to be in the dictionary printed out. The values of the dictionary are list objects. An example tuple I get from the dictionary when printing just above the for loop: >>> (1, ['AARP/United Health Care', '8002277789', 'PO Box 740819', 'Atlanta', 'GA', '30374-0819', 'Paper', '3676']) However, the for loop gives empty lists to the linkworker.GetBestMatch method. If I put a print line just below the for loop, here is what I get: Code: matchlist = [] for k,v in self.ToBeMatchedTable.iteritems(): print self.ToBeMatchedTable.items() matchlist.append(k, linkworker.GetBestMatch(v, self.CentralDataTable.items())) ## Place holder for line to send match list to display window return matchlist Result of first iteration: >>> (0, ['', '', '', '', '', '', '', '']) I literally have no idea whats going on, there is nothing else going on while this loop is executed. Any stupid mistakes I made?

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15  | Next Page >