from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
i run only once,
how to make it to running forever ?
thanks
I was working the following example from Doug Hellmann tutorial on multiprocessing:
import multiprocessing
def worker():
"""worker function"""
print 'Worker'
return
if __name__ == '__main__':
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
When I tried to run it outside the if statement:
import multiprocessing
def worker():
"""worker function"""
print 'Worker'
jobs = []
for i in range(5):
p = multiprocessing.Process(target=worker)
jobs.append(p)
p.start()
It started spawning processes non-stop, without any way of to terminating it. Why would that happen? Why it did not generate 5 processes and exit? Why do I need the if statement?
hello ..
i have the same code as wx Doodle pad in the wx demos
i added a tool to paste images from the clipboard to the pad.
using wx.DrawBitmap() function , but whenever i refresh the buffer .and call funtions ( drawSavedLines and drawSavedBitmap) it keeps putting bitmap above line no matter what i did
even if i called draw bitmap first and then draw lines .
is there anyway to put a line above the bitmap ?
please inform me if i miss anything
thanx in advance
I have a wiki db layout with Page and Revisions. Each Revision has a page_id referencing the Page, a page relationship to the referenced page; each Page has a all_revisions relationship to all its revisions. So far so common.
But I want to implement different epochs for the pages: If a page was deleted and is recreated, the new revisions have a new epoch. To help find the correct revisions, each page has a current_epoch field. Now I want to provide a revisions relation on the page that only contains its revisions, but only those where the epochs match.
This is what I've tried:
revisions = relationship('Revision',
primaryjoin = and_(
'Page.id == Revision.page_id',
'Page.current_epoch == Revision.epoch',
),
foreign_keys=['Page.id', 'Page.current_epoch']
)
Full code (you may run that as it is)
However this always raises ArgumentError: Could not determine relationship direction for primaryjoin condition ...`, I've tried all I had come to mind, it didn't work.
What am I doing wrong? Is this a bad approach for doing this, how could it be done other than with a relationship?
I want to use a generator as the argument passed by a PyQt4 signal, and I am not sure as to the cleanest way. I could just do something like elementChosen=QtCore.pyqtSignal(type((i for i in xrange (i)))), but this just looks ugly. Any suggestions?
Hi all -
I'm creating an arbitrary number of instances (using for loops and ranges). At some event in the future, I need to change an attribute for only one of the instances. What's the best way to do this?
Right now, I'm doing the following:
1) Manage the instances in a list.
2) Iterate through the list to find a key value.
3) Once I find the right object within the list (i.e. key value = value I'm looking for), change whatever attribute I need to change.
for Instance within ListofInstances:
if Instance.KeyValue == SearchValue:
Instance.AttributeToChange = 10
This feels really inefficient: I'm basically iterating over the entire list of instances, even through I only need to change an attribute in one of them.
Should I be storing the Instance references in a structure more suitable for random access (e.g. dictionary with KeyValue as the dictionary key?) Is a dictionary any more efficient in this case? Should I be using something else?
Thanks,
Mike
Hello,
I am trying to use Piston to provide REST support to Django.
I have implemented my handlers as per the documentation provided .
The problem is that i can "read" and "delete" my resource but i cannot "create" or "update".
Each time i hit the relevant api i get a 400 Bad request Error.
I have extended the Resource class for csrf by using this commonly available code snippet:
class CsrfExemptResource(Resource):
"""A Custom Resource that is csrf exempt"""
def init(self, handler, authentication=None):
super(CsrfExemptResource, self).init(handler, authentication)
self.csrf_exempt = getattr(self.handler, 'csrf_exempt', True)
My class (code snippet) looks like this:
user_resource = CsrfExemptResource(User)
class User(BaseHandler):
allowed_methods = ('GET', 'POST', 'PUT', 'DELETE')
@require_extended
def create(self, request):
email = request.GET['email']
password = request.GET['password']
phoneNumber = request.GET['phoneNumber']
firstName = request.GET['firstName']
lastName = request.GET['lastName']
self.createNewUser(self, email,password,phoneNumber,firstName,lastName)
return rc.CREATED
Please let me know how can i get the create method to work using the POST operation?
Every time I create an instance of the TestForm specified below, I have to overwrite the standard id format with auto_id=True. How can this be done once only in the form class instead? Any hints are very welcome.
views.py
from django.forms import ModelForm
from models import Test
class TestForm(ModelForm):
class Meta:
model = Test
def test(request):
form = TestForm(auto_id=True)
I need to programatically encrypt a directory of files, like in a .zip or whatever. Preferably password protected obviously.
How can I accomplish this, and WHAT IS the BEST encryption way to do it, if applicable?
Programming language doesn't matter. I am dictioned in all syntax.
OK, I have the following directory structure (it's a django project):
- project
-- app
and within the app folder, there is a scraper.py file which needs to reference a class defined within models.py
I'm trying to do the following:
import urllib2
import os
import sys
import time
import datetime
import re
import BeautifulSoup
sys.path.append('/home/userspace/Development/')
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
from project.app.models import ClassName
and this code just isn't working. I get an error of:
Traceback (most recent call last):
File "scraper.py", line 14, in
from project.app.models import ClassName
ImportError: No module named project.app.models
This code above used to work, but broke somewhere along the line and I'm extremely confused as to why I'm having problems. On SnowLeopard using python2.5.
"8,5,,1,4,7,,,,7,,1,9,3,6,,,8,6,3,9,,2,5,4,,,,,3,2,,,7,4,1,1,,4,,6,9,,5,,,,5,,,1,,6,3,,,6,5,,,,7,4,,1,7,6,,,,8,,5,,,7,1,,3,9,"
I'm doing a programming challenge where i need to parse this sequence into my sudoku script.
Need to get the above sequence into 8,5,0,1,4,7,0,0,0,7,0,1,9,3,6,0,0,8.........
I tried re but without success, help is appreciated, thanks.
Proxy configuration of a machine can be easily fetched using
def check_proxy():
import urllib2
http_proxy = urllib2.getproxies().get('http')
I need to write a test for the above written function. In order to do that I need to:-
Set the system-wide proxy to an
invalid URL during the test(sounds
like a bad idea).
Supply an invalid
URL to http_proxy.
How can I achieve either of the above?
Hello,
Can someone give me a simple example involving threads in this manner, please.
Problem with my code is that when I click button One, GUI freezes until its finished. I want buttons to stay responsive when def is being executed. How can i fix that?
class fun:
wTree = None
def __init__( self ):
self.wTree = gtk.glade.XML( "ui.glade" )
dic = {
"on_buttonOne" : self.one,
"on_buttonTwo" : self.two,
}
self.wTree.signal_autoconnect( dic )
gtk.main()
def sone(self, widget):
time.sleep(1)
print "1"
time.sleep(1)
print "2"
time.sleep(1)
print "3"
def stwo(self, widget):
time.sleep(1)
print "4"
time.sleep(1)
print "5"
time.sleep(1)
print "6"
do=fun()
Pretty please, help me.
I'm attempting to learn Tkinter with the goal of being able to create a 'real-time' scope to plot data. As a test, I'm trying to draw a polygon on the canvas every time the 'draw' button is pressed. The triangle position is randomized. I have two problems:
There is a triangle on the canvas as soon as the program starts, why and how do I fix this?
It doesn't draw any triangles when I press the button, at least none that I can see.
CODE
from Tkinter import *
from random import randint
class App:
def __init__(self,master):
#frame = Frame(master)
#frame.pack(side = LEFT)
self.plotspc = Canvas(master,height = 100, width = 200, bg = "white")
self.plotspc.grid(row=0,column = 2, rowspan = 5)
self.button = Button(master, text = "Quit", fg = "red", \
command = master.quit)
self.button.grid(row=0,column=0)
self.drawbutton = Button(master, text = "Draw", command = \
self.pt([50,50]))
self.drawbutton.grid(row = 0, column = 1)
def pt(self, coords):
coords[0] = coords[0] + randint(-20,20)
coords[1] = coords[1] + randint(-20,20)
x = (0,5,10)
y = (0,10,0)
xp = [coords[0] + xv for xv in x]
yp = [coords[1] + yv for yv in y]
ptf = zip(xp,yp)
self.plotspc.create_polygon(*ptf)
if _name_ == "_main_":
root = Tk()
app = App(root)
root.mainloop()
The code is formatting strangely within the code tags, I have no idea how to fix this.
newthing = Link(user=request.user,last_updated=datetime.datetime.now())
However, this uses datetime , not the MYSQL "now()".
How can I use mysql's now()?
Why I can't redefine the __and__ operator?
class Cut(object):
def __init__(self, cut):
self.cut = cut
def __and__(self, other):
return Cut("(" + self.cut + ") && (" + other.cut + ")")
a = Cut("a>0")
b = cut("b>0")
c = a and b
print c.cut()
I want (a>0) && (b>0), but I got b, that the usual behaviour of and
I'm using the nice feature in QMessageBox to optionally show detailed text to the user. However, the window after expansion is still fairly small, and one immediately tries to resize the window so more of the details are visible. Even after setting what I think are the proper settings it won't allow resizing.
Here's the relevant snippet of PyQt4 code:
mb = QMessageBox()
mb.setText("Results written to '%s'" % filename)
mb.setDetailedText(str(myData))
mb.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
mb.setSizeGripEnabled(True)
Am I missing a step and/or is this at all possible?
Is it possible to customize a django application to have accept localized date format (e.g dd/mm/yy) in a DateField on an admin form ?
I have a model class :
class MyModel(models.Model):
date = models.DateField("Date")
And associated admin class
class MyModelAdmin(admin.ModelAdmin):
pass
On django administration interface, I would like to be able to input a date in following format : dd/mm/yyyy. However, the date field in the admin form expects yyyy-mm-dd.
How can I customize things ? Nota bene : I have already specified my custom language code (fr-FR) in settings.py, but it seems to have no effect on this date input matter.
Thanks in advance for your answer
lib.py
from django.core.urlresolvers import reverse
def render_reverse(f, kwargs):
"""
kwargs is a dictionary, usually of the form {'args': [cbid]}
"""
return reverse(f, **kwargs)
tests.py
from lib import render_reverse, print_ls
class LibTest(unittest.TestCase):
def test_render_reverse_is_correct(self):
#with patch('webclient.apps.codebundles.lib.reverse') as mock_reverse:
with patch('django.core.urlresolvers.reverse') as mock_reverse:
from lib import render_reverse
mock_f = MagicMock(name='f', return_value='dummy_views')
mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})
mock_reverse.return_value = '/natrium/cb/details/123'
response = render_reverse(mock_f(), mock_kwargs())
self.assertTrue('/natrium/cb/details/' in response)
But instead, I get
File "/var/lib/graphyte-webclient/graphyte-webenv/lib/python2.6/site-packages/django/core/urlresolvers.py", line 296, in reverse
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'dummy_readfile' with arguments '('123',)' and keyword arguments '{}' not found.
Why is it calling reverse instead of my mock_reverse (it is looking up my urls.py!!)
The author of Mock library Michael Foord did a video cast here (around 9:17), and in the example he passed the mock object request to the view function index. Furthermore, he patched POll and assigned an expected return value.
Isn't that what I am doing here? I patched reverse?
Thanks.
Hello.
Here is my problem. I have created a pretty heavy readonly class making many database calls with a static "factory" method. The goal of this method is to avoid killing the database by looking in a pool of already-created objects if an identical instance of the same object (same type, same init parameters) already exists.
If something was found, the method will just return it. No problem. But if not, how may I create an instance of the object, in a way that works with inheritance?
>>> class A(Object):
>>> @classmethod
>>> def get_cached_obj(self, some_identifier):
>>> # Should do something like `return A(idenfier)`, but in a way that works
>>> class B(A):
>>> pass
>>> A.get_cached_obj('foo') # Should do the same as A('foo')
>>> A().get_cached_obj('foo') # Should do the same as A('foo')
>>> B.get_cached_obj('bar') # Should do the same as B('bar')
>>> B().get_cached_obj('bar') # Should do the same as B('bar')
Thanks.
Imagine I have the following:
inFile = "/adda/adas/sdas/hello.txt"
# that instruction give me hello.txt
Name = inFile.name.split("/") [-1]
# that one give me the name I want - just hello
Name1 = Name.split(".") [0]
Is there any chance to simplify that doing the same job in just one expression?
I am trying to get a login form I have in django to only allow three login attempts before redirecting to a "login help" page. I am currently using the builtin "django.contrib.auth.views.login" view with a custom template. How do I force it to redirect to another page after n failed login attempts?
Hi everyone,
I've updated SQLAlchemy to 0.6 but it broke everything. I've noticed it returns tuple not a dictionary anymore. Here's a sample query:
query = session.query(User.id, User.username, User.email).filter(and_(User.id == id, User.username == username)).limit(1)
result = session.execute(query).fetchone()
This piece of code used to return a dictionary in 0.5.
My question is how can I return a dictionary?
How can I lookup an attribute in any scope by name? My first trial is to use globals() and locals(). e.g.
>>> def foo(name):
... a=1
... print globals().get(name), locals().get(name)
...
>>> foo('a')
None 1
>>> b=1
>>> foo('b')
1 None
>>> foo('foo')
<function foo at 0x014744B0> None
So far so good. However it fails to lookup any built-in names.
>>> range
<built-in function range>
>>> foo('range')
None None
>>> int
<type 'int'>
>>> foo('int')
None None
Any idea on how to lookup built-in attributes?
I'm planning to perform sentiment analysis on reviews of product features (collected from Amazon dataset). I have extracted review text from the dataset and performed POS tagging on that. I'm able to extract NN/NNP as well. But my doubt is how do I come to know that extracted words classify as features of the products? I know there are classifiers in nltk but I don't know how I should use it for my project. I'm assuming there are 2 ways of finding whether the extracted word is a product feature or not. One is to compare with a bag of words and find out if my word exists in that. Doubt: How do I create/get bag of words? Second way is to implement some kind of apriori algorithm to find out frequently occurring words as features. I would like to know which method is good and how to go about implementing it. Some pointers to available softwares or code snippets would be helpful! Thanks!