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 have the following code which is attempting to normalize the values of an m x n array (It will be used as input to a neural network, where m is the number of training examples and n is the number of features).
However, when I inspect the array in the interpreter after the script runs, I see that the values are not normalized; that is, they still have the original values. I guess this is because the assignment to the array variable inside the function is only seen within the function.
How can I do this normalization in place? Or do I have to return a new array from the normalize function?
import numpy
def normalize(array, imin = -1, imax = 1):
"""I = Imin + (Imax-Imin)*(D-Dmin)/(Dmax-Dmin)"""
dmin = array.min()
dmax = array.max()
array = imin + (imax - imin)*(array - dmin)/(dmax - dmin)
print array[0]
def main():
array = numpy.loadtxt('test.csv', delimiter=',', skiprows=1)
for column in array.T:
normalize(column)
return array
if __name__ == "__main__":
a = main()
Could you please suggest a simple SMTP server with the very basic APIs(by very basic I mean, to read,write,delete email) that could be run on a linux box?
I just need to convert the crux of the email into XML format and FTP it to another machine.
"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.
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.
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?
ok so basically I am asking the question of their name
I want this to be one input rather than Forename and Surname.
Now is there any way of splitting this name? and taking just the last word from the "Sentence" e.g.
name = "Thomas Winter"
print name.split()
and what would be output is just "Winter"
Hey guys. Here's my problem:
I have a game class that maintains a HUD overlay that has a bunch of elements, including header and footer background sprites. Everything was working fine until I added a 1024x128 footer sprite. Now two of my text labels will not render, despite the fact that they DO exist in my Group and self.elements array. Is there something I'm missing? When I take out the footerHUDImage line, all of the labels render correctly and everything works fine. When I add the footerHUDImage, two of the labels (the first two) no longer render and the third only sometimes renders. HELP PLEASE! Here is the code:
class AoWHUD (object):
def __init__(self, screen, delegate, dataSource):
self.delegate = delegate
self.dataSource = dataSource
self.elements = []
headerHudImage = KJRImage("HUDBackground.png")
self.elements.append(headerHudImage)
headerHudImage.userInteractionEnabled = True
footerHUDImage = KJRImage("ControlsBackground.png")
self.elements.append(footerHUDImage)
footerHUDImage.rect.bottom = screen.get_rect().height
footerHUDImage.userInteractionEnabled = True
lumberMessage = "Lumber: " + str(self.dataSource.lumber)
lumberLabel = KJRLabel(lumberMessage, size = 48, color = (240, 200, 10))
lumberLabel.rect.topleft = (_kSpacingMultiple * 0, 0)
self.elements.append(lumberLabel)
stoneMessage = "Stone: " + str(self.dataSource.stone)
stoneLabel = KJRLabel(stoneMessage, size = 48, color = (240, 200, 10))
stoneLabel.rect.topleft = (_kSpacingMultiple * 1, 0)
self.elements.append(stoneLabel)
metalMessage = "Metal: " + str(self.dataSource.metal)
metalLabel = KJRLabel(metalMessage, size = 48, color = (240, 200, 10))
metalLabel.rect.topleft = (_kSpacingMultiple * 2, 0)
self.elements.append(metalLabel)
foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food)
foodLabel = KJRLabel(foodMessage, size = 48, color = (240, 200, 10))
foodLabel.rect.topleft = (_kSpacingMultiple * 3, 0)
self.elements.append(foodLabel)
self.selectionSprites = {32 : pygame.image.load("Selected32.png").convert_alpha(), 64 : pygame.image.load("Selected64.png")}
self._sprites_ = pygame.sprite.Group()
for e in self.elements:
self._sprites_.add(e)
print self.elements
def draw(self, screen):
if self.dataSource.resourcesChanged:
lumberMessage = "Lumber: " + str(self.dataSource.lumber)
stoneMessage = "Stone: " + str(self.dataSource.stone)
metalMessage = "Metal: " + str(self.dataSource.metal)
foodMessage = "Food: " + str(len(self.dataSource.units)) + "/" + str(self.dataSource.food)
self.elements[2].setText(lumberMessage)
self.elements[2].rect.topleft = (_kSpacingMultiple * 0, 0)
self.elements[3].setText(stoneMessage)
self.elements[3].rect.topleft = (_kSpacingMultiple * 1, 0)
self.elements[4].setText(metalMessage)
self.elements[4].rect.topleft = (_kSpacingMultiple * 2, 0)
self.elements[5].setText(foodMessage)
self.elements[5].rect.topleft = (_kSpacingMultiple * 3, 0)
self.dataSource.resourcesChanged = False
self._sprites_.draw(screen)
if self.delegate.selectedUnit:
theSelectionSprite = self.selectionSprites[self.delegate.selectedUnit.rect.width]
screen.blit(theSelectionSprite, self.delegate.selectedUnit.rect)
I am trying to request.user for a form's clean method, but how can I access the request object? Can I modify the clean method to allow variables input?
Thanks.
Has anyone tried using uWSGI with Cherokee? Can you share your experiences and what documents you relied upon the most? I am trying to get started from the documentation on both (uWSGI and Cherokee) websites. Nothing works yet. I am using Ubuntu 10.04.
I am trying to do a Physics problem in python. I need to install visual python because I get the error that it can't find the visual library when I type import visual from *
The documentation on the Visual Python site is totally useless.
I have gone into synaptic package manger and installed python-visual. But I still get the same error.
Can someone please help?
Hi,
I am in the process of making a webapp, and this webapp needs to have a form wizard. The wizard consists of 3 ModelForms, and it works flawlessly. But I need the second form to be a "edit form". That is, i need it to be a form that is passed an instance.
How can you do this with a form wizard? How do you pass in an instance of a model? I see that the FormWizard class has a get_form method, but isnt there a documented way to use the formwizard for editing/reviewing of data?
I need to write a gui in Tkinter that can choose a csv file, read it in and generate a sequence of buttons based on the names in the first row of the csv file (later the data in the csv file should be used to run a number of simulations).
So far I have managed to write a Tkinter gui that will read the csv file, but I am stomped as to how I should proceed:
from Tkinter import *
import tkFileDialog
import csv
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self,master)
self.grid()
self.createWidgets()
def createWidgets(self):
top = self.winfo_toplevel()
self.menuBar = Menu(top)
top["menu"] = self.menuBar
self.subMenu = Menu(self.menuBar)
self.menuBar.add_cascade(label = "File", menu = self.subMenu)
self.subMenu.add_command( label = "Read Data",command = self.readCSV)
def readCSV(self):
self.filename = tkFileDialog.askopenfilename()
f = open(self.filename,"rb")
read = csv.reader(f, delimiter = ",")
app = Application()
app.master.title("test")
app.mainloop()
Any help is greatly appreciated!
I do not care about concurrency issues.
It is relatively easy to build unique form field:
from django import forms
class UniqueUserEmailField(forms.CharField):
def clean(self, value):
self.check_uniqueness(super(UniqueUserEmailField, self).clean(value))
def check_uniqueness(self, value):
same_user = users.User.all().filter('email', value).get()
if same_user:
raise forms.ValidationError('%s already_registered' % value)
so one could add users on-the-fly. Editing existing user is tricky. This field would not allow to save user having other user email. At the same time it would not allow to save a user with the same email. What code do you use to put a field with uniqueness check into ModelForm?
Hi folks,
I'm trying to add features to Django admin's main page.
I've been playing with index.html, but features added to this page affect all app pages.
Any ideas on what template I'm supposed to use?
Thanks loads!!
I have a small app with Category model and want to make a required foreign key referencing it from Photologue Gallery model.
What's the right approach? I can make many-to-many field in Category, but this way it will not be required in Gallery. Use "register" and modify the Gallery model? Inherit it in my app?
Hello,
I am trying to get the code to list all the directories in a folder, change directory into that folder and get the name of the current folder. The code I have so far is below and isn't working at the minute. I seem to be getting the parent folder name.
import os
for directories in os.listdir(os.getcwd()):
dir = os.path.join('/home/user/workspace', directories)
os.chdir(dir)
current = os.path.dirname(dir)
new = str(current).split("-")[0]
print new
I also have other files in the folder but I do not want to list them. I have tried the below code but I haven't got it working yet either.
for directories in os.path.isdir(os.listdir(os.getcwd())):
Can anyone see where I am going wrong?
Thanks
Hello, I'm loading web-page using urllib. Ther eis russian symbols, but page encoding is 'utf-8'
1
pageData = unicode(requestHandler.read()).decode('utf-8')
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 262: ordinal not in range(128)
2
pageData = requestHandler.read()
soupHandler = BeautifulSoup(pageData)
print soupHandler.findAll(...)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 340-345: ordinal not in range(128)
Hello!
I want to make a fourier-transformation of an image.
But how can I change the picture to an array?
And after this I think I should use numpy.fft.rfft2 for the transformation.
And how to change back from the array to the image?
Thanks in advance.
import wx
class MainFrame(wx.Frame):
def __init__(self,parent,title):
wx.Frame.__init__(self, parent, title=title, size=(640,480))
self.mainPanel=DoubleBufferTest(self,-1)
self.Show(True)
class DoubleBufferTest(wx.Panel):
def __init__(self,parent=None,id=-1):
wx.Panel.__init__(self,parent,id,style=wx.FULL_REPAINT_ON_RESIZE)
self.SetBackgroundColour("#FFFFFF")
self.timer = wx.Timer(self)
self.timer.Start(100)
self.Bind(wx.EVT_TIMER, self.update, self.timer)
self.Bind(wx.EVT_PAINT,self.onPaint)
def onPaint(self,event):
event.Skip()
dc = wx.MemoryDC()
dc.SelectObject(wx.EmptyBitmap(640, 480))
gc = wx.GraphicsContext.Create(dc)
gc.PushState()
gc.SetBrush(wx.Brush("#CFCFCF"))
bgRect=gc.CreatePath()
bgRect.AddRectangle(0,0,640,480)
gc.FillPath(bgRect)
gc.PopState()
dc2=wx.PaintDC(self)
dc2.Blit(0,0,640,480,dc,0,0)
def update(self,event):
self.Refresh()
app = wx.App(False)
f=MainFrame(None,"Test")
app.MainLoop()
I've come up with this code to draw double buffered GraphicsContext content onto a panel, but there's a constant flickering across the window. I've tried different kinds of paths, like lines and curves but it's still there and I don't know what's causing it.
I have the following code for urllib and BeautifulSoup:
getSite = urllib.urlopen(pageName) # open current site
getSitesoup = BeautifulSoup(getSite.read()) # reading the site content
print getSitesoup.originalEncoding
for value in getSitesoup.find_all('link'): # extract all <a> tags
defLinks.append(value.get('href'))
The result of it:
/usr/lib/python2.6/site-packages/bs4/dammit.py:231: UnicodeWarning: Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.
"Some characters could not be decoded, and were "
And when i try to read the site i get:
?7?e????0*"I??G?H????F??????9-??????;??E?YÞBs????????????4i???)?????^W?????`w?Ke??%??*9?.'OQB???V??@?????]???(P??^??q?$?S5???tT*?Z
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've been running my Scrapy project with a couple of accounts (the project scrapes a especific site that requieres login credentials), but no matter the parameters I set, it always runs with the same ones (same credentials).
I'm running under virtualenv. Is there a variable or setting I'm missing?
Edit:
It seems that this problem is Twisted related.
Even when I run:
scrapy crawl -a user='user' -a password='pass' -o items.json -t json SpiderName
I still get an error saying:
ERROR: twisted.internet.error.ReactorNotRestartable
And all the information I get, is the last 'succesful' run of the spider.
Hi,
I'm writing a program and I need some extra functionality from the gtk.Notebook widget, so I have taken to creating my own.
My only problem is styling my tabs so that they look like the tabs in gtk.Notebook and will change according to the user's theme.
I really don't know where to start so any advice would be much appreciated, thanks :)