Re: Standard class for time *period*?
The Python standard library module datetime seems to be what you want. It has objects representing date/times, and deltatimes (i.e., durations). These can be timezone aware or not as you wish. Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology On 3/27/23 6:00 AM, loris.benn...@fu-berlin.de wrote: Hi, I have been around long enough to know that, due to time-zones, daylight saving and whatnot, time-related stuff is complicated. So even if I think something connected with time should exist, there may well be a very good reason why it does not. My problem: I need to deal with what I call a 'period', which is a span of time limited by two dates, start and end. The period has a 'duration', which is the elapsed time between start and end. The duration is essentially a number of seconds, but in my context, because the durations are usually hours or days, I would generally want to display the duration in a format such as "dd-hh:mm:ss" My (possibly ill-founded) expectation: There is a standard class which encapsulates this sort of functionality. My (possibly insufficiently researched) conclusion: Such a standard class does not exist. What is at fault here? My expectation or my conclusion? Cheers, Loris -- https://mail.python.org/mailman/listinfo/python-list
Re: =- and -= snag
On 3/13/23 2:26 PM, morp...@gmail.com wrote: Hi. I was working in Python today, and sat there scratching my head as the numbers for calculations didn't add up. It went into negative numbers, when that shouldn't have been possible. Turns out I had a very small typo, I had =- instead of -=. Isn't it unpythonic to be able to make a mistake like that? Regards, Morten These all mean the same thing, but I don't see a good way to designate the second or third as an error. x = -5 x=-5 x =- 5 Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology -- https://mail.python.org/mailman/listinfo/python-list
Re: Change first occurrence of character x in a string - how?
The string type has a replace function that does what you want. Except you can't change a string -- they are immutable -- so this creates a new string. >>> s = 'linux-raid.vger.kernel.org' >>> new_s = s.replace('.', '@', 1) >>> new_s 'linux-r...@vger.kernel.org' On 2/14/21 1:14 PM, c...@isbd.net wrote: What's the easiest way to change the first occurrence of a specified character in a string? E.g. I want to change linux-raid.vger.kernel.org to linux-r...@vger.kernel.org, it's a fairly general requirement of needing to change '.' to '@'. Alternatively is there an RE 'match' function that would test if linux-r...@vger.kernel.org matches linux-raid.vger.kernel.org? I don't really care if the '.' are all regarded as wild cards, the match will be accurate enough. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Calculations and Variables
On 10/31/19 11:46 AM, ferzan...@gmail.com wrote: The code below which I have written should print the result of 43.6 with the given values I have included at the end of this question, but for some odd reason I get the result of 44.44. bill = (input("Enter the total cost of the meal: \n")) tip = (input("Enter how much the tip is: \n")) split = (input("Enter how many people there are: \n")) total = bill + (bill / tip) Don't you mean total = bill + (bill * tip) ? eachPay = total / split print("Each person will have to pay %.2f" % eachPay) I am aiming for the result of 43.6, but somehow get the result of 44.44. (meal cost: 200) (Tip: 9) (people: 5) I seem to do the calculation below, but get different results each time. Total * Percentage Amount / 100 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Multiprocessing and memory management
On 7/3/19 9:37 AM, ijbrews...@alaska.edu wrote: I have a script that benefits greatly from multiprocessing (it’s generating a bunch of images from data). Of course, as expected each process uses a chunk of memory, and the more processes there are, the more memory used. The amount used per process can vary from around 3 GB (yes, gigabytes) to over 40 or 50 GB, depending on the amount of data being processed (usually closer to 10GB, the 40/50 is fairly rare). This puts me in a position of needing to balance the number of processes with memory usage, such that I maximize resource utilization (running one process at a time would simply take WAY to long) while not overloading RAM (which at best would slow things down due to swap). Obviously this process will be run on a machine with lots of RAM, but as I don’t know how large the datasets that will be fed to it are, I wanted to see if I could build some intelligence into the program such that it doesn’t overload the memory. A couple of approaches I thought of: 1) Determine the total amount of RAM in the machine (how?), assume an average of 10GB per process, and only launch as many processes as calculated to fit. Easy, but would run the risk of under-utilizing the processing capabilities and taking longer to run if most of the processes were using significantly less than 10GB Try psutil to get information about memory (and cpu usage and lots more). For example: >>> import psutil >>> psutil.virtual_memory() svmem(total=16769519616, available=9151971328, percent=45.4, used=7031549952, free=4486520832, active=9026158592, inactive=2238566400, buffers=312815616, cached=4938633216, shared=234295296, slab=593375232) Home page: https://github.com/giampaolo/psutil 2) Somehow monitor the memory usage of the various processes, and if one process needs a lot, pause the others until that one is complete. Of course, I’m not sure if this is even possible. 3) Other approaches? --- Israel Brewster Software Engineer Alaska Volcano Observatory Geophysical Institute - UAF 2156 Koyukuk Drive Fairbanks AK 99775-7320 Work: 907-474-5172 cell: 907-328-9145 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: CAD Application
On 5/5/19 10:23 PM, britt...@gmail.com wrote: Hello All, What are the frameworks available for developing a CAD application with Python? Regards Britto Well, there's PythonCadhttps://sourceforge.net/projects/pythoncad/ It seems to have stopped development about 5 years ago, but it's still available for download. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: namedtuples anamoly
On 10/17/2018 11:13 PM, me.vi...@gmail.com wrote: Hi, I tried using namedtuples and just found a behaviour which I am not able to conclude as correct behaviour. from collections import namedtuple (n, categories) = (int(input()), input().split()) Grade = namedtuple('Grade', categories) Grade.ID = 1 #print(Grade.ID) ob = Grade(10, 50) print(ob.ID) print(ob.MARKS) ob1 = Grade(20, 100) print(ob1.ID) 2 ID MARKS 1 50 1 100 If we set GRADE.ID =1 , Whoa! Don't do that. The Grade object created with the namedtuple call is a class, and part of it's internal implementation is stored in Grade.ID. Try these lines: >>> print(Grade) >>> print(Grade.ID) >>> By reassigning Grade.ID, you are sabotaging the internals of the class. Without looking at those internals, it's not really a surprise that things stop working after you destroy the it so carefully stored in Grade.ID. So now the real question is: What were you trying to accomplish with the assignment? Tell us, and let's see if we can find a way to accomplish yor goal without wrecking the internals of the Grade class. Gary Herron it has impact on all variables. Is this behaviour just like class variable and it has global scope. I expected ob.ID and ob1.ID to be 10. Correct me if Iam wrong. Appreciate any quick response. Kind Rgds, Vinu -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Advice on law firm
This is a Python related forum, but your question has nothing to do with Python. While you might get an answer here, I'm sure you could find a better place to post your question. On 10/17/2018 07:36 PM, rj.amdphr...@gmail.com wrote: Correction: specializing in warranty of merchantability, software licenses, and possibly class action suits. Sent from Mail for Windows 10 From: Ryan Johnson Sent: Wednesday, October 17, 2018 9:26 PM To: python-list@python.org Subject: Advice on law firm Anyone know a good US based law firm that specializes in software licenses and class action suits? Sent from Mail for Windows 10 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: My python code has suddenly started to give me error. Please see code below**
So, tell us the error and we'll see what we can do. Give us something to work with: Cut and past the full error message, trace back, whatever you can. Also tell us what version of Python, what system you are running on, how you run this code, ... On 10/08/2018 10:17 PM, upadhyay.kamay...@gmail.com wrote: ## Calculating the Lower Limits(LLi) and Upper Limit(ULi) for each Band, where i is 1,2,.10 LL1=0 print(LL1) print(P2) print(D2) if(P2>25): UL1=D1 print(UL1) elif(UL1==D2): print(UL1) LL2=UL1 if(P3>25): UL2=D2 print(UL2) elif(UL2==D3): print(UL2) LL3=UL2 if(P4>25): UL3=D3 print(UL3) elif(UL3==D4): print(UL3) LL4=UL3 if(P5>25): UL4=D4 print(UL4) elif(UL4==D5): print(UL4) LL5=UL4 if(P6>25): UL5=D5 print(UL5) elif(UL5==D6): print(UL5) LL6=UL5 if(P7>25): UL6=D6 print(UL6) elif(UL6==D7): print(UL6) LL7=UL6 if(P8>25): UL7=D7 print(UL7) elif(UL7==D8): print(UL7) LL8=UL7 if(P9>25): UL8=D8 print(UL8) elif(UL8==D9): print(UL8) LL9=UL8 if(P10>25): UL9=D9 print(UL9) elif(UL9==D10): print(UL9) LL10=UL9 UL10=("& Above") print(UL10) ** n1=int(UL1) count=0 while (n1>0): count=count+1 n1=n1//10 print(count) B11=LL1 If((count)/2)==0: B12=int((UL1)/(10**(count-2))) B12 elif(B12=int((UL1)/(10**(count-1: B12 B1=(B11,"-",B12,"M") B1 -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Program to find Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1.
On 10/02/2018 01:23 PM, tomusa...@gmail.com wrote: Primes of the form prime(n+2) * prime(n+1) - prime(n) +- 1. DATA 31, 71, 73, 137, 211, 311, 419, 421, 647, 877, 1117, 1487, 1979, 2447, 3079, 3547, 4027, 7307, 7309, 12211, 14243, 18911, 18913, 23557, 25439, 28729, 36683, 37831, 46853, 50411, 53129, 55457, 57367, 60251, 67339, 70489, 74797, 89669, 98909, 98911 EXAMPLE 7*5 - 3 - 1 = 31 11*7 - 5 - 1 = 71 11*7 - 5 + 1 = 73 13*11 - 7 + 1 = 137 Can someone put this in a Python program and post? No, sorry, but that's not how this works. We're not here to do your homework for you, and you won't learn anything if we do. You make an attempt at solving this, asking any specific Python related questions you need help with, and you'll find this to be prompt, friendly, and helpful group. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: import inspect error
You appear to have a local file named keyword.py which is hiding a python installation file of the same name. Gary Herron On 09/17/2018 01:06 AM, jupiter@gmail.com wrote: I have following errors running on Ubuntu 18, any insight how to fix it? Thank you. Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. import inspect Traceback (most recent call last): File "", line 1, in File "/usr/lib/python2.7/inspect.py", line 42, in from collections import namedtuple File "/usr/lib/python2.7/collections.py", line 22, in from keyword import iskeyword as _iskeyword File "keyword.py", line 3, in from inspect import currentframe, getframeinfo ImportError: cannot import name currentframe -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: trying to connect the setarrange and blendshape input target weight while running the script am getting error in the 8th line. (for each in lip_val_list: )
Your indentation of that line is incorrect. You also have indentation errors on lines 14 and 21. (Possibly more, that's all the further I checked.) Do you understand Python's indentation rules? In the future, you can do a lot better to help us help you. First, tell us the error you got instead of just saying you got an error. (Copy and paste the full error message.) Also tell us what version of Python (2 or 3), and what platform, in case any of that matters. Your subject line contains lots of meaningless distractions: What's a setarrange, what's a blendshape, what's an input target weight, what does it mean to connect them? Either none of that is important (as is the case in this simple indentation error), so don't include such distractions, or it does matter, so take the time to define those terms. Gary Herron On 09/13/2018 12:11 AM, christyso...@gmail.com wrote: lf_main_attr = "head_icon.Lf_Sticky_Lips" rt_main_attr = "head_icon.Rt_Sticky_Lips" lip_val_list = [18, 14] lip_name_list = ['upperLip', 'lowerLip'] name_counter = 0 for each in lip_val_list: half_val = (each / 2) + 1 total_val = each + 1 div_val = 10.0 / half_val counter = 0 while(counter -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Probability
On 09/11/2018 11:54 AM, end...@freemail.hu wrote: Hello, I am new to Python and I have an exercise which I struggle with. The question is: In the strategic board game called Risk, one player can attack up to three soldiers simultaneously, while the defending player can defend up to two. In the case of exactly three attackers and two defenders, the collision is as follows. An attacking player rolls three red dice while the defending player rolls two blue dice. Then they compare the bigest throws of the attacker and the defender. The lesser value loses a soldier, in the case of equal values the attacker loses one soldier. Then the second largest numbers are also compared in the same way. Thus, the battle has three outcomes: the attacker loses two soldiers, each side loses 1-1 soldiers, the defender loses two soldiers. Simulate 1000 times the experiment and determine the relative frequency of the three events.Simulate 100 times the experiment and determine the relative frequency of the three events.Calculate the exact probability of the three outcomes by examining all possible cases. The probability is the ratio of the favorable cases and the total number of cases. Write these results with 5 decimal places leaving 3 spaces between them! The output of the program looks like this (of course with other numbers) Attacker Draw Defender 1000 experiment 0.35222 0.4 0.20334 100 experiment 0.33988 0.43011 0.23001 Probability 0.34000 0.43000 0.23000 The aim of this task is to get acquainted with the classical probability field, the relative frequency and the relation of it to the probability.Programming goal: recalling the basic elements of Python programming and generating random numbers.Help: by loading the random package (import random) and calling random.random() one may get a random number between 0 and 1 (by uniform distribution). The code int(random.random()*6)+1 gives back an integer number between 1 and 6. So I did like: import random def dice(): attacker_dice=[random.randint(1,6) for _ in range(3)] defender_dice=[random.randint(1,6) for _ in range(2)] a=max(attacker_dice) b=max(defender_dice) for i in range(1000): F=0 S=0 T=0 if a>b: F+=1 if a==b: S+=1 else: T+=1 Every time through this loop, you set F, S and T to zero. If you want those variables to accumulate values, move the three initialization lines to before the loop: F = 0 S = 0 T = 0 for ... if a>b: F += 1 ... and so on ... But you have another problem. You simulate rolling the dice only once. For your 1000 trials, you need to roll the dice 1000 times. The first few lines that simulate the dice roll must be inside the loop so that each pass through the loop rolls the dice. and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 333. And to get 5digits after the zero i wanted to use "%.5f " %First. Could you help me to finish this, and tell me what am I doing wrong? Thank you -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Python Probability
On 09/11/2018 11:54 AM, end...@freemail.hu wrote: Hello, I am new to Python and I have an exercise which I struggle with. The question is: In the strategic board game called Risk, one player can attack up to three soldiers simultaneously, while the defending player can defend up to two. In the case of exactly three attackers and two defenders, the collision is as follows. An attacking player rolls three red dice while the defending player rolls two blue dice. Then they compare the bigest throws of the attacker and the defender. The lesser value loses a soldier, in the case of equal values the attacker loses one soldier. Then the second largest numbers are also compared in the same way. Thus, the battle has three outcomes: the attacker loses two soldiers, each side loses 1-1 soldiers, the defender loses two soldiers. Simulate 1000 times the experiment and determine the relative frequency of the three events.Simulate 100 times the experiment and determine the relative frequency of the three events.Calculate the exact probability of the three outcomes by examining all possible cases. The probability is the ratio of the favorable cases and the total number of cases. Write these results with 5 decimal places leaving 3 spaces between them! The output of the program looks like this (of course with other numbers) Attacker Draw Defender 1000 experiment 0.35222 0.4 0.20334 100 experiment 0.33988 0.43011 0.23001 Probability 0.34000 0.43000 0.23000 The aim of this task is to get acquainted with the classical probability field, the relative frequency and the relation of it to the probability.Programming goal: recalling the basic elements of Python programming and generating random numbers.Help: by loading the random package (import random) and calling random.random() one may get a random number between 0 and 1 (by uniform distribution). The code int(random.random()*6)+1 gives back an integer number between 1 and 6. So I did like: import random def dice(): attacker_dice=[random.randint(1,6) for _ in range(3)] defender_dice=[random.randint(1,6) for _ in range(2)] a=max(attacker_dice) b=max(defender_dice) for i in range(1000): F=0 S=0 T=0 if a>b: F+=1 if a==b: S+=1 else: T+=1 Every time through this loop, you set F, S and T to zero. If you want those variables to accumulate values, move the three initialization lines to before the loop: F = 0 S = 0 T = 0 for ... if a>b: F += 1 ... and so on ... But you have another problem. You simulate rolling the dice only once. For your 1000 trials, you need to roll the dice 1000 times. The first few lines that simulate the dice roll must be inside the loop so that each pass through the loop rolls the dice. and I wanted to divide the F,T,S with 6^5 and make a table. But its giving me zeros or 333. And to get 5digits after the zero i wanted to use "%.5f " %First. Could you help me to finish this, and tell me what am I doing wrong? Thank you -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: curve_fit in scipy
This is a Python forum, but what you are asking is not a Python question. You might find a better source of answers on a scipy specific forum. But here's my attempt at answers: On 06/19/2018 08:26 AM, sharan.basa...@gmail.com wrote: Hi All, I am working out an exercise on curve_fit function available scipy package. While I understand in general about curve_fit, I am unable to understand the following: params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) Firstly, I don't understand why test_func is passed as an argument to cur_fit You are trying to fit a curve to some data, right. The curve_fit procedure needs to know what curve you are trying to fit. Is it a linear curve, exponential, polynomial or ...? In this example it's a sine function with parameters for regulating amplitude and frequency. But it could be any function with any parameters. To be more precise, test_function is not a single function y=f(x), but a whole family of functions y=f(x; a,b) where a and b define a particular function. Secondly, I don't understand how curve_fit knows the number of arguments that test_func takes. Part of the dynamic nature of Python is that a function carries with it the number of parameters (as just one among many such properties). We call it "introspection" when we examine such properties of objects. The curve_fit function usees such an introspection to find that test_function has two parameters (a and b) defining the family of curves. Full code is available below for reference: import numpy as np # Seed the random number generator for reproducibility np.random.seed(0) x_data = np.linspace(-5, 5, num=50) y_data = 2.9 * np.sin(1.5 * x_data) + np.random.normal(size=50) # And plot it import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data) from scipy import optimize def test_func(x, a, b): return a * np.sin(b * x) params, params_covariance = optimize.curve_fit(test_func, x_data, y_data, p0=[2, 2]) print(params) plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, test_func(x_data, params[0], params[1]), label='Fitted function') plt.legend(loc='best') plt.show() -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: How can an int be '+' with a tuple?
In fact, the value of *any* is *not* an integer. The *any notation causes Python to pack all the arguments into a tuple. This feature is usually used when there are multiple (and an unknown number) of parameters, but it works perfectly well with a single parameter. Here's an example: >>> def progress(*any): print(any) >>> progress(1) (1,) >>> progress(1,2,3) (1, 2, 3) >>> On 06/02/2018 07:55 PM, jf...@ms4.hinet.net wrote: The attached is a script which can run under Python 3.4/Windows Vista correctly. One thing make me puzzled is that the "any + context" at line 18. The "any" was passed as an integer from line 43 and the "context" was defined as a tuple at line 35. This concatenation works! how? Best Regards, Jach Fong --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Numpy array
The "indexing" page of the documentation might help you with this: https://docs.scipy.org/doc/numpy-1.14.0/reference/arrays.indexing.html On 05/18/2018 09:50 PM, sharan.basa...@gmail.com wrote: This is regarding numpy array. I am a bit confused how parts of the array are being accessed in the example below. 1 import scipy as sp 2 data = sp.genfromtxt("web_traffic.tsv", delimiter="\t") 3 print(data[:10]) 4 x = data[:,0] 5 y = data[:,1] Apparently, line 3 prints the first 10 entries in the array line 4 & 5 is to extract all rows but only 1st and second columns alone for x and y respectively. I am confused as to how data[:10] gives the first 10 rows while data[:,0] gives all rows -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Weird side effect of default parameter
This is a well known feature of Python. It's a very common "gotcha" to new Python programmers. Google "Mutable default parameters in Python" for long list of explanations and fixes. In short, don't use a mutable object as a default parameter. Gary Herron On 05/03/2018 12:47 PM, python-list@python.org wrote: Hello, I don't understand the behavior of the code below. Why does the dict property "a" of both objects contain the same keys? This is only if "a=dict" is in the initializer. If I put self.a = dict() into the init function, I get two separate dicts class Foo(object): def __init__(self, x, a=dict()): self.x = x self.a = a self.a[x] = x c = Foo(1) d = Foo(2) print(c.__dict__) print(d.__dict__) robert -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: specifying the same argument multiple times with argparse
On 04/16/2018 02:31 PM, larry.mart...@gmail.com wrote: Is there a way using argparse to be able to specify the same argument multiple times and have them all go into the same list? For example, I'd like to do this: script.py -foo bar -foo baz -foo blah and have the dest for foo have ['bar', 'baz', 'blah'] From the argparse web page (https://docs.python.org/3/library/argparse.html): 'append' - This stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times. Example usage: >>> >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--foo', action='append') >>> parser.parse_args('--foo 1 --foo 2'.split()) Namespace(foo=['1', '2']) I hope that helps. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Please Help
On 01/26/2018 08:33 PM, mohammedfaraz...@gmail.com wrote: import numpy as np x=np.unit8([250) print(x) y=np.unit8([10]) print(y) z=x+y print(z) output [250] [10] [4] My question how is z [4] Despite all the typos in your post, you appear to be doing 8 bit unsigned arithmetic. Do you know what that means? The answer you might have expected (i.e. 260) does not fit in the 0 ... 255 range of 8 bits, and so the result has overflowed and "wrapped around" to produce 4. Try this for a simpler example of the same: >>> np.uint8(260) 4 Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: None is None but not working
On 09/27/2017 01:05 PM, Sayth Renshaw wrote: Hi I have got a successful script setup to rotate through dates and download json data from the url. As the api returns 200 whether successful I want to check if the file returned is not successful. when a file doesn't exist the api returns {'RaceDay': None, 'ErrorInfo': {'SystemId': 200, 'ErrorNo': 55013, 'DisplayMessage': 'File Not Found.', 'ContactSupport': False, 'SupportErrorReference': '200-55013'}, 'Success': False} When I call data = r.json() it says its type is None if it is not successful so I thought it easier to check that. However checking for None does not work the flow in my if else falls straight to else. for dates in fullUrl: r = requests.get(dates) data = r.json() if data is None: print("Nothing here") else: print(data["RaceDay"]) Your data is not None, it's a full dictionary. However, data["RaceDay"] *is* None as shown in your output. Thus your test should be: if data["RaceDay"] is None: ... rather than if data is None: ... and I get output of None None {'MeetingDate': '2017-01- ... and so on. How can I actually get this to check? If i use type(data) I also get None. Cheers Sayth -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
How to change variable from list to float
I have searched for a solution to this but have not found a suitable example. The attached code generates this error: Traceback (most recent call last): File "calcsignal.py", line 7, in siglevfromexist = 34.8 + existattn TypeError: unsupported operand type(s) for +: 'float' and 'list' How do I convert the list variable (i.e. existattn) to a float? Operating details are: Python 3.4.2 Debian 3.16.39-1+deb8u2 (2017-03-07) x86_64 GNU/Linux The following lines are the code in calcsignal.py: azdegpattrev = -47.40715077970316 azattndic = {-0.9: [-0.55], -0.5: [-0.46], 3.5: [-21.0], 1.4: [-7.48], 5.5: [-25.0], 0.0: [0.0], 1.9: [-21.0], 13.0: [-38.0], 15.0: [-39.0], 3.6: [-25.0], 20.0: [-39.0], -1.4: [-7.48], 90.0: [-65.0], -0.4: [-0.39], 0.5: [-0.46], 0.1: [-0.04], 1.0: [-1.31], -90.0: [-65.0], 40.0: [-42.0], 180.0: [-65.0], 1.5: [-10.0], -1.2: [-3.69], 0.3: [-0.28], -0.3: [-0.28], 0.2: [-0.15], -0.1: [-0.04], 1.1: [-2.34], -180.0: [-65.0], -0.2: [-0.15], 1.2: [-3.69], -40.0: [-42.0], 0.4: [-0.39], -5.5: [-25.0], -1.5: [-10.0], -20.0: [-39.0], 0.9: [-0.55], -3.5: [-21.0], -1.9: [-21.0], -15.0: [-39.0], -13.0: [-38.0], 1.3: [-5.39], -1.3: [-5.39], -3.6: [-25.0], -1.0: [-1.31], -1.1: [-2.34]} azlist = [-0.9, -0.5, 3.5, 1.4, 5.5, 0.0, 1.9, 13.0, 15.0, 3.6, 20.0, -1.4, 90.0, -0.4, 0.5, 0.1, 1.0, -90.0, 40.0, 180.0, 1.5, -1.2, 0.3, -0.3, 0.2, -0.1, 1.1, -180.0, -0.2, 1.2, -40.0, 0.4, -5.5, -1.5, -20.0, 0.9, -3.5, -1.9, -15.0, -13.0, 1.3, -1.3, -3.6, -1.0, -1.1] azlist = [float(i) for i in azlist] closestaz = min(azlist, key=lambda x: abs(x - azdegpattrev)) existattn = azattndic[closestaz] siglevfromexist = 34.8 + existattn -- https://mail.python.org/mailman/listinfo/python-list
Re: getting the center of mass of each part of a molecule
On 05/15/2017 01:29 PM, qasimp...@gmail.com wrote: Hi, I need to get the center of mass (COM) of each half of the ligand shown in the figure (https://i.stack.imgur.com/dtdul.png). I get the main COM all the ligand, lets say it is close to C1 atom. In addition to the main COM of all the ligand, I need to find the COM of each half of the ligand. The atoms of the first part/half according to the main COM of the ligand are C2, C7, C8 and C9. As for the second part they are C3, C4, C5 and C6 atoms. The question is how can I divide the ligand in two parts according to the main COM and calculate the COM of each divided part (except for the atom closest to the main COM, C1)? By the way I have multiple ligands. The code should be user firendly. A short part of the input file is here: 1LIG C11 4.434 5.366 1.780 1LIG C22 4.317 5.301 1.940 1LIG C33 4.430 5.286 1.888 1LIG C44 4.380 4.942 2.467 1LIG C55 4.148 4.929 2.443 A short snippet of the code used to get the main COM is here: def heavy_atoms(atoms, xyz, ligand="LIG"): ids = np.arange(len(atoms)) names = [(i[10:15].strip(),i[5:10].strip()) for i,j in atoms] # Ligand atoms lig_atoms = np.array([ rname == ligand and not aname.startswith('H') for aname,rname in names ]) lig_xyz = xyz[lig_atoms,:] # The main COM lig_com = xyz[lig_atoms, :].mean(axis=0) You seem to be asking a chemistry or biochemistry question on this Python programming list. We're a diverse group, but still, that seems to be a vast mismatch. Do you have any hint of an algorithm that will do what you want? Can you find one somewhere, or define one yourself? Once you have an algorithm, it would be appropriate to ask here for help in translating it into a Python program. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Write a function group(L).
On 04/21/2017 01:01 PM, Mohammed Ahmed wrote: Write a function group(L) that takes a list of integers. The function returns a list of two lists one containing the even values and another containing the odd values. it is a python question In fact, this is *not* a question, Python or otherwise. Welcome to python-list. If you ask a Python question, it will probably get answered. If you want someone to do your homework, it will probably not happen. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Who are the "spacists"?
On 03/18/2017 06:46 AM, Mikhail V wrote: On 18 March 2017 at 03:09, Joel Goldstick wrote: On Fri, Mar 17, 2017 at 8:52 PM, Mikhail V wrote: So Python supports both spaces and tabs for indentation. I just wonder, why not forbid spaces in the beginning of lines? How would one come to the idea to use spaces for indentation at all? Space is not even a control/format character, but a word separator. And when editors will be proportional font based, indenting with spaces will not make *any* sense so they are just annoyance. Neither makes it sense in general case of text editing. I think it would be a salvation to forbid spaces for indentation, did such attemps take place? This is not a useful conversation. It has been had over and over in the past. Some people like tabs, some like spaces. In python you can use either, but you must stick to one or the other Not to judge, but usually such opinions come from determined spasists. And "stick to one or the other" is exactly what would make life easier, but in literal sense of global preference. On 18 March 2017 at 05:02, Ben Finney wrote: Mikhail V writes: I just wonder, why not forbid spaces in the beginning of lines? Because that would make countless lines of existing Python code illegal. Yes, yes. And it is of course so hard to clean up spaces in existing code. As a mater of fact, and despite the snark, that is true. A quick count finds 46,209 .py files on my computer, spread across the OS, installed packages, and my own work. I would strongly resist anything that needs that much re-installation and personal attention. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: why this code loop forever after a draw a rectangle
On 09/16/2016 05:18 AM, meInvent bbird wrote: i follow this post to give some time it to operate, wait a long time still looping http://answers.opencv.org/question/60094/libpng-warning-image-width-is-zero-in-ihdr/ i can not stand this Ninja coding life any more, i have to open my code for ask this error import cv2 import numpy as np #from matplotlib import pyplot as plt import time #print("1=" + str(int(sys.argv[1]))) #print("2=" + str(int(sys.argv[2]))) #print("3=" + str(int(sys.argv[3]))) img_rgb = cv2.imread(r'C:\Users\martin\Documents\scree2.png') img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY) template = cv2.imread(r'C:\Users\martin\Documents\dragob.png',0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED) threshold = 0.64 loc = np.where( res >= threshold) pt = [(0,0)] while not zip(*loc[::-1]): threshold = threshold - 0.02 loc = np.where( res >= threshold) counter = 1 print("threshold="+str(threshold)) for pt2 in zip(*loc[::-1]): cv2.rectangle(img_rgb, pt2, (pt2[0] + w, pt2[1] + h), (0,0,255), 2) pt = pt2 crop_img = img_rgb[pt[1]:(pt[1]+h), pt[0]:(pt[0]+w)] counter = counter + 1 cv2.imwrite("C:\\Users\\tester\\Documents\\res.png",crop_img) #import cv2 #winName = "Movement Indicator" #cv2.namedWindow(winName, cv2.WINDOW_NORMAL) img = cv2.imread(r'C:\Users\tester\Documents\res.png',1) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) height, width = gray.shape edges = cv2.Canny(gray,height,width,apertureSize = 3) #edges = cv2.Canny(gray,30,200) #gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) #ret,thresh = cv2.threshold(edges.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE,0) ret,thresh = cv2.threshold(edges,250,150,0) contours,hierarchy = cv2.findContours(thresh, 1, 2) #contours = sorted(contours, key = cv2.contourArea, reverse = True)[:10] im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") #im = img.copy() while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #cv2.imwrite("C:\\Users\\martin\\Documents\\masda"+str(cntcounter)+".png",imi) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) On Friday, September 16, 2016 at 7:34:04 PM UTC+8, Waffle wrote: On 16 September 2016 at 14:24, meInvent bbird wrote: im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im) -- https://mail.python.org/mailman/listinfo/python-list not sure but.. this bit reads really suspicious: while im is None: time.sleep(1) if im is ever None then how will it ever become not None? unless there is some other thread at work i can't really see this happening. and if there is some other thread at work then there is probably some better solution than sleep() Reading the manual for opencv, we see that cv2.rectangle does indeed return None: Python: cv.Rectangle(img, pt1, pt2, color, thickness=1, lineType=8, shift=0) → None So the first pass through your loop
Re: why this code loop forever after a draw a rectangle
On 09/16/2016 04:24 AM, meInvent bbird wrote: im = img.copy() cntcounter = 0 for cnt in contours: epsilon = 0.1*cv2.arcLength(cnt,True) approx = cv2.approxPolyDP(cnt,epsilon,True) #peri = cv2.arcLength(cnt, True) #approx = cv2.approxPolyDP(c, 0.5 * peri, True) #print("len(approx)="+str(len(approx))) if len(approx) == 4: print("approx=" + str(approx)) cntcounter = cntcounter + 1 print("here1") x,y,w,h = cv2.boundingRect(cnt) print("here2") while im is None: time.sleep(1) if im is not None: print("here3") im = cv2.rectangle(im.copy(), (x,y), (x+w, y+h), (0,255,0), 2) #im = cv2.line(im,(x,y),(x+w,y),(0,255,0),2) #im = cv2.line(im,(x+w,y),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y+h),(x+w,y+h),(0,255,0),2) #im = cv2.line(im,(x,y),(x,y+h),(0,255,0),2) cv2.imwrite(r'C:\Users\tester\Documents\masda.png',im) These two lines: while im is None: time.sleep(1) are an infinite loop if im is None; Since you haven't told us what im (or img, contours, cv2) are, I can't tell how im might become None, but it does look like you (confusingly) use im for two different things: an img.copy() and a cv2.rectangle, whatever those may be. Pure guesswork: if cv2.rectangle draws a rectangle, what does it return? If it doesn't return anything, the line im = cv2.rectangle(...) is how im gets the value of None. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: degrees and radians.
On 08/23/2016 09:08 PM, murdocksgra...@gmail.com wrote: On Saturday, May 4, 2002 at 3:37:07 AM UTC-4, Jim Richardson wrote: -BEGIN PGP SIGNED MESSAGE- Hash: SHA1 I am trying to get the math module to deal with degrees rather than radians. (that it deals with radians for the angular functions like sin() isn't mentioned in the docs, which was sort of an eyeopener :) I can't find any info on doing this. I can convert from-to degrees in the code calling the function, but that's a bit clunky. Any pointers to an FM to R? :) -BEGIN PGP SIGNATURE- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE804+jd90bcYOAWPYRAt9KAKCuqeC4ozuXSaKZ5xY27Wv+k04QuQCcCrCZ WyichPnKgXo+GaDdAebsaeU= =h+vc -END PGP SIGNATURE- -- Jim Richardson Anarchist, pagan and proud of it http://www.eskimo.com/~warlock Linux, from watches to supercomputers, for grandmas and geeks. For what is is worth.. Electrical Engineers for the most part work in degrees NOT Radians for example try doing polar to rectangular or vice versa in polar. I have never seen it done. Also Borland C and C++ used Degrees and NOT Radians.. go look at the libraries Just for what its worth. Do you really need anything more complex than this? >>> toRadians = math.pi/180.0 >>> math.sin(90*toRadians) 1.0 Perhaps I'm not understanding what you mean by "clunky", but this seems pretty clean and simple to me. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
DED processing
I have to go out for a while, so for DED processing two options from my end: 1. Process as you all have been in the past for now. If you all do this, the records that have not been mailed prior to the latest list are contained in a MailManage Job name DED_master. If you chose to process as in the past, these records should be exported to a spreadsheet and added to whatever new file you have for today. 2. I can come in tomorrow morning at about 9:00 and walk Greg thru the way I process the DED job. Let me know. -- https://mail.python.org/mailman/listinfo/python-list
Re: A strange list concatenation result
On 08/11/2016 03:06 PM, Mok-Kong Shen wrote: def test(list1,list2): list1+=[4,5,6] list2=list2+[4,5,6] print("inside ",list1,list2) return # With list1=list2=[1,2,3] test(list1,list2) print("outside",list1,list2) # I got the following: # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6, 4, 5, 6] # outside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] # With list1=[1,2,3] list2=[1,2,3] test(list1,list2) print("outside",list1,list2) # I got the following: # inside [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] # outside [1, 2, 3, 4, 5, 6] [1, 2, 3] I think the following shows the same issue in a much simpler fashion: In this (and your first) example, there is only one list, although it has two names to reference it. >>> list1 = list2 = [1,2,3] >>> list1 += [4,5,6] >>> print(list1, list2) [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6] In this next example, there are two separate lists: >>> list1 = [1,2,3] >>> list2 = [1,2,3] >>> list1 += [4,5,6] >>> print(list1, list2) [1, 2, 3, 4, 5, 6] [1, 2, 3] Does that help? Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Operator precedence problem
On 06/04/2016 11:53 PM, ICT Ezy wrote: 2 ** 3 ** 2 Answer is 512 Why not 64? Order is right-left or left-right? Evidently right to left, but you already figured that out. Python 3.5.1+ (default, Mar 30 2016, 22:46:26) [GCC 5.3.1 20160330] on linux Type "help", "copyright", "credits" or "license" for more information. >>> 2 ** 3 ** 2 512 >>> 2 ** (3 ** 2) 512 >>> (2 ** 3) ** 2 64 >>> Here's the relevant documentation page: https://docs.python.org/3/reference/expressions.html Look for "... except for exponentiation, which groups from right to left" Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Spreading a class over multiple files
On 06/04/2016 11:55 PM, Mark Summerfield wrote: Sometimes I want to spread a class over multiple files. There’s and easy way to do this in Python using what's called a Mixin class and (multiple) inheritance: (See https://en.wikipedia.org/wiki/Mixin for more information.) In one file, say extras.py class ExtraMethodsMixin: def extra_1(...): ... def extra_2(...): ... In the main class file: from extras import ExtraMethodsMixin class MainClass(ExtraMethodsMixin): def __init__(...): ... # and so on The result will be essentially the same as if all three methods were defined in MainCLass. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 My primary use case is when I create a "Model" class to reflect an entire SQL database. I want a model instance to provide a single point of access to the database, but the database has many tables each requiring its own methods since they differ in their structure, purpose, validation needs, etc. A secondary use case is when I create "MainWindow" classes in GUI programming and have lots of methods to reflect all the actions (e.g., menu options and toolbar actions, plus interaction with the main widget(s)). To meet these needs I've devised an approach that I think is easy to use and understand and which doesn't use any tricky or hard to maintain code. My question is -- are there nicer/better ways to achieve this? Here's a summary of my approach. A fuller discussion is on my website: https://www.qtrac.eu/pyclassmulti.html # Lib.py # This provides the two functions (both decorators) used to support my approach def add_methods_from(*modules): def decorator(Class): for module in modules: for method in getattr(module, "__methods__"): setattr(Class, method.__name__, method) return Class return decorator def register_method(methods): # A decorator used purely for its side-effect def register_method(method): methods.append(method) return method # Unchanged and not strictly necessary return register_method # Model.py # This provides my model but some methods are in separate files import Lib import _ModelConfig import _ModelOutput @Lib.add_methods_from(_ModelConfig, _ModelOutput) class Model: ... def small_method(self): ... # _ModelConfig.py # _ModelOutput has the same structure so not shown import Lib __methods__ = [] # self is a Model register_method = Lib.register_method(__methods__) @register_method def config(self): ... So, that's the overall pattern of my solution. Is there a nicer/better way? Could I cleanly avoid the explicit imports (e.g., import _ModelConfig), without resorting to stack frame hacks or similar? -- https://mail.python.org/mailman/listinfo/python-list
Re: Image loading problem
On 05/21/2016 08:22 AM, sweating_...@yahoo.com wrote: Hi All, I am working on an image project, and I can display my image in main(). I mean, I can load my image in my main(). Needless, it is awkward. I am trying to load my image with a function, but got an empty image window popped up, no image content loaded. Please take a look at code: rom Tkinter import * def load_img(win): img = PhotoImage(file="xxx.gif") Label(win, image=img).pack() win = Tk() load_img(win) win.mainloop() Somebody can help me out? Thanks! I believe this the problem (However It's been long since I used Tkinter, so be warned ... ): The function load_img creates a local variable named img which goes out of scope and is deleted immediately when the function returns. However, Tkinter needs you to keep that image around as long as the Label uses it. So, some solutions are: keep_me = [] # Global for keeping references to images def load_img(win): img = PhotoImage(file="xxx.gif") keep_me.append(img) Label(win, image=img).pack() or def load_img(win): img = PhotoImage(file="xxx.gif") Label(win, image=img).pack() return img saved_img = load_img(win) ... Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: def __init__(self):
On 04/26/2016 06:49 AM, Random832 wrote: On Tue, Apr 26, 2016, at 03:34, Ben Finney wrote: That's needlessly confusing: ‘__init__’ is not a constructor because it does not construct the instance. The ‘__new__’ method is the constructor for a class (and returns the new instance). the __new__ method is the *allocator*. "constructor" is used in many languages to name a method that initializes an object once it already "exists". Saying you can't call it that in Python is needlessly confusing. Agreed. For a newbie asking about __init__, I'll stick with my original answer (that it's the constructor), and suggest ignoring the overly pedantic (and confusing) response to the contrary. -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: def __init__(self):
On 04/25/2016 11:21 PM, San wrote: Hi All, Pls let me why " def __init__(self): " declaration required, what's the use of this one.Pls explain me in details. Thanks in advance. If you understand object-oriented-programming, then this will make sense: The __init__ method is the constructor for instances of a class. It is not required, but the situations in which a constructor is not needed are few and unusual. If you don't know object-oriented-programming, then I'd suggest you put that high on your list of things to learn. It's a valuable tool. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: what is the difference between one-line-operation and 2-line-operation
On 04/25/2016 07:13 AM, oyster wrote: for a simple code [code] vexList = [1, 2, 3] print('vexList', list(vexList)) vexList=map(lambda e: e+1, vexList) print('vexList', list(vexList)) vexList = list(vexList) print('vexList', list(vexList)) vexList=map(lambda e: e*2,vexList) print('vexList', list(vexList)) [/code] py27 says [quote] ('vexList', [1, 2, 3]) ('vexList', [2, 3, 4]) ('vexList', [2, 3, 4]) ('vexList', [4, 6, 8]) [/quote] but py34 says [quote] vexList [1, 2, 3] vexList [2, 3, 4] vexList [] vexList [] [/quote] The difference in behaviour between Python2 and Python3 is the map function. In P2 it returned a list, while in P3 it returns an iterator. Your code runs through that iterator twice with the list() function. The first time it gets the elements of the list as expected, but the second time, the iterator is exhausted and returns no objects. A simpler example: "b" is a map object (iterator), then list(b) is run twice. >>> a = [1,2,3] >>> b = map(lambda e: e+1, a) >>> b >>> list(b) [2, 3, 4] >>> list(b) [] I hope that helps. Gary Herron -- Dr. Gary Herron Professor of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Exclude every nth element from list?
On 03/26/2016 09:49 AM, beliavsky--- via Python-list wrote: I can use x[::n] to select every nth element of a list. Is there a one-liner to get a list that excludes every nth element? Yes: >>> L=list(range(20)) >>> [x for i,x in enumerate(L) if i%3 != 0] [1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19] Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: PLEASE HELP -- TOTALLY NEW TO PYTHON
On 03/25/2016 10:31 PM, Juan Dent wrote: I am trying to run ‘python cppdep.py’ but get the following: I would guess that this code was written some time ago for Python2, but that you have downloaded and run it with Python3. Try installing Python2 instead of Python3. Or try talking whoever wrote it into converting it to Python3. Or my guess is completely wrong and the code is buggy and won't run until fixed. (Which brings up the questions: What is cppdep.py? Who wrote it? How do you know that it runs?) Gary Herron analyzing dependencies among all components ... Traceback (most recent call last): File "cppdep.py", line 675, in main() File "cppdep.py", line 643, in main calculate_graph(digraph) File "cppdep.py", line 570, in calculate_graph (cycles, dict_node2cycle) = make_DAG(digraph, key_node) File "/Users/juandent/Downloads/cppdep-master/networkx_ext.py", line 79, in make_DAG for ind in range(len(subgraphs)-1, -1, -1): TypeError: object of type 'generator' has no len() Please, I know no python and am in a hurry to get this working… Please help Regards, Juan -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Struggeling with collections
On 03/07/2016 12:24 AM, Faling Dutchman wrote: Hey folks, I am just starting off in python, but have good knowledge of both Java and C#. Now is the problem that I need to have multiple instances of one dictionary, that is not a problem if you know how many, but now, it is an unknown amount. Some background info: I am making a library for an API. This library must be easy to use for the people who are going to use it. So I am making the models for the data, the connections and so on, so they just have to fill in the gaps. In C# and Java I did it with objects, but they do not work alike in python, or at least that is what I have found. If I do this: class Item: def __init__(self, id, productId, quantity, pageCount, files, option, metadata): self.id = id self.productId = productId self.quantity = quantity self.pageCount = pageCount self.files = files self.option = option self.metadata = metadata itm = Item(1,None,1,1,'asdf',{'asdf': 3, 'ads': 55},None) print(itm) it prints: <__main__.Item object at 0x02EBF3B0> So that is not usefull to me. There can be an infinite amount of objects of Item, and it needs to be easy accessable, just like for i in items print(i) and it has to show all the parameters of the class Item and not say "ive got an object at this memory address, have a nice day" I hope my question is clear. It's not clear in the slightest. In fact there isn't even a question here. Ignoring everything about numbers of objects and libraries and access (of what?), it seems you want an object of type Item to be able to print itself nicely.Please correct me if I've got that wrong. You can do so by defining a member __str__ (or __repr__). Here's a small example. The returned formatted string can be as simple or complex as you wish. >>> class C: ... def __init__(self, a, b): ... self.a = a ... self.b = b ... def __str__(self): ... return "C(a={}, b={})".format(self.a, self.b) # Modify to suit your needs. ... >>> print(C(1,2)) C(a=1, b=2) >>> Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: list reversal error
On 03/03/2016 02:51 PM, vlyamt...@gmail.com wrote: i have list of strings "data" and i am trying to build reverse list data1 data1 = [] for i in range(len(data)): j = len(data) - i data1.append(data[j]) but i have the following error: data1.append(data[j]) IndexError: list index out of range am i doing it wrong? Thanks Look at the values (say with a print) you get from your line j = len(data) - i You'll find that that produces (with a list of 4 elements for example) 4,3,2,1 when in fact you want 3,2,1,0. Soo you really want j = len(data) - i -1 Better yet, use more of Python with data1 = list(reversed(data)) Or don't even make a new list, just reverse the original list in place >>> L=[1,2,3] >>> L.reverse() >>> L [3, 2, 1] Or even better, if you simply want to iterate through the original list, but in reverse order: for datum in reversed(data): ... whatever with datum ... which wastes no time actually reversing the list, but simply loops through them back to front. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with dateutil
On 02/13/2016 12:27 PM, Tom P wrote: On 02/13/2016 07:13 PM, Gary Herron wrote: On 02/13/2016 09:58 AM, Tom P wrote: I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? Yes, there is a way to specify your own format. Search the datetime documentation for datetime.strptime(date_string, format) Gary Herron Thanks. I started out with datetime.strptime but AFAICS that means I have to go through try/except for every conceivable format. Are you saying that I can't use dateutil.parser? Well now... If by "every conceivable format" you are including formats that the author of dateutil.parser did not conceive of, then of course you cannot use dateutil.parser. But you have the code for dateutil.parser -- perhaps you could modify it to accept whatever odd formats you care about. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: problem with dateutil
On 02/13/2016 09:58 AM, Tom P wrote: I am writing a program that has to deal with various date/time formats and convert these into timestamps. It looks as if dateutil.parser.parse should be able to handle about any format, but what I get is: datetimestr = '2012-10-22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2012, 10, 22, 11, 22, 33) However: datetimestr = '2012:10:22 11:22:33' print(dateutil.parser.parse(datetimestr)) result: datetime.datetime(2016, 2, 13, 11, 22, 33) In other words, it's getting the date wrong when colons are used to separate :MM:DD. Is there a way to include this as a valid format? Yes, there is a way to specify your own format. Search the datetime documentation for datetime.strptime(date_string, format) Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: import cannot be used inside eval
On 02/03/2016 09:03 PM, 阎兆珣 wrote: a = input("tell me which py to execute: ") print(a) print('import '+a) print(type('import'+a)) eval('print(a)') Eval is meant to evaluate Python expressions. The import is a statement, not an expression. Also, it's a bad idea to use eval like this, and it's a *really* bad idea to use eval with user supplied input. The user could inject *any* malicious code. Instead, use the importlib module to programmatically import a module. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Duplicate Output
Hi Debian stretch OS KDE Desktop Code written with Kate Run in command line with $python getFileNames.py Code: from os import walk import subprocess f = [] x = "" for (dirpath, dirnames, filenames) in walk('.'): print(filenames) This prints [][] What am I doing wrong or how do I remove the duplicate list. Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: 'string.join' is wrong in my Python console
On 12/02/2015 10:55 PM, Robert wrote: Hi, I read the tutorial on "Why is join() a string method instead of a list or tuple method?" at link: https://docs.python.org/2/faq/design.html#why-must-self-be-used-explicitly-in-method-definitions-and-calls I have a problem on running the last line: --- If none of these arguments persuade you, then for the moment you can continue to use the join() function from the string module, which allows you to write string.join(['1', '2', '4', '8', '16'], ", ") --- My Python console is 2.7. It should be no problem because I see the tutorial is 2.7 too. The console has these display: string.join(['1', '2', '4', '8', '16'], ", ") --- NameError Traceback (most recent call last) in () > 1 string.join(['1', '2', '4', '8', '16'], ", ") NameError: name 'string' is not defined From the context, I don't see string should be replaced by something else. Could you tell me why I have such an error? You are trying to use the *string* module without importing it, I'd guess. Try: import string first then you should be able to access string.join without error. Gary Herron Thanks, -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: reading from a txt file
On 11/26/2015 12:34 PM, vincentype...@gmail.com wrote: Hey, I'm wondering how to read individual strings in a text file. I can read a text file by lines with .readlines() , but I need to read specifically by strings, not including spaces. Thanks in advance Read the lines with readlines(), as you say, then split each line into whatever pieces you want with split (or with any of the many other string methods). A minimal example (without readlines): >>> lines = ['a b c', 'aa bb cc'] >>> for line in lines: ... words = line.split() ... print(words) ... ['a', 'b', 'c'] ['aa', 'bb', 'cc'] -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Why won't this run?
On 11/15/2015 12:38 PM, jbak36 wrote: Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32 Type "copyright", "credits" or "license()" for more information. #this program says hello and asks for my name print:('Hello world!') Hello world! You are lying to us somehow. That attempt to print (as you've written it) does not produce the the line of output you've indicated. Instead it produces a syntax error, because Python does not use a colon in that situation. So change your print:(...) lines to print(...) (without the colon) and try again. If there is further trouble, ask another question, but please cut and paste the actual and *exact* results into the email. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Pyvenv use
Hi all, I needed to switch a projects from python 2.7 to 3.4 and had trouble setting up the virtual environment using the virtualenvwrapper utility. It seemed to want to install python 2.7 no matter what I did. I switched to pyvenv which solved the problem. But I now need to completely clean out the virtual environment and can't seem to figure you how to do this. The utilities like lsvirtualenv and rmvirtualenv are not available and I can no longer find a .vertualenv file. Is anyone conversant enough with pyvenv to help. There are several howto's showing how to use pyvenv to set up a virtual environment but nothing showing how to locate and clean house afterwards. The --clean may work but requires a reinstall. The resulting environment gives error messages when I try using pip to reinstall django or python. Further, trying to start a new project with django-admin.py loads the bin, include and lib directories into the project instead of the normal django setup. django 1.8 Debian 8 (jessie) OS python 3.4 Any help will be sincerely appreciated. Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Errors installing xmiparser with Python 3.4 and windows - any help?
Laura, Thanks for the pointer to PyXB, I think this will work for my purposes and it appears to be Python 3.4 / Windows compatible. Thank you to all who helped. On Friday, October 9, 2015 at 1:14:32 PM UTC-5, Laura Creighton wrote: > In a message of Fri, 09 Oct 2015 10:24:34 -0700, Gary Hanyzewski writes: > >I am trying to install xmiparser-1.5.dev-r124826 into python 3.4.0 on a > >windows machine. > >When I try and install (either with pip or setup.py install) I get a number > >of syntax errors in the code ( below) > > > >Has anyone managed to install and use the xmiparser module in python 3.4? If > >so what's the trick? if not any pointers on what I can do to get it to go. > >Are there any other xmi parsers or tools? > > > >Thanks > > > >Gary > > If XMI is just XML according to a particular schema, then you can get the > schema over here: http://www.omg.org/spec/XMI/2.5.1/ > > And then parse it with PyXB. > https://pypi.python.org/pypi/PyXB > > But maybe I don't understand what XMI is well enough. > > Laura -- https://mail.python.org/mailman/listinfo/python-list
Errors installing xmiparser with Python 3.4 and windows - any help?
I am trying to install xmiparser-1.5.dev-r124826 into python 3.4.0 on a windows machine. When I try and install (either with pip or setup.py install) I get a number of syntax errors in the code ( below) Has anyone managed to install and use the xmiparser module in python 3.4? If so what's the trick? if not any pointers on what I can do to get it to go. Are there any other xmi parsers or tools? Thanks Gary Error output below -- >python setup.py install running install running bdist_egg running egg_info writing entry points to xmiparser.egg-info\entry_points.txt writing namespace_packages to xmiparser.egg-info\namespace_packages.txt writing requirements to xmiparser.egg-info\requires.txt writing dependency_links to xmiparser.egg-info\dependency_links.txt writing xmiparser.egg-info\PKG-INFO writing top-level names to xmiparser.egg-info\top_level.txt reading manifest file 'xmiparser.egg-info\SOURCES.txt' writing manifest file 'xmiparser.egg-info\SOURCES.txt' installing library code to build\bdist.win-amd64\egg running install_lib running build_py creating build\bdist.win-amd64\egg creating build\bdist.win-amd64\egg\xmiparser creating build\bdist.win-amd64\egg\xmiparser\doc copying build\lib\xmiparser\doc\umlsample.zargo -> build\bdist.win-amd64\egg\xmi parser\doc copying build\lib\xmiparser\interfaces.py -> build\bdist.win-amd64\egg\xmiparser creating build\bdist.win-amd64\egg\xmiparser\tests copying build\lib\xmiparser\tests\test_doctest.py -> build\bdist.win-amd64\egg\x miparser\tests copying build\lib\xmiparser\tests\xmiparser.txt -> build\bdist.win-amd64\egg\xmi parser\tests copying build\lib\xmiparser\tests\__init__.py -> build\bdist.win-amd64\egg\xmipa rser\tests copying build\lib\xmiparser\utils.py -> build\bdist.win-amd64\egg\xmiparser copying build\lib\xmiparser\xmiparser.py -> build\bdist.win-amd64\egg\xmiparser copying build\lib\xmiparser\zargoparser.py -> build\bdist.win-amd64\egg\xmiparse r copying build\lib\xmiparser\__init__.py -> build\bdist.win-amd64\egg\xmiparser byte-compiling build\bdist.win-amd64\egg\xmiparser\interfaces.py to interfaces.c python-34.pyc byte-compiling build\bdist.win-amd64\egg\xmiparser\tests\test_doctest.py to test _doctest.cpython-34.pyc byte-compiling build\bdist.win-amd64\egg\xmiparser\tests\__init__.py to __init__ .cpython-34.pyc byte-compiling build\bdist.win-amd64\egg\xmiparser\utils.py to utils.cpython-34. pyc byte-compiling build\bdist.win-amd64\egg\xmiparser\xmiparser.py to xmiparser.cpy thon-34.pyc File "build\bdist.win-amd64\egg\xmiparser\xmiparser.py", line 400 raise TypeError, 'element %s has empty taggedValue' % self.getId(el) ^ SyntaxError: invalid syntax byte-compiling build\bdist.win-amd64\egg\xmiparser\zargoparser.py to zargoparser .cpython-34.pyc byte-compiling build\bdist.win-amd64\egg\xmiparser\__init__.py to __init__.cpyth on-34.pyc creating build\bdist.win-amd64\egg\EGG-INFO copying xmiparser.egg-info\PKG-INFO -> build\bdist.win-amd64\egg\EGG-INFO copying xmiparser.egg-info\SOURCES.txt -> build\bdist.win-amd64\egg\EGG-INFO copying xmiparser.egg-info\dependency_links.txt -> build\bdist.win-amd64\egg\EGG -INFO copying xmiparser.egg-info\entry_points.txt -> build\bdist.win-amd64\egg\EGG-INF O copying xmiparser.egg-info\namespace_packages.txt -> build\bdist.win-amd64\egg\E GG-INFO copying xmiparser.egg-info\not-zip-safe -> build\bdist.win-amd64\egg\EGG-INFO copying xmiparser.egg-info\requires.txt -> build\bdist.win-amd64\egg\EGG-INFO copying xmiparser.egg-info\top_level.txt -> build\bdist.win-amd64\egg\EGG-INFO creating 'dist\xmiparser-1.5.dev_r124826-py3.4.egg' and adding 'build\bdist.win- amd64\egg' to it removing 'build\bdist.win-amd64\egg' (and everything under it) Processing xmiparser-1.5.dev_r124826-py3.4.egg removing 'c:\python34\lib\site-packages\xmiparser-1.5.dev_r124826-py3.4.egg' (an d everything under it) creating c:\python34\lib\site-packages\xmiparser-1.5.dev_r124826-py3.4.egg Extracting xmiparser-1.5.dev_r124826-py3.4.egg to c:\python34\lib\site-packages File "c:\python34\lib\site-packages\xmiparser-1.5.dev_r124826-py3.4.egg\xmipar ser\xmiparser.py", line 400 raise TypeError, 'element %s has empty taggedValue' % self.getId(el) ^ SyntaxError: invalid syntax xmiparser 1.5.dev-r124826 is already the active version in easy-install.pth Installed c:\python34\lib\site-packages\xmiparser-1.5.dev_r124826-py3.4.egg Processing dependencies for xmiparser==1.5.dev-r124826 Searching for zope.interface Reading https://pypi.python.org/simple/zope.interface/ Best match: zope.interface 4.1.3 Downloading https://pypi.python.org/packages/source/z/zope.interface/zope.interf ace-4.1.3.tar.gz#md5=9ae3d24c0c7415deb249dd1a132f0f79 Processing zope.interface-4.1.3.tar.gz Writing C:\Users\GHANYZ~1\AppData\Local\Temp\easy_install-hnq
Re: Lesson 39 of Learning Python the Hard Way hangs (Fixed?)
On 09/09/2015 01:45 PM, John Gordon wrote: In Gary Roach writes: Traceback (most recent call last): File "/root/mystuff/mystuff/ex39_test.py", line 6, in hashmap.set(states, 'Oregon', 'OR') File "/root/mystuff/mystuff/hashmap.py", line 50, in set i, k, v = get_slot(aMap, key) TypeError: 'NoneType' object is not iterable Execution Successful! Where does the message "Execution Successful!" come from? It seems like you have other code that you haven't shown us. In any case, I saved your code and ran it, and did not get an error. No other code. Ninja-IDE tacked the "Execution Successful" at the end if the error message. Dont know why. Interesting that you ran the code successfully. I have tried to run the code in both Ninja and at the command line and got the exact same error message. A note: If you could, please post your replies to the list. If you don't, it either breaks the thread or ends up sending a copy to my personal email address. I am assuming that your email client gives you that choice. If not, I'm not sure how you would assure that the proper way happens. I use the icedove (thunderbird) mail client and the choice is a drop down list at the top of the mail editor page. Thanks for your reply. Still confused Gary R. PS I copied over my code with the one from the lesson and all of a sudden it works. I then used the code I copied to the email. It also worked. Now I can't duplicate the problem. The problems fixed but -- https://mail.python.org/mailman/listinfo/python-list
Re: Lesson 39 of Learning Python the Hard Way hangs
On 09/09/2015 01:45 PM, John Gordon wrote: In Gary Roach writes: Traceback (most recent call last): File "/root/mystuff/mystuff/ex39_test.py", line 6, in hashmap.set(states, 'Oregon', 'OR') File "/root/mystuff/mystuff/hashmap.py", line 50, in set i, k, v = get_slot(aMap, key) TypeError: 'NoneType' object is not iterable Execution Successful! Where does the message "Execution Successful!" come from? It seems like you have other code that you haven't shown us. In any case, I saved your code and ran it, and did not get an error. No other code. Ninja-IDE tacked the "Execution Successful" at the end if the error message. Dont know why. Interesting that you ran the code successfully. I have tried to run the code in both Ninja and at the command line and got the exact same error message. A note: If you could, please post your replies to the list. If you don't, it either breaks the thread or ends up sending a copy to my personal email address. I am assuming that your email client gives you that choice. If not, I'm not sure how you would assure that the proper way happens. I use the icedove (thunderbird) mail client and the choice is a drop down list at the top of the mail editor page. Thanks for your reply. Still confused Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Lesson 39 of Learning Python the Hard Way hangs (Fixed?)
On 09/09/2015 01:45 PM, John Gordon wrote: In Gary Roach writes: Traceback (most recent call last): File "/root/mystuff/mystuff/ex39_test.py", line 6, in hashmap.set(states, 'Oregon', 'OR') File "/root/mystuff/mystuff/hashmap.py", line 50, in set i, k, v = get_slot(aMap, key) TypeError: 'NoneType' object is not iterable Execution Successful! Where does the message "Execution Successful!" come from? It seems like you have other code that you haven't shown us. In any case, I saved your code and ran it, and did not get an error. No other code. Ninja-IDE tacked the "Execution Successful" at the end if the error message. Dont know why. Interesting that you ran the code successfully. I have tried to run the code in both Ninja and at the command line and got the exact same error message. A note: If you could, please post your replies to the list. If you don't, it either breaks the thread or ends up sending a copy to my personal email address. I am assuming that your email client gives you that choice. If not, I'm not sure how you would assure that the proper way happens. I use the icedove (thunderbird) mail client and the choice is a drop down list at the top of the mail editor page. Thanks for your reply. Still confused Gary R. PS I copied over my code with the one from the lesson and all of a sudden it works. I then used the code I copied to the email. It also worked. Now I can't duplicate the problem. The problems fixed but -- https://mail.python.org/mailman/listinfo/python-list
Lesson 39 of Learning Python the Hard Way hangs
Hi all I am new to python but not programming (Although rusty) and am using Learning Python The Hard Way. I really like it. System: --- Debian 8 (jessie) KDE Desktop Python 2.7 (It's going to be a while before 2,7 goes away. There is just too much code out there. Ninja-IDE IDE - I like this a lot. I can't seem to find out how to put breaks into the code though. The debugger plugin is installed. -- For some reason lesson 39 is hanging and I can't find the cause. A print statement inserted into the get_slot function just after bucket shows that get_bucket is returning an []. It' not surprising that enumerate() doesn't like this very much. I just can't find the cause. The error message is as follows: --- Running: /root/mystuff/mystuff/ex39_test.py (Wed Sep 9 09:57:51 2015) Traceback (most recent call last): File "/root/mystuff/mystuff/ex39_test.py", line 6, in hashmap.set(states, 'Oregon', 'OR') File "/root/mystuff/mystuff/hashmap.py", line 50, in set i, k, v = get_slot(aMap, key) TypeError: 'NoneType' object is not iterable Execution Successful! NOTE: Line 50 is the - i, k, v = get_slot(aMap, key)- of def set. The calling code is: # -*- coding: utf-8 -*- import hashmap # creat a mapping of stat to abbreviation states = hashmap.new() hashmap.set(states, 'Oregon', 'OR') The hashmap code is as follows: def new(num_buckets=256): """Initializes a Map with the given number of buckets.""" aMap = [] for i in range(0, num_buckets): aMap.append([]) return aMap def hash_key(aMap, key): """Given a key this will create a number and then convert it to an index for the aMap's buckets.""" return hash(key) % len(aMap) def get_bucket(aMap, key): """Given a key, find the bucket where it would go.""" bucket_id = hash_key(aMap, key) return aMap[bucket_id] def get_slot(aMap, key, default=None): """ Returns the index, key, and value of a slot found in a bucket. Returns -1, key, and default (None if not set) when not found. """ bucket = get_bucket(aMap, key) for i, kv in enumerate(bucket): k, v = kv if key == k: return i, k, v return -1, key, default def get(aMap, key, default=None): """Gets the value in a bucket for the given key, or the default.""" i, k, v = get_slot(aMap, key, default=default) return v def set(aMap, key, value): """Sets the key to the value, replacing any existing value.""" bucket = get_bucket(aMap, key) i, k, v = get_slot(aMap, key) if i >= 0: # the key exists, replace it bucket[i] = (key, value) else: # the key does not, append to create it bucket.append((key, value)) def delete(aMap, key): """Deletes the given key from the Map.""" bucket = get_bucket(aMap, key) for i in xrange(len(bucket)): k, v = bucket[i] if key == k: del bucket[i] break def list(aMap): """Prints out what's in the Map.""" for bucket in aMap: if bucket: for k, v in bucket: print k, v Very frustrating and probably a stupid error. Any help will be sincerely appreciated. Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: Is Django the way to go for a newbie?
On 08/08/2015 09:08 PM, Dwight GoldWinde wrote: I am both new to Python and I haven’t even touched Django yet. I understand I that I need Django or something like it to develop my website. From what I have read, Python and Django somewhat go together. Is that true? Or is there another development platform better for someone like me than Django? Any and all feedback or questions are much appreciated. BIG SMILE... Always, Dwight www.3forliving.key.to (video playlist on YouTube) www.couragebooks.key.to (all my books on Amazon) I'm also somewhat of a newbie but seem to be a little further down the road than you are. So hear is some advise from someone with recent bruises. The advise to learn python first is a very good piece of advice. I tried Postgresql and Django first and got bogged down just about the time that I was starting to get past the setup phase. You might try "Learning Python The Hard Way". It's working for me. Django v.s. other frameworks. It depends on what you want to do. I'm working on a data archiving project so the fact that Dango was / is developed by a couple of newspaper journalists fits well with my project. This may not be true for you. I will say that once you set the system up you will probably never see the sql database again. A very good thing. What ever you do set up virtualenv and vertualenvwrapper. Not only will this keep you project code away from the rest of your system, it will allow you to run different versions of software simultaneously. (Note: Unless you are using SQLite your database engine will be installed globally. Everything else inside the wrapper using pip.) There are a lot of scripting languages out there and everyone has a favorite. No matter what Python strikes me as being a good choice. You will need some kind of an Integrated Development Environment (IDE). I happen to like Ninja-Ide. (Don't everyone start throwing rocks. We all have our favorites. An no, I haven't checked them all out.) This is my first programming in some years too. I use to be a whiz at fortran, C and Xbase but haven't done anything since I retired. Good luck Gary R -- https://mail.python.org/mailman/listinfo/python-list
Re: Improper Django Project error (solved)
On 07/30/2015 11:15 PM, dieter wrote: Gary Roach writes: Being new to Django and Python, I have two projects setup side by side, each in it's own virtualenv wrapper. The twr_project is running Django 1.7, python 2.7 and is set up to duplicate the 'Tango With Rango' tutorial. The archivedb project is running Django 1.8, python 2.7 and is my actual project. As this is more a "Django" (than a general "Python") question, you might get better help in a "Django" mailing list/support forum. Actually you are dead correct on that. Your "subject" indicates that you likely see (somewhere) the "Django" error message "Improper Django Project error". Likely, you have corrupted you "Django" project setup. Read about how "Django" projects must look like and fix your setup. The real problem was that the settings.py files for Django 1.7 and 1.8 have some very significant differences with the format of the TEMPLATES = [] tuple. So the problem's solved --- sort of . I am using Ninja-IDE as my IDE. I like it a lot. At this point both projects are essentially identical with the exception of name changes. The twr project work down to the first template inclusion ( index.html ). The archivedb project refuses to find the home.html template file. The system layout is exactly the same. I wiped the home.html file and attempted to re-install it but my IDE gave the following error window: Sorry, either settings file or virtualenv are missingthese are required for Django Plugin to work in thepresent version, we are working on fixing this. I have virtualenv installed and active and the settings file is present. You should ask this question on a "Ninja-IDE" mailing list/support forum. Ninja_IDE is just reporting an apparent problem. The real problem is that the browser can't find the file. A Django problem. -- https://mail.python.org/mailman/listinfo/python-list
Re: Improper Django Project error (solved)
On 07/30/2015 11:15 PM, dieter wrote: Gary Roach writes: Being new to Django and Python, I have two projects setup side by side, each in it's own virtualenv wrapper. The twr_project is running Django 1.7, python 2.7 and is set up to duplicate the 'Tango With Rango' tutorial. The archivedb project is running Django 1.8, python 2.7 and is my actual project. As this is more a "Django" (than a general "Python") question, you might get better help in a "Django" mailing list/support forum. Actually you are dead correct on that. Your "subject" indicates that you likely see (somewhere) the "Django" error message "Improper Django Project error". Likely, you have corrupted you "Django" project setup. Read about how "Django" projects must look like and fix your setup. The real problem was that the settings.py files for Django 1.7 and 1.8 have some very significant differences with the format of the TEMPLATES = [] tuple. So the problem's solved --- sort of . I am using Ninja-IDE as my IDE. I like it a lot. At this point both projects are essentially identical with the exception of name changes. The twr project work down to the first template inclusion ( index.html ). The archivedb project refuses to find the home.html template file. The system layout is exactly the same. I wiped the home.html file and attempted to re-install it but my IDE gave the following error window: Sorry, either settings file or virtualenv are missingthese are required for Django Plugin to work in thepresent version, we are working on fixing this. I have virtualenv installed and active and the settings file is present. You should ask this question on a "Ninja-IDE" mailing list/support forum. Ninja_IDE is just reporting an apparent problem. The real problem is that the browser can't find the file. A Django problem. -- https://mail.python.org/mailman/listinfo/python-list
Improper Django Project error
Hi all Being new to Django and Python, I have two projects setup side by side, each in it's own virtualenv wrapper. The twr_project is running Django 1.7, python 2.7 and is set up to duplicate the 'Tango With Rango' tutorial. The archivedb project is running Django 1.8, python 2.7 and is my actual project. I am using Ninja-IDE as my IDE. I like it a lot. At this point both projects are essentially identical with the exception of name changes. The twr project work down to the first template inclusion ( index.html ). The archivedb project refuses to find the home.html template file. The system layout is exactly the same. I wiped the home.html file and attempted to re-install it but my IDE gave the following error window: Sorry, either settings file or virtualenv are missingthese are required for Django Plugin to work in thepresent version, we are working on fixing this. I have virtualenv installed and active and the settings file is present. In any case, the IDE won't let me save the home.html file without some fiddling. Even if I get the file saved the web server can't find it. (file not found error). The only difference between index.html (Django 1.7) and home.html (Django 1.8) is the name changes. I have inserted print statements in the url tree to try debugging this but all the path information returned seems reasonable. Is this a bug in Ninja-IDE, Django 1.8 or is it something else. If you need more information, please let me know Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: password authentication failed (SOLVED)
On 07/22/2015 04:44 PM, Chris Angelico wrote: On Thu, Jul 23, 2015 at 9:35 AM, Gary Roach wrote: At this point, I'm confused about a few things. Does the postgresql server and my archivedb reside globally or are they inside my archivedb virtual environment. I think globally. Your virtual environment is a Python construct only. That's where Python packages get installed, so if you don't activate it, you might not be able to use psycopg2, but as you surmise, the database itself is elsewhere on the system. To get pgAdmin3 to work, I have to have it set so that it logs in as gary ( no choice with this) and set group to root. Then in application > advanced options set run as different user to root. This assumes that you are using a KDE4 desktop and have these option by right clicking the icons. pgAdmin3 data: Server Group > Server(1) > archivedb |_ Host name - 127.0.0.1 |_ username - archive |_ connected - no Archivedb requires a password to go deeper and takes the xx password that is in the django settings.py file. This opens up access to archivedb and lists archivedb > Schema(1) > public > tables(10). At this point I found that all of the sequences and all of the tables are owned by root. This is probably the root (no pun intended) cause. Now what do I do about it. I'm not sure how this came about so don't know how to fix it. Ah, all owned by root. Okay! I've never actually tried this, but you might be able to directly reassign a bunch of things: http://www.postgresql.org/docs/9.4/static/sql-reassign-owned.html Make sure you have a backup. Reassigning root in this way is quite possibly a bad idea. If there aren't too many tables, you could use ALTER TABLE: http://www.postgresql.org/docs/9.4/static/sql-altertable.html ALTER TABLE tablename OWNER TO archives; But in theory, you shouldn't need to worry about owners at all - just make sure permissions are all assigned. Which you have done. So it's entirely possible none of this will change anything. :( Worst case, you may need to do an SQL dump of the entire database, then check the export, make sure ownership is correct, and reimport into a brand new database. Tedious, but it's certain to fix the problem. ChrisA pgAdmin3 showed two potential problems. The first connection listed in pg_hba.conf was: local all postgres radius. I removed this line so that the first line would be: local all all trust. Since all connections will be handled through Django? there should not be a problem with keeping loose security at this point. The second problem was that all fo the sequence and table files in archivedb showed the owner to be root. I changed them all to archive - the user listed in Django's settings.py file. Python manage.py migrate now works with no errors. Thank you for your help. I found an O'Reilly book - PosgreSQL Up & Running, 2nd Edition, by Regina Obe and Leo Hsu that is very good. If I had read the book first, I would have avoided some of these problems. One of the things that I have found very frustrating is that most of the documentation is too compartmentalized. If an author is writing about Django they get sloppy with the database setup and visa versa. It now seems to me that: Postgresql should be set up first, the setup being completely disconnected from the Python / Django project All communication with the database will pass through Django with the exception of admin maintenance. Please correct me if I'm wrong. Gary R. -- https://mail.python.org/mailman/listinfo/python-list
Re: password authentication failed
On 07/16/2015 04:53 PM, Chris Angelico wrote: On Fri, Jul 17, 2015 at 9:34 AM, Gary Roach wrote: On 07/15/2015 11:25 AM, Chris Angelico wrote: You should then be able to create a regular user, and grant appropriate permissions: postgres=# create user archives password 'traded-links-linguistics-informal'; CREATE ROLE postgres=# grant all on database archivedb to archives; GRANT I really appreciate the help Chris. I created a user archive with password 'xx' and changed the settings.py file accordingly. When I tried python manage.py migrate I got the following error with it's traceback: (archivedb)root@supercrunch:~/archivedb# python manage.py migrate [chomp] django.db.utils.ProgrammingError: permission denied for relation django_migrations This suggests that your new user doesn't have permissions set yet. Did you do the grant command as listed above? If so, you may have to also do this: $ sudo sudo -u postgres psql archivedb postgres=# grant all on all tables in schema X to archives; I did the above. Replace X with the name of the database schema you use - possibly "public" or some other user name. You can list multiple schema names, separated by commas, if you need to. To list all schemas in the database: select distinct table_schema from information_schema.tables; I did all of the above. Since I only plan on one datebase - excluding the system db's - I'm dumping everything into the public schema. Hope that helps! ChrisA I'm still getting the same migration error. At this point, I'm confused about a few things. Does the postgresql server and my archivedb reside globally or are they inside my archivedb virtual environment. I think globally. To get pgAdmin3 to work, I have to have it set so that it logs in as gary ( no choice with this) and set group to root. Then in application > advanced options set run as different user to root. This assumes that you are using a KDE4 desktop and have these option by right clicking the icons. pgAdmin3 data: Server Group > Server(1) > archivedb |_ Host name - 127.0.0.1 |_ username - archive |_ connected - no Archivedb requires a password to go deeper and takes the xx password that is in the django settings.py file. This opens up access to archivedb and lists archivedb > Schema(1) > public > tables(10). At this point I found that all of the sequences and all of the tables are owned by root. This is probably the root (no pun intended) cause. Now what do I do about it. I'm not sure how this came about so don't know how to fix it. In the OS I have a postgres user in the passwd file and in the group file have the following: gary:x:1000:root,backuppc,sudo,postgres,users root:x:0:backuppc,gary,staff,postgres,users postgres:x:117:root,gary Normally, I don't have to worry too much about security because my two user network resides behind a verizon router firewall. I don't have much in the way of sensitive data either. This project may be different. So maybe I need to tighten things up a bit. Thanks for your help Gary R -- https://mail.python.org/mailman/listinfo/python-list
Re: password authentication failed
On 07/16/2015 04:53 PM, Chris Angelico wrote: On Fri, Jul 17, 2015 at 9:34 AM, Gary Roach wrote: On 07/15/2015 11:25 AM, Chris Angelico wrote: You should then be able to create a regular user, and grant appropriate permissions: postgres=# create user archives password 'traded-links-linguistics-informal'; CREATE ROLE postgres=# grant all on database archivedb to archives; GRANT I really appreciate the help Chris. I created a user archive with password 'xx' and changed the settings.py file accordingly. When I tried python manage.py migrate I got the following error with it's traceback: (archivedb)root@supercrunch:~/archivedb# python manage.py migrate [chomp] django.db.utils.ProgrammingError: permission denied for relation django_migrations This suggests that your new user doesn't have permissions set yet. Did you do the grant command as listed above? If so, you may have to also do this: $ sudo sudo -u postgres psql archivedb postgres=# grant all on all tables in schema X to archives; I did the above. Replace X with the name of the database schema you use - possibly "public" or some other user name. You can list multiple schema names, separated by commas, if you need to. To list all schemas in the database: select distinct table_schema from information_schema.tables; I did all of the above. Since I only plan on one datebase - excluding the system db's - I'm dumping everything into the public schema. Hope that helps! ChrisA I'm still getting the same migration error. At this point, I'm confused about a few things. Does the postgresql server and my archivedb reside globally or are they inside my archivedb virtual environment. I think globally. To get pgAdmin3 to work, I have to have it set so that it logs in as gary ( no choice with this) and set group to root. Then in application > advanced options set run as different user to root. This assumes that you are using a KDE4 desktop and have these option by right clicking the icons. pgAdmin3 data: Server Group > Server(1) > archivedb |_ Host name - 127.0.0.1 |_ username - archive |_ connected - no Archivedb requires a password to go deeper and takes the xx password that is in the django settings.py file. This opens up access to archivedb and lists archivedb > Schema(1) > public > tables(10). At this point I found that all of the sequences and all of the tables are owned by root. This is probably the root (no pun intended) cause. Now what do I do about it. I'm not sure how this came about so don't know how to fix it. In the OS I have a postgres user in the passwd file and in the group file have the following: gary:x:1000:root,backuppc,sudo,postgres,users root:x:0:backuppc,gary,staff,postgres,users postgres:x:117:root,gary Normally, I don't have to worry too much about security because my two user network resides behind a verizon router firewall. I don't have much in the way of sensitive data either. This project may be different. So maybe I need to tighten things up a bit. Thanks for your help Gary R -- https://mail.python.org/mailman/listinfo/python-list
Re: Should non-security 2.7 bugs be fixed?
On 07/18/2015 04:36 PM, Terry Reedy wrote: I would like more viewpoints from 2.7 users. I read that (incorrectly of course) and just had to ask: How do you intend to extract a viewpoint from that last 7/10 of a user? With apologies, Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: password authentication failed
On 07/15/2015 11:25 AM, Chris Angelico wrote: On Thu, Jul 16, 2015 at 3:13 AM, Gary Roach wrote: Every time I try to do a python manage.py migrate I get: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" DATABASES = { 'default': { 'USER': 'postgres', 'PASSWORD': 'xx', # A valid debian pw } } PostgreSQL users are not the same as Unix users, and their passwords aren't necessarily the same. I would recommend *not* using the postgres user, which is the database superuser; instead, create a new user explicitly. On most Debian PostgreSQL installations, you should be able to invoke 'psql' while running as user 'postgres', either by su'ing to postgres or with sudo, for instance: $ sudo sudo -u postgres psql That should get you into a database CLI as superuser. Your prompt should look like this: postgres=# You should then be able to create a regular user, and grant appropriate permissions: postgres=# create user archives password 'traded-links-linguistics-informal'; CREATE ROLE postgres=# grant all on database archivedb to archives; GRANT (Make sure you have the semicolons at the ends, otherwise you'll think it's done nothing. It's actually waiting for you to type more lines for the same command, but the prompt difference is so subtle that it's easy to think it's silently ignoring you.) Then you should be able to use user name 'archives' and password 'traded-links-linguistics-informal' (of course, you don't want to use that; that's just what my password generating parrot came up with) instead of 'postgres' and whatever the Unix password was. Incidentally, I usually don't have any password on my postgres Unix user, nor on the corresponding database users. Safer to use sudo, eg to root and then down to postgres, as shown above. ChrisA I really appreciate the help Chris. I created a user archive with password 'xx' and changed the settings.py file accordingly. When I tried python manage.py migrate I got the following error with it's traceback: (archivedb)root@supercrunch:~/archivedb# python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 180, in build_graph self.applied_migrations = recorder.applied_migrations() File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 60, in applied_migrations return set(tuple(x) for x in self.migration_qs.values_list("app", "name")) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/models/query.py", line 162, in __iter__ self._fetch_all() File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/models/query.py", line 965, in _fetch_all self._result_cache = list(self.iterator()) File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/models/query.py", line 1220, in iterator for row in compiler.results_iter(): File "/root/.virtualenvs/archivedb/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 783, in res
password authentication failed
Every time I try to do a python manage.py migrate I get: django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres" FATAL: password authentication failed for user "postgres" System Debian linux jessie python 2.79 Django 1.8 Postgresql 9.4.3 database Using virtualenv and virtualenvwrapper Postgres has root privileges in the Debian passwd file. Project settings.py file database setup # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'archivedb', 'USER': 'postgres', 'PASSWORD': 'xx', # A valid debian pw 'HOST': '127.0.0.1', 'PORT': '5432' } } I'm not certain how this should be corrected. Postgres ( using \d commands) does not seem to have any privileges set. Am I supposed to go outside the virtual environment to set up a postgres account in postgres or is Django supposed to do this with the migrate command. I feel like I am at a critical point where I can really screw things up and need some expert advise. This is my first time working with python / Django and am really shaky. I do have another learning project (rango) using SQLite that works fine. Gary R -- https://mail.python.org/mailman/listinfo/python-list
Re: Can anybody explain the '-' in a 2-D creation code?
On 06/25/2015 06:07 PM, fl wrote: Hi, I read Ned's tutorial on Python. It is very interesting. On its last example, I cannot understand the '_' in: board=[[0]*8 for _ in range(8)] I know '_' is the precious answer, but it is still unclear what it is in the above line. Can you explain it to me? Thanks, He uses _ to indicate a variable whose name and value he does not care about, but it *is* a valid variable name. He could have used ... for i in range ... or ... for unused_variable in range ... This is a valid, though probably unclear, use of that same name: >>> _ = 123 >>> print(_) 123 >>> Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: Why this list of dictionaries doesn't work?
On 06/18/2015 10:57 AM, Gilcan Machado wrote: Hi, I'm trying to write a list of dictionaries like: people = ( {'name':'john', 'age':12} , {'name':'kacey', 'age':18} ) I've thought the code below would do the task. But it doesn't work. Never say "it doesn't work" on this list. Tell us what it did, and what you expected. Provide a copy of the full error message. That's much more helpful than making us guess. And if I "print(people)" what I get is not the organize data structure like above. Thanks of any help! []s Gilcan #!/usr/bin/env python from collections import defaultdict person = defaultdict(dict) If you want *two* different dictionaries, you'll have to create *two* of them. You code creates only this one. people = list() person['name'] = 'jose' person['age'] = 12 people.append(person) Here's where you need to create the second one. person['name'] = 'kacey' person['age'] = 18 people.append(person) for person in people: print( person['nome'] ) Typo here: 'name', not 'nome'. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: So what's happening here?
On 06/05/2015 06:39 AM, Todd wrote: On Fri, Jun 5, 2015 at 3:23 PM, Gary Herron <mailto:gary.her...@islandtraining.com>> wrote: On 06/05/2015 06:11 AM, Paul Appleby wrote: On Fri, 05 Jun 2015 14:55:11 +0200, Todd wrote: Numpy arrays are not lists, they are numpy arrays. They are two different data types with different behaviors. In lists, slicing is a copy. In numpy arrays, it is a view (a data structure representing some part of another data structure). You need to explicitly copy the numpy array using the "copy" method to get a copy rather than a view: OK, thanks. I see. (I'd have thought that id(a[1]) and id(b[1]) would be the same if they were the same element via different "views", but the id's seem to change according to rules that I can't fathom.) Nope. It's odder than that. a[1] is still a view into the inderlying numpy array, and your id is the id of that view. Each such index produces a new such view object. Check this out: >>> import numpy >>> a = numpy.array([1,2,3]) >>> id(a[1]) 28392768 >>> id(a[1]) 28409872 This produces two different view of the same underlying object. a[1] and b[1] are not views: >>> a[1].flags['OWNDATA'] True >>> b[1].flags['OWNDATA'] True >>> a[1:2].flags['OWNDATA'] False Right. My bad. Each execution of a[1] creates a new numpy.int64 object with the value from the array. >>> type(a[1]) Each execution of id(a[1]) creates an int64 object which is immediately used and then deleted. Two successive executions of id(a[1]) may or may not reuse the same piece of memory, depending on what else is going on in memory. Indeed when I produced the above example with id(a[1]), a third and fourth runs of id(a[1]) did indeed repeat 28409872, but they are all new creations of an int64 object which happen to use the same recently freed bit of memory. Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: So what's happening here?
On 06/05/2015 06:11 AM, Paul Appleby wrote: On Fri, 05 Jun 2015 14:55:11 +0200, Todd wrote: Numpy arrays are not lists, they are numpy arrays. They are two different data types with different behaviors. In lists, slicing is a copy. In numpy arrays, it is a view (a data structure representing some part of another data structure). You need to explicitly copy the numpy array using the "copy" method to get a copy rather than a view: OK, thanks. I see. (I'd have thought that id(a[1]) and id(b[1]) would be the same if they were the same element via different "views", but the id's seem to change according to rules that I can't fathom.) Nope. It's odder than that. a[1] is still a view into the inderlying numpy array, and your id is the id of that view. Each such index produces a new such view object. Check this out: >>> import numpy >>> a = numpy.array([1,2,3]) >>> id(a[1]) 28392768 >>> id(a[1]) 28409872 This produces two different view of the same underlying object. Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: How to inverse a particle emitter
On 06/04/2015 04:15 PM, stephenpprane...@gmail.com wrote: hey, i really need help, im a straight up beginner in scripting and i need to figure out how to make an inverted particle emitter using python in maya Python is a programming language. Maya is a modeling and animation application (or a Mesoamerican civilization). An "inverted particle emitter" sounds like something you'd build in your backyard. You are going to have to put in a *LOT* more time explaining how those three are connected in one project. In truth, I can kind of guess what you want, (although I have no idea what "inverse" has to do with anything), but I won't waste my time doing so. If you take the time to carefully explain what you want, then I'm sure you will find plenty of people here who will take the time to answer you. Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: Multiple thread program problem
On 06/03/2015 01:41 PM, Mohan Mohta wrote: Hello I am trying to create multiple thread through the below program but I am getting an error #! /usr/bin/python import os import subprocess import thread import threading from thread import start_new_thread def proc(f) : com1="ssh -B " com2=line.strip('\n') com3= " uname -a" co=str("ssh -B ")+ str(com2) + str(" uname -a") subprocess.call(co,shell=True) print "" return f = open('/tmp/python/1') for line in f: t=thread.start_new_thread(proc(f),()) You are calling the function f yourself, but what you want here is for the thread to call f once it's running. So do t=thread.start_new_thread(proc, (f,)) # Procedure to call and a tuple of args for it. t.start() I don't think the thread has a start method. f.close() c = raw_input(" Type anything to quit") Execution output: Linux abc.myhomenetwork.com 2.6.18-348.25.1.el5 #1 SMP Thu Apr 10 06:32:45 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux Traceback (most recent call last): File "./readfile1.py", line 19, in t=thread.start_new_thread(proc(f),()) TypeError: first arg must be callable You should probably also consider using the higher-level threading module rather than the lower level thread module. (Also consider using Python3 instead of Python2.) Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 06/03/2015 11:22 AM, John McKenzie wrote: Hello. Very new to Python and looking for some basic help. Would like a set-up where something happens when a key is pressed. Not propose a question, have the user type something, then hit return, then something happens, but just the R key is pressed, something happens, then something else happens if the B key is pressed, then a third thing happens if the G key is pressed. My research only served to confuse me. Firstly, I do not understand how it is possible for this to be a difficult thing not built into the system for any scripting language made within the last few decades. More to the point I am unclear on specific suggestions. Most of them seem to be for Windows only and I want this working on a Raspberry Pi. Saw getch but I am still confused if it is platform specific or not, or requires a module to be installed or not. Just get errors if I try to install getch using PIP. If you are using Python through a CLI (command line interface i.e., a shell), then in fact your request doesn't really make sense. CLIs by their nature don't support that kind of interaction. BUT don't despair. Nearly every GIU framework on the planet has a Python interface, and they all allow for a window to be opened with event processing of your choice. This are some good places to start: https://wiki.python.org/moin/GuiProgramming https://wiki.python.org/moin/GUI%20Programming%20in%20Python Several of these (Tkinter and the curses module) are distributed with Python, so you should already have them installed. Gary Herron Other suggestions seemed to be overkill and confused me to due to my beginner level knowledge and the fact these suggestions have other, more complicated elements to them. I just want a button press on a device connected to a Raspberry Pi to trigger an action. If anyone can give me some guidance on this I would appreciate it. Thank you. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Keypress Input
On 06/03/2015 11:22 AM, John McKenzie wrote: Hello. Very new to Python and looking for some basic help. Would like a set-up where something happens when a key is pressed. Not propose a question, have the user type something, then hit return, then something happens, but just the R key is pressed, something happens, then something else happens if the B key is pressed, then a third thing happens if the G key is pressed. My research only served to confuse me. Firstly, I do not understand how it is possible for this to be a difficult thing not built into the system for any scripting language made within the last few decades. More to the point I am unclear on specific suggestions. Most of them seem to be for Windows only and I want this working on a Raspberry Pi. Saw getch but I am still confused if it is platform specific or not, or requires a module to be installed or not. Just get errors if I try to install getch using PIP. If you are using Python through a CLI (command line interface i.e., a shell), then in fact your request doesn't really make sense. CLIs by their nature don't support that kind of interaction. BUT don't despair. Nearly every GIU framework on the planet has a Python interface, and they all allow for a window to be opened with event processing of your choice. This are some good places to start: https://wiki.python.org/moin/GuiProgramming https://wiki.python.org/moin/GUI%20Programming%20in%20Python Several of these (Tkinter and the curses module) are distributed with Python, so you should already have them installed. Gary Herron Other suggestions seemed to be overkill and confused me to due to my beginner level knowledge and the fact these suggestions have other, more complicated elements to them. I just want a button press on a device connected to a Raspberry Pi to trigger an action. If anyone can give me some guidance on this I would appreciate it. Thank you. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Please help on this sorted function
On 06/02/2015 01:20 PM, fl wrote: Hi, I try to learn sorted(). With the tutorial example: ff=sorted({1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) ff [1, 2, 3, 4, 5] I don't see what sorted does in this dictionary, i.e. the sequence of 1..5 is unchanged. Could you explain it to me? Thanks, It's best to think of dictionaries as unordered collections of key/value pairs. Dictionaries are not sequences, do not have any particular ordering, and in full generality *can't* be sorted in any sensible way. For instance, this slightly odd (but perfectly legal) dictionary >>> d = {'a':123, 456:'b'} can't be sorted >>> sorted(d) Traceback (most recent call last): File "", line 1, in TypeError: unorderable types: int() < str() because it doesn't make sense to order/compare the two keys 'a' and 456. If your dictionary is a little better behaved, say >>> d = {'a':123, 'b':456} you may be able to sort the keys >>> sorted(d) ['a', 'b'] or the values >>> sorted(d.values()) [123, 456] or the key/value tuples (called items) >>> sorted(d.items()) [('a', 123), ('b', 456)] but each of those attempts to sort could fail on a general dictionary if the individual keys or values are not sortable. There is also an implementation of a type of dictionary that remembers the order in which the items are *inserted*. It's in the collections module and called OrderedDict. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Where is 'palindrome' defined?
On 05/31/2015 09:46 PM, fl wrote: Hi, When I search solution of reverse a string/number, I came across a short function online: def palindrome(num): return str(num) == str(num)[::-1] I thought that it is a general function. And with the following variable: No, this function is not built into Python because ... Well it's hard to say why. It's not very general, or not useful to many programmers, or nobody's thought about it or made a case for including it in Python, etc. But that should be no problem. You can define it yourself (by entering the two line you have above). Then it will be defined, and calling parlindrome('...') will produce a result rather than an error. Gary Herron a '1234_' parlindrome(a) Traceback (most recent call last): File "", line 1, in parlindrome(a) NameError: name 'parlindrome' is not defined Then, I find that parlindrome is a special checking mirrored word. I use Python 2.7.9. Why does the error message show name 'parlindrome' is not defined Thanks, -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Returning a custom file object (Python 3)
On 05/27/2015 10:29 PM, Marko Rauhamaa wrote: Ben Finney : It seems the existing ‘open’ implementation doesn't allow you to override the type of object returned. The question is, can you assign to the builtin namespace. I'm guessing you can't. Of course you can. Python2: >>> __builtins__.open = "whatever" >>> Python3: >>> import builtins >>> builtins.open = "whatever" >>> Of course doing so is like shooting yourself in the foot: Any subsequent pain is your own fault and probably well deserved. Gary Herron Within a module, you can simply do: open = MyFile Also, in other modules, you can: from myfile import open Marko -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Array of Functions
On 05/26/2015 05:43 PM, richard_riehle wrote: I realized that I mentioned earlier that I found a solution to my original question, but that I never posted an example of the solution. So, here is a simplified example for anyone who is interested. def fArray(fselect, fparm = 1): def A1(p = fparm): if p == 1: print("printing A1[1]") else: print("printing A1[other]") def A2(p = fparm): if p == 1: print("printing A2[1]") else: print("printing A2[other]") A = [A1, A2] A[fselect]() Nested functions are often confusing and unclear, and there is really no need for them here. This does the same thing: def A1(p): print("printing", "A1[1]" if p==1 else "A1[other]")) def A2(p): print("printing", "A2[1]" if p==1 else "A2[other]")) def fArray(fselect, fparm=1): A = [A1,A2] A[fselect](fparm) In this example, I enclosed two functions within another function, and then put those two functions in a list. Then, with appropriate parameters, I called one of the functions in the list, associated the formal parameter with the function in a call to the array, and presto, it performs the function. The more advanced problem I wanted to solve, a two dimensional array of functions, once this example is understood, becomes trivial to implement. In fact, the more interesting problem I wanted to solve involved a dictionary of functions in a two-dimensional array, and that too was easy to do in Python. When I compare what this would require in C, C++, Java, or most other languages, I find Python to be really easy for solving this kind of problem. Next, I plan to develop the solution using decorators and assertions to empower it with a greater level of portability and to make the functions more generic. I hope someone finds this interesting. Richard Riehle, PhD -- https://mail.python.org/mailman/listinfo/python-list
Re: a more precise distance algorithm
On 05/25/2015 09:13 PM, ravas wrote: On Monday, May 25, 2015 at 8:11:25 PM UTC-7, Steven D'Aprano wrote: Let's compare three methods. ... which shows that: (1) It's not hard to find mismatches; (2) It's not obvious which of the three methods is more accurate. Thank you; that is very helpful! I'm curious: what about the sqrt() function being last is detrimental? From a point of ignorance it seems like we are just producing errors sooner, and then multiplying them, with this alternative method. It's probably not the square root that's causing the inaccuracies. In many other cases, and probably here also, it's the summing of two numbers that have vastly different values that loses precision. A demonstration: >>> big = 1.0 >>> small = 0.1 >>> (big+small)-big # Should produce a value =small, but gives an exact zero instead. 0.0 The squaring of the two values in x*x+y*y just makes the addition even more error prone since the squares make large values even larger and small values even smaller. Gary Herron. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: a more precise distance algorithm
On 05/25/2015 12:21 PM, ravas wrote: I read an interesting comment: """ The coolest thing I've ever discovered about Pythagorean's Theorem is an alternate way to calculate it. If you write a program that uses the distance form c = sqrt(a^2 + b^2) you will suffer from the lose of half of your available precision because the square root operation is last. A more accurate calculation is c = a * sqrt(1 + b^2 / a^2). If a is less than b, you should swap them and of course handle the special case of a = 0. """ Is this valid? Does it apply to python? This is a statement about floating point numeric calculations on a computer,. As such, it does apply to Python which uses the underlying hardware for floating point calculations. Validity is another matter. Where did you find the quote? Gary Herron Any other thoughts? :D My imagining: def distance(A, B): """ A & B are objects with x and y attributes :return: the distance between A and B """ dx = B.x - A.x dy = B.y - A.y a = min(dx, dy) b = max(dx, dy) if a == 0: return b elif b == 0: return a else: return a * sqrt(1 + (b / a)**2) -- https://mail.python.org/mailman/listinfo/python-list
Re: I do not have access to the right _hierarchy.py source file
On 05/17/2015 09:18 AM, pegah Aliz wrote: ... To solve this problem, I checked linkage() function and inside it I needed to check _hierarchy.linkage() method. I use pycharm text editor and when I asked for "linkage" source code, it opened up a python file namely "_hierarchy.py" inside the directory like the following: .PyCharm40/system/python_stubs/-1247972723/scipy/cluster/_hierarchy.py This python file doesn't have any definition for all included functions. I am wondering what is the correct source of this function to revise it and solve my problem. I would be appreciated if someone helps me to explore the correct source. Thanks and Regards Pegah Please tell us: * What platform you are on; Linux, Windows, ... * How you installed PyCharm * What contents that file currently has * Why you think it's incorrect. I think it's far more likely that that file is correct, and you are somehow misinterpreting its contents, but we can't even begin to guess until you show us its current content. Gary -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Rule of order for dot operators?
On 05/16/2015 12:20 PM, C.D. Reimer wrote: Greetings, Noobie question regarding a single line of code that transforms a URL slug ("this-is-a-slug") into a title ("This Is A Slug"). title = slug.replace('-',' ').title() This line also works if I switched the dot operators around. title = slug.title().replace('-',' ') I'm reading the first example as character replacement first and title capitalization second, and the second example as title capitalization first and character replacement second. Does python perform the dot operators from left to right or according to a rule of order (i.e., multiplication/division before add/subtract)? Yes, that's correct. Gary Herron Thank you, Chris Reimer -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: use of subprocess module inside generator
On 05/13/2015 12:43 PM, Peter wrote: I'm using Python 3.4.3 on Windows 7 (with latest patches) to develop a sqlcmd module for accessing SQL Server (via Microsoft's sqlcmd.exe). My goal is to develop a 100% Python 3 module that's easy to use, flexible, and by design shifts the majority of future SQL Server Python database access maintenance to Microsoft. So far, I've successfully and quickly converted a few of my Python pyodbc applications/tools to use this new module. However, I recently ran into an apparent Python issue which cost me a few hours to diagnose and work around. I doubt that you've hit a bug -- we've all done this kind of thing many times, and there's certainly no restriction on making procedure calls within a generator -- so that's probably not the problem either. My guess is that you've misinterpreted the failure of the original code. I don't know how that might be, but I do spot one oddity in your original code which may be responsible. See below ... I'm hoping that someone might know what the root cause of my issue was. Perhaps I've hit a bug/restriction with Python generators? My original generator function looked like this: def _raw_data(cl, stdout, *, opath=None, timeout=timeout): stdout = subprocess.check_output(cl, universal_newlines=True, timeout=timeout) This seems muddled -- you pass in a parameter, stdout, only to immediately overwrite its value with the output of check_output. What was in stdout originally, and more importantly, did you expect the newly assigned value from check_output to be returned to the calling procedure? If so, that's your bug, because parameters in function calls don't work that way. This makes sense with your workaround, since the assignment to stdout is preserved when done outside the function. I hope that helps. Gary Herron if opath is None: for line in stdout.splitlines(): yield line.strip() else: with open(opath) as f: for line in f: yield line.strip() The above function appeared to work fine, if the command line directed sqlcmd.exe to send its output to stdout. However, if the command line directed sqlcmd.exe to send its output to a file, subprocess.check_output would never be called when next was called on the returned generator. I verified this behavior with print statements inside my code, as well as, inside the subprocess module. My work around was to simply move the call to subprocess.check_output outside of the generator function (see below) to its caller (a non-generator function). With this minor change, everything appears to work as expected. OK, so am I missing something here? def _raw_data(stdout, *, opath=None): if opath is None: for line in stdout.splitlines(): yield line.strip() else: with open(opath) as f: for line in f: yield line.strip() Thank you in advance for your assistance. Peter Santoro -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: anomaly
On 05/12/2015 04:55 AM, Antoon Pardon wrote: Op 11-05-15 om 16:13 schreef Chris Angelico: Why does Python have most built-ins as simply looked-up names that can be overridden? Because otherwise, there would be a veritable ton of keywords: But that doesn't answer the question why the developers chose "True" to be a keyword and "int" to be a looked-up name. and pretending to justify that choice by stating that the python thought is: We're all adults here, if you want to override a builtin, who are we to stop you. That is disingenuous. Bull. Some design decisions were made with the knowledge that * they provide a freedom which may be useful but can be misused (e.g., shadowing builtins), versus * they would be too disruptive of abusable (e.g. shadowing keywords) Python tends to use the first category more than C family languages, and that's where the "We're all adults" argument applies. You may argue about which category any particular feature ought to fall into, and in fact several things (shadowing None, True, and False) have changed category during the evolution of Python. But to imply that the "adult" argument should drive *all* decisions is foolish. And disingenuous. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: anomaly
On 05/10/2015 05:48 PM, zipher wrote: On Sunday, May 10, 2015 at 11:44:36 AM UTC-5, Ian wrote: On Sun, May 10, 2015 at 10:34 AM, Mark Rosenblitt-Janssen wrote: Here's something that might be wrong in Python (tried on v2.7): class int(str): pass This defines a new class named "int" that is a subclass of str. It has no relation to the builtin class int. int(3) '3' This creates an instance of the above "int" class, which is basically equivalent to calling "str(3)". Were you expecting a different result? Sorry, yes. If you're going to define a concept called "keywords", I don't think you should allow them to be shadowed by a class definition. Mark Huh? Python has plenty of keywords, and indeed, none of them can be redefined or shadowed.But you would gain nothing (and lose a bit or dynamic-language freedom) by making int a keyword. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: anomaly
On 05/10/2015 09:48 AM, Rustom Mody wrote: On Sunday, May 10, 2015 at 10:14:36 PM UTC+5:30, Ian wrote: On Sun, May 10, 2015 at 10:34 AM, Mark Rosenblitt-Janssen wrote: Here's something that might be wrong in Python (tried on v2.7): class int(str): pass This defines a new class named "int" that is a subclass of str. It has no relation to the builtin class int. int(3) '3' This creates an instance of the above "int" class, which is basically equivalent to calling "str(3)". Were you expecting a different result? In C (family) languages int is a keyword From that pov this is completely bizarre Not really. Expecting Python to act like C family languages *is* bizarre. Common Python thought:: "We're all adults here."If you want to override a builtin within your own namespace, who are we to stop you? Besides, it's still available as __builtins__.int (unless you've also overridden that). -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Try Except Specific Error Messages
On 04/30/2015 04:27 PM, brandon wallace wrote: Hi, I am try to get more specific error messages using try/except. I ran this code with the cable unplugged to see the error message. I got #!/usr/bin/env python3 import urllib.request webpage = urllib.request.urlopen("http://fakewebsite.com/";) text = webpage.read().decode("utf8") I got two errors. This: [] socket.gaierror: [Errno -2] Name or service not known and this: [] urllib.error.URLError: Note the error message here. The exception is named "urllib.error.URLError" NOT "URLError" as you use in the next bit of code. You could import that specific error if you wanted to access it that way: from urllib.error import URLError otherwise you should use the fully qualified name urllib.error.URLError. I tried this but got more error messages. As a side note, that is never a useful thing to say in this group. Take the time to tell is the actual errors message you got. That way I don't have to waste my time running your code to see what error message you are getting. try: webpage = urllib.request.urlopen("http://fakewebsite.com/";) text = webpage.read().decode("utf8") except URLError as err: print("URLError: " + str(err)) How do I wrap urllib.request with try/except? -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: l = range(int(1E9))
On 04/30/2015 09:06 AM, Cecil Westerhof wrote: If I execute: l = range(int(1E9) The python process gobbles up all the memory and is killed. The problem is that after this my swap is completely used, because other processes have swapped to it. This make those programs more slowly. Is there a way to circumvent Python claiming all the memory? By the way: this is CPython 2.7.8. Well, that could be considered the problem. In Python3, the range function returns a range object which takes up almost no resources, while in Python2 it produces a list. Both can be iterated over, so they produce the same result in the most common use case (i.e., iteration), but the Python3 version generates the elements only as needed. If you really *wanted* the list (but WHY?) in Python3, do list(range(...)), but then you get what you deserve. :-) Python3: >>> l = range(int(1E9)) >>> l range(0, 100000) -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Best GUI for Python
On 04/26/2015 11:07 AM, Cecil Westerhof wrote: Op Sunday 26 Apr 2015 19:12 CEST schreef Gary Herron: On 04/26/2015 09:32 AM, Cecil Westerhof wrote: Op Sunday 26 Apr 2015 17:09 CEST schreef Steven D'Aprano: On Sun, 26 Apr 2015 11:02 pm, Cecil Westerhof wrote: I want to use a GUI for Python. When searching I found (beside some others) Tkinter and wxPython. From what I found it looks like Tkinter is slightly better. What would be the pros/cons of these two? Would there be a compelling reason to use another GUI? Tkinter is easier to use, as it is standard with Python. So long as you have Tk/Tcl installed on your computer, Tkinter should work fine. However, Tkinter probably looks a bit more old fashioned. wxPython probably looks a bit more modern and may be a bit more powerful, but it will require a large extra library. It's also a lot harder to learn to use wxPython unless you are comfortable with C++ programming. Well, I did my share of C++ programming. ;-) Have you seen this? https://wiki.python.org/moin/GuiProgramming Dabo looks interesting, but also a little bit dead. Well, maybe I just should evaluate Tkinter and wxPython both. Now wxPython looks more interesting. But it is easier to make a reasonable decision when I have a little more information. :-D For the moment I limit it to Tkinter and wxPython. I wouldn't recommend limiting yourself like that. I've used both successively (years ago), then pyGTK for a batch of projects, followed by pyglet for some years and many projects, and most recently PyQt. They are all worthy GUI programming libraries, and each of them is cross platform (as I required to develop on Linux, but deploy occasionally on Windows). I did say for the moment. ;-) But just curious: what is the reason you use five different kinds of GUI? It seems like it makes think difficult for you. I mean the question as enlightenment for myself. Yikes, Stated like that it does sound excessive but in reality it's spread over about 20 years of Python and graphics/GUI programming. Experimenting with a new GUI every 5 years or so just keeps the interest levels up. -- https://mail.python.org/mailman/listinfo/python-list
Re: Best GUI for Python
On 04/26/2015 09:32 AM, Cecil Westerhof wrote: Op Sunday 26 Apr 2015 17:09 CEST schreef Steven D'Aprano: On Sun, 26 Apr 2015 11:02 pm, Cecil Westerhof wrote: I want to use a GUI for Python. When searching I found (beside some others) Tkinter and wxPython. From what I found it looks like Tkinter is slightly better. What would be the pros/cons of these two? Would there be a compelling reason to use another GUI? Tkinter is easier to use, as it is standard with Python. So long as you have Tk/Tcl installed on your computer, Tkinter should work fine. However, Tkinter probably looks a bit more old fashioned. wxPython probably looks a bit more modern and may be a bit more powerful, but it will require a large extra library. It's also a lot harder to learn to use wxPython unless you are comfortable with C++ programming. Well, I did my share of C++ programming. ;-) Have you seen this? https://wiki.python.org/moin/GuiProgramming Dabo looks interesting, but also a little bit dead. Well, maybe I just should evaluate Tkinter and wxPython both. Now wxPython looks more interesting. But it is easier to make a reasonable decision when I have a little more information. :-D For the moment I limit it to Tkinter and wxPython. I wouldn't recommend limiting yourself like that. I've used both successively (years ago), then pyGTK for a batch of projects, followed by pyglet for some years and many projects, and most recently PyQt. They are all worthy GUI programming libraries, and each of them is cross platform (as I required to develop on Linux, but deploy occasionally on Windows). -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: xlwt 1.0.0 released!
On 04/15/2015 02:51 PM, Chris Withers wrote: Hi All, I'm pleased to announce the release of xlwt 1.0.0. What a curiously incomplete announcement. Could you tell us what xlwt is? I see no hint here. Gary Herron This release contains the following: - Python 3 support. - An initial set of unit tests. - An initial set of Sphinx documentation. - Move to setuptools for packaging. - Wire up Travis, Coveralls and ReadTheDocs. - Allow longs as row indexes. Big thanks to Thomas Kluyver for his work on Python 3 support, Manfred Moitzi for donating his unit tests. Belated thanks to Landon Jurgens for his help on converting the documentation to Sphinx. If you find any problems, please ask about them on the python-ex...@googlegroups.com list, or submit an issue on GitHub: https://github.com/python-excel/xlwt/issues There's also details of all things Python and Excel related here: http://www.python-excel.org/ NB: This is likely the last "new feature" release of xlwt. If there are bugs, we will try and fix them, but it may be a slow process. If you're starting a new project, you should probably consider openpyxl or xlsxwriter instead. cheers, Chris -- https://mail.python.org/mailman/listinfo/python-list
Re: PIL(LOW) - What am I missing?
On 03/25/2015 08:54 PM, kai.pet...@gmail.com wrote: I create an image as per: img = Image.new('1', (1024, 1280), 1) I then draw on it and do: imagedata = list(img.getdata()) print len(imagedata) This gives me 1228800 instead of the expected 1310720 (1024 * 1280) - any ideas what I am missing? As always, any help much appreciated. Kai Are you sure? Both Python2 and Python3 give me the expected 1310720, I'm running PILLOW version 2.6.1 on Linux (with both Python 3.4.2 and Python 2.7.8). >>> from PIL import Image >>> img = Image.new('1', (1024, 1280), 1) >>> imagedata = list(img.getdata()) >>> print len(imagedata) 1310720 -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Supply condition in function call
On 03/25/2015 10:29 AM, Manuel Graune wrote: Hi, I'm looking for a way to supply a condition to an if-statement inside a function body when calling the function. I can sort of get what I want with using eval (see code below) but I would like to achieve this in a safer way. If there is a solution which is safer while being less flexible, that would be fine. Also, supplying the condition as a string is not necessary. What I want to do is basically like this: def test1(a, b, condition="True"): for i,j in zip(a,b): c=i+j if eval(condition): print("Foo") test1([0,1,2,3],[1,2,3,4],"i+j >4") print("Bar") test1([0,1,2,3],[1,2,3,4],"c >4") print("Bar") test1([0,1,2,3],[1,2,3,4],"a[i] >2") print("Bar") test1([0,1,2,3],[1,2,3,4]) This is nicely done with lambda expressions: To pass in a condition as a function: test1([0,1,2,3],[1,2,3,4], lambda i,j: i+j<4) To check the condition in the function: if condition(i,j): To get the full range of conditions, you will need to include all the variables needed by any condition you can imagine. So the above suggestions may need to be expanded to: ... lambda i,j,a,b: ... or whatever and ... condition(i,j,a,b) ... or whatever If any of your conditions gets too long/complex for a lambda (or you just don't like Python's lambda expressions), then just create a function for your condition: def cond1(i,j,a,b): return i+j>4 and do test1(..., cond1) and if condition(i,j,a,b): -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Daylight savings time question
On 03/24/2015 03:24 PM, Dan Stromberg wrote: Is there a way of "adding" 4 hours and getting a jump of 5 hours on March 8th, 2015 (due to Daylight Savings Time), without hardcoding when to spring forward and when to fall back? I'd love it if there's some library that'll do this for me. #!/usr/bin/python import pytz import datetime def main(): # On 2015-03-08, 2:00 AM to 2:59AM Pacific time does not exist - the clock jumps forward an hour. weird_naive_datetime = datetime.datetime(2015, 3, 8, 1, 0, 0).replace(tzinfo=pytz.timezone('US/Pacific')) weird_tz_aware_datetime = weird_naive_datetime.replace(tzinfo=pytz.timezone('US/Pacific')) print(weird_tz_aware_datetime) four_hours=datetime.timedelta(hours=4) print('Four hours later is:') print(weird_tz_aware_datetime + four_hours) print('...but I want numerically 5 hours later, because of Daylight Savings Time') main() Thanks! The pyzt module (which you've imported) has lots to say about this. Look at its procedures "localize' and 'normalize' and all the rest of the pyzt documentation. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Regex Python Help
On 03/24/2015 11:13 AM, gdot...@gmail.com wrote: I am creating a tool to search a filesystem for one simple string. I cannot get the syntax correct. Thank you in advance for your help. import sys import re import os path='/' viewfiles=os.listdir(path) for allfiles in viewfiles: file= os.path.join(path, allfiles) text=open(file, "r") for line in text: if re.match("DECRYPT_I", line): print line, -- This should search every file for the simple regex "DECRYPT_I" This is from the root down. The error is: SyntaxError: Missing parentheses in call to 'print' Please help. Gregg Dotoli You appear to be using Python3, but have written code for Python2. There are a number of differences between the two, but your particular error runs into the different syntax for prints. Python2: print line # This is a statement Python3 print(line) # This is a procedure call -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: id() and is operator
On 02/22/2015 10:02 PM, Terry Reedy wrote: On 2/22/2015 4:25 PM, Marko Rauhamaa wrote: LJ : id(b[0]) 4582 [...] id(b[2]) 4582 Please correct me if I am wrong, but according to this b[2] and b[0] are the same object. Now, b[0] is b[2] False This is a true statement: If X is Y, then id(X) == id(Y). However, this is generally not a true statement: If X is Y, then id(X) is id(Y). If X and Y exist at the *same time*, then (X is Y) == (id(X) is id(Y)). Since X and Y in the example above do not exist at the same time, it is nonsensical to compare them. Not quite. You've been bitten by the "is" versus "==" trap. You could use id(X)==id(Y) but not id(X) is id(Y) not even if X and Y are the same object. Simple examples: >>> a=3 >>> id(a) is id(a) False >>> a=3 >>> b=a >>> id(a) is id(b) False The explanation is that each call to id() makes its own independent Python integer object containing the large integer (10771264 in this case). The two integer objects satisfy "==", but they are separate Python objects so they do not satisfy "is". As a side note, It is an implementation detail whether two Python integer objects created independently but with the same value are separate objects or references to a single object. CPython caches small integers so that only one integer object of each value exists, but not so for large integers. You can experiment with the cutoff on your particular flavor of Python. On mine (Python 3.4.2 (default, Oct 8 2014, 13:08:17) ;[GCC 4.9.1] on linux) it's somewhere between 200 and 300: >>> 201 is 1+200 True >>> 301 is 1+300 False Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: id() and is operator
On 02/22/2015 09:53 AM, LJ wrote: Hi everyone. Quick question here. Lets suppose if have the following numpy array: b=np.array([[0]*2]*3) and then: id(b[0]) 4582 id(b[1]) 45857512 id(b[2]) 4582 Please correct me if I am wrong, but according to this b[2] and b[0] are the same object. Now, b[0] is b[2] False Any clarification is much appreciated. Cheers, In fact, b[0] and b[2] are different objects as can be seen here: >>> import numpy as np >>> b=np.array([[0]*2]*3) >>> b[0]=1 // broadcast into both ints in row 0 >>> b[1]=2 // ... row 1 >>> b[2]=3 // ... row 2 >>> b array([[1, 1], [2, 2], [3, 3]]) When you extracted b[0], you got a newly created python/numpy object (1x2 array of ints) briefly stored at location 4582 but then deleted immediately after that use. A little later, the extraction of b[2] used the same bit of memory. The id of a temporarily created value is meaningless, and apparently misleading. As a separate issue, each of b, b[0], b[1], and b[2] do *all* refer to the same underlying array of ints as can be seen here: >>> r = b[0] >>> r[0] = 123 >>> b array([[123, 1], [ 2, 2], [ 3, 3]]) but the Python/numpy objects that wrap portions of that underlying array of ints are all distinct. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Delegation in Python
On 01/24/2015 03:38 PM, Brian Gladman wrote: On 24/01/2015 23:22, Chris Angelico wrote: class RF(Fraction): def is_integer(self): return self.numerator % self.denominator == 0 Thanks for your help on this. I must admit that nowhere in a lot of searching did I find that delegation is achieved by doing nothing! Brian That's *not* "doing nothing". And it's not even really "delegation". It's just sub-classing Fraction to add one new method and inherit all other methods. Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: Delegation in Python
On 01/24/2015 03:22 PM, Chris Angelico wrote: On Sun, Jan 25, 2015 at 9:57 AM, Brian Gladman wrote: But I am not clear on how to delegate from my new class to the existing Fraction class. This is what I have: -- class RF(Fraction): def __new__(self, x, y): super().__new__(self, x, y) def is_integer(self): return self.numerator % self.denominator == 0 def __getattr__(self, attr): return getattr(self, attr) If you just drop everything but your new method, it should work just fine. class RF(Fraction): def is_integer(self): return self.numerator % self.denominator == 0 However, this doesn't ensure that operations on RFs will return more RFs - they'll often return Fractions instead. There's no easy fix for that, sorry. ChrisA You can always "monkey-path" the Fraction class on the fly to add a new method to it. I think most would consider this a bad idea, but it does work. Try this: >>> from fractions import Fraction >>> def is_integer(self): ... return self.numerator % self.denominator == 0 ... >>> Fraction.is_integer = is_integer # Monkey-patch Fraction >>> >>> Fraction(1,2).is_integer() False >>> Fraction(2,1).is_integer() True Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: MS-DOS Commands
On 01/11/2015 02:13 PM, Jenacee Owens wrote: I'm new to python and every time i type a command into the MS-DOS Commands it looks like this. strings Traceback";line 1 in name error:name strings'is not defined how can i fix this? What where you trying to accomplish, and what did you expect that to do? It's not a valid Python statement, so an error message that says as much is to be expected. You really should start with a Python tutorial. More comments: * You did not type that "into the MS-DOS Commands", but rather to Python (or more accurately, to the Python interpreter). * Python does not have "commands", but rather "statements". * There is a module named strings, and you could import it (to use Python's terminology) with the "import strings" statement, but there's probably not much need to do so. But then the "strings" statement you typed would not produce an error message, but would just print out a line informing you that strings is a module -- not very useful. * Rather than using Python in an MS-DOS window, you should consider trying statements and programs in Idle -- A reasonable GUI environment to experiment with Python. It came with your installation of Python. * In the future, questions should be accompanied with information about your version of Python (Python2 or Python3) and the platform you are running it on. (Apparently Windows in your case.) Gary Herron -- https://mail.python.org/mailman/listinfo/python-list
Re: surprise - byte in set
On 01/03/2015 10:50 AM, patrick vrijlandt wrote: Hello list, Let me first wish you all the best in 2015! Today I was trying to test for occurrence of a byte in a set ... >>> sys.version '3.4.2 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:15:05) [MSC v.1600 32 bit (Intel)]' >>> 'b' in 'abc' True >>> b'b' in b'abc' True >>> 'b' in set('abc') True >>> b'b' in set(b'abc') False I was surprised by the last result. What happened? (Examples simplified; I was planning to manipulate the set) The surprise is really that the 3rd test is True not that the fourth is False. First, as should be expected, a byte string is a sequence of (small) ints. So b'b' is a (short) byte string and the set set(b'abc') is composed of three ints. You should not expect your inclusion test to return True when testing for a bytes-type object in a set of int-type objects. And that explains your False result in the 4th test. >>> type(b'abc') >>> type(b'abc'[0]) But things are different for strings. You might think a string is a sequence of characters, but Python does not have a character type. In fact the elements of a string are just 1 char long strings: >>> type('abc') >>> type('abc'[0]) You would not logically expect to find a string 'b' in a set of characters in, say C++, where the two types are different. But that's not the Python way. In Python a set of characters set('abc') is really a set of (short) strings, and the character 'b' is really a (short) string, so the inclusion test works. Python's way of returning a 1-byte string when indexing a string (instead of returning an element of type character) allows this surprising result. >>> 'abc'[0] 'a' >>> 'abc'[0][0] 'a' >>> 'abc'[0][0][0] 'a' >>> 'abc'[0][0][0][0] 'a' ... I've never considered this a problem, but a infinitely indexable object *is* a bit of an oddity. Patrick --- Dit e-mailbericht is gecontroleerd op virussen met Avast antivirussoftware. http://www.avast.com -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list
Re: problems with Methods in Python 3.4.2
On 12/18/2014 09:27 AM, Marcus Lütolf wrote: Hello Dears, 1)I am trying to do this: >>> dir(_builtins_) It's __builtins__ not _builtins_ (double underscores at each end not single underscores) I am getting this: Traceback (most recent call last): File "", line 1, in dir(_builtins_) NameError: name '_builtins_' is not defined 2)I am trying to do this: >>> 'TTA',_add_('GGA') To call a method use "." not ",". And the method you are trying to call is __add__ not _add_. But why... just do "TTA"+"GGA" I’am getting this : Traceback (most recent call last): File "", line 1, in 'TTA',_add_('GGA') NameError: name '_add_' is not defined 3)I am trying to do this: >>> -3 .abs() abs is a function not a method. do: abs(-3) I’am getting this Traceback (most recent call last): File "", line 1, in -3 .abs() AttributeError: 'int' object has no attribute 'abs' 4) finally, after printing >>>abs._doc_() Again, use double underscores abs.__doc__() I am getting this (and so on) : Traceback (most recent call last): File "", line 1, in abs._doc_() AttributeError: 'builtin_function_or_method' object has no attribute '_doc_' What did I do wrong ? Thanks for help, Marcus Luetolf, M.D., 90 Bondastreet, CH-7000 Chur, Switzerland. -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- https://mail.python.org/mailman/listinfo/python-list