Search Results

Search found 15187 results on 608 pages for 'boost python'.

Page 132/608 | < Previous Page | 128 129 130 131 132 133 134 135 136 137 138 139  | Next Page >

  • Need help understanding some Python code

    - by Yarin
    I'm new to Python, and stumped by this piece of code from the Boto project: class SubdomainCallingFormat(_CallingFormat): @assert_case_insensitive def get_bucket_server(self, server, bucket): return '%s.%s' % (bucket, server) def assert_case_insensitive(f): def wrapper(*args, **kwargs): if len(args) == 3 and not (args[2].islower() or args[2].isalnum()): raise BotoClientError("Bucket names cannot contain upper-case " \ "characters when using either the sub-domain or virtual " \ "hosting calling format.") return f(*args, **kwargs) return wrapper Trying to understand what's going on here. What is the '@' symbol in @assert_case_sensitive ? What do the args *args, **kwargs mean? What does 'f' represent? Thanks!

    Read the article

  • Python having problems writing/reading and testing in a correct format

    - by Ionut
    I’m trying to make a program that will do the following: check if auth_file exists if yes - read file and try to login using data from that file - if data is wrong - request new data if no - request some data and then create the file and fill it with requested data So far: import json import getpass import os import requests filename = ".auth_data" auth_file = os.path.realpath(filename) url = 'http://example.com/api' headers = {'content-type': 'application/json'} def load_auth_file(): try: f = open(auth_file, "r") auth_data = f.read() r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return auth_data else: print "Incorrect login..." req_auth() except IOError: f = file(auth_file, "w") f.write(req_auth()) f.close() def req_auth(): user = str(raw_input('Username: ')) password = getpass.getpass('Password: ') auth_data = (user, password) r = requests.get(url, auth=auth_data, headers=headers) if r.reason == 'OK': return user, password elif r.reason == "FORBIDDEN": print "Incorrect login information..." req_auth() return False I have the following problems(understanding and applying the correct way): I can't find a correct way of storing the returned data from req_auth() to auth_file in a format that can be read and used in load_auth file PS: Of course I'm a beginner in Python and I'm sure I have missed some key elements here :(

    Read the article

  • Dealing with Windows line-endings in Python

    - by Adam Nelson
    I've got a 700MB XML file coming from a Windows provider. As one might expect, the line endings are '\r\n' (or ^M in vi). What is the most efficient way to deal with this situation aside from getting the supplier to send over '\n' :-) Use os.linesep Use rstrip() (requiring opening the file ... which seems crazy) Using Universal newline support is not standard on my Mac Snow Leopard - so isn't an option. I'm open to anything that requires Python 2.6+ but it needs to work on Snow Leopard and Ubuntu 9.10 with minimal external requirements. I don't mind a small performance penalty but I am looking for the standard best way to deal with this.

    Read the article

  • Using Nose & NoseXUnit on a Python package

    - by Wraith
    This is a previous post detailing a CI setup for Python. The asker and answerer detail the use of Nose and NoseXUnit with Hudson for their builds. However, NoseXUnit throws an error when run on any source folder where init.py is present: File "build/bdist.linux-x86_64/egg/nosexunit/tools.py", line 59, in packages nosexunit.excepts.ToolError: following folder can not contain __init__.py file: /home/dev/source/web2py/applications I can't think of a source folder of mine that is not a package also. Is there a step I am missing when dealing with NoseXUnit?

    Read the article

  • Summary count for Python logging

    - by Craig McQueen
    At the end of my Python program, I'd like to be able to get a summary of the number of items logged through the standard logging module. I'd specifically like to be able to get a count for each specified name (and possibly its children). E.g. if I have: input_logger = getLogger('input') input_logger.debug("got input1") input_logger.debug("got input2") input_logger.debug("got input3") network_input_logger = getLogger('input.network') network_input_logger.debug("got network input1") network_input_logger.debug("got network input2") getLogger('output') output_logger.debug("sent output1") Then at the end I'd like to get a summary such as: input: 5 input.network: 2 output: 1 Perhaps by calling a getcount() method for a logger or a handler. What would be a good way to achieve this? I imagine it would involve a sub-class of one of the logging classes, but I'm not sure which one would be best.

    Read the article

  • Python CSV file processing

    - by kingwarchief
    I just got introduced to python, the first language I get to learn, and I have this question below: I have an excel based CSV file with two columns (or rows, Pythonically) that I am working on. What I need to do is to perform some operations so that I can compare the two data entries in each 'row'. To be more precise, one column has constant numbers all the way down, whereas the other column varies. So I need to count the number of times the varying column data entry values crosses the constant value on the other column. For example: Varying Column; Constant Column 24 25 26 25 crosses 27 25 26 25 25.5 25 23 25 crossed 26 25 crossed So in this case the number of times there is a cross

    Read the article

  • Python universal feedparser xml

    - by timg
    I am trying to read an xml feed with the python feedparser, but cannot seem to navigate the elements. Here is what I am trying: import feedparser d = feedparser.parse('http://www.website.com/feed') text= d.status.test and here is the xml: <?xml version="1.0" encoding="UTF-8"?> <statuses type="array"> <status> <created>Tue Dec 21 14:16:12 +0000 2010</created> <id>123</id> <text>Hello</text> </status> </statuses>

    Read the article

  • may be python error!!!

    - by bahar
    Hi I'm not familiar with python, I just want to check something so I tried to run a .py code in linux so I wrote : ./waf wifi-olsr-flowmon --plot which is a .py program after that whatever I want to run just see these error: /home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscript: error: Traceback (most recent call last): File "/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/.waf-1.5.16-e6d03192b5ddfa5ef2c8d65308e48e42/wafadmin/Utils.py", line 197, in load_module exec(compile(code,file_path,'exec'),module.__dict__) File "/home/bahar/Desktop/ns/ns-allinone-3.9/ns-allinone-3.9/ns-3.9/wscript", line 32, in <module> import cflags # override the build profiles from waf ImportError: No module named cflags I dont know what does it mean or why it happened, would you please tell me what is the problem . Bests

    Read the article

  • Using Python simplejson for transmitting JSON to another server results in unicode encoding problems

    - by Mark
    Hi there, I'm encoding a string with Python's simplejson library with special characters: hello testing spécißl characters plusses: +++++ special chars :œ?´®†¥¨ˆøp“ß?ƒ©??°¬O˜çv?˜µ== However, when I encode it and transmit it to the other machine (using POST), it turns out like this: {'message': ['{"body": "hello testing sp\\u00e9ci\\u00dfl characters\\n\\nplusses: \\n\\nspecial chars :\\u0153\\u2211\\u00b4\\u00ae\\u2020\\u00a5\\u00a8\\u02c6\\u00f8\\u03c0\\u201c\\u00df\\u2202\\u0192\\u00a9\\u02d9\\u2206\\u02da\\u00ac\\u03a9\\u2248\\u00e7\\u221a\\u222b\\u02dc\\u00b5\\u2264\\u2265"}']} The + signs are completely stripped and the rest are in this unicode(?) format. My code for this is: data = {'body': data_string} data_encoded = json.dumps(data) Any ideas? Thanks! Edit: I've tried using json.dumps(data, ensure_ascii=False) but it results in a UnicodeError ordinal not in range error.

    Read the article

  • Problems inserting file data into sqlite database using python

    - by tylerc230
    I'm trying to open an image file in python and add that data to an sqlite table. I created the table using: "CREATE TABLE "images" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL , "description" VARCHAR, "image" BLOB );" I am trying to add the image to the db using: imageFile = open(imageName, 'rb') b = sqlite3.Binary(imageFile.read()) targetCursor.execute("INSERT INTO images (image) values(?)", (b,)) targetCursor.execute("SELECT id from images") for id in targetCursor: imageid= id[0] targetCursor.execute("INSERT INTO %s (questionID,imageID) values(?,?)" % table, (questionId, imageid)) When I print the value of 'b' it looks like binary data but when I call: 'select image from images where id = 1' I get '????' printed to the console. Anyone know what I'm doing wrong?

    Read the article

  • python input UnicodeDecodeError:

    - by The man on the Clapham omnibus
    python 3.x >>> a = input() hope >>> a 'hope' >>> b = input() håpe >>> b 'håpe' >>> c = input() start typing hå... delete using backspace... and change to hope Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'utf8' codec can't decode byte 0xc3 in position 1: invalid continuation byte >>> The situation is not terrible, I am working around it, but find it strange that when deleting, the bytes get messed up. Has anyone else experienced this? the terminal history shows that I thought that I entered h?ope any ideas? in the script that is using this, I do import readline to give command line history.

    Read the article

  • How to display and change an icon inside a python Tk Frame

    - by codingJoe
    I have a python Tkinter Frame that displays several fields. I want to also add an red/yellow/green icon that will display the status of an external device. The icon is loaded from a file called ICON_LED_RED.ico. How do I display the icon in my frame? How do I change the icon at runtime? for example replace BitmapImage('RED.ico') with BitmapImage('GREEN.ico') class Application(Frame): def init(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): # ...other frame code.. works just fine. self.OKBTN = Button(self) self.OKBTN["text"] = "OK" self.OKBTN["fg"] = "red" self.OKBTN["command"] = self.ok_btn_func self.OKBTN.pack({"side": "left"}) # when I add the following the frame window is not visible # The process is locked up such that I have to do a kill -9 self.statusFrame = Frame(self, bd=2, relief=RIDGE) Label(self.statusFrame, text='Status:').pack(side=LEFT, padx=5) self.statIcon = BitmapImage('data/ICON_LED_RED.ico') Label (self.statusFrame, image=self.statIcon ).grid() self.statusFrame.pack(expand=1, fill=X, pady=10, padx=5)

    Read the article

  • How to connect to foreign DB2 database using Python (Ubuntu)

    - by dblips
    sudo easy_install ibm_db-1.0.1-py2.5-linux-i686.egg only works after sudo apt-get install python-dev. Some troubles to find that out in the first place ... Downloaded from IBM site v9.5fp5_linuxia32_dsdriver.tar.gz and pointing IBM_DB_DIR and IBM_DB_LIB to the clidriver(/lib) dir -- is this needed/correct one? -- libdb2.so(.1) is in there... Nevertheless: >>> import ibm_db Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libdb2.so.1: cannot open shared object file: No such file or directory Any help is very much appreciated!

    Read the article

  • C# style properties in python

    - by 3D-Grabber
    I am looking for a way to define properties in Python similar to C#, with nested get/set definitions. This is how far I got: #### definition #### def Prop(fcn): f = fcn() return property(f['get'], f['set']) #### test #### class Example(object): @Prop def myattr(): def get(self): return self._value def set(self, value): self._value = value return locals() # <- how to get rid of this? e = Example() e.myattr = 'somevalue' print e.myattr The problem with this is, that it still needs the definition to 'return locals()'. Is there a way to get rid of it? Maybe with a nested decorator?

    Read the article

  • Python unittest with expensive setup

    - by Staale
    My test file is basically: class Test(unittest.TestCase): def testOk(): pass if __name__ == "__main__": expensiveSetup() try: unittest.main() finally: cleanUp() However, I do wish to run my test through Netbeans testing tools, and to do that I need unittests that don't rely on an environment setup done in main. Looking at http://stackoverflow.com/questions/402483/caching-result-of-setup-using-python-unittest - it recommends using Nose. However, I don't think Netbeans supports this. I didn't find any information indicating that it does. Additionally, I am the only one here actually writing tests, so I don't want to introduce additional dependencies for the other 2 developers unless they are needed. How can I do the setup and cleanup once for all the tests in my TestSuite? The expensive setup here is creating some files with dummy data, as well as setting up and tearing down a simple xml-rpc server. I also have 2 test classes, one testing locally and one testing all methods over xml-rpc.

    Read the article

  • How to add a custom loglevel to Python's logging facility

    - by tuergeist
    Hi, I'd like to have loglevel TRACE (5) for my application as I don't think that debug() is enought. Additionally log(5, msg) isn't what I want. The question is, how can I add a custom log level to a Python logger? Actually I've a mylogger.py with the following content: import logging @property def log(obj): myLogger = logging.getLogger(obj.__class__.__name__) return myLogger In my code I use it in the following way: class ExampleClass(object): from mylogger import log def __init__(self): '''The constructor with the logger''' self.log.debug("Init runs") Now I'd like to call self.log.trace("foo bar") Thanks in advance for your help.

    Read the article

  • AUTOMATING EXCEL MACRO USING PYTHON

    - by user324056
    Hi all, Here is my question... I am using python in Linux to automate an excel. I have finished writing data into excel by using pyexcelerator package. Now comes the real challenge. I have to add another tab to the existing sheet and that tab should contain the macro run in the first tab. All these things should be automated. I googled a lot and found win32come to do a job in macro, but that was only for windows. Anyone have any idea of how to do this, or can you guide me with few suggestions. Thanks in advance.

    Read the article

  • Python .app doesn't read .txt file like it should

    - by Bambo
    This question relates to this one: Python app which reads and writes into its current working directory as a .app/exe i got the path to the .txt file fine however now when i try to open it and read the contents it seems that it doesn't extract the data properly. Here's my code - http://pastie.org/4876896 These are the errors i'm getting: 30/09/2012 10:28:49.103 [0x0-0x4e04e].org.pythonmac.unspecified.main: for index, item in enumerate( lines ): # iterate through lines 30/09/2012 10:28:49.103 [0x0-0x4e04e].org.pythonmac.unspecified.main: TypeError: 'NoneType' object is not iterable I kind of understand what the errors mean however i'm not sure why they are being flagged up because if i run my script with it not in a .app form it doesn't get these errors and extracts the data fine.

    Read the article

  • python - returns incorrect positive #

    - by tekknolagi
    what i'm trying to do is write a quadratic equation solver but when the solution should be -1, as in quadratic(2, 4, 2) it returns 1 what am i doing wrong? #!/usr/bin/python import math def quadratic(a, b, c): #a = raw_input("What\'s your `a` value?\t") #b = raw_input("What\'s your `b` value?\t") #c = raw_input("What\'s your `c` value?\t") a, b, c = float(a), float(b), float(c) disc = (b*b)-(4*a*c) print "Discriminant is:\n" + str(disc) if disc = 0: root = math.sqrt(disc) top1 = b + root top2 = b - root sol1 = top1/(2*a) sol2 = top2/(2*a) if sol1 != sol2: print "Solution 1:\n" + str(sol1) + "\nSolution 2:\n" + str(sol2) if sol1 == sol2: print "One solution:\n" + str(sol1) else: print "No solution!" EDIT: it returns the following... import mathmodules mathmodules.quadratic(2, 4, 2) Discriminant is: 0.0 One solution: 1.0

    Read the article

  • Beginner questions regarding Python classes.

    - by Andy
    Hi. I am new to Python so please don't flame me if I ask something too noobish :) 1. Consider I have a class: class Test: def __init__(self, x, y): self.x = x self.y = y def wow(): print 5 * 5 Now I try to create an object of the class: x = Test(3, 4) This works as expected. However, when I try to call the method wow(), it returns an error, which is fixed by changing wow() to: def wow(self) Why do I need to include self and if I don't, what does the method mean?2. In the definition of __init__: def __init__(self, x, y): self.x = x self.y = y Why do I need to declare x and y, when I can do this: def __init__(self): self.x = x self.y = y I hope I am being clear... Thanks for your time.

    Read the article

  • Python Textwrap - forcing 'hard' breaks

    - by Tom Werner
    I am trying to use textwrap to format an import file that is quite particular in how it is formatted. Basically, it is as follows (line length shortened for simplicity): abcdef <- Ok line abcdef ghijk <- Note leading space to indicate wrapped line lm Now, I have got code to work as follows: wrapper = TextWrapper(width=80, subsequent_indent=' ', break_long_words=True, break_on_hyphens=False) for l in lines: wrapline=wrapper.wrap(l) This works nearly perfectly, however, the text wrapping code doesn't do a hard break at the 80 character mark, it tries to be smart and break on a space (at approx 20 chars in). I have got round this by replacing all spaces in the string list with a unique character (#), wrapping them and then removing the character, but surely there must be a cleaner way? N.B Any possible answers need to work on Python 2.4 - sorry!

    Read the article

  • IDLE wont start Python 2.6.5

    - by anteater7171
    I was using it as my primary text editor for quite sometime. However, one day it just stopped working. This had happened to me several times before, so I simply tried to end all procceses using windows task manager. However that didn't work. I've recently tried getting it to work again. Whenever I try to reopen it it informs me that it's subprocess couldn't connect. I tried uninstalling it and reinstalling it, yet the problem persists. Anyone have any other solutions? Important facts: Windows 7, Python 2.6.5

    Read the article

  • Identifying a function call in a python script line in runtime

    - by Dani
    I have a python script that I run with 'exec'. The script's string has calls to functions. When a function is called, I would like it to know the line number and offset in line for that call in the script (in the string I fed exec with). Here is an example. If my script is: foo1(); foo2(); foo1() foo3() And if I have code that prints (line,offset) in every function, I should get (0,0), (0,8), (0,16), (1,0) In most cases this can be easily done by getting the stack frame, because it contains the line number and the function name. The only problem is when there are two functions with the same name in a certain line. Unfortunately this is a common case for me. Any ideas?

    Read the article

  • stuck in while loop python

    - by user1717330
    I am creating a chat server in python and got quite far as a noob in the language. I am having 1 problem at the moment which I want to solve before I go further, but I cannot seem to find how to get the problem solved. It is about a while loop that continues.. in the below code is where it goes wrong while 1: try: data = self.channel.recv ( 1024 ) print "Message from client: ", data if "exit" in data: self.channel.send("You have closed youre connection.\n") break except KeyboardInterrupt: break except: raise When this piece of code get executed, on my client I need to enter "exit" to quit the connection. This works as a charm, but when I use CTRL+C to exit the connection, my server prints "Message from client: " a couple of thousand times. where am I going wrong?

    Read the article

  • list python package dependencies without loading them ?

    - by Denis
    Say that python package A requires B, C and D; is there a way to list A → B C D without loading them ? Requires in the metadata (yolk -M A) are often incomplete, grr. One can download A.tar / A.egg, then look through A/setup.py, but some of those are pretty gory. (I'd have thought that getting at least first-level dependencies could be mechanized; even a 98 % solution would be better than avalanching downloads.) A related question: pip-upgrade-package-without-upgrading-dependencies

    Read the article

< Previous Page | 128 129 130 131 132 133 134 135 136 137 138 139  | Next Page >