Hi folks,
I have a WSGI app that I would like to place behind SSL. My WSGI server is gevent.
What would a good way to serve the app through SSL in this case be?
Hi all,
I am csv.reader to pull in info from a very long sheet. I am doing work on that data set and then I am using the xlwt package to give me a workable excel file.
However, I get this error:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 34: ordinal not in range(128)
My question to you all is, how can I find exactly where that error is in my data set? Also, is there some code that I can write which will look through my data set and find out where the issues lie (because some data sets run without the above error and others have problems)?
def maxVote(nLabels):
count = {}
maxList = []
maxCount = 0
for nLabel in nLabels:
if nLabel in count:
count[nLabel] += 1
else:
count[nLabel] = 1
#Check if the count is max
if count[nLabel] > maxCount:
maxCount = count[nLabel]
maxList = [nLabel,]
elif count[nLabel]==maxCount:
maxList.append(nLabel)
return random.choice(maxList)
nLabels contains a list of integers.
The above function returns the integer with highest frequency, if more than one have same frequency then a randomly selected integer from them is returned.
E.g. maxVote([1,3,4,5,5,5,3,12,11]) is 5
I have a regular expression, links = re.compile('<a(.+?)href=(?:"|\')?((?:https?://|/)[^\'"]+)(?:"|\')?(.*?)>(.+?)</a>',re.I).findall(data)
to find links in some html, it is taking a long time on certain html, any optimization advice?
One that it chokes on is http://freeyourmindonline.net/Blog/
In the following script, I get the "stop message received" output but the process never ends. Why is that? Is there another way to end a process besides terminate or os.kill that is along these lines?
from multiprocessing import Process
from time import sleep
class Test(Process):
def __init__(self):
Process.__init__(self)
self.stop = False
def run(self):
while self.stop == False:
print "running"
sleep(1.0)
def end(self):
print "stop message received"
self.stop = True
if __name__ == "__main__":
test = Test()
test.start()
sleep(1.0)
test.end()
test.join()
Hi,
My string is
mystring = "<tr><td><span class='para'><b>Total Amount : </b>INR (Indian Rupees)
100.00</span></td></tr>"
My problem here is I have to search and get the total amount
test = re.search("(Indian Rupees)(\d{2})(?:\D|$)", mystring)
but my test give me None.
How can I get the values and values can be 10.00, 100.00, 1000.00
Thanks
Hello Stack Overflow,
I have come upon a couple of lines of code similar to this one, but I'm unsure how I should break it:
blueprint = Blueprint(self.blueprint_map[str(self.ui.blueprint_combo.currentText())], runs=self.ui.runs_spin.text(), me=self.ui.me_spin.text(), pe=self.ui.pe_skill_combo.currentIndex())
Thanks in advance
I have some code in which is throwing an error (I'm using repl.it)
import random
students = ['s1:0','s2:0','s3:0']
while True:
print'\n'*50
print'Ticket Machine'.center(80)
print'-'*80
print'1. Clear Student Ticket Values'.center(80)
print'2. Draw Tickets'.center(80)
menu = raw_input('-'*80+'\nChoose an Option: ')
if menu == '1':
print'\n'*50
print'CLEARED!'
students = ['s1:0','s2:0','s3:0']
raw_input('Press enter to return to the main menu!')
elif menu == '2':
tickets = []
print'\n'*50
times = int(raw_input('How many tickets to draw? ')
for a in students:
for i in range(a.split(':')[1]):
tickets.append(a.split(':')[0])
for b in range(1,times+1):
print str(b) + '. ' + random.choice(tickets)
else:
print'\n'*50
print'That was not an option!'
raw_input('Press enter to return to the main menu!')
But it is throwing this error:
File "<stdin>", line 19
for a in students:
^
SyntaxError: invalid syntax
I am planning on using this in a class, but I can't use it until the bug is fixed, also, student names have been removed for privacy reasons.
Suppose I have a function which can either take an iterable/iterator or a non-iterable as an argument. Iterability is checked with try: iter(arg).
Depending whether the input is an iterable or not, the outcome of the method will be different. Not when I want to pass a non-iterable as iterable input, it is easy to do: I’ll just wrap it with a tuple.
What do I do when I want to pass an iterable (a string for example) but want the function to take it as if it’s non-iterable? E.g. make that iter(str) fails.
I am starting use Memcached to make my website faster.
For constant data in my database I use this:
from django.core.cache import cache
cache_key = 'regions'
regions = cache.get(cache_key)
if result is None:
"""Not Found in Cache"""
regions = Regions.objects.all()
cache.set(cache_key, regions, 2592000) #(2592000sekund = 30 dni)
return regions
For seldom changed data I use signals:
from django.core.cache import cache
from django.db.models import signals
def nuke_social_network_cache(self, instance, **kwargs):
cache_key = 'networks_for_%s' % (self.instance.user_id,)
cache.delete(cache_key)
signals.post_save.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
signals.post_delete.connect(nuke_social_network_cache, sender=SocialNetworkProfile)
Is it correct way?
I installed django-memcached-0.1.2, which show me:
Memcached Server Stats
Server Keys Hits Gets Hit_Rate Traffic_In Traffic_Out Usage Uptime
127.0.0.1 15 220 276 79% 83.1 KB 364.1 KB 18.4 KB 22:21:25
Can sombody explain what columns means?
And last question.
I have templates where I am getting much records from a few table (relationships).
So in my view I get records from one table and in templates show it and related info from others.
Generating page last a few seconds for very small table (<100records).
Is it some easy way to cache queries from templates?
Have I to do some big structure in my view (with all related tables), cache it and send to template?
I am making a simple metronome where it plays a tick sound every few milliseconds depending on the bpm and plays the sound using the winsound module. I use tkinter because there will be a gui component later but for now the metronome code is working, it plays the sound at a constant rate, but even though I set the after loop to play the sound every few milliseconds, it waits longer and the beat is slower than it should be. Is it a problem with the code or a problem with the way I calculate the time?
Thanks.
Here is my code.
from Tkinter import *
import winsound,time,threading
root=Tk()
c=Canvas(root)
c.pack()
class metronome():
def __init__(self,root,canvas,tempo=100):
self.root=root
self.root.bind("<1>",self.stop)
self.c=canvas
self.thread=threading.Thread(target=self.play)
self.thread.daemon=True
self.pause=False
self.tempo=tempo/60.0
self.tempo=1.0/self.tempo
self.tempo*=1000
def play(self):
winsound.PlaySound("tick.wav",winsound.SND_FILENAME)
self.sound=self.c.after(int(self.tempo),self.play)
def stop(self,e):
self.c.after_cancel(self.sound)
beat=metronome(root,c,120)
beat.thread.start()
root.mainloop()
I need to match two cases by one reg expression and do replacement
'long.file.name.jpg' - 'long.file.name_suff.jpg'
'long.file.name_a.jpg' - 'long.file.name_suff.jpg'
I'm trying to do the following
re.sub('(\_a)?\.[^\.]*$' , '_suff.',"long.file.name.jpg")
But this is cut the extension '.jpg' and I'm getting
long.file.name_suff. instead of long.file.name_suff.jpg
I understand that this is because of [^.]*$ part, but I can't exclude it, because
I have to find last occurance of '_a' to replace or last '.'
Is there a way to replace only part of the match?
I want to remove some symbols from a string using a regular expression, for example:
== (that occur both at the beginning and at the end of a line),
* (at the beginning of a line ONLY).
def some_func():
clean = re.sub(r'= {2,}', '', clean) #Removes 2 or more occurrences of = at the beg and at the end of a line.
clean = re.sub(r'^\* {1,}', '', clean) #Removes 1 or more occurrences of * at the beginning of a line.
What's wrong with my code? It seems like expressions are wrong. How do I remove a character/symbol if it's at the beginning or at the end of the line (with one or more occurrences)?
Say I have a list of datetimes, and we know each datetime to be the recorded time of an event happening.
Is it possible in matplotlib to graph the frequency of this event occuring over time, showing this data in a cumulative graph (so that each point is greater or equal to all of the points that went before it), without preprocessing this list? (e.g. passing datetime objects directly to some wonderful matplotlib function)
Or do I need to turn this list of datetimes into a list of dictionary items, such as:
{"year": 1998, "month": 12, "date": 15, "events": 92}
and then generate a graph from this list?
Sorry if this seems like a silly question - I'm not all too familiar with matplotlib, and would like to save myself the effort of doing this the latter way if matplotlib can already deal with datetime objects itself.
A simplified version of my problem:
I have a list comprehension that i use to set bitflags on a two dimensional list so:
s = FLAG1 | FLAG2 | FLAG3
[[c.set_state(s) for c in row] for row in self.__map]
All set_state does is:
self.state |= f
This works fine but I have to have this function "set_state" in every cell in __map. Every cell in __map has a .state so what I'm trying to do is something like:
[[c.state |= s for c in row] for row in self.map]
or
map(lambda c: c.state |= s, [c for c in row for row in self.__map])
Except that neither works (Syntax error). Perhaps I'm barking up the wrong tree with map/lamda but I would like to get rid on set_state. And perhaps know why assignment does not work in the list-comprehension
I have written a small function, which uses ElementTree and xpath to extract the text contents of certain elements in an xml file:
#!/usr/bin/env python2.5
import doctest
from xml.etree import ElementTree
from StringIO import StringIO
def parse_xml_etree(sin, xpath):
"""
Takes as input a stream containing XML and an XPath expression.
Applies the XPath expression to the XML and returns a generator
yielding the text contents of each element returned.
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem1').next()
'one'
>>> parse_xml_etree(
... StringIO('<test><elem1>one</elem1><elem2>two</elem2></test>'),
... '//elem2').next()
'two'
>>> parse_xml_etree(
... StringIO('<test><null>�</null><elem3>three</elem3></test>'),
... '//elem2').next()
'three'
"""
tree = ElementTree.parse(sin)
for element in tree.findall(xpath):
yield element.text
if __name__ == '__main__':
doctest.testmod(verbose=True)
The third test fails with the following exception:
ExpatError: reference to invalid character number: line 1, column 13
Is the entity illegal XML? Regardless whether it is or not, the files I want to parse contain it, and I need some way to parse them. Any suggestions for another parser than Expat, or settings for Expat, that would allow me to do that?
i am reading a csv file and i want to store this in datastore, but i am getting string from file for datetime field.
i want to type cast it to datetime
also same for date and time separately
error::BadValueError: Property HB_Create_Ship_Date must be a datetime
Hi, I have around 5 GB of html data which I want to process to find links to a set of websites and perform some additional filtering. Right now I use simple regexp for each site and iterate over them, searching for matches. In my case links can be outside of "a" tags and be not well formed in many ways(like "\n" in the middle of link) so I try to grab as much "links" as I can and check them later in other scripts(so no BeatifulSoup\lxml\etc). The problem is that my script is pretty slow, so I am thinking about any ways to speed it up. I am writing a set of test to check different approaches, but hope to get some advices :)
Right now I am thinking about getting all links without filtering first(maybe using C module or standalone app, which doesn't use regexp but simple search to get start and end of every link) and then using regexp to match ones I need.
Hi,
I am trying to 'destructure' a dictionary and associate values with variables names after its keys. Something like
params = {'a':1,'b':2}
a,b = params.values()
but since dictionaries are not ordered, there is no guarantee that params.values() will return values in the order of (a,b). Is there a nice way to do this?
Thanks
Hay All.
I have a list which consists of many lists, here is an example
[
[Obj, Obj, Obj, Obj],
[Obj],
[Obj],
[
[Obj,Obj],
[Obj,Obj,Obj]
]
]
Is there a way to join all these items together as 1 list, so the output will be something like
[Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj,Obj]
Thanks
Just wondering why
import sys
exit(0)
gives me this error:
Traceback (most recent call last):
File "<pyshell#1>", line 1, in ?
exit(0)
TypeError: 'str' object is not callable
but
from sys import exit
exit(0)
works fine?
I am using gd_client.UpdateCell to update values in a google spreadsheet and am looking for a way to update the formatting of the cell i.e. color, lines, textsize.....
Can this be done?
Are there examples or other documentation available?
Anything to get me going would be great
I have a list of users users["pirates"] and they're stored in the format ['pirate1','pirate2'].
If I hand the list over to a def and query for it in MongoDB, it returns data based on the first index (e.g. pirate1) only. If I hand over a list in the format ["pirate1","pirate"], it returns data based on all the elements in the list. So I think there's something wrong with the encapsulation of the elements in the list. My question: can I change the encapsulation from ' to " without replacing every ' on every element with a loop manually?
Short Example:
aList = list()
# get pirate Stuff
# users["pirates"] is a list returned by a former query
# so e.g. users["pirates"][0] may be peter without any quotes
for pirate in users["pirates"]:
aList.append(pirate)
aVar = pirateDef(aList)
print(aVar)
the definition:
def pirateDef(inputList = list()):
# prepare query
col = mongoConnect().MYCOL
# query for pirates Arrrr
pirates = col.find({ "_id" : {"$in" : inputList}}
).sort("_id",1).limit(50)
# loop over users
userList = list()
for person in pirates:
# do stuff that has nothing to do with the problem
# append user to userlist
userList.append(person)
return userList
If the given list has ' encapsulation it returns:
'pirates': [{'pirate': 'Arrr', '_id': 'blabla'}]
If capsulated with " it returns:
'pirates' : [{'_id': 'blabla', 'pirate' : 'Arrr'}, {'_id': 'blabla2', 'pirate' : 'cheers'}]
EDIT: I tried figuring out, that the problem has to be in the MongoDB query. The list is handed over to the Def correctly, but after querying pirates only consists of 1 element...
Thanks for helping me
Codehai