I would love to be able to do
>>> A = numpy.array(((1,2),(3,4)))
>>> idx = (0,0)
>>> A[*idx]
and get
1
however this is not valid syntax. Is there a way of doing this without explicitly writing out
>>> A[idx[0], idx[1]]
?
APNG is backwards compatible with PNG. I opened up an apng and png file in a hex editor and the first few bytes look identical. So if a user uploads either of these formats, how do I detect what the format really is? I've seen this done on some sites that block apng.
I'm guessing the ImageMagick library makes this easy, but what if I were to do the detect without the use of an image processing library (for learning purposes)? Can I look for specific bytes that tell me if the file is apng?
Solutions in any language is welcome.
How do we get a particular filtered row as series?
Example dataframe:
>>> df = pd.DataFrame({'date': [20130101, 20130101, 20130102], 'location': ['a', 'a', 'c']})
>>> df
date location
0 20130101 a
1 20130101 a
2 20130102 c
I need to select the row where location is c as a series.
I tried:
row = df[df["location"] == "c"].head(1) # gives a dataframe
row = df.ix[df["location"] == "c"] # also gives a dataframe with single row
In either cases I can't the row as series.
I have a list of tuples that I'm trying to incorporate into a SQL query but I can't figure out how to join them together without adding slashes. My like this:
list = [('val', 'val'), ('val', 'val'), ('val', 'val')]
If I turn each tuple into a string and try to join them with a a comma I'll get something like
' (\'val\, \'val\'), ... '
What's the right way to do this, so I can get the list (without brackets) as a string?
"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.
How can I write a program in php to get the domain information of an existing domain or if a domain name is already taken...? I would like to get the information using php.
Hi all.
I am looking for information on the integration of some of the new Windows 7 taskbar features into my PyQt applications.
Specifically if there already exists the possibility to use the new progress indicator (see here) and the quick links (www.petri.co.il/wp-content/uploads/new_win7_taskbar_features_8.gif).
If anyone could provide a few links or just a "not implemented yet", I'd be very grateful.
Thanks a lot.
I have the same code, written using win32com and xlrd. xlrd preforms the algorithm in less than a second, while win32com takes minutes.
Here is the win32com:
def makeDict(ws):
"""makes dict with key as header name,
value as tuple of column begin and column end (inclusive)"""
wsHeaders = {} # key is header name, value is column begin and end inclusive
for cnum in xrange(9, find_last_col(ws)):
if ws.Cells(7, cnum).Value:
wsHeaders[str(ws.Cells(7, cnum).Value)] = (cnum, find_last_col(ws))
for cend in xrange(cnum + 1, find_last_col(ws)): #finds end column
if ws.Cells(7, cend).Value:
wsHeaders[str(ws.Cells(7, cnum).Value)] = (cnum, cend - 1)
break
return wsHeaders
And the xlrd
def makeDict(ws):
"""makes dict with key as header name,
value as tuple of column begin and column end (inclusive)"""
wsHeaders = {} # key is header name, value is column begin and end inclusive
for cnum in xrange(8, ws.ncols):
if ws.cell_value(6, cnum):
wsHeaders[str(ws.cell_value(6, cnum))] = (cnum, ws.ncols)
for cend in xrange(cnum + 1, ws.ncols):#finds end column
if ws.cell_value(6, cend):
wsHeaders[str(ws.cell_value(6, cnum))] = (cnum, cend - 1)
break
return wsHeaders
There is a byte at a specific index in a byte string which represents eight flags; one flag per bit in the byte. If a flag is set, its corresponding bit is 1, otherwise its 0. For example, if I've got
b'\x21'
the flags would be
0001 0101 # Three flags are set at indexes 3, 5 and 7
# and the others are not set
What would be the best way to get each bit value in that byte, so I know whether a particular flag is set or not? (Preferably using bitwise operations)
I'm designing a system where users will be able to register and afterward authenticate with client certificates in addition to username/password authentication.
The client certificates will have to be valid certificates issued by a configured list of certificate authorities and will be checked (validated) when presented.
In the registration phase, I need to store part(s) of the client certificate in a user repository (DB, LDAP, whatever) so that I can map the user who authenticates with client certificate to an internal "user".
One fairly obvious choice would be to use certificate fingerprint; But fingerprint itself is not enough, since collisions may occur (even though they're not probable), so we need to store additional information from the certificate. This SO question is also informative in this regard.
RFC 2459 defines (4.1.2.2) that certificate serial number must be unique within a given CA.
With all of this combined, I'm thinking of storing certificate serial number and certificate issuer for each registered user. Given that client certificates will be verified and valid, this should uniquely identify each client certificate. That way, even when client certificate is renewed, it would still be valid (serial number stays the same, and so does the issuer).
Did I miss something?
I store user-uploaded images in the Google App Engine datastore as db.Blob, as proposed in the docs. I then serve those images on /images/<id>.jpg.
The server always sends a 200 OK response, which means that the browser has to download the same image multiple time (== slower) and that the server has to send the same image multiple times (== more expensive).
As most of those images will likely never change, I'd like to be able to send a 304 Not Modified response. I am thinking about calculating some kind of hash of the picture when the user uploads it, and then use this to know if the user already has this image (maybe send the hash as an Etag?)
I have found this answer and this answer that explain the logic pretty well, but I have 2 questions:
Is it possible to send an Etag in Google App Engine?
Has anyone implemented such logic, and/or is there any code snippet available?
Okay this is probably a really dumb question, however its really starting to hurt. I have a numpy matrix, and basically i print it out row by row. However i want to make each row be formatted and separated properly.
>>> arr = numpy.matrix([[x for x in range(5)] for y in range(5)])
>>> arr
matrix([[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]])
Lets say i want to print the first row, and add a '|' between each element:
>>> '|'.join(map(str, arr[0,]))
'[[0 1 2 3 4]]'
Err...
>>> '|'.join(map(lambda x: str(x[0]), arr[0]))
'[[0 1 2 3 4]]'
I am really confused by this behavior why does it do this?
I have a simple django's query set like:
qs = AModel.objects.exclude(state="F").order_by("order")
I'd like to use it as follows:
qs[0:3].update(state='F')
expected = qs[3] # throws error here
But last statement throws:
"Cannot update a query once a slice has been taken."
How can I duplicate the query set?
I am using json touch to get some data from my server database and everything works fine but I've got a little problem. I have some images stored as longblob in the db and I can't download them to my iphone app. All I get is a 'null' array. Does anyone know why this is happening???
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?
from threading import Timer
def hello():
print "hello, world"
t = Timer(30.0, hello)
t.start()
This code only fires the timer once.
How can I make the timer run forever?
Thanks,
I have a simple form for managing manufacturers in my shop. After posting form, ajax call returns json with updated data to the form. Problem is, that the returned string is invalid. It looks like it was double-escaped. Strangely similar approach across the whole shop works without any problems. I'm also using jquery 1.6 as javascript framework.
Model contains of 3 fields : char for name, text for description and image field for manufacturer logo.
The function :
def update_data(request, manufacturer_id):
"""Updates data of manufacturer with given manufacturer id.
"""
manufacturer = Manufacturer.objects.get(pk=manufacturer_id)
form = ManufacturerDataForm(request.FILES, request.POST, instance=manufacturer)
if form.is_valid():
form.save()
msg = _(u"Manufacturer data has been saved.")
html = [
["#data", manufacturer_data_inline(request, manufacturer_id, form)],
["#selectable-factories-inline", selectable_manufacturers_inline(request, manufacturer_id)],
]
result = simplejson.dumps({
"html": html
}, cls=LazyEncoder)
return HttpResponse(result)
The error in console : error with invalid JSON :
uncaught exception: Invalid JSON: {"html": [["#data", "\n<h2>Dane</h2>\n<div class="\"manufacturer-image\"">\n \n</div>\n<form action="\"/manage/update-manufacturer-data/1\"" method="\"post\"">\n \n <div class="\"field\"">\n <div class="\"label\"">\n <label for="\"id_name\"">Nazwa</label>:\n </div>\n \n \n <div class="\"error\"">\n <input id="\"id_name\"" name="\"name\"" maxlength="\"50\"" type="\"text\"">\n <ul class="\"errorlist\""><li>Pole wymagane</li></ul>\n </div>\n \n </div>\n\n <div class="\"field\"">\n <div class="\"label\"">\n <label for="\"id_image\"">Zdjecie</label>:\n </div>\n \n \n <div>\n <input name="\"image\"" id="\"id_image\"" type="\"file\"">\n </div>\n \n </div>\n\n <div class="\"field\"">\n <div class="\"label\"">\n <label for="\"id_description\"">Opis</label>:\n </div>\n \n \n <div>\n <textarea id="\"id_description\"" rows="\"10\"" cols="\"40\"" name="\"description\""></textarea>\n </div>\n \n </div>\n \n <div class="\"buttons\"">\n <input class="\"ajax-save-button" button\"="" type="\"submit\"">\n </div>\n</form>"], ["#selectable-factories-inline", "\n <div>\n <a class="\"selectable" selected\"\n="" href="%5C%22/manage/manufacturer/1%5C%22">\n L1\n </a>\n </div>\n\n <div>\n <a class="\"selectable" \"\n="" href="%5C%22/manage/manufacturer/4%5C%22">\n KR3W\n </a>\n </div>\n\n <div>\n <a class="\"selectable" \"\n="" href="%5C%22/manage/manufacturer/3%5C%22">\n L1TA\n </a>\n </div>\n\n"]]}
Any ideas ?
modules
import sys
import string
Importing and reading the files form the Command Prompt
Document = open(sys.argv[1],"r")
Document = open('Wc.txt', 'r')
Document = Document.read().lower()
Dictionary = open(sys.argv[2],"r")
Dictionary = open('Dict.txt', 'r')
Dictionary = Dictionary.read()
def Format(Infile):
for ch in string.punctuation:
Infile = Infile.replace(ch, "")
for no in string.digits:
Infile = Infile.replace(no, " ")
Infile = Infile.lower()
return(Infile)
def Corrections(Infile, DictWords):
Misspelled = set([])
Infile = Infile.split()
DictWords = DictWords.splitlines()
for word in Infile:
if word not in DictWords:
Misspelled.add(word)
Misspelled = sorted(Misspelled)
return (Misspelled)
def Linecheck(Infile,ErrorWords):
Infile = Infile.split()
lineno = 0
Noset = list()
for line in Infile:
lineno += 1
line = line.split()
for word in line:
if word == ErrorWords:
Noset.append(lineno)
sorted(Noset)
return(Noset)
def addkey(error,linenum):
Nodict = {}
for line in linenum:
Nodict.setdefault(error,[]).append(linenum)
return Nodict
FormatDoc = Format(Document)
SpellingMistakes = Corrections(FormatDoc,Dictionary)
alp = str(SpellingMistakes)
for word in SpellingMistakes:
nSet = str(Linecheck(FormatDoc,word))
nSet = nSet.split()
linelist = addkey(word, nSet)
print(linelist)
#
# for word in Nodict.keys():
# Nodict[word].append(line)
Prints each incorrect word on a new line
Hello, this seems like quite an easy problem but I can't figure out what is going on here.
Basically, what I'd like to do is create two different thumbnails from one image on a Django model. What ends up happening is that it seems to be looping and recreating the same image (while appending an underscore to it each time) until it throws up an error that the filename is to big. So, you end up something like:
OSError: [Errno 36] File name too long: 'someimg________________etc.jpg'
Here is the code:
def save(self, *args, **kwargs):
if self.image:
iname = os.path.split(self.image.name)[-1]
fname, ext = os.path.splitext(iname)
tlname, tsname = fname + '_thumb_l' + ext, fname + '_thumb_s' + ext
self.thumb_large.save(tlname, make_thumb(self.image, size=(250,250)))
self.thumb_small.save(tsname, make_thumb(self.image, size=(100,100)))
super(Artist, self).save(*args, **kwargs)
def make_thumb(infile, size=(100,100)):
infile.seek(0)
image = Image.open(infile)
if image.mode not in ('L', 'RGB'):
image.convert('RGB')
image.thumbnail(size, Image.ANTIALIAS)
temp = StringIO()
image.save(temp, 'png')
return ContentFile(temp.getvalue())
I didn't show imports for the sake of brevity. Assume there are two ImageFields on the Artist model: thumb_large, and thumb_small.
If this isn't the correct way to do it, I'd appreciate any feedback. Thanks!
Hello!
I'm using google appengine and Django. I'm using de djangoforms module and wanted to specify the form instance with the information that comes from the query below.
userquery = db.GqlQuery("SELECT * FROM User WHERE googleaccount = :1", users.get_current_user())
form = forms.AccountForm(data=request.POST or None,instance=?????)
I've found a snippet in a sample app that does this trick, but I can't modify it to work with the query I need.
gift = User.get(db.Key.from_path(User.kind(), int(gift_id)))
if gift is None:
return http.HttpResponseNotFound('No gift exists with that key (%r)' %
gift_id)
form = RegisterForm(data=request.POST or None, instance=gift)
Could anyone help me?
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.
We have a bunch of formsets:
EmailAddressInlineFormSet = generic_inlineformset_factory(
EmailAddress, extra=1,
exclude=["created_by","last_modified_by"])
emailaddressformset = EmailAddressInlineFormSet(
instance=person,
prefix="emailaddress")
# [ more definitions ]
and, in the view, we process them as:
emailaddressformset = EmailAddressInlineFormSet(
request.POST,
instance=person,
prefix="emailaddress")
# [ more definitions ]
So, nothing fancy or unordinary.
The unfortunate or unordinary fact is, we have 15 of these formsets, one for email addresses, other for phone numbers etc. so the view code is ugly and not-so-manageable. What would be the most unhackish way to handle this number of formsets in a single view?
At the end -i guess- I'm looking for a class or a functionality like multiple_generic_inline_formset and open to all kind of suggestions or discussions.
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?
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.