Search Results

Search found 13693 results on 548 pages for 'python metaprogramming'.

Page 148/548 | < Previous Page | 144 145 146 147 148 149 150 151 152 153 154 155  | Next Page >

  • Python __import__ parameter confusion

    - by CMC
    I'm trying to import a module, while passing some global variables, but it does not seem to work: File test_1: test_2 = __import__("test_2", {"testvar": 1}) File test_2: print testvar This seems like it should work, and print a 1, but I get the following error when I run test_1: Traceback (most recent call last): File ".../test_1.py", line 1, in <module> print testvar NameError: name 'testvar' is not defined What am I doing wrong?

    Read the article

  • Python/PyParsing: Difficulty with setResultsName

    - by Rosarch
    I think I'm making a mistake in how I call setResultsName(): from pyparsing import * DEPT_CODE = Regex(r'[A-Z]{2,}').setResultsName("Dept Code") COURSE_NUMBER = Regex(r'[0-9]{4}').setResultsName("Course Number") COURSE_NUMBER.setParseAction(lambda s, l, toks : int(toks[0])) course = DEPT_CODE + COURSE_NUMBER course.setResultsName("course") statement = course From IDLE: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) The output I hope for: >>> myparser import * >>> statement.parseString("CS 2110") (['CS', 2110], {'Course': ['CS', 2110], 'Dept Code': [('CS', 0)], 'Course Number': [(2110, 1)]}) Does setResultsName() only work for terminals?

    Read the article

  • Python Decorators and inheritance

    - by wheaties
    Help a guy out. Can't seem to get a decorator to work with inheritance. Broke it down to the simplest little example in my scratch workspace. Still can't seem to get it working. class bar(object): def __init__(self): self.val = 4 def setVal(self,x): self.val = x def decor(self, func): def increment(self, x): return func( self, x ) + self.val return increment class foo(bar): def __init__(self): bar.__init__(self) @decor def add(self, x): return x Oops, name "decor" is not defined. Okay, how about @bar.decor? TypeError: unbound method "decor" must be called with a bar instance as first argument (got function instance instead) Ok, how about @self.decor? Name "self" is not defined. Ok, how about @foo.decor?! Name "foo" is not defined. AaaaAAaAaaaarrrrgggg... What am I doing wrong?

    Read the article

  • Python: needs more than 1 value to unpack

    - by Rosarch
    What am I doing wrong to get this error? replacements = {} replacements["**"] = ("<strong>", "</strong>") replacements["__"] = ("<em>", "</em>") replacements["--"] = ("<blink>", "</blink>") replacements["=="] = ("<marquee>", "</marquee>") replacements["@@"] = ("<code>", "</code>") for delimiter, (open_tag, close_tag) in replacements: # error here message = self.replaceFormatting(delimiter, message, open_tag, close_tag); The error: Traceback (most recent call last): File "", line 1, in for shit, (a, b) in replacements: ValueError: need more than 1 value to unpack All the values tuples have two values. Right?

    Read the article

  • how to display my list with n amount on each line in Python

    - by user1786698
    im trying to display my list with 7 states on each line here is what i have so far, but it displays as one long string of all the states with quotes around each state. I forgot to mention that this is for my CS class and we havent learned iter yet so we not allowed to use it. the only hint i was given was to to turn STATE_LIST into a string then use '\n' to break it up state = str(STATE_LIST) displaystates = Text(Point(WINDOW_WIDTH/2, WINDOW_HEIGHT/2), state.split('\n')) displaystates.draw(win) and STATE_LIST looks like this STATE_VOTES = { "AL" : 9, # Alabama "AK" : 3, # Alaska "AZ" : 11, # Arizona "AR" : 6, # Arkansas "CA" : 55, # California "CO" : 9, # Colorado "CT" : 7, # Connecticut "DE" : 3, # Delaware "DC" : 3, # Washington DC "FL" : 29, # Florida "GA" : 16, # Georgia "HI" : 4, # Hawaii "ID" : 4, # Idaho "IL" : 20, # Illinois "IN" : 11, # Indiana "IA" : 6, # Iowa "KS" : 6, # Kansas "KY" : 8, # Kentucky "LA" : 8, # Louisiana "ME" : 4, # Maine "MD" : 10, # Maryland "MA" : 11, # Massachusetts "MI" : 16, # Michigan "MN" : 10, # Minnesota "MS" : 6, # Mississippi "MO" : 10, # Missouri "MT" : 3, # Montana "NE" : 5, # Nebraska "NV" : 6, # Nevada "NH" : 4, # New Hampshire "NJ" : 14, # New Jersey "NM" : 5, # New Mexico "NY" : 29, # New York "NC" : 15, # North Carolina "ND" : 3, # North Dakota "OH" : 18, # Ohio "OK" : 7, # Oklahoma "OR" : 7, # Oregon "PA" : 20, # Pennsylvania "RI" : 4, # Rhode Island "SC" : 9, # South Carolina "SD" : 3, # South Dakota "TN" : 11, # Tennessee "TX" : 38, # Texas "UT" : 6, # Utah "VT" : 3, # Vermont "VA" : 13, # Virginia "WA" : 12, # Washington "WV" : 5, # West Virginia "WI" : 10, # Wisconsin "WY" : 3 # Wyoming } STATE_LIST = sorted(list(STATE_VOTES.keys())) I am trying to get it to look somewhat like this

    Read the article

  • python Requests login to website returns 403

    - by Jeff
    I'm trying to use requests to login to a website but as you can guess I'm having a problem here's the the code that I'm using import requests EMAIL = '***' PASSWORD = '***' URL = 'https://portal.bitcasa.com/login' client = requests.session(config={'verbose': sys.stderr}) login_data = {'username': EMAIL, 'password': PASSWORD,} r = client.post(URL, data=login_data, headers={"Referer": "foo"}) print r and if I print out r.text I get <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head><script type="text/javascript">var NREUMQ=NREUMQ||[];NREUMQ.push(["mark","firstbyte",new Date().getTime()])</script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta name="robots" content="NONE,NOARCHIVE"> <title>403 Forbidden</title> <style type="text/css"> html * { padding:0; margin:0; } body * { padding:10px 20px; } body * * { padding:0; } body { font:small sans-serif; background:#eee; } body>div { border-bottom:1px solid #ddd; } h1 { font-weight:normal; margin-bottom:.4em; } h1 span { font-size:60%; color:#666; font-weight:normal; } #info { background:#f6f6f6; } #info ul { margin: 0.5em 4em; } #info p, #summary p { padding-top:10px; } #summary { background: #ffc; } #explanation { background:#eee; border-bottom: 0px none; } </style> </head> <body> <div id="summary"> <h1>Forbidden <span>(403)</span></h1> <p>CSRF verification failed. Request aborted.</p> </div> <div id="explanation"> <p><small>More information is available with DEBUG=True.</small></p> </div> <script type="text/javascript">if(!NREUMQ.f){NREUMQ.f=function(){NREUMQ.push(["load",new Date().getTime()]);var e=document.createElement("script");e.type="text/javascript";e.src=(("http:"===document.location.protocol)?"http:":"https:")+"//"+"d1ros97qkrwjf5.cloudfront.net/42/eum/rum.js";document.body.appendChild(e);if(NREUMQ.a)NREUMQ.a();};NREUMQ.a=window.onload;window.onload=NREUMQ.f;};NREUMQ.push(["nrfj","beacon-1.newrelic.com","0e859e0620",778660,"ZAZRbUcHWBAHURFYX11MdUxbBUIKCVxKVVpSDVRWGwtfBwJeAEZRQQYdWkYUUFklQRdXZloGRHRcAlIPA0UEQ1UdE0FWVgNFEDlEDFRH",0,7,new Date().getTime(),"","","","",""])</script></body> </html> They're using a combination of django and pyramid. I've been playing around with this for about two days now but, obviously, have gotten nowhere. Thanks for your help.

    Read the article

  • ImageChops.duplicate - python

    - by ariel
    Hi I am tring to use the function ImageChops.dulpicate from the PIL module and I get an error I don't understand: this is the code import PIL import Image import ImageChops import os PathDemo4a='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/demo4a' PathDemo4b='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/demo4b' PathDemo4c='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/demo4c' PathBlackBoard='C:/Documents and Settings/Ariel/My Documents/My Dropbox/lecture/BlackBoard.bmp' Slides=os.listdir(PathDemo4a) for slide in Slides: #BB=Image.open(PathBlackBoard) BB=ImageChops.duplicate(PathBlackBoard) #BB=BlackBoard and this is the error; Traceback (most recent call last): File "", line 1, in ImageChops.duplicate('c:/1.BMP') File "C:\Python26\lib\site-packages\PIL\ImageChops.py", line 57, in duplicate return image.copy() AttributeError: 'str' object has no attribute 'copy' any help would be much appriciated Ariel

    Read the article

  • Python (Django). Store telnet connection

    - by Shamanu4
    Hello. I am programming web interface which communicates with cisco switches via telnet. I want to make such system which will be storing one telnet connection per switch and every script (web interface, cron jobs, etc.) will have access to it. This is needed to make a single query queue for each device and prevent huge cisco processor load caused by several concurent telnet connections. How do I can do this?

    Read the article

  • Python Twisted Client Connection Lost

    - by MovieYoda
    I have this twisted client, which connects with a twisted server having an index. I ran this client from command-line. It worked fine. Now I modified it to run in loop (see main()) so that I can keep querying. But the client runs only once. Next time it simply says connection lost \n Connection lost - goodbye!. What am i doing wrong? In the loop I am reconnecting to the server, it that wrong? from twisted.internet import reactor from twisted.internet import protocol from settings import AS_SERVER_HOST, AS_SERVER_PORT # a client protocol class Spell_client(protocol.Protocol): """Once connected, send a message, then print the result.""" def connectionMade(self): self.transport.write(self.factory.query) def dataReceived(self, data): "As soon as any data is received, write it back." if data == '!': self.factory.results = '' else: self.factory.results = data self.transport.loseConnection() def connectionLost(self, reason): print "\tconnection lost" class Spell_Factory(protocol.ClientFactory): protocol = Spell_client def __init__(self, query): self.query = query self.results = '' def clientConnectionFailed(self, connector, reason): print "\tConnection failed - goodbye!" reactor.stop() def clientConnectionLost(self, connector, reason): print "\tConnection lost - goodbye!" reactor.stop() # this connects the protocol to a server runing on port 8090 def main(): print 'Connecting to %s:%d' % (AS_SERVER_HOST, AS_SERVER_PORT) while True: print query = raw_input("Query:") if query == '': return f = Spell_Factory(query) reactor.connectTCP(AS_SERVER_HOST, AS_SERVER_PORT, f) reactor.run() print f.results return if __name__ == '__main__': main()

    Read the article

  • Python regular expression help

    - by dlw
    Hi SO, I can't seem to create the correct regular expression to extract the correct tokens from my string. Padding the beginning of the string with a space generates the correct output, but seems less than optimal: >>> import re >>> s = '-edge_0triggered a-b | -level_Sensitive c-d | a-b-c' >>> re.findall(r'\W(-[\w_]+)',' '+s) ['-edge_0triggered', '-level_Sensitive'] # correct output Here are some of the regular expressions I've tried, does anyone have a regex suggestion that doesn't involve changing the original string and generates the correct output >>> re.findall(r'(-[\w_]+)',s) ['-edge_0triggered', '-b', '-level_Sensitive', '-d', '-b', '-c'] >>> re.findall(r'\W(-[\w_]+)',s) ['-level_Sensitive'] Thanks -- DW

    Read the article

  • Change/Update a pane using python wx.AUI

    - by Dan
    I'm using wx.AUI and having a bit of a problem managing panes. Once you have created a new pane using AddPane(), what is the syntax to update or change the pane? I've seen the SetPane command but I can't find any examples. Can someone direct me to an example? Or perhaps it makes sense to use some command to delete the pane and create a new one? Thanks in advance for your time.

    Read the article

  • sorting in python

    - by tipu
    I have a hashmap like so: results[tweet_id] = {"score" : float(dot(query,doc) / (norm(query) * norm(doc))), "tweet" : tweet} What I'd like to do is to sort results by the innser "score" key. I don't know how possible this is, I saw many sorting tutorials but they were for simple (not nested) data structures.

    Read the article

  • Python: Script works, but seems to deadlock after some time

    - by sberry2A
    I have the following script, which is working for the most part Link to PasteBin The script's job is to start a number of threads which in turn each start a subprocess with Popen. The output from each subprocess is as follows: 1 2 3 . . . n Done Bascially the subprocess is transferring 10M records from tables in one database to different tables in another db with a lot of data massaging/manipulation in between because of the different schemas. If the subprocess fails at any time in it's execution (bad records, duplicate primary keys, etc), or it completes successfully, it will output "Done\n". If there are no more records to select against for transfer then it will output "NO DATA\n" My intent was to create my script "tableTransfer.py" which would spawn a number of these processes, read their output, and in turn output information such as number of updates completed, time remaining, time elapsed, and number of transfers per second. I started running the process last night and checked in this morning to see it had deadlocked. There were not subprocceses running, there are still records to be updated, and the script had not exited. It was simply sitting there, no longer outputting the current information because no subprocces were running to update the total number complete which is what controls updates to the output. This is running on OS X. I am looking for three things: I would like to get rid of the possibility of this deadlock occurring so I don't need to check in on it as frequently. Is there some issue with locking? Am I doing this in a bad way (gThreading variable to control looping of spawning additional thread... etc.) I would appreciate some suggestions for improving my overall methodology. How should I handle ctrl-c exit? Right now I need to kill the process, but assume I should be able to use the signal module or other to catch the signal and kill the threads, is that right? I am not sure whether I should be pasting my entire script here, since I usually just paste snippets. Let me know if I should paste it here as well.

    Read the article

  • Python thinks I'm a different IP

    - by Yongho
    I'm trying to set a page that displays the visitor's IP. All the methods I have tried show an IP different from the IP my computer has. I've tried: Looking up http://www.whatismyip.com/automation/n09230945.asp Using socket.getaddrinfo(socket.gethostname(), None)[0][4][0] How can I find the real IP of the visitor?

    Read the article

  • Fetch wrong SVN credentials with Python

    - by user1029968
    Could anyone here let me know how can I check if provided SVN credentials (username and password) are proper? With pysvn there is callback_get_login parameter but in case credentials are wrong, callback is prompted over and over without any way to cancel this and return failure information. Please let me know how can I (not neccesserily with pysvn) check if provided SVN credentials are okay. Thank you in advance!

    Read the article

  • Python datetime to Unix timestamp

    - by Off Rhoden
    I have to create an "Expires" value 5 minutes in the future, but I have to supply it in UNIX Timestamp format. I have this so far, but it seems like a hack. def expires(): '''return a UNIX style timestamp representing 5 minutes from now''' epoch = datetime.datetime(1970, 1, 1) seconds_in_a_day = 60 * 60 * 24 five_minutes = datetime.timedelta(seconds=5*60) five_minutes_from_now = datetime.datetime.now() + five_minutes since_epoch = five_minutes_from_now - epoch return since_epoch.days * seconds_in_a_day + since_epoch.seconds Is there a module or function that does the timestamp conversion for me?

    Read the article

  • Python float copy question

    - by SJA
    Hi, I'm puzzled by some behaviour I'm seeing when copying a float array member into another variable - please help! For example data_entry[1] = 9.6850069951 new_value = data_entry[1] <comment> #print both 9.6850069951 9.6850663300 I'm aware of the problem of binary storage of floats but I thought with a direct copy of memory we would end up with the same value. Any ideas? I need better precision than this! thanks in advance Stuart

    Read the article

  • making binned boxplot in matplotlib with numpy and scipy in Python

    - by user248237
    I have a 2-d array containing pairs of values and I'd like to make a boxplot of the y-values by different bins of the x-values. I.e. if the array is: my_array = array([[1, 40.5], [4.5, 60], ...]]) then I'd like to bin my_array[:, 0] and then for each of the bins, produce a boxplot of the corresponding my_array[:, 1] values that fall into each box. So in the end I want the plot to contain number of bins-many box plots. I tried the following: min_x = min(my_array[:, 0]) max_x = max(my_array[:, 1]) num_bins = 3 bins = linspace(min_x, max_x, num_bins) elts_to_bins = digitize(my_array[:, 0], bins) However, this gives me values in elts_to_bins that range from 1 to 3. I thought I should get 0-based indices for the bins, and I only wanted 3 bins. I'm assuming this is due to some trickyness with how bins are represented in linspace vs. digitize. What is the easiest way to achieve this? I want num_bins-many equally spaced bins, with the first bin containing the lower half of the data and the upper bin containing the upper half... i.e., I want each data point to fall into some bin, so that I can make a boxplot. thanks.

    Read the article

  • Use of infix operator hack in production code (Python)

    - by Casebash
    What is your opinion of using the infix operator hack in production code? Issues: The effect this will have on speed. The potential for a clashes with an object with these operators already defined. This seems particularly dangerous with generic code that is intended to handle objects of any type. It is a shame that this isn't built in - it really does improve readability

    Read the article

  • Concise way to getattr() and use it if not None in Python

    - by MTsoul
    I am finding myself doing the following a bit too often: attr = getattr(obj, 'attr', None) if attr is not None: attr() # Do something, either attr(), or func(attr), or whatever else: # Do something else Is there a more pythonic way of writing that? Is this better? (At least not in performance, IMO.) try: obj.attr() # or whatever except AttributeError: # Do something else

    Read the article

  • Match HTML tags in two strings using regex in Python

    - by jack
    I want to verify that the HTML tags present in a source string are also present in a target string. For example: >> source = '<em>Hello</em><label>What's your name</label>' >> verify_target(’<em>Hi</em><label>My name is Jim</label>') True >> verify_target('<label>My name is Jim</label><em>Hi</em>') True >> verify_target('<em>Hi<label>My name is Jim</label></em>') False

    Read the article

< Previous Page | 144 145 146 147 148 149 150 151 152 153 154 155  | Next Page >