>>> import math
>>> math.pow(2, 3000)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OverflowError: math range error
How can I fix it? thanx.
I am trying to use the Google Contacts API to connect to a user's contact information, on my Google apps domain.
Generating an access_token using the gdata api's ContactsService clientlogin function while using the API key for my project works fine, but I would prefer to not store the user's credentials, and from the information I have found that method uses OAuth1.0
So, to use OAuth2.0 I have:
Generated a Service Account in the developer's console for my project
Granted access to the service account for the scope of https://www.google.com/m8/feeds/ in the Google apps domain admin panel
Attempted to generate credentials using SignedJwtAssertionCredentials:
credentials = SignedJwtAssertionCredentials(
service_account_name=service_account_email,
private_key=key_from_p12_file,
scope='https://www.google.com/m8/feeds/',
sub=user_email')
The problem I am running into is that attempting to generate an access token using this method fails. It succeeds in generating the token when I remove the sub parameter, but then that token fails when I try to fetch the user's contacts.
Does anyone know why this might be happening?
Here's my code:
import cx_Oracle
conn = cx_Oracle.connect(usr, pwd, url)
cursor = conn.cursor()
cursor.execute("UPDATE SO SET STATUS='PE' WHERE ID='100'")
conn.commit()
If I remove the conn.commit(), the table isn't updated. But for select statements, I don't need that conn.commit(). I'm curious why?
When declaring a class that inherits from a specific class:
class C(dict):
added_attribute = 0
the documentation for C lists all the methods of dict (either through help(C) or pydoc).
Is there a way to hide the inherited methods from the automatically generated documentation (the documentation string can refer to the base class, for non-overwritten methods)?
This would be useful: pydoc lists the functions defined in a module after its classes. Thus, when the classes have a very long documentation, a lot of less than useful information is printed before the new functions provided by the module are presented, which makes the documentation harder to exploit (you have to skip all the documentation for the inherited methods until you reach something specific to the module being documented).
I've got a class like this:
class Image (models.Model):
...
sizes = ((90,90), (300,250))
def resize_image(self):
for size in sizes:
...
and another class like this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image)
what i'd like to do with that class is this:
class SomeClassWithAnImage (models.Model):
...
an_image = models.ForeignKey(Image, sizes=((90,90), (150, 120)))
where i'm can specify the sizes that i want the Image class to use to resize itself as a argument rather than being hard coded on the class. I realise I could pass these in when calling resize_image if that was called directly but the idea is that the resize_image method is called automatically when the object is persisted to the db.
if I try to pass arguments through the foreign key declaration like this i get an error straight away. is there an easy / better way to do this before I begin hacking down into django?
I have the following django test case that is giving me errors:
class MyTesting(unittest.TestCase):
def setUp(self):
self.u1 = User.objects.create(username='user1')
self.up1 = UserProfile.objects.create(user=self.u1)
def testA(self):
...
def testB(self):
...
When I run my tests, testA will pass sucessfully but before testB starts, I get the following error:
IntegrityError: column username is not unique
It's clear that it is trying to create self.u1 before each test case and finding that it already exists in the Database. How do I get it to properly clean up after each test case so that subsequent cases run correctly?
I am building a tree for a spell checker with suggestions. Each node contains a key (a letter) and a value (array of letters down that path).
So assume the following sub-trie in my big trie:
W
/ \
a e
| |
k k
| |
is word--> e e
|
...
This is just a subpath of a sub-trie. W is a node and a and e are two nodes in its value array etc...
At each node, I check if the next letter in the word is a value of the node. I am trying to support mistyped vowels for now. So 'weke' will yield 'wake' as a suggestion. Here's my searchWord function in my trie:
def searchWord(self, word, path=""):
if len(word) > 0:
key = word[0]
word = word[1:]
if self.values.has_key(key):
path = path + key
nextNode = self.values[key]
return nextNode.searchWord(word, path)
else:
# check here if key is a vowel. If it is, check for other vowel substitutes
else:
if self.isWord:
return path # this is the word found
else:
return None
Given 'weke', at the end when word is of length zero and path is 'weke', my code will hit the second big else block. weke is not marked as a word and so it will return with None. This will return out of searchWord with None.
To avoid this, at each stack unwind or recursion backtrack, I need to check if a letter is a vowel and if it is, do the checking again.
I changed the if self.values.has_key(key) loop to the following:
if self.values.has_key(key):
path = path + key
nextNode = self.values[key]
ret = nextNode.searchWord(word, path)
if ret == None:
# check if key == vowel and replace path
# return nextNode.searchWord(...
return ret
What am I doing wrong here? What can I do when backtracking to achieve what I'm trying to do?
Hi,
I'm trying to implement a shuttle control in wxPython but there doesn't seem to be one. I've decided to use two listbox controls. The shuttle control looks like this:
I've got two listboxes — one's populated, one's not. Could someone show me how to add a selected item to the second list box when it is double clicked? It should be removed from the first. When it is double clicked in the second, it should be added to the first and removed from the second. The shuttle control implements these by default but it's a pity it isn't there.
Thank you.
hi i have a simpel tkinter window. consists of a small window, a timer, and a button for set timer. dont want to go in details with the code...
Now all the widgets in my windows eg. button, Label Ect. will have to change color.
EG. i Have a global variabel wich i will set as color "red" fx...
All the widgets BACKGROUND option is associated with the global variabel.
Now on button press i will change the global variable to "green" so that the background of all widgets ect. will change color, but they DONT. i thought the .mainloop() sort of UPDATED the window. how can i have the widgets to change background color when my variable change WITHOUT restarting my application???
ty
Xanthar
I have the following code which searches all the directory in the current directory and then takes data from those files to plot the graph. The data is read correctly as verified by printing but there are no points plotted on graph.
import argparse
import os
import matplotlib.pyplot as plt
#find the present working directory
pwd=os.path.dirname(os.path.abspath(__file__))
#find all the folders in the present working directory.
dirs = [f for f in os.listdir('.') if os.path.isdir(f)]
plt.figure()
plt.xlim(0, 20000)
plt.ylim(0, 1)
for directory in dirs:
os.chdir(os.path.join(pwd, directory));
chd_dir = os.path.dirname(os.path.abspath(__file__))
files = [ fl for fl in os.listdir('.') if os.path.isfile(fl) ]
print files
for f in files:
f_obj = open(os.path.join(chd_dir, f), 'r')
list_x = []
list_y = []
for i in xrange(0,4):
f_obj.next()
for line in f_obj:
temp_list = line.split()
print temp_list
list_y.append(temp_list[0])
list_x.append(temp_list[1])
print 'final_lsit'
print list_x
print list_y
plt.plot(list_x, list_y, 'r.')
f_obj.close()
os.chdir(pwd)
plt.savefig("test.jpg")
The input files look like the following:
5
865 14709 15573
14709 1.32667e-06
664 0.815601
14719 1.55333e-06
674 0.813277
14729 1.82667e-06
684 0.810185
14739 1.4e-06
694 0.808459
Can anybody help me with why this is happening? Being new I would like to know some tutorial where I can get help with kind of plotting as the tutorial I was following made me end up here.
Any help appreciated.
I'm running an application from supervisord and I have to set up an environment for it. There are about 30 environment variables that need to be set. I've tried putting all on one big
environment=
line and that doesn't seem to work. I've also tried multiple enviroment= lines, and that doesn't seem to work either. I've also tried both with and without ' around the env value.
What's the best way to set up my environment such that it remains intact under supervisord control? Should I be calling my actual program (tornado, fwiw) from a shell script with the environment preloaded there? Ideally, I'd like to put all of the enviroment variables into an include file and load them with supervisor, but I'm open to doing it another way.
I have a function that attempts to take a list of usernames, look each one up in a user table, and then add them to a membership table. If even one username is invalid, I want the entire list to be rolled back, including any users that have already been processed. I thought that using sessions was the best way to do this but I'm running into a DetachedInstanceError:
DetachedInstanceError: Instance <Organization at 0x7fc35cb5df90> is not bound to a Session; attribute refresh operation cannot proceed
Full stack trace is here.
The error seems to trigger when I attempt to access the user (model) object that is returned by the query. From my reading I understand that it has something to do with there being multiple sessions, but none of the suggestions I saw on other threads worked for me. Code is below:
def add_members_in_bulk(organization_eid, users):
"""Add users to an organization in bulk - helper function for add_member()"""
"""Returns "success" on success and id of first failed student on failure"""
session = query_session.get_session()
session.begin_nested()
users = users.split('\n')
for u in users:
try:
user = user_lookup.by_student_id(u)
except ObjectNotFoundError:
session.rollback()
return u
if user:
membership.add_user_to_organization(
user.entity_id,
organization_eid,
'',
[]
)
session.flush()
session.commit()
return 'success'
here's the membership.add_user_to_organization:
def add_user_to_organization(user_eid, organization_eid, title, tag_ids):
"""Add a User to an Organization with the given title"""
user = user_lookup.by_eid(user_eid)
organization = organization_lookup.by_eid(organization_eid)
new_membership = OrganizationMembership(
organization_eid=organization.entity_id,
user_eid=user.entity_id,
title=title)
new_membership.tags = [get_tag_by_id(tag_id) for tag_id in tag_ids]
crud.add(new_membership)
and here is the lookup by ID query:
def by_student_id(student_id, include_disabled=False):
"""Get User by RIN"""
try:
return get_query_set(include_disabled).filter(User.student_id == student_id).one()
except NoResultFound:
raise ObjectNotFoundError("User with RIN %s does not exist." % student_id)
Is there a way to pickle a class definition?
What I'd like to do is pickle the definition (which may created dynamically), and then send it over a TCP connection so that an instance can be created on the other end.
I understand that there may be dependencies, like modules and global variables that the class relies on. I'd like to bundle these in the pickling process as well, but I'm not concerned about automatically detecting the dependencies because it's okay if the onus is on the user to specify them.
I have a dictionary called number_devices I'm passing to a template, the dictionary keys are the ids of a list of objects I'm also passing to the template (called implementations). I'm iterating over the list of objects and then trying to use the object.id to get a value out of the dict like so:
{% for implementation in implementations %}
{{ number_devices.implementation.id }}
{% endfor %}
Unfortunately number_devices.implementation is evaluated first, then the result.id is evaluated obviously returning and displaying nothing. I can't use parentheses like:
{{ number_devices.(implementation.id) }}
because I get a parse error. How do I get around this annoyance in Django templates?
Thanks for any help!
I'm trying to export data to a csv file. It should contain a header (from datastack) and restacked arrays with my data (from datastack). One line in datastack has the same length as dataset. The code below works but it removes parts of the first line from datastack. Any ideas why that could be?
s = ','.join(itertools.chain(dataset)) + '\n'
newfile = 'export.csv'
f = open(newfile,'w')
f.write(s)
numpy.savetxt(newfile, (numpy.transpose(datastack)), delimiter=', ')
f.close()
Hello,
I have a script that does various things and access paramenters using sys.argv but when the script gets to the unittest part of the code it says there is no module for this. The script that I have is:
class MyScript():
def __init__(self):
self.value = sys.argv[1]
def hello(self):
print self.value
def suite(self):
modules_to_test = ('external_sanity_onvif', 'starttest')
alltests = unittest.TestSuite()
for module in map(__import__, modules_to_test):
alltests.addTest(unittest.findTestCases(module))
return alltests
if __name__ == '__main__':
Run = MyScript()
Run.hello()
log_file = 'log_file.txt'
test_file = open(log_file, "w")
runner = unittest.TextTestRunner(test_file)
unittest.main(defaultTest='Run.suite', testRunner=runner)
Say I enter ./script.py Hello in the command line. The error I get is:
AttributeError: 'module' object has no attribute 'Hello'
If I remove the unittest module it works. Also if I remove the testrunner log and leave it at:
unittest.main(defaultTest='Run.suite')
This still doesn't work.
Can anyone help.
Thanks
I've implemented my servers in the following way:
def makeServer(application, port):
factory = protocol.ServerFactory()
factory.protocol = MyChat
factory.clients = []
internet.TCPServer(port, factory).setServiceParent(application)
application = service.Application("chatserver")
server1 = makeServer(application, port=1025)
server2 = makeServer(application, port=1026)
server3 = makeServer(application, port=1027)
Note that MyChat is an event handling class that has a "receiveMessage" action:
def lineReceived(self, line):
print "received", repr(line)
for c in self.factory.clients:
c.transport.write(message + '\n')
I want server1 to be able to pass messages to server2. Rather, I want server1 to be treated as a client of server2. If server1 receives the message "hi" then I want it to send that same exact message to server2.
How can I accomplish this?
I'm having a attribute on my model to allow the user to order the objects. I have to update the element's order depending on a list, that contains the object's ids in the new order; right now I'm iterating over the whole queryset and set one objects after the other. What would be the easiest/fastest way to do the same with the whole queryset?
def update_ordering(model, order):
""" order is in the form [id,id,id,id] for example: [8,4,5,1,3] """
id_to_order = dict((order[i], i) for i in range(len(order)))
for x in model.objects.all():
x.order = id_to_order[x.id]
x.save()
Hi all,
I wanna show a gtk.Window under a gtk.widget.
But I don't know how to retrieve the gtk.widget's coordinates for my gtk.window.
Anyone knows ?
Thanks.
I am trying to generate tree with fasta file input and Alignment with MuscleCommandline
import sys,os, subprocess
from Bio import AlignIO
from Bio.Align.Applications import MuscleCommandline
cline = MuscleCommandline(input="c:\Python26\opuntia.fasta")
child= subprocess.Popen(str(cline),
stdout = subprocess.PIPE,
stderr=subprocess.PIPE,
shell=(sys.platform!="win32"))
align=AlignIO.read(child.stdout,"fasta")
outfile=open('c:\Python26\opuntia.phy','w')
AlignIO.write([align],outfile,'phylip')
outfile.close()
I always encounter with these problems
Traceback (most recent call last):
File "", line 244, in run_nodebug
File "C:\Python26\muscleIO.py", line 11, in
align=AlignIO.read(child.stdout,"fasta")
File "C:\Python26\Lib\site-packages\Bio\AlignIO_init_.py", line 423, in read
raise ValueError("No records found in handle")
ValueError: No records found in handle
Given a string named line whose raw version has this value:
\rRAWSTRING
how can I detect if it has the escape character \r? What I've tried is:
if repr(line).startswith('\r'):
blah...
but it doesn't catch it. I also tried find, such as:
if repr(line).find('\r') != -1:
blah
doesn't work either. What am I missing?
thx!
I'm creating my own Group model; I'm not referring to the builtin Group model. I want each hroup to be a member of another group (it's parent), but there is the one "top" group that doesn't have a parent group.
The admin interface won't let me create a group without entering a parent. I get the error personnel_group.parent_id may not be NULL. My Group model looks like this:
class Group(models.Model):
name = models.CharField(max_length=50)
parent = models.ForeignKey('self', blank=True, null=True)
order = models.IntegerField()
icon = models.ImageField(upload_to='groups', blank=True, null=True)
description = models.TextField(blank=True, null=True)
How can I accomplish this?
Thanks.
Hello,
I am trying to build a list of lists using the following code:
list=3*[[]]
Now I am trying to append a string to the list in position 0:
list[0].append("hello")
However, instead of receiving the list
[ ["hello"] , [], [] ]
I am receiving the list:
[ ["hello"] ,["hello"] , ["hello"] ]
Am I missing something?
Thanks,
Joel
What I'm trying to do is query the datastore for a model where the key is not the key of an object I already have. Here's some code:
class User(db.Model):
partner = db.SelfReferenceProperty()
def text_message(self, msg):
user = User.get_or_insert(msg.sender)
if not user.partner:
# user doesn't have a partner, find them one
# BUG: this line returns 'user' himself... :(
other = db.Query(User).filter('partner =', None).get()
if other:
# connect users
else:
# no one to connect to!
The idea is to find another User who doesn't have a partner, that isn't the User we already know.
I've tried filter('key !=, user.key()), filter('__key__ !=, user.key()) and a couple others, and nothing returns another User who doesn't have a partner.
filter('foo !=, user.key()) also returns nothing, for the record.