Search Results

Search found 68 results on 3 pages for 'keyerror'.

Page 2/3 | < Previous Page | 1 2 3  | Next Page >

  • Unable to locate package lightread

    - by TENG PENG
    I have changed my source to local server. I'm using Ubuntu 12.10. When I type apt-cache search in terminal, it shows nothing. When I install lightread it shows Unable to locate package lightread. When I install lightread manually by python. It shows python '/home/peng/Downloads/quickly_trunk/setup.py' Traceback (most recent call last): File "/home/peng/Downloads/quickly_trunk/setup.py", line 93, in <module> data_files=[('share/icons/hicolor/128x128/apps', ['data/media/lightread.png'])] File "/usr/lib/python2.7/dist-packages/DistUtilsExtra/auto.py", line 71, in setup src_mark(src, 'setup.py') File "/usr/lib/python2.7/dist-packages/DistUtilsExtra/auto.py", line 527, in src_mark src.remove(path) KeyError: 'setup.py' How to solve the problem?

    Read the article

  • *UPDATED* help with django and accented characters?

    - by Asinox
    Hi guys, i have a problem with my accented characters, Django admin save my data without encoding to something like "&aacute;" Example: if im trying a word like " Canción ", i would like to save in this way: Canci&oacute;n, and not Canción. im usign Sociable app: {% load sociable_tags %} {% get_sociable Facebook TwitThis Google MySpace del.icio.us YahooBuzz Live as sociable_links with url=object.get_absolute_url title=object.titulo %} {% for link in sociable_links %} <a href="{{ link.link }}"><img alt="{{ link.site }}" title="{{ link.site }}" src="{{ link.image }}" /></a> {% endfor %} But im getting error if my object.titulo (title of the article) have a accented word. aught KeyError while rendering: u'\xfa' Any idea ? i had in my SETTING: DEFAULT_CHARSET = 'utf-8' i had in my mysql database: utf8_general_ci COMPLETED ERROR: Traceback: File "C:\wamp\bin\Python26\lib\site-packages\django\core\handlers\base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\views\generic\date_based.py" in object_detail 366. response = HttpResponse(t.render(c), mimetype=mimetype) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 173. return self._render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in _render 167. return self.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\loader_tags.py" in render 125. return compiled_parent._render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in _render 167. return self.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\loader_tags.py" in render 62. result = block.nodelist.render(context) File "C:\wamp\bin\Python26\lib\site-packages\django\template\__init__.py" in render 796. bits.append(self.render_node(node, context)) File "C:\wamp\bin\Python26\lib\site-packages\django\template\debug.py" in render_node 72. result = node.render(context) File "C:\wamp\bin\Python26\lib\site-packages\sociable\templatetags\sociable_tags.py" in render 37. 'link': sociable.genlink(site, **self.values), File "C:\wamp\bin\Python26\lib\site-packages\sociable\sociable.py" in genlink 20. values['title'] = quote_plus(kwargs['title']) File "C:\wamp\bin\Python26\lib\urllib.py" in quote_plus 1228. s = quote(s, safe + ' ') File "C:\wamp\bin\Python26\lib\urllib.py" in quote 1222. res = map(safe_map.__getitem__, s) Exception Type: TemplateSyntaxError at /noticia/2010/jun/10/matan-domingo-paquete-en-la-avenida-san-vicente-de-paul/ Exception Value: Caught KeyError while rendering: u'\xfa' thanks, sorry with my English

    Read the article

  • Get client ip with python

    - by Elad
    Hi, I'm a newbie in python. I want to write a simple web that prints the client ip on screen my http.conf Handler: AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On The cgi.escape(os.environ["REMOTE_ADDR"]) return this error: KeyError: 'REMOTE_ADDR' and I just get lost with the BaseHTTPRequestHandler so what is the simple way to get the client ip? thank you.

    Read the article

  • List of Django model instance foreign keys losing consistency during state changes.

    - by Joshua
    I have model, Match, with two foreign keys: class Match(model.Model): winner = models.ForeignKey(Player) loser = models.ForeignKey(Player) When I loop over Match I find that each model instance uses a unique object for the foreign key. This ends up biting me because it introduces inconsistency, here is an example: >>> def print_elo(match_list): ... for match in match_list: ... print match.winner.id, match.winner.elo ... print match.loser.id, match.loser.elo ... >>> print_elo(teacher_match_list) 4 1192.0000000000 2 1192.0000000000 5 1208.0000000000 2 1192.0000000000 5 1208.0000000000 4 1192.0000000000 >>> teacher_match_list[0].winner.elo = 3000 >>> print_elo(teacher_match_list) 4 3000 # Object 4 2 1192.0000000000 5 1208.0000000000 2 1192.0000000000 5 1208.0000000000 4 1192.0000000000 # Object 4 >>> I solved this problem like so: def unify_refrences(match_list): """Makes each unique refrence to a model instance non-unique. In cases where multiple model instances are being used django creates a new object for each model instance, even if it that means creating the same instance twice. If one of these objects has its state changed any other object refrencing the same model instance will not be updated. This method ensure that state changes are seen. It makes sure that variables which hold objects pointing to the same model all hold the same object. Visually this means that a list of [var1, var2] whose internals look like so: var1 --> object1 --> model1 var2 --> object2 --> model1 Will result in the internals being changed so that: var1 --> object1 --> model1 var2 ------^ """ match_dict = {} for match in match_list: try: match.winner = match_dict[match.winner.id] except KeyError: match_dict[match.winner.id] = match.winner try: match.loser = match_dict[match.loser.id] except KeyError: match_dict[match.loser.id] = match.loser My question: Is there a way to solve the problem more elegantly through the use of QuerySets without needing to call save at any point? If not, I'd like to make the solution more generic: how can you get a list of the foreign keys on a model instance or do you have a better generic solution to my problem? Please correct me if you think I don't understand why this is happening.

    Read the article

  • insert multiple elements in string in python

    - by Anurag Sharma
    I have to build a string like this { name: "john", url: "www.dkd.com", email: "[email protected]" } where john, www.dkd.com and [email protected] are to be supplied by variables I tried to do the following s1 = "{'name:' {0},'url:' {1},'emailid:' {2}}" s1.format("john","www.dkd.com","[email protected]") I am getting the following error Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: "'name" Dont able to understand what I am doing wrong

    Read the article

  • add a decorate function to a class

    - by wiso
    I have a decorated function (simplified version): class Memoize: def __init__(self, function): self.function = function self.memoized = {} def __call__(self, *args, **kwds): hash = args try: return self.memoized[hash] except KeyError: self.memoized[hash] = self.function(*args) return self.memoized[hash] @Memoize def _DrawPlot(self, options): do something... now I want to add this method to a pre-esisting class. ROOT.TChain.DrawPlot = _DrawPlot when I call this method: chain = TChain() chain.DrawPlot(opts) I got: self.memoized[hash] = self.function(*args) TypeError: _DrawPlot() takes exactly 2 arguments (1 given) why doesn't it propagate self?

    Read the article

  • Optimizing a memoization decorator not increase call stack

    - by Tyler Crompton
    I have a very, very basic memoization decorator that I need to optimize below: def memoize(function): memos = {} def wrapper(*args): try: return memos[args] except KeyError: pass result = function(*args) memos[args] = result return result return wrapper The goal is to make this so that it doesn't add on to the call stack. It actually doubles it right now. I realize that I can embed this on a function by function basis, but that is not desired as I would like a global solution for memoizing. Any ideas?

    Read the article

  • Python script to remove all comments from XML file

    - by Jennifer Greentree
    I am trying to build a python script that will take in an XML document and remove all of the comment blocks from it. I tried something along the lines of: tree = ElementTree() tree.parse(file) commentElements = tree.findall('//comment()') for element in commentElements: element.parentNode.remove(element) Doing this yields a weird error from python: "KeyError: '()' I know there are ways to easily edit the file using other methods ( like sed ), but I have to do it in a python script.

    Read the article

  • Which style of return is "better" for a method that might return None?

    - by Daenyth
    I have a method that will either return an object or None if the lookup fails. Which style of the following is better? def get_foo(needle): haystack = object_dict() if needle not in haystack: return None return haystack[needle] or, def get_foo(needle): haystack = object_dict() try: return haystack[needle] except KeyError: # Needle not found return None I'm undecided as to which is more more desirable myself. Another choice would be return haystack[needle] if needle in haystack else None, but I'm not sure that's any better.

    Read the article

  • Python: if key in dict vs. try/except

    - by LeeMobile
    I have a question about idioms and readability, and there seems to be a clash of Python philosophies for this particular case: I want to build dictionary A from dictionary B. If a specific key does not exist in B, then do nothing and continue on. Which way is better? try: A["blah"] = B["blah"] except KeyError: pass or if "blah" in B: A["blah"] = B["blah"] "Do and ask for forgiveness" vs. "simplicity and explicitness". Which is better and why?

    Read the article

  • Http.Request and cookies Python

    - by Kyle
    I am trying to retrieve source code from a webpage with an already issued cookie and write the source code to a txt file. If I remove the cookies=cookie portion I can retrieve the source code but I need to somehow send the cookie with the http.request. output = open('Filler.txt', 'w+') http = urllib3.PoolManager() cookie =('users' , '1597413515') r = http.request('http://google.com' , 'GET' , cookies=cookie) output.write(r.data) output.close() I get a KeyError: None

    Read the article

  • Kickstart Partitioning Configuration

    - by Flo
    I'be been trying to run a kickstart script with the following partition configuration: #Clear the masterboot record zerombr bootloader --location=mbr --driveorder=sda --append=" rhgb crashkernel=auto quiet" # Set up the partitions/logical volumes/logical groups clearpart --all part /boot --fstype=ext4 --asprimary --size=512 --ondisk=sda part swap --size=2048 --fstype=swap --ondisk=sda part pv.01 --fstype=ext4 --grow --size=200 --ondisk=sda part pv.02 --fstype=ext4 --grow --size=200 --ondisk=sdb volgroup VolGroup pv.01 pv.02 --pesize=32768 logvol /opt --fstype=ext4 --name=opt.fs --vgname=VolGroup --size=40000 logvol / --fstype=ext4 --name=root.fs --vgname=VolGroup --size=78000 I have two hard drives and it looks to me like its a really simple configuration. When I run the kickstart I keep getting all these errors that have to do with python files for configuring partitions. The only actual maybe useful piece of information is KeyError /dev/sda/ I tried a number of alterations of this configuration but nothing really worked. Any ideas?

    Read the article

  • Python dictionary key missing

    - by Greg K
    I thought I'd put together a quick script to consolidate the CSS rules I have distributed across multiple CSS files, then I can minify it. I'm new to Python but figured this would be a good exercise to try a new language. My main loop isn't parsing the CSS as I thought it would. I populate a list with selectors parsed from the CSS files to return the CSS rules in order. Later in the script, the list contains an element that is not found in the dictionary. for line in self.file.readlines(): if self.hasSelector(line): selector = self.getSelector(line) if selector not in self.order: self.order.append(selector) elif selector and self.hasProperty(line): # rules.setdefault(selector,[]).append(self.getProperty(line)) property = self.getProperty(line) properties = [] if selector not in rules else rules[selector] if property not in properties: properties.append(property) rules[selector] = properties # print "%s :: %s" % (selector, "".join(rules[selector])) return rules Error encountered: $ css-combine combined.css test1.css test2.css Traceback (most recent call last): File "css-combine", line 108, in <module> c.run(outfile, stylesheets) File "css-combine", line 64, in run [(selector, rules[selector]) for selector in parser.order], KeyError: 'p' Swap the inputs: $ css-combine combined.css test2.css test1.css Traceback (most recent call last): File "css-combine", line 108, in <module> c.run(outfile, stylesheets) File "css-combine", line 64, in run [(selector, rules[selector]) for selector in parser.order], KeyError: '#header_.title' I've done some quirky things in the code like sub spaces for underscores in dictionary key names in case it was an issue - maybe this is a benign precaution? Depending on the order of the inputs, a different key cannot be found in the dictionary. The script: #!/usr/bin/env python import optparse import re class CssParser: def __init__(self): self.file = False self.order = [] # store rules assignment order def parse(self, rules = {}): if self.file == False: raise IOError("No file to parse") selector = False for line in self.file.readlines(): if self.hasSelector(line): selector = self.getSelector(line) if selector not in self.order: self.order.append(selector) elif selector and self.hasProperty(line): # rules.setdefault(selector,[]).append(self.getProperty(line)) property = self.getProperty(line) properties = [] if selector not in rules else rules[selector] if property not in properties: properties.append(property) rules[selector] = properties # print "%s :: %s" % (selector, "".join(rules[selector])) return rules def hasSelector(self, line): return True if re.search("^([#a-z,\.:\s]+){", line) else False def getSelector(self, line): s = re.search("^([#a-z,:\.\s]+){", line).group(1) return "_".join(s.strip().split()) def hasProperty(self, line): return True if re.search("^\s?[a-z-]+:[^;]+;", line) else False def getProperty(self, line): return re.search("([a-z-]+:[^;]+;)", line).group(1) class Consolidator: """Class to consolidate CSS rule attributes""" def run(self, outfile, files): parser = CssParser() rules = {} for file in files: try: parser.file = open(file) rules = parser.parse(rules) except IOError: print "Cannot read file: " + file finally: parser.file.close() self.serialize( [(selector, rules[selector]) for selector in parser.order], outfile ) def serialize(self, rules, outfile): try: f = open(outfile, "w") for rule in rules: f.write( "%s {\n\t%s\n}\n\n" % ( " ".join(rule[0].split("_")), "\n\t".join(rule[1]) ) ) except IOError: print "Cannot write output to: " + outfile finally: f.close() def init(): op = optparse.OptionParser( usage="Usage: %prog [options] <output file> <stylesheet1> " + "<stylesheet2> ... <stylesheetN>", description="Combine CSS rules spread across multiple " + "stylesheets into a single file" ) opts, args = op.parse_args() if len(args) < 3: if len(args) == 1: print "Error: No input files specified.\n" elif len(args) == 2: print "Error: One input file specified, nothing to combine.\n" op.print_help(); exit(-1) return [opts, args] if __name__ == '__main__': opts, args = init() outfile, stylesheets = [args[0], args[1:]] c = Consolidator() c.run(outfile, stylesheets) Test CSS file 1: body { background-color: #e7e7e7; } p { margin: 1em 0em; } File 2: body { font-size: 16px; } #header .title { font-family: Tahoma, Geneva, sans-serif; font-size: 1.9em; } #header .title a, #header .title a:hover { color: #f5f5f5; border-bottom: none; text-shadow: 2px 2px 3px rgba(0, 0, 0, 1); } Thanks in advance.

    Read the article

  • Unit testing authorization in a Pylons app fails; cookies aren't been correctly set or recorded

    - by Ian Stevens
    I'm having an issue running unit tests for authorization in a Pylons app. It appears as though certain cookies set in the test case may not be correctly written or parsed. Cookies work fine when hitting the app with a browser. Here is my test case inside a paste-generated TestController: def test_good_login(self): r = self.app.post('/dologin', params={'login': self.user['username'], 'password': self.password}) r = r.follow() # Should only be one redirect to root assert 'http://localhost/' == r.request.url assert 'Dashboard' in r This is supposed to test that a login of an existing account forwards the user to the dashboard page. Instead, what happens is that the user is redirected back to the login. The first POST works, sets the user in the session and returns cookies. Although those cookies are sent in the follow request, they don't seem to be correctly parsed. I start by setting a breakpoint at the beginning of the above method and see what the login response returns: > nosetests --pdb --pdb-failure -s foo.tests.functional.test_account:TestMainController.test_good_login Running setup_config() from foo.websetup > /Users/istevens/dev/foo/foo/tests/functional/test_account.py(33)test_good_login() -> r = self.app.post('/dologin', params={'login': self.user['username'], 'password': self.password}) (Pdb) n > /Users/istevens/dev/foo/foo/tests/functional/test_account.py(34)test_good_login() -> r = r.follow() # Should only be one redirect to root (Pdb) p r.cookies_set {'auth_tkt': '"4c898eb72f7ad38551eb11e1936303374bd871934bd871833d19ad8a79000000!"'} (Pdb) p r.request.environ['REMOTE_USER'] '4bd871833d19ad8a79000000' (Pdb) p r.headers['Location'] 'http://localhost/?__logins=0' A session appears to be created and a cookie sent back. The browser is redirected to the root, not the login, which also indicates a successful login. If I step past the follow(), I get: > /Users/istevens/dev/foo/foo/tests/functional/test_account.py(35)test_good_login() -> assert 'http://localhost/' == r.request.url (Pdb) p r.request.headers {'Host': 'localhost:80', 'Cookie': 'auth_tkt=""\\"4c898eb72f7ad38551eb11e1936303374bd871934bd871833d19ad8a79000000!\\"""; '} (Pdb) p r.request.environ['REMOTE_USER'] *** KeyError: KeyError('REMOTE_USER',) (Pdb) p r.request.environ['HTTP_COOKIE'] 'auth_tkt=""\\"4c898eb72f7ad38551eb11e1936303374bd871934bd871833d19ad8a79000000!\\"""; ' (Pdb) p r.request.cookies {'auth_tkt': ''} (Pdb) p r <302 Found text/html location: http://localhost/login?__logins=1&came_from=http%3A%2F%2Flocalhost%2F body='302 Found...y. '/149> This indicates to me that the cookie was passed in on the request, although with dubious escaping. The environ appears to be without the session created on the prior request. The cookie has been copied to the environ from the headers, but the cookies in the request seems incorrectly set. Lastly, the user is redirected to the login page, indicating that the user isn't logged in. Authorization in the app is done via repoze.who and repoze.who.plugins.ldap with repoze.who_friendlyform performing the challenge. I'm using the stock tests.TestController created by paste: class TestController(TestCase): def __init__(self, *args, **kwargs): if pylons.test.pylonsapp: wsgiapp = pylons.test.pylonsapp else: wsgiapp = loadapp('config:%s' % config['__file__']) self.app = TestApp(wsgiapp) url._push_object(URLGenerator(config['routes.map'], environ)) TestCase.__init__(self, *args, **kwargs) That's a webtest.TestApp, by the way. The encoding of the cookie is done in webtest.TestApp using Cookie: >>> from Cookie import _quote >>> _quote('"84533cf9f661f97239208fb844a09a6d4bd8552d4bd8550c3d19ad8339000000!"') '"\\"84533cf9f661f97239208fb844a09a6d4bd8552d4bd8550c3d19ad8339000000!\\""' I trust that that's correct. My guess is that something on the response side is incorrectly parsing the cookie data into cookies in the server-side request. But what? Any ideas?

    Read the article

  • juju bootstrap key error?

    - by mxdog
    I followed the guides the best as i could. there is some information missing like do as root or as regular user ..formatting, quotes no quotes..what the password or paraphrase for ssh should be ..couple other trivial things. that im sure add up to where im at (stuck!) so i have a working mass server on mx-nas-01 and 3 nodes and have been trying to get juju to start. I have tried this as both root and my regular account, sudo no-sudo and here is the output i get from juju bootstrap (however i try it) I don't know if this could be a host,domain,account issue or what i will mention i did have to shut off my dhcp server and install masq (all defaults) to get the maas pxe to work for the nodes mxdog@mx-nas-01:/$ juju bootstrap Traceback (most recent call last): File "/usr/bin/juju", line 8, in main(sys.argv[1:]) File "/usr/lib/python2.7/dist-packages/juju/control/init.py", line 183, in main env_config.load_or_write_sample() File "/usr/lib/python2.7/dist-packages/juju/environment/config.py", line 229, in load_or_write_sample self.load() File "/usr/lib/python2.7/dist-packages/juju/environment/config.py", line 115, in load self.parse(file.read(), path) File "/usr/lib/python2.7/dist-packages/juju/environment/config.py", line 138, in parse config = SCHEMA.coerce(config, []) File "/usr/lib/python2.7/dist-packages/juju/lib/schema.py", line 266, in coerce new_dict[k] = self.schema[k].coerce(v, path) File "/usr/lib/python2.7/dist-packages/juju/lib/schema.py", line 233, in coerce new_subvalue = self.value_schema.coerce(subvalue, value_path) File "/usr/lib/python2.7/dist-packages/juju/lib/schema.py", line 301, in coerce return self.schemas[selected].coerce(value, path) KeyError: 'mass' environments: maas: type: mass mass-server: http://192.168.0.30:80/MAAS mass-oauth: tDRdtJeEKVARBh93eT:N5dK5HSZBsA45cBdx9:S8wMNrfkT9PeYvQN9YrnbHGxmKARv8vb admin-secret: ########## default-series: precise

    Read the article

  • Issue reading packets from a pcap file. dpkt

    - by Chris
    I am running the following test script to try to read packets from a sample .pcap file I have downloaded. import socket import dpkt import sys pcapReader = dpkt.pcap.Reader(file("test1.pcap", "rb")) for ts, data in pcapReader: ether = dpkt.ethernet.Ethernet(data) if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise ip = ether.data src = socket.inet_ntoa(ip.src) dst = socket.inet_ntoa(ip.dst) print "%s -> %s" % (src, dst) For some reason, this is not being interpreted properly. When running it, I get KeyError: 138 module body in test.py at line 4 function __init__ in pcap.py at line 105 Program exited. Why is this? What's wrong?

    Read the article

  • help with django and accented characters?

    - by Asinox
    Hi guys, i have a problem with my accented characters, Django admin save my data without encoding to something like "&aacute;" Example: if im trying a word like " Canción ", i would like to save in this way: Canci&oacute;n, and not Canción. im usign Sociable app: {% load sociable_tags %} {% get_sociable Facebook TwitThis Google MySpace del.icio.us YahooBuzz Live as sociable_links with url=object.get_absolute_url title=object.titulo %} {% for link in sociable_links %} <a href="{{ link.link }}"><img alt="{{ link.site }}" title="{{ link.site }}" src="{{ link.image }}" /></a> {% endfor %} But im getting error if my object.titulo (title of the article) have a accented word. aught KeyError while rendering: u'\xfa' Any idea ? i had in my SETTING: DEFAULT_CHARSET = 'utf-8' i had in my mysql database: utf8_general_ci thanks, sorry with my English

    Read the article

  • Issue reading packets from a pcap file. dpkt module. What gives?

    - by Chris
    I am running the following test script to try to read packets from a sample .pcap file I have downloaded. It won't seem to run. I have all of the modules, but no examples seem to be running. import socket import dpkt import sys pcapReader = dpkt.pcap.Reader(file("test1.pcap", "rb")) for ts, data in pcapReader: ether = dpkt.ethernet.Ethernet(data) if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise ip = ether.data src = socket.inet_ntoa(ip.src) dst = socket.inet_ntoa(ip.dst) print "%s -> %s" % (src, dst) For some reason, this is not being interpreted properly. When running it, I get KeyError: 138 module body in test.py at line 4 function __init__ in pcap.py at line 105 Program exited. Why is this? What's wrong?

    Read the article

  • How do i use repoze.who?

    - by misterwebz
    I'm having some trouble understanding how repoze.who works. I've followed a tutorial i found by searching on google and here's what i already have: This is what i added in my middleware.py file from repoze.who.config import make_middleware_with_config as make_who_with_config app = make_who_with_config(app, global_conf, app_conf['who.config_file'], app_conf['who.log_file'], app_conf['who.log_level']) Here's the who.ini : http://pastebin.com/w5Tba2Fp Here's repoze_auth.py in /lib/auth/: from paste.httpexceptions import HTTPFound from iwant.model import User class UserModelPlugin(object): def authenticate(self, environ, identity): try: username = identity['login'] password = identity['password'] except KeyError: return None success = User.authenticate(username, password) return success def add_metadata(self, environ, identity): username = identity.get('repoze.who.userid') user = User.get(username) if user is not None: identity['user'] = user I've also checked the plugins in the repoze.who folder, but i failed to understand how it's supposed to be used. I'd appreciate it if someone would push me in the right direction.

    Read the article

  • Accessing a dictionary value by custom object value in Python?

    - by Sam
    So I have a square that's made up of a series of points. At every point there is a corresponding value. What I want to do is build a dictionary like this: class Point: def __init__(self, x, y): self._x = x self._y = y square = {} for x in range(0, 5): for y in range(0, 5): point = Point(x,y) square[point] = None However, if I later create a new point object and try to access the value of the dictionary with the key of that point it doesn't work.. square[Point(2,2)] Traceback (most recent call last): File "<pyshell#19>", line 1, in <module> square[Point(2,2)] KeyError: <__main__.Point instance at 0x02E6C378> I'm guessing that this is because python doesn't consider two objects with the same properties to be the same object? Is there any way around this? Thanks

    Read the article

  • trying to use code_swarm but Im having some python scripting problems

    - by theprojectabot
    I am having issues running this: link-mbp:codeswarm-0.1 benb$ python convert_logs/convert_logs.py -perforce-path Traceback (most recent call last): File “convert_logs/convert_logs.py”, line 408, in main() File “convert_logs/convert_logs.py”, line 350, in main files = run_marshal(’p4 -G describe -s “‘ + changelist['change'] + ‘”‘) KeyError: ‘change’ link-mbp:codeswarm-0.1 benb$ I am trying to use code_swarm from this link http://blog.perforce.com/blog/?p=780&cpage=1#comment-965 to visualize my codebase changes. if I run p4 changes everything shows correct but the code in this python script doesnt seem to process correctly... if I run p4 describe on a a changelist number it correctly reports ideas?

    Read the article

  • Parsing JSON file with Python -> google map api

    - by Hannes
    Hi all, I am trying to get started with JSON in Python, but it seems that I misunderstand something in the JSON concept. I followed the google api example, which works fine. But when I change the code to a lower level in the JSON response (as shown below, where I try to get access to the location), I get the following error message for code below: Traceback (most recent call last): File "geoCode.py", line 11, in test = json.dumps([s['location'] for s in jsonResponse['results']], indent=3) KeyError: 'location' How can I get access to lower information level in the JSON file in python? Do I have to go to a higher level and search the result string? That seems very weird to me? Here is the code I have tried to run: import urllib, json URL2 = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false" googleResponse = urllib.urlopen(URL2); jsonResponse = json.loads(googleResponse.read()) test = json.dumps([s['location'] for s in jsonResponse['results']], indent=3) print test Thank you for your responses.

    Read the article

  • how to show all method and data when the object not has "__iter__" function in python..

    - by zjm1126
    i find a way : (1):the dir(object) is : a="['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate']" (2): b=eval(a) (3)and it became a list of all method : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dict__', '__doc__', '__getattribute__', '__getitem__', '__hash__', '__init__', '__iter__', '__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', '__weakref__', '_errors', '_fields', '_prefix', '_unbound_fields', 'confirm', 'data', 'email', 'errors', 'password', 'populate_obj', 'process', 'username', 'validate'] (3)then show the object's method,and all code is : s='' a=eval(str(dir(object))) for i in a: s+=str(i)+':'+str(object[i]) print s but it show error : KeyError: '__class__' so how to make my code running . thanks

    Read the article

  • DEADLOCK_WRAP error when using Berkeley Db in python (bsddb)

    - by JiminyCricket
    I am using a berkdb to store a huge list of key-value pairs but for some reason when i try to access some of the data later i get this error: try: key = 'scrape011201-590652' contenttext = contentdict[key] except: print the error <type 'exceptions.KeyError'> 'scrape011201-590652' in contenttext = contentdict[key]\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in __getitem__\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n', 'File "/usr/lib64/python2.5/bsddb/dbutils.py", line 62, in DeadlockWrap\n return function(*_args, **_kwargs)\n', ' File "/usr/lib64/python2.5/bsddb/__init__.py", line 223, in <lambda>\n return _DeadlockWrap(lambda: self.db[key]) # self.db[key]\n'] I am not sure what DeadlockWrap is but there isnt any other program or process accessing the berkdb or writing to it (as far as i know,) so not sure how we could get a deadlock, if its referring to that. Is it possible that I am trying to access the data to rapidly? I have this function call in a loop, so something like for i in hugelist: #try to get a value from the berkdb #do something with it I am running this with multiple datasets and this error only occurs with one of them, the largest one, not the others.

    Read the article

  • python sending incomplete data over socket

    - by tipu
    I have this socket server script, import SocketServer import shelve import zlib class MyTCPHandler(SocketServer.BaseRequestHandler): def handle(self): self.words = shelve.open('/home/tipu/Dropbox/dev/workspace/search/words.db', 'r'); self.tweets = shelve.open('/home/tipu/Dropbox/dev/workspace/search/tweets.db', 'r'); param = self.request.recv(1024).strip() try: result = str(self.words[param]) except KeyError: result = "set()" self.request.send(str(result)) if __name__ == "__main__": HOST, PORT = "localhost", 50007 SocketServer.TCPServer.allow_reuse_address = True server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler) server.serve_forever() And this receiver, from django.http import HttpResponse from django.template import Context, loader import shelve import zlib import socket def index(req, param = ''): HOST = 'localhost' PORT = 50007 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((HOST, PORT)) s.send(param) data = zlib.decompress(s.recv(131072)) s.close() print 'Received', repr(data) t = loader.get_template('index.html') c = Context({ 'foo' : data }) return HttpResponse(t.render(c)) I am sending strings to the receiver that are in the hundreds of kilobytes. I end up only receiving a portion of it. Is there a way that I can fix that so that the whole string is sent?

    Read the article

< Previous Page | 1 2 3  | Next Page >