Hello, i have 2 classes.
How i call first.TQ in Second ? Without creating object First in Second.
class First:
def __init__(self):
self.str = ""
def TQ(self):
pass
def main(self):
T = Second(self.str) # Called here
class Second():
def __init__(self):
list = {u"RANDINT":first.TQ} # List of funcs maybe called in first
.....
.....
return data
I have an array of files. I'd like to be able to break that array down into one array with multiple subarrays, each subarray contains files that were created on the same day. So right now if the array contains files from March 1 - March 31, I'd like to have an array with 31 subarrays (assuming there is at least 1 file for each day).
In the long run, I'm trying to find the file from each day with the latest creation/modification time. If there is a way to bundle that into the iterations that are required above to save some CPU cycles, that would be even more ideal. Then I'd have one flat array with 31 files, one for each day, for the latest file created on each individual day.
Implement this loop: total up the product of the numbers from 1 to x.
Implement this loop: total up the product of the numbers from a to b.
Implement this loop: total up the sum of the numbers from a to b.
Implement this loop: total up the sum of the numbers from 1 to x.
Implement this loop: count the number of characters in a string s.
i'm very lost on implementing loops these are just some examples that i am having trouble with-- if someone could help me understand how to do them that would be awesome
I am looking into the unittest package, and I'm not sure of the proper way to structure my test cases when writing a lot of them for the same method. Say I have a fact function which calculates the factorial of a number; would this testing file be OK?
import unittest
class functions_tester(unittest.TestCase):
def test_fact_1(self):
self.assertEqual(1, fact(1))
def test_fact_2(self):
self.assertEqual(2, fact(2))
def test_fact_3(self):
self.assertEqual(6, fact(3))
def test_fact_4(self):
self.assertEqual(24, fact(4))
def test_fact_5(self):
self.assertFalse(1==fact(5))
def test_fact_6(self):
self.assertRaises(RuntimeError, fact, -1)
#fact(-1)
if __name__ == "__main__":
unittest.main()
It seems sloppy to have so many test methods for one method. I'd like to just have one testing method and put a ton of basic test cases (ie 4! ==24, 3!==6, 5!==120, and so on), but unittest doesn't let you do that.
What is the best way to structure a testing file in this scenario?
Thanks in advance for the help.
I'm reading some data from avro file using the avro library. It takes about a minute to load 33K objects from the file. This seem very slow to me, specially with the Java version reading the same file in about 1sec.
Here is the code, am I doing something wrong?
import avro.datafile
import avro.io
from time import time
def load(filename):
fo = open(filename, "rb")
reader = avro.datafile.DataFileReader(fo, avro.io.DatumReader())
for i, record in enumerate(reader):
pass
return i + 1
def main(argv=None):
import sys
from argparse import ArgumentParser
argv = argv or sys.argv
parser = ArgumentParser(description="Read avro file")
start = time()
num_records = load("events.avro")
end = time()
print("{0} records in {1} seconds".format(num_records, end - start))
if __name__ == "__main__":
main()
Here's the deal. I'm trying to write an arkanoid clone game and the thing is that I need a window menu like you get in pyGTK. For example File-(Open/Save/Exit) .. something like that and opening an "about" context where the author should be written.
I'm already using pyGame for writting the game logic. I've tried pgu to write the GUI but that doesn't help me, altough it has those menu elements I'm taking about, you can't include the screen of the game in it's container.
Does anybody know how to include such window menus with the usage of pyGame ?
Hi,
I have some strings that I want to delete some unwanted characters from them.
For example: Adam'sApple ---- AdamsApple.(case insensitive)
Can someone help me, I need the fastest way to do it, cause I have a couple of millions of records that have to be polished.
Thanks
I have a binary data format consisting of 18,000+ packed int64s, ints, shorts, bytes and chars. The data is packed to minimize it's size, so they don't always use byte sized chunks. For example, a number whose min and max value are 31, 32 respectively might be stored with a single bit where the actual value is bitvalue + min, so 0 is 31 and 1 is 32. I am looking for the most efficient way to unpack all of these for subsequent processing and database storage.
Right now I am able to read any value by using either struct.unpack, or BitBuffer. I use struct.unpack for any data that starts on a bit where (bit-offset % 8 == 0 and data-length % 8 == 0) and I use BitBuffer for anything else.
I know the offset and size of every packed piece of data, so what is going to be the fasted way to completely unpack them?
Many thanks.
The tutorial on the django website shows this code for the models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
How did they turn from class attributes into instance attributes? Did I get class attributes wrong?
Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:
"(?P<start>some_pattern)(?P<replace>foo)(?P<end>end)"
And then concatenate the start group with the new data for replace and then the end group.
Is there a better method for this?
Hello everybody,
I have two nested lists of different sizes:
A = [[1, 7, 3, 5], [5, 5, 14, 10]]
B = [[1, 17, 3, 5], [1487, 34, 14, 74], [1487, 34, 3, 87], [141, 25, 14, 10]]
I'd like to gather all nested lists from list B if A[2:4] == B[2:4] and put it into list L:
L = [[1, 17, 3, 5], [141, 25, 14, 10]]
Would you help me with this?
I'm trying to write a script to import a database file. I wrote the script to export the file like so:
import sqlite3
con = sqlite3.connect('../sqlite.db')
with open('../dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
Now I want to be able to import that database. I tried:
import sqlite3
con = sqlite3.connect('../sqlite.db')
f = open('../dump.sql','r')
str = f.read()
con.execute(str)
but I'm not allowed to execute more than one statement. Is there a way to get it to run a .sql script directly?
Trying to integrate openmeetings with django website, but can't understand how properly configure ImportDoctor:
(here :// replaced with __ 'cause spam protection)
print url
http://sovershenstvo.com.ua:5080/openmeetings/services/UserService?wsdl
imp = Import('http__schemas.xmlsoap.org/soap/encoding/')
imp.filter.add('http__services.axis.openmeetings.org')
imp.filter.add('http__basic.beans.hibernate.app.openmeetings.org/xsd')
imp.filter.add('http__basic.beans.data.app.openmeetings.org/xsd')
imp.filter.add('http__services.axis.openmeetings.org')
d = ImportDoctor(imp)
client = Client(url, doctor = d)
client.service.getSession()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python2.6/site-packages/suds/client.py", line 539, in call
return client.invoke(args, kwargs)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 598, in invoke
result = self.send(msg)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 627, in send
result = self.succeeded(binding, reply.message)
File "/usr/lib/python2.6/site-packages/suds/client.py", line 659, in succeeded
r, p = binding.get_reply(self.method, reply)
File "/usr/lib/python2.6/site-packages/suds/bindings/binding.py", line 159, in get_reply
resolved = rtypes[0].resolve(nobuiltin=True)
File "/usr/lib/python2.6/site-packages/suds/xsd/sxbasic.py", line 63, in resolve
raise TypeNotFound(qref)
suds.TypeNotFound: Type not found: '(Sessiondata, http__basic.beans.hibernate.app.openmeetings.org/xsd, )'
what i'm doing wrong? please help and sorry for my english, but you are my last chance to save position :(
need webinars at morning (2.26 am now)
Hello, I have got some code to pass in a variable into a script from the command line. The script is:
import sys, os
def function(var):
print var
class function_call(object):
def __init__(self, sysArgs):
try:
self.function = None
self.args = []
self.modulePath = sysArgs[0]
self.moduleDir, tail = os.path.split(self.modulePath)
self.moduleName, ext = os.path.splitext(tail)
__import__(self.moduleName)
self.module = sys.modules[self.moduleName]
if len(sysArgs) > 1:
self.functionName = sysArgs[1]
self.function = self.module.__dict__[self.functionName]
self.args = sysArgs[2:]
except Exception, e:
sys.stderr.write("%s %s\n" % ("PythonCall#__init__", e))
def execute(self):
try:
if self.function:
self.function(*self.args)
except Exception, e:
sys.stderr.write("%s %s\n" % ("PythonCall#execute", e))
if __name__=="__main__":
test = test()
function_call(sys.argv).execute()
This works by entering ./function <function> <arg1 arg2 ....>. The problem is that I want to to select the function I want that is in a class rather than just a function by itself. The code I have tried is the same except that function(var): is in a class. I was hoping for some ideas on how to modify my function_call class to accept this.
Thanks for any help.
× 139886
I am trying to log in to betfair.com by using mechanize. I have tried several ways but it always fail.
This is the code I have developed so far, can anyone help me to identify what is wrong with it and how I can improve it to log into my betfair account?
Thanks,
import cookielib
import urllib
import urllib2
from BeautifulSoup import BeautifulSoup
import mechanize
from mechanize import Browser
import re
bf_username_name = "username"
bf_password_name = "password"
bf_form_name = "loginForm"
bf_username = "xxxxx"
bf_password = "yyyyy"
urlLogIn = "http://www.betfair.com/"
accountUrl = "https://myaccount.betfair.com/account/home?rlhm=0&" # This url I will use to verify if log in has been successful
br = mechanize.Browser(factory=mechanize.RobustFactory())
br.addheaders = [("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_5_8) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.90 Safari/537.1")]
br.open(urlLogIn)
br.select_form(nr=0)
print br.form
br.form[bf_username_name] = bf_username
br.form[bf_password_name] = bf_password
print br.form #just to check username and psw have been recorded correctly
responseSubmit = br.submit()
response = br.open(accountUrl)
text_file = open("LogInResponse.html", "w")
text_file.write(responseSubmit.read()) #this file should show the home page with me logged in, but it show home page as if I was not logged it
text_file.close()
text_file = open("Account.html", "w")
text_file.write(response.read()) #this file should show my account page, but it should a pop up with an error
text_file.close()
I'm having a new problem here ..
CODE 1:
try:
urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D.get(val['name'])))
except KeyError:
print "expected parameter not provided - "+val["name"]+" is missing"
exit(0)
CODE 2:
try:
urlParams += "%s=%s&"%(val['name'], data.get(val['name'], serverInfo_D[val['name']]))
except KeyError:
print "expected parameter not provided - "+val["name"]+" is missing"
exit(0)
see the diffrence in serverInfo_D[val['name']] & serverInfo_D.get(val['name'])
code 2 fails but code 1 works
the data
serverInfo_D:{'user': 'usr', 'pass': 'pass'}
data: {'par1': 9995, 'extraparam1': 22}
val: {'par1','user','pass','extraparam1'}
exception are raised for for data dict .. and all code in for loop which iterates over val
I know that I can dynamically add an instance method to an object by doing something like:
import types
def my_method(self):
# logic of method
# ...
# instance is some instance of some class
instance.my_method = types.MethodType(my_method, instance)
Later on I can call instance.my_method() and self will be bound correctly and everything works.
Now, my question: how to do the exact same thing to obtain the behavior that decorating the new method with @property would give?
I would guess something like:
instance.my_method = types.MethodType(my_method, instance)
instance.my_method = property(instance.my_method)
But, doing that instance.my_method returns a property object.
Hi,
I'm using windows and linux machines for the same project. The default encoding for stdin on windows is cp1252 and on linux is utf-8.
I would like to change everything to uft-8.
Is it possible? How can I do it?
Thanks
Eduardo
Is there a more Pythonic way to put this loop together?:
while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
UPDATE:
I think this syntax is probably what I'm going to go with:
while tree.getChildren():
tree = tree.getChildren()[0]
So I have this dictionary:
ScoreDict = {"Blue": {'R1': 89, 'R2': 80},
"Brown": {'R1': 61, 'R2': 77},
"Purple": {'R1': 60, 'R2': 98},
"Green": {'R1': 74, 'R2': 91},
"Red": {'R1': 87, 'Lon': 74}}
Is there any way how I can convert this dictionary into a list like this:
ScoreList = [['Blue', 89, 80], ['Brown', 61, 77],
['Purple', 60, 98], ['Green', 74, 91], ['Red', 87, 74]]
I'm not too familiar with dictionaries, so I really need some help here. Thanks in advance!
I have created a Form with labels and entries..but for some reason the entries are not being created,
peoplegui.py
from tkinter import *
from tkinter.messagebox import showerror
import shelve
shelvename = 'class-shelve'
fieldnames = ('name','age','job','pay')
def makewidgets():
global entries
window = Tk()
window.title('People Shelve')
form = Frame(window)
form.pack()
entries = {}
for (ix, label) in enumerate(('key',) + fieldnames):
lab = Label(form, text=label)
ent = Entry(form)
lab.grid(row=ix, column=0)
lab.grid(row=ix, column=1)
entries[label] = ent
Button(window, text="Fetch", command=fetchRecord).pack(side=LEFT)
Button(window, text="Update", command=updateRecord).pack(side=LEFT)
Button(window, text="Quit", command=window.quit).pack(side=RIGHT)
return window
def fetchRecord():
print('In fetch')
def updateRecord():
print('In update')
if __name__ == '__main__':
window = makewidgets()
window.mainloop()
When I run it the labels are created but not the entries.
I have a variable in init of a module which get loaded from the database and takes about 15 seconds.
For django development server everything is working fine but looks like with apache2 and mod_wsgi the module is loaded with every request (taking 15 seconds).
Any idea about this behavior?
Update: I have enabled daemon mode in mod wsgi, looks like its not reloading the modules now! needs more testing and I will update.