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?
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.
I am creating multisites platform. Anybody can make simple site, with my platform. I plan to use django multidb support. One db for one site. And i need to change db settings depending on request.get_host().
I think that i's not good idea. Prompt other decisions? How it is realised on various designers of sites?
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?
I have a dialog created in PyQt. It's purpose and functionality don't matter.
The init is:
class MyDialog(QWidget, ui_module.Ui_Dialog):
def __init__(self, parent=None):
super(MyDialog, self).__init__(parent)
self.setupUi(self)
self.installEventFilter(self)
self.setWindowFlags(Qt.Dialog | Qt.WindowTitleHint)
self.showMaximized()
Then I have event filtering method:
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress:
key = event.key()
if key == Qt.Key_F11:
if self.isFullScreen():
self.setWindowFlags(self._flags)
if self._state == 'm':
self.showMaximized()
else:
self.showNormal()
self.setGeometry(self._geometry)
else:
self._state = 'm' if self.isMaximized() else 'n'
self._flags = self.windowFlags()
self._geometry = self.geometry()
self.setWindowFlags(Qt.Tool | Qt.FramelessWindowHint)
self.showFullScreen()
return True
elif key == Qt.Key_Escape:
self.close()
return QWidget.eventFilter(self, obj, event)
As can be seen, Esc is used for dialog hiding, and F11 is used for toggling full-screen. In addition, if the user changed the dialog mode from the initial maximized to normal and possibly moved the dialog, it's state and position are restored after exiting the full-screen.
Finally, the dialog is created on the MainWindow action triggered:
d = MyDialog(self)
d.show()
It works fine on Linux (Ubuntu Lucid), but quite strange on Windows 7:
if I go to the full-screen from the maximized mode, I can't exit full-screen (on F11 dialog disappears and appears in full-screen mode again. If I change the dialog's mode to Normal (by double-clicking its title), then go to full-screen and then return back, the dialog is shown in the normal mode, in the correct position, but without the title line.
Most probably the reason for both cases is the same - the setWindowFlags doesn't work. But why?
Is it also possible that it is the bug in the recent PyQt version? On Ubuntu I have 4.6.x from apt, and on Windows - the latest installer from the riverbank site.
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.
I have a 100x200 2D array expressed as a numpy array consisting of black (0) and white (255) cells. It is a bitmap file. I then have 2D shapes (it's easiest to think of them as letters) that are also 2D black and white cells.
I know I can naively iterate through the matrix but this is going to be a 'hot' portion of my code so speed is an concern. Is there a fast way to perform this in numpy/scipy?
I looked briefly at Scipy's correlate function. I am not interested in 'fuzzy matches', only exact matches. I also looked at some academic papers but they are above my head.
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
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)
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.
Hello,
I have three panes with the InfoPane center option.
I want to know how to set their size.
Using this code:
import wx
import wx.aui
class MyFrame(wx.Frame):
def __init__(self, parent, id=-1, title='wx.aui Test',
pos=wx.DefaultPosition, size=(800, 600),
style=wx.DEFAULT_FRAME_STYLE):
wx.Frame.__init__(self, parent, id, title, pos, size, style)
self._mgr = wx.aui.AuiManager(self)
# create several text controls
text1 = wx.TextCtrl(self, -1, 'Pane 1 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text2 = wx.TextCtrl(self, -1, 'Pane 2 - sample text',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
text3 = wx.TextCtrl(self, -1, 'Main content window',
wx.DefaultPosition, wx.Size(200,150),
wx.NO_BORDER | wx.TE_MULTILINE)
# add the panes to the manager
self._mgr.AddPane(text1, wx.CENTER)
self._mgr.AddPane(text2, wx.CENTER)
self._mgr.AddPane(text3, wx.CENTER)
# tell the manager to 'commit' all the changes just made
self._mgr.Update()
self.Bind(wx.EVT_CLOSE, self.OnClose)
def OnClose(self, event):
# deinitialize the frame manager
self._mgr.UnInit()
# delete the frame
self.Destroy()
app = wx.App()
frame = MyFrame(None)
frame.Show()
app.MainLoop()
I want to know what is called when we change the size of the panes.
If you tell me that, I can do the rest by myself :)
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()?
I'm using matplotlib to plot log-normalized images but I would like the original raw image data to be represented in the colorbar rather than the [0-1] interval. I get the feeling there's a more matplotlib'y way of doing this by using some sort of normalization object and not transforming the data beforehand... in any case, there could be negative values in the raw image.
import matplotlib.pyplot as plt
import numpy as np
def log_transform(im):
'''returns log(image) scaled to the interval [0,1]'''
try:
(min, max) = (im[im > 0].min(), im.max())
if (max > min) and (max > 0):
return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
except:
pass
return im
a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)
I've tried using cb.set_array, but that didn't appear to do anything, and cb.set_clim, but that rescales the colors completely.
Thanks in advance for any help :)
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!
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.
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?
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.
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?
"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.
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?
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
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
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.
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?