content stringlengths 85 101k | title stringlengths 0 150 | question stringlengths 15 48k | answers list | answers_scores list | non_answers list | non_answers_scores list | tags list | name stringlengths 35 137 |
|---|---|---|---|---|---|---|---|---|
Q:
Can scipy calculate (double) integrals with complex-valued integrands (real and imaginary parts in integrand)?
(Couldn't upload the picture showing the integral as I'm a new user.)
A:
Yes. Those integrals (I'll assume they're area integrals over a region in 2D space) can be calculated using an appropriate quadr... | Can scipy calculate (double) integrals with complex-valued integrands (real and imaginary parts in integrand)? | (Couldn't upload the picture showing the integral as I'm a new user.)
| [
"Yes. Those integrals (I'll assume they're area integrals over a region in 2D space) can be calculated using an appropriate quadrature rule.\nYou can also use Green's theorem to convert them into contour integrals and use Gaussian quadrature to integrate along the path. \n",
"Thanks duffymo!\nI am calculating H... | [
1,
0
] | [] | [] | [
"python",
"scipy"
] | stackoverflow_0003520672_python_scipy.txt |
Q:
Finding all sentences from list of keywords to dict
I have list of possible words to make anagram of the given words. Each string of list is key to dictionary and has value of one or more words. Which is the best (fastest, pythonic) way to make all possible sentences in the order of the keys from the words in each... | Finding all sentences from list of keywords to dict | I have list of possible words to make anagram of the given words. Each string of list is key to dictionary and has value of one or more words. Which is the best (fastest, pythonic) way to make all possible sentences in the order of the keys from the words in each list of the corresponding keys in the dictionary.
Lists ... | [
"Use the product function in the itertools module to produce all combinations of your iterables\nimport itertools\n\nfor sentence in itertools.product(['a','b','c'], ['d','e','f'], ['g','h','i']):\n print sentence\n\nThe output will be tuples, but these can easily be converted to strings or lists if required.\n"... | [
6,
1,
0
] | [] | [] | [
"combinations",
"dictionary",
"python",
"word"
] | stackoverflow_0003526357_combinations_dictionary_python_word.txt |
Q:
PHP returning content-length of 0 to python's urllib
My code fetches CSV data from a PHP page using httplib. When I open the page in Firefox or Chrome, the data displays just fine. However, when I try to fetch it with my python code, I get a header with content-length: 0 and no data. This page is the only one that... | PHP returning content-length of 0 to python's urllib | My code fetches CSV data from a PHP page using httplib. When I open the page in Firefox or Chrome, the data displays just fine. However, when I try to fetch it with my python code, I get a header with content-length: 0 and no data. This page is the only one that does this - in another page in the same directory, the py... | [
"Perhaps the PHP script expects to see some HTTP header or headers that the httplib module isn't sending. For example, httplib does not seem to send Accept, Accept-Language, or User-Agent headers by default. You may need to add one or more of those to the request() call. It does seem to send a proper Host header, t... | [
1,
1
] | [] | [] | [
"content_length",
"php",
"python"
] | stackoverflow_0003526534_content_length_php_python.txt |
Q:
redirecting standard output to print messages in gui instead of terminal
#!/usr/bin/python
import wx
import os
import sys
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(480, 400))
self.panel = MyPanel(self, -1)
self.Cen... | redirecting standard output to print messages in gui instead of terminal | #!/usr/bin/python
import wx
import os
import sys
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(480, 400))
self.panel = MyPanel(self, -1)
self.Centre()
self.Show(True)
setstd()
print 'test'
""... | [
"When you use the print statement with wxPython, where it ends up depends on how you called wx.App(). \nwx.App(redirect=False) or simply wx.App(0) will send print statements to a console window, otherwise they will be sent to a little textbox window.\n",
"I finally found:\nhttp://www.velocityreviews.com/forums/t... | [
2,
2
] | [] | [] | [
"python"
] | stackoverflow_0003526461_python.txt |
Q:
Pythonic way to compare two lists and print the unmatched items?
I have two Python lists of dictionaries, entries9 and entries10. I want to compare the items and write joint items to a new list called joint_items. I also want to save the unmatched items to two new lists, unmatched_items_9 and unmatched_items_10.
T... | Pythonic way to compare two lists and print the unmatched items? | I have two Python lists of dictionaries, entries9 and entries10. I want to compare the items and write joint items to a new list called joint_items. I also want to save the unmatched items to two new lists, unmatched_items_9 and unmatched_items_10.
This is my code. Getting the joint_items and unmatched_items_9 (in the ... | [
"The equivalent of what you're currently doing, but the other way around, is:\nunmatched_items_10 = [d for d in entries10 if d not in entries9]\n\nWhile more concise than your way of coding it, this has the same performance problem: it will take time proportional to the number of items in each list. If the lengths... | [
10,
0,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0003526196_list_python.txt |
Q:
difference between default and optional arguments
okay code:
#!/usr/bin/python
import wx
import sys
class XPinst(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
def OnInit(self):
frame = wx.Frame(None, -1, title='Redirect Test', size=(... | difference between default and optional arguments | okay code:
#!/usr/bin/python
import wx
import sys
class XPinst(wx.App):
def __init__(self, redirect=False, filename=None):
wx.App.__init__(self, redirect, filename)
def OnInit(self):
frame = wx.Frame(None, -1, title='Redirect Test', size=(620,450), style=wx.STAY_ON_TOP|wx.DEFAULT_FRAME_STYLE)
... | [
"Runs fine for me with one tweak; you're missing a colon after your subclassed wx.Frame statement.\nOne comment; if you're just \"passing through\" arguments to the parent initalizer, use *args and/or **kwargs to save some typing.\nclass MyFrame(wx.Frame):\n def __init__(self, *args, **kwargs):\n wx.Frame... | [
1,
1
] | [] | [] | [
"keyword_argument",
"optional_parameters",
"python",
"wxpython"
] | stackoverflow_0003527468_keyword_argument_optional_parameters_python_wxpython.txt |
Q:
Python + MySQLDB Batch Insert/Update command for two of the same databases
I'm working with two databases, a local version and the version on the server. The server is the most up to date version and instead of recopying all values on all tables from the server to my local version,
I would like to enter each tab... | Python + MySQLDB Batch Insert/Update command for two of the same databases | I'm working with two databases, a local version and the version on the server. The server is the most up to date version and instead of recopying all values on all tables from the server to my local version,
I would like to enter each table and only insert/update the values that have changed, from server, and copy th... | [
"If all of your tables' records had timestamps, you could identify \"the values that have changed in the server\" -- otherwise, it's not clear how you plan to do that part (which has nothing to do with insert or update, it's a question of \"selecting things right\").\nOnce you have all the important values, somecur... | [
0
] | [] | [] | [
"batch_file",
"mysql",
"python"
] | stackoverflow_0003526629_batch_file_mysql_python.txt |
Q:
Determine local connectivity in python
How can I tell if my client system has a network connection using python? I can assume the client connected with DHCP. I can't use lists of known reliable sites to ping to test the connection, as it needs to work in isolated networks as well as open ones.
I thought about fetc... | Determine local connectivity in python | How can I tell if my client system has a network connection using python? I can assume the client connected with DHCP. I can't use lists of known reliable sites to ping to test the connection, as it needs to work in isolated networks as well as open ones.
I thought about fetching the local ip (should work, so long as i... | [
"localhost should always return 127.0.0.1 in ip4, '::1' in ip6, so of course it's not going to be useful -- it's the loopback interface, not the ethernet card or whatever;-).\nPersonally, I'd use subprocess.Popen to run ifconfig and parse the results (it's spelled ipconfig in Windows) -- not ideal, but pretty pract... | [
4
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003527720_python_sockets.txt |
Q:
extract specific set of lines from files
I have many large (~30 MB a piece) tab-delimited text files with variable-width lines. I want to extract the 2nd field from the nth (here, n=4) and next-to-last line (the last line is empty). I can get them separately using awk:
awk 'NR==4{print $2}' filename.dat
and (I do... | extract specific set of lines from files | I have many large (~30 MB a piece) tab-delimited text files with variable-width lines. I want to extract the 2nd field from the nth (here, n=4) and next-to-last line (the last line is empty). I can get them separately using awk:
awk 'NR==4{print $2}' filename.dat
and (I don't comprehend this entirely but)
awk '{y=x "\... | [
"awk 'NR==4{print $2};{y=x \"\\n\" $2};END{print y}' filename.dat\n\n",
"You can pass the number of lines into awk:\nawk -v lines=$( wc -l < filename.dat ) -v n=4 '\n NR == n || NR == lines-1 {print $2}\n' filename.dat\n\nNote, in the wc command, use the < redirection to avoid the filename being printed.\n",
... | [
3,
2,
1,
1
] | [] | [] | [
"awk",
"python",
"text_processing"
] | stackoverflow_0003518068_awk_python_text_processing.txt |
Q:
How to generate a UUID of type long (to be consumed by a java program) in Python?
How do you generate UUID of type long (64 bits - to be consumed by a java program) using Python?
I read about the UUID module. So I played with it a bit:
>>> import uuid
>>> uuid.uuid1().int
315596929882403038588122750660996915734L
... | How to generate a UUID of type long (to be consumed by a java program) in Python? | How do you generate UUID of type long (64 bits - to be consumed by a java program) using Python?
I read about the UUID module. So I played with it a bit:
>>> import uuid
>>> uuid.uuid1().int
315596929882403038588122750660996915734L
Why is there an "L" at the end of the integer generated by uuid.uuid1().int? If it's a... | [
"The L signifies that it's a long integer value (greater than 32 bits).\nStandard UUIDs are always 128 bits; if you want something that's only 64 bits, you'll need to either only use a sub-part of a UUID, or use something other than a UUID.\n",
"Depending on how unique you need it to be, you may be able to genera... | [
8,
4,
1,
1
] | [] | [] | [
"guid",
"java",
"long_integer",
"python",
"uuid"
] | stackoverflow_0003528119_guid_java_long_integer_python_uuid.txt |
Q:
python target string key count invalid syntax
Why am i getting an "invalid syntax" when i run below code. Python 2.7
from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0 #fsi=find string index
while fsi<len(target):
fsi=dna.find(key,fsi)
if fsi!=-1:
... | python target string key count invalid syntax | Why am i getting an "invalid syntax" when i run below code. Python 2.7
from string import *
def countSubStringMatch(target,key):
counter=0
fsi=0 #fsi=find string index
while fsi<len(target):
fsi=dna.find(key,fsi)
if fsi!=-1:
counter+=1
else:
counter=0
... | [
"In the line:\ndef countSubStringMatch(\"atgacatgcacaagtatgcat\",\"atgc\")\n\nYou should remove the def. def is used when defining a function, not when calling it.\n",
"Other things wrong with your code:\n\nYou don't use and don't need anything in the string module. Don't import from it.\nDon't do from somemodule... | [
5,
3,
3
] | [] | [] | [
"python",
"string",
"syntax"
] | stackoverflow_0003525952_python_string_syntax.txt |
Q:
search and replace text inline in file in Python
I am trying to convert a file which contains ip address in the traditional format to a file which contains ip address in the binary format.
The file contents are as follows.
src-ip{ 192.168.64.54 }
dst-ip{ 192.168.43.87 }
The code I have is as follows.
import re
fr... | search and replace text inline in file in Python | I am trying to convert a file which contains ip address in the traditional format to a file which contains ip address in the binary format.
The file contents are as follows.
src-ip{ 192.168.64.54 }
dst-ip{ 192.168.43.87 }
The code I have is as follows.
import re
from decimal import *
filter = open("filter.txt", "r")
... | [
"with open('filter.txt') as filter_:\n with open(\"format.txt\", \"w\") as format: \n for line in filter_:\n if line != '\\n':\n ip = line.split()\n ip[1] = '.'.join(bin(int(x)+256)[3:] for x in ip[1].split('.'))\n ip[4]= '.'.join(bin(int(x)+256)[3:]... | [
2,
1,
0,
0
] | [] | [] | [
"python",
"regex",
"replace"
] | stackoverflow_0003527975_python_regex_replace.txt |
Q:
How to receive and parse a HTTP incoming request using python?
How to receive and parse a HTTP incoming request using python?
A:
You can do:
python -m SimpleHTTPServer 8080
By default it serves the current working directory.
To get an idea of how this is put together/parses the requests or to work out how to b... | How to receive and parse a HTTP incoming request using python? | How to receive and parse a HTTP incoming request using python?
| [
"You can do:\npython -m SimpleHTTPServer 8080 \n\nBy default it serves the current working directory.\nTo get an idea of how this is put together/parses the requests or to work out how to build one for your own needs, look at the \"SimpleHTTPServer.py\" module in the lib directory of your python install.\nYou could... | [
1,
0
] | [] | [] | [
"http",
"python"
] | stackoverflow_0003528865_http_python.txt |
Q:
Extract certain elements from a list
I have no clue about Python and started to use it on some files. I managed to find out how to do all the things that I need, except for 2 things.
1st
>>>line = ['0', '1', '2', '3', '4', '5', '6']
>>>#prints all elements of line as expected
>>>print string.join(line)
0 1 2 3 4 5... | Extract certain elements from a list | I have no clue about Python and started to use it on some files. I managed to find out how to do all the things that I need, except for 2 things.
1st
>>>line = ['0', '1', '2', '3', '4', '5', '6']
>>>#prints all elements of line as expected
>>>print string.join(line)
0 1 2 3 4 5 6
>>>#prints the first two elements as e... | [
"Provided the join here is just to have a nice string to print or store as result (with a coma as separator, in the OP example it would have been whatever was in string).\nline = ['A', 'B', 'C', 'D', 'E', 'F', 'G']\n\nprint ','.join (line[0:2])\n\nA,B\nprint ','.join (line[i] for i in [0,1,2,4,5,6])\n\nA,B,C,E,F,G\... | [
5,
2,
2,
2,
1,
1,
1
] | [] | [] | [
"join",
"python"
] | stackoverflow_0003529103_join_python.txt |
Q:
Python regex, how-to group an item within a regex
I'm having trouble creating a regex.
Here is a sample of the text on which the regex should work:
<b>Additional Equipment Items</b> <br>
40001 <br>
1 Battery Marathon L (8 cells type L6V110) <br>
40002 <br>
What I now want to select is >>1<< and >>Battery Marath... | Python regex, how-to group an item within a regex | I'm having trouble creating a regex.
Here is a sample of the text on which the regex should work:
<b>Additional Equipment Items</b> <br>
40001 <br>
1 Battery Marathon L (8 cells type L6V110) <br>
40002 <br>
What I now want to select is >>1<< and >>Battery Marathon L (8 cells type L6V110)<<.
Therefore I have produce... | [
"Okay I sometimes just hate Regex. Some whitespaces owned me...\nHere is the solution:\n<b>.*Items\\s*<\\/b>\\s*<br>(?:\\s*[1-4]0[0-9][0-9][0-9] <br>\\s*(\\d*)\\s*(.*) <br>)\n\n"
] | [
0
] | [] | [] | [
"grouping",
"python",
"regex"
] | stackoverflow_0003528640_grouping_python_regex.txt |
Q:
Replace a pattern in python
How to replace the pattern in the string with
decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)"
The first pattern "(++info++)" needs to replaced with (++info a++)
The second pattern "(++info++)" needs to replaced with (++info b++)
The third pattern "(++info+... | Replace a pattern in python | How to replace the pattern in the string with
decoded_str=" Name(++info++)Age(++info++)Adress of the emp(++info++)"
The first pattern "(++info++)" needs to replaced with (++info a++)
The second pattern "(++info++)" needs to replaced with (++info b++)
The third pattern "(++info++)" needs to replaced with (++inf... | [
"This should be simple enough:\nfor character in range(ord('a'), ord('z')):\n if \"(++info++)\" not in decoded_str:\n break\n decoded_str = decoded_str.replace(\"(++info++)\", \"(++info {0}++)\".format(chr(character)), 1)\n\nprint decoded_str\n\nIt has the added benefit of stopping at 'z'. If you want ... | [
4,
3,
2,
1,
1,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0003528545_python.txt |
Q:
Google Docs API and Python: How to change the owner of a document?
I am using the gdata-python library to perform a number of operations via the Google Docs API. This library uses version 2 of the protocol, which does not support changing the ownership of a document.
Has anyone managed to find a successful workaro... | Google Docs API and Python: How to change the owner of a document? | I am using the gdata-python library to perform a number of operations via the Google Docs API. This library uses version 2 of the protocol, which does not support changing the ownership of a document.
Has anyone managed to find a successful workaround which lets them change the owner of a document using the version 2 A... | [
"I'm not sure if it is good form to answer my own question, or just add a comment.\nIt turns out that a little bit more RTFM'ing was required - http://code.google.com/intl/nl-NL/apis/documents/docs/3.0/developers_guide_python.html#ACLRetrieve\nThis document is incompatible with version 2 of the API - it turns out I... | [
1
] | [] | [] | [
"gdata",
"python"
] | stackoverflow_0003519827_gdata_python.txt |
Q:
Find the largest image dimensions from list of images
I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions.
All the images are in common web-compatible formats — JPG, GIF, PNG, etc.
Thank you.
A:
Assuming that the "s... | Find the largest image dimensions from list of images | I have a list (the paths) of images saved locally. How can I find the largest image from these? I'm not referring to the file size but the dimensions.
All the images are in common web-compatible formats — JPG, GIF, PNG, etc.
Thank you.
| [
"Assuming that the \"size\" of an image is its area :\nfrom PIL import Image\n\ndef get_img_size(path):\n width, height = Image.open(path).size\n return width*height\n\nlargest = max(the_paths, key=get_img_size)\n\n",
"Use Python Imaging Library (PIL). Something like this:\nfrom PIL import Image\nfilenames ... | [
7,
6,
0
] | [
"import Image\n\nsrc = Image.open(image)\nsize = src.size \n\nsize will be a tuple with the image dimensions (witdh and height)\n"
] | [
-2
] | [
"python"
] | stackoverflow_0003529552_python.txt |
Q:
Why do Python programmers still use old-style division?
I started using Python in 2001. I loved the simplicity of the language, but one feature that annoyed the heck out of me was the / operator, which would bite me in subtle places like
def mean(seq):
"""
Return the arithmetic mean of a list
(unless ... | Why do Python programmers still use old-style division? | I started using Python in 2001. I loved the simplicity of the language, but one feature that annoyed the heck out of me was the / operator, which would bite me in subtle places like
def mean(seq):
"""
Return the arithmetic mean of a list
(unless it just happens to contain all ints)
"""
return sum(s... | [
"I think // for truncation is reasonably well known, but people are reluctant to \"import from the future\" in every module they write.\nThe classic approach (using float(sum(seq)) and so on to get a float result, int(...) to truncate an otherwise-float division) is the one you'd use in C++ (and with slightly diffe... | [
8,
2,
1
] | [] | [] | [
"integer_division",
"python"
] | stackoverflow_0003528325_integer_division_python.txt |
Q:
Issue with Django Inline form
I have attached TestInline in the FoobarAdmin, this thing works well but i want logged in user to be pre-populated for the added_by field
from django.contrib import admin
from django.contrib.auth.models import User
class Test(models.Model):
description = models.TextField()
a... | Issue with Django Inline form | I have attached TestInline in the FoobarAdmin, this thing works well but i want logged in user to be pre-populated for the added_by field
from django.contrib import admin
from django.contrib.auth.models import User
class Test(models.Model):
description = models.TextField()
added_on = models.DateTimeField(auto... | [
"See prepopulated_fields in the admin docs.\nIf I understand what you need correctly, I think this article by James Bennett tackles the issue pretty well.\nFinally (in case you haven't seen them), there are two other informative posts on prepopulating admin fields.\n"
] | [
1
] | [] | [] | [
"django",
"django_admin",
"python"
] | stackoverflow_0003529806_django_django_admin_python.txt |
Q:
Django ORM Query: getting "has many" relation objects
There is a model:
class DomainPosition(models.Model):
domain = models.ForeignKey(Domain)
keyword = models.ForeignKey(Keyword)
date = models.DateField()
position = models.IntegerField()
class Meta:
ordering = ['domain', 'keywo... | Django ORM Query: getting "has many" relation objects | There is a model:
class DomainPosition(models.Model):
domain = models.ForeignKey(Domain)
keyword = models.ForeignKey(Keyword)
date = models.DateField()
position = models.IntegerField()
class Meta:
ordering = ['domain', 'keyword']
How to get the positions records for a template if fo... | [
"def show_domain_history(request, domain_name):\n domain = Domain.objects.filter(name__contains=domain_name)\n if not domain:\n return HttpResponseRedirect('/')\n else:\n variables = {'domain': domain }\n return render_to_response('history.html', variables)\n\nnow in the template you c... | [
1,
0
] | [] | [] | [
"django",
"django_models",
"django_orm",
"python"
] | stackoverflow_0003528783_django_django_models_django_orm_python.txt |
Q:
Multi processing subprocess
I'm new to subprocess module of python, currently my implementation is not multi processed.
import subprocess,shlex
def forcedParsing(fname):
cmd = 'strings "%s"' % (fname)
#print cmd
args= shlex.split(cmd)
try:
sp = subprocess.Popen( arg... | Multi processing subprocess | I'm new to subprocess module of python, currently my implementation is not multi processed.
import subprocess,shlex
def forcedParsing(fname):
cmd = 'strings "%s"' % (fname)
#print cmd
args= shlex.split(cmd)
try:
sp = subprocess.Popen( args, shell = False, stdout = subpro... | [
"1) subprocess.communicate() seems the right option for what you are trying to do. And you don't need to poll the proces, communicate() returns only when it's finished.\n2) you mean forking to paralellize work? take a look at multiprocessing (python >= 2.6). Running parallel processes using subprocess is of course ... | [
3,
2,
1
] | [] | [] | [
"fork",
"multithreading",
"process",
"python",
"subprocess"
] | stackoverflow_0003530806_fork_multithreading_process_python_subprocess.txt |
Q:
Python auth_handler not working for me
I've been reading about Python's urllib2's ability to open and read directories that are password protected, but even after looking at examples in the docs, and here on StackOverflow, I can't get my script to work.
import urllib2
# Create an OpenerDirector with support for Ba... | Python auth_handler not working for me | I've been reading about Python's urllib2's ability to open and read directories that are password protected, but even after looking at examples in the docs, and here on StackOverflow, I can't get my script to work.
import urllib2
# Create an OpenerDirector with support for Basic HTTP Authentication...
auth_handler = ur... | [
"auth_handler is only for basic HTTP authentication. The site here contains a HTML form, so you'll need to submit your username/password as POST data.\nI recommend you using the mechanize module that will simplify the login for you.\nQuick example:\nimport mechanize\n\nbrowser = mechanize.Browser()\n\nbrowser.open(... | [
3
] | [] | [] | [
"authentication",
"python",
"urllib2",
"urlopen"
] | stackoverflow_0003530910_authentication_python_urllib2_urlopen.txt |
Q:
Suds Performance - client.factory.create() takes more than 2 minutes
I'm using Suds to send/receive SOAP messages in Python. It is taking an insanely long time to create an object to send via the soap envelope.
client = Client(wsdldict['Contact'], faults=True, headers=session) #takes ~5 seconds
lq1=client.factory... | Suds Performance - client.factory.create() takes more than 2 minutes | I'm using Suds to send/receive SOAP messages in Python. It is taking an insanely long time to create an object to send via the soap envelope.
client = Client(wsdldict['Contact'], faults=True, headers=session) #takes ~5 seconds
lq1=client.factory.create("ns1:ListOfContactQuery") #takes ~130 seconds
The WSDL file is fa... | [
"SUDS performance does breakdown on large WSDL files. I have experienced this same thing before with the Citrix NetScaler SOAP API. \nIf you are able to filter your WSDL into a subset of required commands, store the file on disk and load it locally, or make use of SUDS' caching functionality, you can dramatically i... | [
6
] | [] | [] | [
"python",
"suds",
"web_services"
] | stackoverflow_0003531537_python_suds_web_services.txt |
Q:
How to refer to "\" sign in python string
I have problem with refering to special symbol in string:
I have: path='C:\dir\dir1\dir2\filename.doc'
and I want filename.
When I try: filename=path[path.rfind("\"):-4]
then interpreter says it's an error line right from "\" since is treated as a comment.
A:
You can use... | How to refer to "\" sign in python string | I have problem with refering to special symbol in string:
I have: path='C:\dir\dir1\dir2\filename.doc'
and I want filename.
When I try: filename=path[path.rfind("\"):-4]
then interpreter says it's an error line right from "\" since is treated as a comment.
| [
"You can use \"\\\\\", technically it would be better to use os.path.sep if you insist on using backslashes. But better yet, use / in your paths, it works fine on Windows\nPython has builtin functions to manipulate paths. Note that you need to double the backslashes if you still prefer them to forwardslashes\n>>> i... | [
12,
2,
1,
0,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0003531430_python_string.txt |
Q:
Python dictionary reference to neighbor dictionary element
I'm trying to create something following:
dictionary = {
'key1': ['val1','val2'],
'key2': @key1
}
where @key1 is reference to dictionary['key1'].
Thank You in advance.
A:
Use a new class:
class DictRef(object):
def __init__(self, d, key): self... | Python dictionary reference to neighbor dictionary element | I'm trying to create something following:
dictionary = {
'key1': ['val1','val2'],
'key2': @key1
}
where @key1 is reference to dictionary['key1'].
Thank You in advance.
| [
"Use a new class:\nclass DictRef(object):\n def __init__(self, d, key): self.d, self.key = d, key\n\nd = {}\nd.update({\n 'key1': ['val1','val2'],\n 'key2': DictRef(d, 'key1')\n})\n\nNote the odd syntax because you have no way to know inside of which dictionary you are creating DictRef.\n",
"I'd expand A... | [
4,
4
] | [] | [] | [
"dictionary",
"python"
] | stackoverflow_0003531198_dictionary_python.txt |
Q:
Most optimal way to reverse search list of similar strings
I have a list of data that includes both command strings as well as the alphabet, upper and lowercase, totaling to 512+ (including sub-lists) strings. I want to parse the input data, but i cant think of any way to do it properly other than starting from th... | Most optimal way to reverse search list of similar strings | I have a list of data that includes both command strings as well as the alphabet, upper and lowercase, totaling to 512+ (including sub-lists) strings. I want to parse the input data, but i cant think of any way to do it properly other than starting from the largest possible command size and cutting it down until i find... | [
"It sounds like you're searching through the list for every substring. How about you built a dict to lookup the keys. Of cause you still have to start searching at the longest subkey.\nL = ['a', 'b',['aa','bb','cc'], 'c']\n\ndef lookups( L ):\n \"\"\" returns `item`, `code` tuples \"\"\"\n for i, item in enum... | [
2,
1
] | [] | [] | [
"arrays",
"indexing",
"multidimensional_array",
"python",
"reverse"
] | stackoverflow_0003531669_arrays_indexing_multidimensional_array_python_reverse.txt |
Q:
SelfReferenceProperty question
I am trying to use google appengine. I have this model:
def Human(db.Model):
name = db.StringProperty()
friends = db.SelfReferenceProperty()
This Human has more than one friend. So, how to handle this with google appengine?
A:
For simple many-to-many relationships, use a ListPro... | SelfReferenceProperty question | I am trying to use google appengine. I have this model:
def Human(db.Model):
name = db.StringProperty()
friends = db.SelfReferenceProperty()
This Human has more than one friend. So, how to handle this with google appengine?
| [
"For simple many-to-many relationships, use a ListProperty with a list of keys.\nIf you need to store additional metadata, give the model its own relationship, e.g. Friendship.\nExamples of both can be found @ http://code.google.com/appengine/articles/modeling.html\n"
] | [
5
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003531936_google_app_engine_python.txt |
Q:
Sorted quantile mean via Rpy
The real goal here is to find the quantile means (or sums, or median, etc.) in Python. Since I'm not a power user of Python but have used R for a while, my chosen route is via Rpy. However, I ran into the problem that the returned list of means are not correspondent to the order of the... | Sorted quantile mean via Rpy | The real goal here is to find the quantile means (or sums, or median, etc.) in Python. Since I'm not a power user of Python but have used R for a while, my chosen route is via Rpy. However, I ran into the problem that the returned list of means are not correspondent to the order of the quantiles. In particular, I have ... | [
"Try rpy2.\nWith rpy2 >= 2.1.0, this could be:\nfrom rpy2.robjects.vectors import IntVector\nfrom rpy2.robjects.packages import importr\nbase = importr('base')\nstats = importr('stats')\n\na = IntVector((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))\nb = IntVector((2, 4, 20, 40, 200, 400, 2000, 4000, 20000, 40000))\nprob = base.... | [
4,
2,
0
] | [] | [] | [
"python",
"quantile",
"r",
"rpy2"
] | stackoverflow_0003530896_python_quantile_r_rpy2.txt |
Q:
Send keyboard event using subprocess
I have two python scripts. First one is just a script waiting for user keyboard input. When user presses a key it prints a pressed key value.
Second script calls first one through subprocess using Popen like this
p = Popen('python first_script.py', shell=True, universal_newline... | Send keyboard event using subprocess | I have two python scripts. First one is just a script waiting for user keyboard input. When user presses a key it prints a pressed key value.
Second script calls first one through subprocess using Popen like this
p = Popen('python first_script.py', shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, stderr=ST... | [
"subprocess per se has no facilities to \"send keyboard events\" (to the sub-process or to any other process). You need other aproaches, such as the one this article shows for Windows.\n"
] | [
2
] | [] | [] | [
"python",
"subprocess"
] | stackoverflow_0003531953_python_subprocess.txt |
Q:
Flipping bits in python
Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper.
To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n]
for i in range(lower,upper+1):
n ^= (1 << len(bit_... | Flipping bits in python | Given an integer n , i want to toggle all bits in the binary representation of that number in the range say lower to upper.
To do this i do the following [bit_string is a string containing 1's and 0's and is a binary representation of n]
for i in range(lower,upper+1):
n ^= (1 << len(bit_string)-1-i) #Toggle the ith ... | [
"For the \"flipping\", you can make a single bitmap (with ones in all positions of interest) and a single exclusive-or:\nn ^= ((1<<upper)-1)&~((1<<lower)-1)\n\nFor bit-counts, once you isolate (n & mask) for the same \"mask\" as the above RHS, slicing it into e.g. 8-bit slices and looking up the 8-bit counts in a l... | [
12,
1,
1,
0
] | [] | [] | [
"algorithm",
"python"
] | stackoverflow_0003532018_algorithm_python.txt |
Q:
Jython: Access singleton Java class (static)
I cannot seem to get the syntax quite right for this: I have a Jython script and a Java application loaded into the same JVM (for testing).
I need to access a particular part of the application through a Singleton class from the Jython script. How do I do this?
Thanks
... | Jython: Access singleton Java class (static) | I cannot seem to get the syntax quite right for this: I have a Jython script and a Java application loaded into the same JVM (for testing).
I need to access a particular part of the application through a Singleton class from the Jython script. How do I do this?
Thanks
EDIT:
The set up is for automated testing, so assu... | [
"Didn't this work?\nfrom some.pkg import MySingleton\n\nmyInstance = MySingleton.getInstance()\n\nIf that doesn't work, try this: (I'm not sure if this works)\nmySingletonClass = MySingleton(MySingleton)\nmyInstance = mySingletonClass.getInstance()\n\n"
] | [
1
] | [] | [] | [
"java",
"jython",
"python",
"singleton",
"static"
] | stackoverflow_0003528397_java_jython_python_singleton_static.txt |
Q:
How do I ensure data integrity for objects in google app engine without using key names?
I'm having a bit of trouble in Google App Engine ensuring that my data is correct when using an ancestor relationship without key names.
Let me explain a little more: I've got a parent entity category, and I want to create a c... | How do I ensure data integrity for objects in google app engine without using key names? | I'm having a bit of trouble in Google App Engine ensuring that my data is correct when using an ancestor relationship without key names.
Let me explain a little more: I've got a parent entity category, and I want to create a child entity item. I'd like to create a function that takes a category name and item name, and ... | [
"Here is an approach to solving your problem. It is not an ideal approach in many ways, and I sincerely hope that someone other AppEnginer will come up with a neater solution than I have. If not, give this a try.\nMy approach utilizes the following strategy: it creates entities that act as aliases for the Category ... | [
2,
0
] | [] | [] | [
"data_integrity",
"google_app_engine",
"python",
"transactions"
] | stackoverflow_0003525387_data_integrity_google_app_engine_python_transactions.txt |
Q:
python: cannot concatenate 'str' and 'long' objects
I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
Here's my code:
self.fields['question_' + question.id] = forms.Choic... | python: cannot concatenate 'str' and 'long' objects | I'm trying to set up a choice field in django, but I don't think this is a django issue. The choices field takes an iterable (e.g., a list or tuple) of 2-tuples to use as choices for this field.
Here's my code:
self.fields['question_' + question.id] = forms.ChoiceField(
label=question.label,
... | [
"Most likely it's highlighting the last line only because you split the statement over multiple lines.\nThe fix for the actual problem will most likely be changing\nself.fields['question_' + question.id]\n\nto\nself.fields['question_' + str(question.id)]\n\nAs you can quickly test in a Python interpreter, adding a ... | [
36,
6,
2,
2
] | [
"This is a problem with doing too many things in one line - the error messages become slightly less helpful. Had you written it as below the problem would be much easier to find\nquestion_id = 'question_' + question.id\nself.fields[question_id] = forms.ChoiceField(\n label=question.label,\n ... | [
-2
] | [
"python"
] | stackoverflow_0003532873_python.txt |
Q:
How to enable the libattr frature(abbreviated xattr) in linux?
I want to use xattr in python, but found the xattr's keys() is empty, does that indicate the libattr feature wasn't enabled?
I've learned the libattr feature is disabled in ext3/ext4 by default, but how to enable it?
Expect your help!
Thank you~
>>> im... | How to enable the libattr frature(abbreviated xattr) in linux? | I want to use xattr in python, but found the xattr's keys() is empty, does that indicate the libattr feature wasn't enabled?
I've learned the libattr feature is disabled in ext3/ext4 by default, but how to enable it?
Expect your help!
Thank you~
>>> import xattr
>>> x = xattr.xattr('tiger_8a428_userdvd.dmg')
>>> x
<xat... | [
"Maybe you can use the following:\n>>> x = xattr.get_all('tiger_8a428_userdvd.dmg')\nShould be better.\n"
] | [
0
] | [] | [] | [
"attr",
"linux",
"python"
] | stackoverflow_0003438924_attr_linux_python.txt |
Q:
How to control LabView VI front panel switches (on/off, bar adjuster) using Python scripts?
I have a LabView front panel controlling switches and sensor voltage adjustors to the hardware and need to control these with a Python script. I do not have much knowledge of LabView. Please explain how this could be done.
... | How to control LabView VI front panel switches (on/off, bar adjuster) using Python scripts? | I have a LabView front panel controlling switches and sensor voltage adjustors to the hardware and need to control these with a Python script. I do not have much knowledge of LabView. Please explain how this could be done.
| [
"I found one reference on the LabVIEW discussion board that succeeded in this, it uses the following code:\nimport win32com.client //load the interface\nlabview = win32com.client.Dispatch(\"Labview.Application\") //get a ref to the Labview application\nVI = labview.getvireference(r'C:\\TEMP\\python.vi') //load the ... | [
5,
1
] | [] | [] | [
"labview",
"python"
] | stackoverflow_0003524479_labview_python.txt |
Q:
random.randint for non integer number? [Python]
How can I make a random number between something like 0.1 to 0.9 ?
randint only work for integer numbers =/
Thank you
A:
Use random.uniform(). For your example, random.uniform(0.1, 0.9).
It's equivalent to using random.random() to get a value between 0.0 and 1.0, ... | random.randint for non integer number? [Python] | How can I make a random number between something like 0.1 to 0.9 ?
randint only work for integer numbers =/
Thank you
| [
"Use random.uniform(). For your example, random.uniform(0.1, 0.9).\nIt's equivalent to using random.random() to get a value between 0.0 and 1.0, then scaling and shifting the value appropriately:\ndef rand_float_range(start, end):\n return random.random() * (end - start) + start\n\n"
] | [
16
] | [] | [] | [
"python",
"random"
] | stackoverflow_0003533247_python_random.txt |
Q:
Python: How to extract required information from a string?
I am new to Python. Is there a StringTokenizer in Python? Can I do character by character scanning and copying.
I have the following input string
data = '123:Palo Alto, CA -> 456:Seattle, WA 789'
I need to extract the two (city, state) fields from this st... | Python: How to extract required information from a string? | I am new to Python. Is there a StringTokenizer in Python? Can I do character by character scanning and copying.
I have the following input string
data = '123:Palo Alto, CA -> 456:Seattle, WA 789'
I need to extract the two (city, state) fields from this string. Here is the code I wrote
name_list = []
while i < len(data... | [
"data = '123:Palo Alto, CA -> 456:Seattle, WA 789'\ncitys = []\nfor record in data.split(\"->\"):\n citys.append(\n re.search(r\":(?P<city>[\\w\\s]+),\\s*(?P<state>[\\w]+)\",record)\n .groupdict()\n )\n\nprint citys\n\nGives:\n[{'city': 'Palo Alto', 'state': 'CA'}, {'city': 'Seattle', 'state': '... | [
8,
3,
3,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0003533072_python.txt |
Q:
Country-based Super User Access
I'm looking to provide super-user access to entities belonging to a specific country.
eg. Swedish SU can only admin Swedish entities, etc...
However, I'm new to django (taking over an old system) and I need a lifeline.
I'd like to be able to specify a relationship table.
I've alrea... | Country-based Super User Access | I'm looking to provide super-user access to entities belonging to a specific country.
eg. Swedish SU can only admin Swedish entities, etc...
However, I'm new to django (taking over an old system) and I need a lifeline.
I'd like to be able to specify a relationship table.
I've already added a userprofile and with that ... | [
"Correct me if I am wrong. It seems to me that you are trying to establish an many to many relationship between UserProfile and Country. If so the best way to go about it would be to use a ManyToManyField. Something like this:\nclass UserProfile(models.Model):\n countries = models.ManyToManyField(Country)\n\nYou... | [
1
] | [] | [] | [
"database_design",
"django",
"django_models",
"python"
] | stackoverflow_0003532574_database_design_django_django_models_python.txt |
Q:
Python. Output of crypto.cipher.blowfish and .AES can be translated neither into unicode (as sqlite wants), nor into hex
Okay, I'm totally new to Python, so I decided to make a simple app. Here is my encryption function:
from Crypto.Cipher import AES
def encPass(login, password):
keyPhr=os.environ['HOME']+logi... | Python. Output of crypto.cipher.blowfish and .AES can be translated neither into unicode (as sqlite wants), nor into hex | Okay, I'm totally new to Python, so I decided to make a simple app. Here is my encryption function:
from Crypto.Cipher import AES
def encPass(login, password):
keyPhr=os.environ['HOME']+login
hashObj = hashlib.md5()
hashObj.update(keyPhr)
keyPhr=hashObj.hexdigest()
keyObj=AES.new(keyPhr)
encPwd=... | [
"You can use buffer and insert the encPwd as a blob.\nOr you can use something like base64 to convert your encPwd to ASCII (which is a subset of UTF8) so you can insert it as a string.\n"
] | [
1
] | [] | [] | [
"encryption",
"python",
"sqlite"
] | stackoverflow_0003533665_encryption_python_sqlite.txt |
Q:
Access to aliased functions in a Python module
I am consolidating many shell-like operations into a single module. I would then like to be able to do:
pyscript.py:
from shell import *
basename("/path/to/file.ext")
and the shell.py module contains:
shell.py:
from os.path import basename
The problem is that funct... | Access to aliased functions in a Python module | I am consolidating many shell-like operations into a single module. I would then like to be able to do:
pyscript.py:
from shell import *
basename("/path/to/file.ext")
and the shell.py module contains:
shell.py:
from os.path import basename
The problem is that functions imported to the shell module are not available,... | [
"Are you sure you're not just using the wrong syntax? This works for me in 2.6.\nfrom shell import * \nbasename(\"/path/to/file.ext\")\n\nshell.py:\nfrom os.path import basename\n\n",
"It's not a bug, it's a feature :-)\nIf you import m1 in a module m2 and then import m2 into another module, it will only import t... | [
3,
2
] | [] | [] | [
"python"
] | stackoverflow_0003533653_python.txt |
Q:
gtk: detect click on a cell in a TreeView
I'm displaying some data as a TreeView. How can I detect a click on a particular tree-view cell, so that I know which column of which row was clicked on?
This is what I want to do, so maybe there's a better way: Part of the data is a series of True/False values indicating ... | gtk: detect click on a cell in a TreeView | I'm displaying some data as a TreeView. How can I detect a click on a particular tree-view cell, so that I know which column of which row was clicked on?
This is what I want to do, so maybe there's a better way: Part of the data is a series of True/False values indicating a particular set of options. For example, the o... | [
"The row-activated signal is sent when a GTK TreeView row is double-clicked.\n",
"Ah from this grea tutorial and the API docs, I can just connect to the row-activated event, which will give me all the information I need.\n"
] | [
6,
0
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003534127_gtk_pygtk_python_user_interface.txt |
Q:
Setting the default value of a function input to equal another input in Python
Consider the following function, which does not work in Python, but I will use to explain what I need to do.
def exampleFunction(a, b, c = a):
...function body...
That is I want to assign to variable c the same value that variable ... | Setting the default value of a function input to equal another input in Python | Consider the following function, which does not work in Python, but I will use to explain what I need to do.
def exampleFunction(a, b, c = a):
...function body...
That is I want to assign to variable c the same value that variable a would take, unless an alternative value is specified. The above code does not work... | [
"def example(a, b, c=None):\n if c is None:\n c = a\n ...\n\nThe default value for the keyword argument can't be a variable (if it is, it's converted to a fixed value when the function is defined.) Commonly used to pass arguments to a main function:\ndef main(argv=None):\n if argv is None:\n ... | [
30,
17,
1
] | [] | [] | [
"default_value",
"function",
"keyword_argument",
"python"
] | stackoverflow_0003534371_default_value_function_keyword_argument_python.txt |
Q:
Plotting a list of Complex nos on Z-plane in python
I tried:
plot(z)
where z is a list of complex numbers, which plots abs(z) versus index.
plot( z.real, z.imag )
doesn't work, it says list doesn't have attribute real.
A:
If z is a list of complex, use
[k.real for k in z]
to extract the real parts of every nu... | Plotting a list of Complex nos on Z-plane in python | I tried:
plot(z)
where z is a list of complex numbers, which plots abs(z) versus index.
plot( z.real, z.imag )
doesn't work, it says list doesn't have attribute real.
| [
"If z is a list of complex, use\n[k.real for k in z]\n\nto extract the real parts of every number in the list.\n",
"If I'm understanding your question correctly, it might work if you fix the attribute error. \".real\" and \".imag\" must be performed on complex numbers as far as I know, meaning they won't work un... | [
3,
0
] | [] | [] | [
"python"
] | stackoverflow_0003530904_python.txt |
Q:
Python regex, matching pattern over multiple lines.. why isn't this working?
I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my docume... | Python regex, matching pattern over multiple lines.. why isn't this working? | I know that for parsing I should ideally remove all spaces and linebreaks but I was just doing this as a quick fix for something I was trying and I can't figure out why its not working.. I have wrapped different areas of text in my document with the wrappers like "####1" and am trying to parse based on this but its jus... | [
"Multiline doesn't mean . will match line return, it means that ^ and $ are limited to lines only\n\nre.M\n re.MULTILINE\nWhen specified, the pattern character '^' matches at the beginning of the string and at the >beginning of each line (immediately following each newline); and the pattern character '$' >matches ... | [
26,
19
] | [] | [] | [
"parsing",
"python",
"regex"
] | stackoverflow_0003534507_parsing_python_regex.txt |
Q:
Uploaded and not converted files do not appear in the document feed in Google Docs
I trying to retrieve a complete list of files from a given directory with code like this
uri = '%s' % fentry.content.src
feed = gd_client.GetDocumentListFeed(uri=uri)
for r in feed.entry:
print r.title.text.decode("utf-8")
It w... | Uploaded and not converted files do not appear in the document feed in Google Docs | I trying to retrieve a complete list of files from a given directory with code like this
uri = '%s' % fentry.content.src
feed = gd_client.GetDocumentListFeed(uri=uri)
for r in feed.entry:
print r.title.text.decode("utf-8")
It works except that it only return "real" Google Documents files and does not return files,... | [
"I have the suspicion that you are using a wrong uri. Read here about the different options you have:\nhttp://code.google.com/intl/en-US/apis/documents/docs/3.0/developers_guide_protocol.html#ListDocs\n"
] | [
1
] | [] | [] | [
"google_docs_api",
"python"
] | stackoverflow_0003535311_google_docs_api_python.txt |
Q:
Select Children of an Object With ForeignKey in Django?
I'm brand new to Django, so the answer to this is probably very simple. However, I can't figure it out.
Say I have two bare-bones Models.
class Blog(models.Model):
title = models.CharField(max_length=160)
text = models.TextField()
class Comment(model... | Select Children of an Object With ForeignKey in Django? | I'm brand new to Django, so the answer to this is probably very simple. However, I can't figure it out.
Say I have two bare-bones Models.
class Blog(models.Model):
title = models.CharField(max_length=160)
text = models.TextField()
class Comment(models.Model):
blog = models.ForeignKey(Blog)
text = model... | [
"to follow foreign keys 'backwards' you use\nblog.comment_set.all()\n\n"
] | [
47
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003535615_django_python.txt |
Q:
Parsing blockbased program output using Python
I am trying to parse the output of a statistical program (Mplus) using Python.
The format of the output (example here) is structured in blocks, sub-blocks, columns, etc. where the whitespace and breaks are very important. Depending on the eg. options requested you ge... | Parsing blockbased program output using Python | I am trying to parse the output of a statistical program (Mplus) using Python.
The format of the output (example here) is structured in blocks, sub-blocks, columns, etc. where the whitespace and breaks are very important. Depending on the eg. options requested you get an addional (sub)block or column here or there.
Ap... | [
"Based on your example, what you have is a bunch of different, nested sub-formats that, individually, are very easily parsed. What can be overwhelming is the sheer number of formats and the fact that they can be nested in different ways. \nAt the lowest level you have a set of whitespace-separated values on a sin... | [
1,
1,
1,
0,
0
] | [] | [] | [
"block",
"parsing",
"python"
] | stackoverflow_0003533443_block_parsing_python.txt |
Q:
Python doesn't save data to sqlite db
This is my code:
conn = sqlite3.connect(nnpcconfig.commondb)
cur = conn.cursor()
query = ['2124124', 'test2', 'test3', 'test4', 'test5']
cur.execute("insert into users(id, encpass, sname, name, fname) values (?, ?, ?, ?, ?)", query)
conn.commit
cur.execute("select * from users... | Python doesn't save data to sqlite db | This is my code:
conn = sqlite3.connect(nnpcconfig.commondb)
cur = conn.cursor()
query = ['2124124', 'test2', 'test3', 'test4', 'test5']
cur.execute("insert into users(id, encpass, sname, name, fname) values (?, ?, ?, ?, ?)", query)
conn.commit
cur.execute("select * from users")
for row in cur:
print row
This code... | [
"You have another mistake: conn.commit instead of conn.commit()\n"
] | [
10
] | [] | [] | [
"database",
"python",
"sql",
"sqlite"
] | stackoverflow_0003535532_database_python_sql_sqlite.txt |
Q:
Python efficiency of and vs multiple ifs
Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like
if expr1 == expr2 and expr3==expr4:
dostuff()
different from an efficiency standpoint then:
if expr1 == expr2:
if expr3 == expr4:... | Python efficiency of and vs multiple ifs | Is there an efficiency difference between using and in an if statement and using multiple if statements? In other words, is something like
if expr1 == expr2 and expr3==expr4:
dostuff()
different from an efficiency standpoint then:
if expr1 == expr2:
if expr3 == expr4:
dostuff()
My very basic testing does not... | [
"This isn't enough of a performance difference, if any, to affect your decision. IMO, the decision here should be made purely from a readability perspective. The first is generally more standard, I think, but there are situations when the second might be clearer. Choose the method that best gets your intent across.... | [
14,
14,
7,
5,
2
] | [] | [] | [
"conditional",
"performance",
"python"
] | stackoverflow_0003533338_conditional_performance_python.txt |
Q:
Traversing an ftp folder with python
I need to write a python script that traverses a folder on a FTP server.
for file in ftpfolder:
#get it
#do something untoward with it
Snippets and non-wheel-reinvention advice welcome.
A:
ftputil is the third-party module you're looking for:
ftputil is a high-level FTP cli... | Traversing an ftp folder with python | I need to write a python script that traverses a folder on a FTP server.
for file in ftpfolder:
#get it
#do something untoward with it
Snippets and non-wheel-reinvention advice welcome.
| [
"ftputil is the third-party module you're looking for:\n\nftputil is a high-level FTP client\n library for the Python programming\n language. ftputil implements a virtual\n file system for accessing FTP servers,\n that is, it can generate file-like\n objects for remote files. The library\n supports many funct... | [
14
] | [] | [] | [
"directory",
"download",
"ftp",
"python",
"traversal"
] | stackoverflow_0003535936_directory_download_ftp_python_traversal.txt |
Q:
Encode and pad netbios name using python
I'm trying to create a simple script that will convert a string (max 15 chars) to a netbios name (see http://support.microsoft.com/kb/194203) :
name = sys.argv[1].upper()
converted = ''.join([chr((ord(c)>>4) + ord('A'))+chr((ord(c)&0xF) + ord('A')) for c in name])
print con... | Encode and pad netbios name using python | I'm trying to create a simple script that will convert a string (max 15 chars) to a netbios name (see http://support.microsoft.com/kb/194203) :
name = sys.argv[1].upper()
converted = ''.join([chr((ord(c)>>4) + ord('A'))+chr((ord(c)&0xF) + ord('A')) for c in name])
print converted
Trying to convert the name : "testing"... | [
"... + ((16 - len(name)) * '4341')\n\n"
] | [
0
] | [] | [] | [
"netbios",
"python"
] | stackoverflow_0003536100_netbios_python.txt |
Q:
Does Python 2.5.2 follow Unicode for lower() and upper()?
I'm making a Google AppEngine Application. Does the Python 2.5.2 runtime environment follow the Unicode Standards? (For example, the lower() and upper() methods on unicode objects.)
A:
Yes and no.
For an example, see the code being discussed here: How can... | Does Python 2.5.2 follow Unicode for lower() and upper()? | I'm making a Google AppEngine Application. Does the Python 2.5.2 runtime environment follow the Unicode Standards? (For example, the lower() and upper() methods on unicode objects.)
| [
"Yes and no.\nFor an example, see the code being discussed here: How can I convert Unicode to uppercase to print it?\nCheck here for a formal, well-written document:\nhttp://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python\n"
] | [
5
] | [] | [] | [
"case_sensitive",
"python",
"unicode"
] | stackoverflow_0003536397_case_sensitive_python_unicode.txt |
Q:
Unicode case conversion
I am given either a single character or a string, and am using Python.
How do I find out if a specific character has a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode?
And how do I find out if a string has one or more characters that ... | Unicode case conversion | I am given either a single character or a string, and am using Python.
How do I find out if a specific character has a lowercase equivalent according to the standards (standard and special case mappings) proposed by Unicode?
And how do I find out if a string has one or more characters that have a lowercase equivalent a... | [
"def haslower(unicodechar):\n return unicodechar != unicodechar.lower()\n\ndef anylower(unicodestring):\n return any(haslower(c) for c in unicodestring)\n\nThis will only work correctly in as much as the Python version you're using has correctly implemented the .lower() method per unicode standards, of course... | [
5,
1
] | [] | [] | [
"case_sensitive",
"python",
"unicode"
] | stackoverflow_0003536355_case_sensitive_python_unicode.txt |
Q:
convert string rep of hexadecimal into actual hexadecimal
Possible Duplicate:
how to parse hex or decimal int in Python
i have a bunch of Hexadecimal colors in a database stored as strings.
e.g. '0xFFFF00'
when i get them from the database i need to convert this string into an actual hexadecimal number, so
0xFFF... | convert string rep of hexadecimal into actual hexadecimal |
Possible Duplicate:
how to parse hex or decimal int in Python
i have a bunch of Hexadecimal colors in a database stored as strings.
e.g. '0xFFFF00'
when i get them from the database i need to convert this string into an actual hexadecimal number, so
0xFFFF00
how can i do this in python
| [
"This is one way to do it:\n>>> s = '0xFFFF00'\n>>> i = int(s, 16)\n>>> print i\n\n",
"hex(int('0xFFFF00', 16))\n",
"Also this works \nnumber = int('0xFFFF00',0)\nprint(\"%x follows %x\" % (number+1, number))\n\n0 argument tells interpreter to follow the Python rules of numbers to decide the used format of numb... | [
5,
0,
0
] | [] | [] | [
"hex",
"python"
] | stackoverflow_0003535324_hex_python.txt |
Q:
Python MIT Open Courseware Stock Market Simulation Incomplete?
I just copied this code from the MIT video lecture that is posted online: (Lec 23 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008). Since I had to copy it from a video lecture, I'm not sure I got the complete program. It is not ... | Python MIT Open Courseware Stock Market Simulation Incomplete? | I just copied this code from the MIT video lecture that is posted online: (Lec 23 | MIT 6.00 Introduction to Computer Science and Programming, Fall 2008). Since I had to copy it from a video lecture, I'm not sure I got the complete program. It is not working as is, I could use some guidance.
Thanks.
import pylab, ran... | [
"You seem to be missing mean = 0.0 and need to change an a to an s:\ndef runSim(stks, fig, mo):\n mean = 0.0\n for s in stks:\n for d in range(numDays):\n s.makeMove(bias, mo)\n s.showHistory(fig)\n mean += s.getPrice()\n mean = mean/float(numStks)\n pylab.axhline(mean)\n... | [
1,
1
] | [] | [] | [
"python",
"simulation"
] | stackoverflow_0003534767_python_simulation.txt |
Q:
Python performance: search large list vs sqlite
Lets say I have a database table which consists of three columns: id, field1 and field2. This table may have anywhere between 100 and 100,000 rows in it. I have a python script that should insert 10-1,000 new rows into this table. However, if the new field1 alread... | Python performance: search large list vs sqlite | Lets say I have a database table which consists of three columns: id, field1 and field2. This table may have anywhere between 100 and 100,000 rows in it. I have a python script that should insert 10-1,000 new rows into this table. However, if the new field1 already exists in the table, it should do an UPDATE, not an... | [
"If I understand your question correctly, it seems like you could simply use SQLite's built in conflict handling mechanism.\nAssuming you have a UNIQUE constraint on field1, you could simple use:\nINSERT OR REPLACE INTO table VALUES (...)\n\nThe following syntax is also supported (identical semantics):\nREPLACE INT... | [
9,
1,
0,
0
] | [] | [] | [
"performance",
"python",
"sqlite"
] | stackoverflow_0003404556_performance_python_sqlite.txt |
Q:
Building mod_wsgi using python 2.5 on Snow Leopard
I'm using the Python 2.5 that came with Mac OS X Snow Leopard (10.6). I've set the defaults value: defaults write com.apple.versioner.python Version 2.5 and normally I get python 2.5 as it suggests.
However when I try to build mod_wsgi, that doesn't seem to adhere... | Building mod_wsgi using python 2.5 on Snow Leopard | I'm using the Python 2.5 that came with Mac OS X Snow Leopard (10.6). I've set the defaults value: defaults write com.apple.versioner.python Version 2.5 and normally I get python 2.5 as it suggests.
However when I try to build mod_wsgi, that doesn't seem to adhere. I've used the --with-python=/usr/bin/python2.5 option ... | [
"Try using '--disable-framework' to 'configure'. This will result in -L/-l being used to link Python library rather than framework link. This is necessary as don't know a way to make a framework link use a version other than what is designated as 'Current'.\n"
] | [
2
] | [] | [] | [
"macos",
"mod_wsgi",
"python"
] | stackoverflow_0003534508_macos_mod_wsgi_python.txt |
Q:
Implementing parser for markdown-like language
I have markup language which is similar to markdown and the one used by SO.
Legacy parser was based on regexes and was complete nightmare to maintain, so I've come up with my own solution based on EBNF grammar and implemented via mxTextTools/SimpleParse.
However, ther... | Implementing parser for markdown-like language | I have markup language which is similar to markdown and the one used by SO.
Legacy parser was based on regexes and was complete nightmare to maintain, so I've come up with my own solution based on EBNF grammar and implemented via mxTextTools/SimpleParse.
However, there are issues with some tokens which may include each... | [
"If one thing includes another, then normally you treat them as separate tokens and then nest them in the grammar. Lepl (http://www.acooke.org/lepl which I wrote) and PyParsing (which is probably the most popular pure-Python parser) both allow you to nest things recursively.\nSo in Lepl you could write code someth... | [
6
] | [] | [] | [
"ebnf",
"grammar",
"markup",
"parsing",
"python"
] | stackoverflow_0003535706_ebnf_grammar_markup_parsing_python.txt |
Q:
google appengine datastore client
Is there a tool/client to view inside and make queries for google appengine datastore?
A:
Starting with release 1.1.9 of the App Engine SDK, however, there's a new way to interact with the datastore, in the form of the remote_api module. This module allows remote access to the A... | google appengine datastore client | Is there a tool/client to view inside and make queries for google appengine datastore?
| [
"\nStarting with release 1.1.9 of the App Engine SDK, however, there's a new way to interact with the datastore, in the form of the remote_api module. This module allows remote access to the App Engine datastore, using the same APIs you know and love from writing App Engine Apps.\n\n\nhttp://code.google.com/appengi... | [
3,
1
] | [] | [] | [
"client",
"command_line",
"google_app_engine",
"python"
] | stackoverflow_0003536770_client_command_line_google_app_engine_python.txt |
Q:
How to create an excel chart using py-appscript?
I am using Excel 2011 v14 and trying to dynamically create a chart based on the selected range on my worksheet. To select a range, I use the following code segment:
xl = app('Microsoft Excel')
tcell = 'B'
qcell = 'C'
for r in xrange(2, 16):
xl.cells[tcell + str... | How to create an excel chart using py-appscript? | I am using Excel 2011 v14 and trying to dynamically create a chart based on the selected range on my worksheet. To select a range, I use the following code segment:
xl = app('Microsoft Excel')
tcell = 'B'
qcell = 'C'
for r in xrange(2, 16):
xl.cells[tcell + str(r)].value.set(r)
xl.cells[qcell + str(r)].value.s... | [
"As I suggested to someone else who had a similar question, you should sort out how to make this work in native Applescript first and then port to py-appscript. There is a lot that can go wrong in your code snippet and there could be (and usually are) errors being returned by Applescript that the framework doesn't ... | [
0
] | [] | [] | [
"applescript",
"charts",
"excel",
"python"
] | stackoverflow_0003533305_applescript_charts_excel_python.txt |
Q:
gtk logic behind treeviewcolumns needing cell renderers
From what I understand about GTK, if I have a TreeView, I can't just use any widget I want to display information about a column. For text, you need a gtk.CellRendererText. For toggle buttons, a gtk.CellRendererToggle. For anything else, it seems you have to ... | gtk logic behind treeviewcolumns needing cell renderers | From what I understand about GTK, if I have a TreeView, I can't just use any widget I want to display information about a column. For text, you need a gtk.CellRendererText. For toggle buttons, a gtk.CellRendererToggle. For anything else, it seems you have to implement yourself, which, from a sample one for buttons that... | [
"To write a custom CellRenderer (copy-pasted from this link!):\n\n\nRegister some new properties that your\n renderer needs with the type system\n and write your own set_property and\n get_property functions to set and get\n your new renderer's properties.\nWrite your own cell_renderer_get_size\n function and ... | [
2
] | [] | [] | [
"gtk",
"pygtk",
"python",
"user_interface"
] | stackoverflow_0003533442_gtk_pygtk_python_user_interface.txt |
Q:
How to get all the minimum elements according to its first element of the inside list in a nested list?
Simply put! there is this list say LST = [[12,1],[23,2],[16,3],[12,4],[14,5]] and i want to get all the minimum elements of this list according to its first element of the inside list. So for the above example t... | How to get all the minimum elements according to its first element of the inside list in a nested list? | Simply put! there is this list say LST = [[12,1],[23,2],[16,3],[12,4],[14,5]] and i want to get all the minimum elements of this list according to its first element of the inside list. So for the above example the answer would be [12,1] and [12,4]. Is there any typical way in python of doing this?
Thanking you in advan... | [
"Two passes:\nminval = min(LST)[0]\nreturn [x for x in LST if x[0] == minval]\n\nOne pass:\ndef all_minima(iterable, key=None):\n if key is None: key = id\n hasminvalue = False\n minvalue = None\n minlist = []\n for entry in iterable:\n value = key(entry)\n if not hasminvalue or value < minvalue:\n ... | [
5,
3,
2
] | [
"minval = min(x[0] for x in LST)\nresult = [x for x in LST if x[0]==minval]\n\n"
] | [
-1
] | [
"list",
"minimum",
"python"
] | stackoverflow_0003537170_list_minimum_python.txt |
Q:
python import error
what's wrong with my imports?
App folder structure:
myapp/
models/models.py contains SpotModel()
tests/tests.py contains TestSpotModel(unittest.TestCase). tests.py imports from myapp.models.models import * which works like a charm
scripts/import.py contains from myapp.models.models import *
t... | python import error | what's wrong with my imports?
App folder structure:
myapp/
models/models.py contains SpotModel()
tests/tests.py contains TestSpotModel(unittest.TestCase). tests.py imports from myapp.models.models import * which works like a charm
scripts/import.py contains from myapp.models.models import *
the problem is that import... | [
"It is __init__.py not init.py. Make sure each of the directory in hierarchy contains it in order to be able to import.\nEDIT: I managed to reproduce it.\nHere's the directory structure:\n\ncesar@cesar-laptop:/tmp/asdasd$ tree\n.\n`-- myapp\n |-- __init__.py\n |-- models\n | |-- __init__.py\n | `-- ... | [
4,
1,
1,
0
] | [] | [] | [
"importerror",
"python",
"python_import"
] | stackoverflow_0003537850_importerror_python_python_import.txt |
Q:
pyAMF for GAE (Google App Engine), little help needed:
# I need this behaviour:
# 1) check if the service from flash is included in the services array
# 2) if not, return false or an error | if yes, step 3
# 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name')
# 4) and t... | pyAMF for GAE (Google App Engine), little help needed: | # I need this behaviour:
# 1) check if the service from flash is included in the services array
# 2) if not, return false or an error | if yes, step 3
# 3) combine the rootPath('app.controllers') with the service name('sub1.sub2.sub3.function_name')
# 4) and then get the function('function_name') from the 'app.controll... | [
"Solved last night! thanks @njoyce\nfrom pyamf.remoting.gateway.google import WebAppGateway\nimport logging\n\nclass TottysGateway(WebAppGateway):\ndef __init__(self, services_available, root_path, not_found_service, logger, debug):\n # override the contructor and then call the super\n self.services_available... | [
0
] | [] | [] | [
"google_app_engine",
"pyamf",
"python",
"web_applications"
] | stackoverflow_0003535802_google_app_engine_pyamf_python_web_applications.txt |
Q:
I'm using pyAMF in my app, but I want to set smart service like explained here:
In a normal application i set services
services = {
'users.login': login,
'test': router
}
but I would like to do like this:
services = [
'users.login',
'test'
]
and every request goes to router function. this takes 2... | I'm using pyAMF in my app, but I want to set smart service like explained here: | In a normal application i set services
services = {
'users.login': login,
'test': router
}
but I would like to do like this:
services = [
'users.login',
'test'
]
and every request goes to router function. this takes 2 params: service name (can be "users.login" or "test" in this case) and input (that i... | [
"If I understand your question correctly, in order to achieve this, you are going to need to to override getServiceRequest on the Gateway class that you are using:\nfrom pyamf.remoting.gateway.django import DjangoGateway\nfrom pyamf.remoting.gateway import UnknownServiceError\n\n\nclass MyGateway(DjangoGateway):\n ... | [
2,
0
] | [] | [] | [
"pyamf",
"python"
] | stackoverflow_0003357342_pyamf_python.txt |
Q:
How to reconstruct python source from loaded modules (sys.modules)?
Is it possible to construct human readable source for loaded modules if you have access to sys.modules?
People tell me you cannot, but I'm sure it is possible in Python.
A:
You can disassemble a Python-coded module using the dis module of the st... | How to reconstruct python source from loaded modules (sys.modules)? | Is it possible to construct human readable source for loaded modules if you have access to sys.modules?
People tell me you cannot, but I'm sure it is possible in Python.
| [
"You can disassemble a Python-coded module using the dis module of the standard library: that produces definitely human readable source, just not Python source, but rather bytecode source. Putting eggs back together starting from the omelette is a tad harder.\nThere used to be a decompiler for Python 2.3 (see here... | [
4,
0
] | [] | [] | [
"decompiling",
"python",
"reverse_engineering"
] | stackoverflow_0003538236_decompiling_python_reverse_engineering.txt |
Q:
Any one have an example that uses the element.sourceline method from lxml.html
I hope I asked that correctly. I am trying to figure out what element.sourceline does and if there is some way I can use its features. I have tried building my elements from the html a number of ways but every time I iterate through m... | Any one have an example that uses the element.sourceline method from lxml.html | I hope I asked that correctly. I am trying to figure out what element.sourceline does and if there is some way I can use its features. I have tried building my elements from the html a number of ways but every time I iterate through my elements and ask for sourceline I always get None. When I tried to use the built-... | [
"sourceline will return the line number determined at the time of parsing a document. So it won't apply to an Element that was added through the API. For example:\nfrom lxml import etree\n\nxml = '<doc>\\n<foo>rain in spain</foo>\\n</doc>'\nroot = etree.fromstring(xml)\n\nprint root.find('foo').sourceline # 2\n\n... | [
3
] | [] | [] | [
"html",
"lxml",
"parsing",
"python"
] | stackoverflow_0003538248_html_lxml_parsing_python.txt |
Q:
Does python have a robust pop3, smtp, mime library where I could build a webmail interface?
Does python have a full fledged email library with things for pop, smtp, pop3 with ssl, mime?
I want to create a web mail interface that pulls emails from email servers, and then shows the emails, along with attachments, ca... | Does python have a robust pop3, smtp, mime library where I could build a webmail interface? | Does python have a full fledged email library with things for pop, smtp, pop3 with ssl, mime?
I want to create a web mail interface that pulls emails from email servers, and then shows the emails, along with attachments, can display the sender, subject, etc. (handles all the encoding issues etc).
It's one thing to be a... | [
"It has all the components you need, in a more modular and flexible arrangement than you appear to envisage -- the standard library's email package deals with the message once you have received it, and separate modules each deal with means of sending and receiving, such as pop, smtp, imap. SSL is an option for eac... | [
2,
2
] | [] | [] | [
"email",
"mime",
"pop3",
"python",
"smtp"
] | stackoverflow_0003538430_email_mime_pop3_python_smtp.txt |
Q:
Casting sockets to subtypes
I'm trying to create my own subclass of socket.socket that will be able to handle custom messages. So far my code looks like this:
self._sockets.append(s)
logging.debug("Waiting for incoming connections on port %d" % (port))
while not self.shutdown:
inputready,output... | Casting sockets to subtypes | I'm trying to create my own subclass of socket.socket that will be able to handle custom messages. So far my code looks like this:
self._sockets.append(s)
logging.debug("Waiting for incoming connections on port %d" % (port))
while not self.shutdown:
inputready,outputready,exceptready = select(self._... | [
"From your description it appears that you are making a message handler that has-a socket (or sockets). When designing classes has-a indicates composition and delegation while is-a can indicate inheritance.\nSo it is not appropriate to inherit from socket.socket, and your code is already looking a bit hybrid. Somet... | [
2,
1
] | [] | [] | [
"python",
"sockets"
] | stackoverflow_0003538619_python_sockets.txt |
Q:
Python Reverse Find in String
I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index.
An example: I want to find the index of the 2nd I by using the index and str.rfind()
s = "Hello, I am 12! I like plankton but I don't like Baseball."
index = 34 #p... | Python Reverse Find in String | I have a string and an arbitrary index into the string. I want find the first occurrence of a substring before the index.
An example: I want to find the index of the 2nd I by using the index and str.rfind()
s = "Hello, I am 12! I like plankton but I don't like Baseball."
index = 34 #points to the 't' in 'but'
index_of_... | [
"Your call tell rfind to start looking at index 34. You want to use the rfind overload that takes a string, a start and an end. Tell it to start at the beginning of the string (0) and stop looking at index:\n>>> s = \"Hello, I am 12! I like plankton but I don't like Baseball.\"\n>>> index = 34 #points to the 't' in... | [
65,
2
] | [] | [] | [
"find",
"python",
"reverse",
"string"
] | stackoverflow_0003537717_find_python_reverse_string.txt |
Q:
python/win32: post a click event to a window?
I want to simulate a mouse click on a window, but I want to post the click event directly to the window (not by simulating a general mouse click using win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)). What's the proper way to do it? I've tried the following, ... | python/win32: post a click event to a window? | I want to simulate a mouse click on a window, but I want to post the click event directly to the window (not by simulating a general mouse click using win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)). What's the proper way to do it? I've tried the following, but it doesn't seem to have an effect:
def MAKELONG... | [
"If window is the window that owns the menu, this won't work because WM_LBUTTONDOWN is for the window's client area, and the menu area is non-client. I haven't tested this, but you might try posting WM_NCLBUTTONDOWN instead, with a wParam of HTMENU, and mouse position in screen coordinates.\nAnother alternative wou... | [
0
] | [] | [] | [
"python",
"winapi",
"windows"
] | stackoverflow_0003354952_python_winapi_windows.txt |
Q:
Python: rewinding one line in file when iterating with f.next()
Python's f.tell doesn't work as I expected when you iterate over a file with f.next():
>>> f=open(".bash_profile", "r")
>>> f.tell()
0
>>> f.next()
"alias rm='rm -i'\n"
>>> f.tell()
397
>>> f.next()
"alias cp='cp -i'\n"
>>> f.tell()
397
>>> f.next()
"... | Python: rewinding one line in file when iterating with f.next() | Python's f.tell doesn't work as I expected when you iterate over a file with f.next():
>>> f=open(".bash_profile", "r")
>>> f.tell()
0
>>> f.next()
"alias rm='rm -i'\n"
>>> f.tell()
397
>>> f.next()
"alias cp='cp -i'\n"
>>> f.tell()
397
>>> f.next()
"alias mv='mv -i'\n"
>>> f.tell()
397
Looks like it gives you the pos... | [
"No. I would make an adapter that largely forwarded all calls, but kept a copy of the last line when you did next and then let you call a different method to make that line pop out again.\nI would actually make the adapter be an adapter that could wrap any iterable instead of a wrapper for file because that sounds... | [
12,
5,
1
] | [] | [] | [
"next",
"python",
"seek"
] | stackoverflow_0003539107_next_python_seek.txt |
Q:
Serve static files through a view in Django
I am writng a Django application that let's you download a file after some requirements have been met (you have to log on, for example). The file needs to be inaccessible otherwise.
Serve the file through Apache won't work: I have to check in the database for the user's... | Serve static files through a view in Django | I am writng a Django application that let's you download a file after some requirements have been met (you have to log on, for example). The file needs to be inaccessible otherwise.
Serve the file through Apache won't work: I have to check in the database for the user's permissions. Furthermore, don't have permission ... | [
"You have to open() the file in binary mode (consider docs).\nJust like this:\nfile = open(location, 'rb')\n\nI don't know whether it is applicable to you (since you are not allowed to change your Apache's settings), but I'd suggest to use Lighttpd + mod_secdownload for performance reasons. This elegant solution le... | [
4
] | [] | [] | [
"django",
"python"
] | stackoverflow_0003539187_django_python.txt |
Q:
How to implement MousePressEvent for a Qt-Designer Widget in PyQt
I've got a Widget (QTabeleWidget, QLabels and some QButtons). It was built in Qt-Designer, and now I have to implement some things. For that I need the mousePressEvent.
Usually I would write a subclass and write something like this:
def mousePressE... | How to implement MousePressEvent for a Qt-Designer Widget in PyQt | I've got a Widget (QTabeleWidget, QLabels and some QButtons). It was built in Qt-Designer, and now I have to implement some things. For that I need the mousePressEvent.
Usually I would write a subclass and write something like this:
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
prin... | [
"With PyQt there are three different ways to work with forms created in designer:\n\nUse single inheritance and make the form a member variable\nUse multiple inheritance\nDynamically generate the members directly from the UI file\n\nSingle Inheritance:\nclass MyTableWidget(QTableWidget):\n def __init__(self, par... | [
4
] | [] | [] | [
"pyqt4",
"python",
"qt_designer"
] | stackoverflow_0003539095_pyqt4_python_qt_designer.txt |
Q:
What does Instance() do in Python assignments?
var = Instance(object)?
A:
It calls the __call__() method.
A:
Actually, I thought it was from the standard library. On inspection, it is from enthought.traits.api.Instance. It holds a reference to an object instance. If you pass a specific class to the constructor... | What does Instance() do in Python assignments? | var = Instance(object)?
| [
"It calls the __call__() method.\n",
"Actually, I thought it was from the standard library. On inspection, it is from enthought.traits.api.Instance. It holds a reference to an object instance. If you pass a specific class to the constructor (e.g. Instance(MyClass) ), it does validation to make sure you pass the c... | [
4,
0
] | [] | [] | [
"python"
] | stackoverflow_0003538724_python.txt |
Q:
Python, PyTables, Java - tying all together
Question in nutshell
What is the best way to get Python and Java to play nice with each other?
More detailed explanation
I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:
We have an... | Python, PyTables, Java - tying all together | Question in nutshell
What is the best way to get Python and Java to play nice with each other?
More detailed explanation
I have a somewhat complicated situation. I'll try my best to explain both in pictures and words. Here's the current system architecture:
We have an agent-based modeling simulation written in Java.... | [
"This is an epic question, and there are lots of considerations. Since you didn't mention any specific performance or architectural constraints, I'll try and offer the best well-rounded suggestions.\nThe initial plan of using PyTables as an intermediary layer between your other elements and the datafiles seems sol... | [
13,
5,
0,
0
] | [] | [] | [
"architecture",
"hdf5",
"java",
"pytables",
"python"
] | stackoverflow_0001953731_architecture_hdf5_java_pytables_python.txt |
Q:
UnicodeDecodeError on import of a .pyd file
I've started to slowly dabble with the Python/C API and after much fiddling and finagling, I was able to build a spam.pyd file.
However, I must be missing something with this process and was hoping that someone could point me in the right direction. I thought that once ... | UnicodeDecodeError on import of a .pyd file | I've started to slowly dabble with the Python/C API and after much fiddling and finagling, I was able to build a spam.pyd file.
However, I must be missing something with this process and was hoping that someone could point me in the right direction. I thought that once spam.pyd was created, I could call it from Python... | [
"You say: Well, it looks like the problem was that I had written the C code in an editor that saved the file with ANSI encoding.\nThis is exceedingly unlikely. There are no non-ASCII characters visible in your published C source. If there were any, you would have got an error message from the C compiler (except may... | [
2
] | [] | [] | [
"python",
"python_3.x"
] | stackoverflow_0003536471_python_python_3.x.txt |
Q:
How to compare unicode strings with entity ref to non-unicode string
I am evaluating hundreds of thousands of html files. I am looking for particular parts of the files. There can be small variations in the way the files were created
For example, in one file I can have a section heading (after I converted it to ... | How to compare unicode strings with entity ref to non-unicode string | I am evaluating hundreds of thousands of html files. I am looking for particular parts of the files. There can be small variations in the way the files were created
For example, in one file I can have a section heading (after I converted it to upper and split then joined the text to get rid of possibly inconsistent w... | [
"You are correct that if S1='A' and S2 = u'A', then S1 == S2. Instead of assuming this though, you can do a simple test:\nkey_dict= {u'A':'Value1',\n 'A':'Value2'}\n\nprint key_dict\nprint u'A' == 'A'\n\nThis outputs:\n{u'A': 'Value2'}\nTrue\n\nThat resolved, let's look at:\nnew_string=u'KEY1A\\x97DEMOGRAPH... | [
2,
1
] | [] | [] | [
"entities",
"html",
"python",
"unicode"
] | stackoverflow_0003539312_entities_html_python_unicode.txt |
Q:
Deleting an arbitrary chunk of a file
What is the most efficient way to delete an arbitrary chunk of a file, given the start and end offsets? I'd prefer to use Python, but I can fall back to C if I have to.
Say the file is this
..............xxxxxxxx----------------
I want to remove a chunk of it:
................. | Deleting an arbitrary chunk of a file | What is the most efficient way to delete an arbitrary chunk of a file, given the start and end offsets? I'd prefer to use Python, but I can fall back to C if I have to.
Say the file is this
..............xxxxxxxx----------------
I want to remove a chunk of it:
..............[xxxxxxxx]----------------
After the opera... | [
"The best performance will almost invariably be obtained by writing a new version of the file and then having it atomically write the old version, because filesystems are strongly optimized for such sequential access, and so is the underlying hardware (with the possible exception of some of the newest SSDs, but, ev... | [
4,
0,
0
] | [] | [] | [
"c",
"file_io",
"python"
] | stackoverflow_0003539517_c_file_io_python.txt |
Q:
How to detect if a Blobstore entry is an image so get_serving_url would work?
I have a general purpose file storage backed by Google App Engine Blobstore, when I show users it's contents I would like to differentiate images from other files — I would like to show thumbnail for each image.
Python get_serving_url fu... | How to detect if a Blobstore entry is an image so get_serving_url would work? | I have a general purpose file storage backed by Google App Engine Blobstore, when I show users it's contents I would like to differentiate images from other files — I would like to show thumbnail for each image.
Python get_serving_url function does not care (at least at dev server) if given blob is in fact an image, ja... | [
"Depending on how the images were uploaded to your Blobstore, they may all contain their MIME types, which you could try to use as a method of determining which items are most likely to contain valid image data using BlobInfo:\nblob_info = BlobInfo.get(blob_image_key)\n\n# All valid image formats for the GAE Images... | [
3,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003538526_google_app_engine_python.txt |
Q:
Can I add "Smartypants" to restructuredText?
I use restructuredText, and I like what smartypants does for Markdown. Is there a way to enable the same thing for restructuredText?
A:
Have you tried smartypants.py? I don't know how well it's implemented, much less how well it works for your specific use cases, but... | Can I add "Smartypants" to restructuredText? | I use restructuredText, and I like what smartypants does for Markdown. Is there a way to enable the same thing for restructuredText?
| [
"Have you tried smartypants.py? I don't know how well it's implemented, much less how well it works for your specific use cases, but it does seem to target exactly your goal, unicode-ification of some ascii constructs (however, it runs on HTML, so I guess you'd run it after restructuredText or whatever other \"pro... | [
2,
1
] | [] | [] | [
"python",
"restructuredtext"
] | stackoverflow_0003527054_python_restructuredtext.txt |
Q:
Regular expressions split and match
>>> zznew
'...0002211 118 7.5 "Weeds" (2005) {The Love Circle Overlap (#4.10)}'
>>> re.split('\(+\d+\)',zznew)
['...0002211 118 7.5 "Weeds" ', ' {The Love Circle Overlap (#4.10)}']
>>> m = re.match('\(+\d+\)',zznew)
>>> m.groups()
Traceback (most recent call last):
File "<p... | Regular expressions split and match | >>> zznew
'...0002211 118 7.5 "Weeds" (2005) {The Love Circle Overlap (#4.10)}'
>>> re.split('\(+\d+\)',zznew)
['...0002211 118 7.5 "Weeds" ', ' {The Love Circle Overlap (#4.10)}']
>>> m = re.match('\(+\d+\)',zznew)
>>> m.groups()
Traceback (most recent call last):
File "<pyshell#104>", line 1, in <module>
m.g... | [
"Use re.search instead of re.match.\nThe difference between these two methods is that re.match only matches if the match starts at the beginning of the string, whereas re.search can match anywhere in the string. See the documentation for more details.\nAs NullUserException points out, if you want to extract the yea... | [
2
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003539758_python_regex.txt |
Q:
Constructing a random string
How to construct a string to have more than 5 characters and maximum of 15 characters using random function in python
import string
letters = list(string.lowercase)
A:
After the import and assignment you already have, assuming you want all possible lengths with the same prob... | Constructing a random string | How to construct a string to have more than 5 characters and maximum of 15 characters using random function in python
import string
letters = list(string.lowercase)
| [
"After the import and assignment you already have, assuming you want all possible lengths with the same probability:\nimport random\n\nlength = random.randrange(5, 16)\n\nrandstr = ''.join(random.choice(letters) for _ in range(length))\n\n"
] | [
7
] | [] | [] | [
"python"
] | stackoverflow_0003539945_python.txt |
Q:
Obtaining an invertible square matrix from a non-square matrix of full rank in numpy or matlab
Assume you have an NxM matrix A of full rank, where M>N. If we denote the columns by C_i (with dimensions Nx1), then we can write the matrix as
A = [C_1, C_2, ..., C_M]
How can you obtain the first linearly independent... | Obtaining an invertible square matrix from a non-square matrix of full rank in numpy or matlab | Assume you have an NxM matrix A of full rank, where M>N. If we denote the columns by C_i (with dimensions Nx1), then we can write the matrix as
A = [C_1, C_2, ..., C_M]
How can you obtain the first linearly independent columns of the original matrix A, so that you can construct a new NxN matrix B that is an invertibl... | [
"Easy, peasy in MATLAB. Use QR, specifically, the pivoted QR.\nM = [3 0 0 0 0;\n 0 0 1 0 0;\n 0 0 0 0 1; \n 0 2 0 0 0]\n\n[Q,R,E] = qr(M)\nQ =\n 1 0 0 0\n 0 0 1 0\n 0 0 0 1\n 0 1 0 0\n\nR =\n 3 0 0 0 0\n 0 2 ... | [
6,
1
] | [] | [] | [
"linear_algebra",
"matlab",
"numpy",
"python",
"svd"
] | stackoverflow_0003539026_linear_algebra_matlab_numpy_python_svd.txt |
Q:
Determining a timezone in Python
Given a local timestamp and a UTC timestamp, is it possible to determine the timezone and whether DST is in effect?
A:
If your "UTC timestamp" is a float (int would suffice) of "seconds from the epoch", and your "local timestamp" is some weird version of it shifted into your loca... | Determining a timezone in Python | Given a local timestamp and a UTC timestamp, is it possible to determine the timezone and whether DST is in effect?
| [
"If your \"UTC timestamp\" is a float (int would suffice) of \"seconds from the epoch\", and your \"local timestamp\" is some weird version of it shifted into your local time coordinates (there is no \"epoch\" except the UTC one), module time in the standard Python library suffices. \nAs these docs show, given \"s... | [
3,
0
] | [] | [] | [
"python",
"timezone"
] | stackoverflow_0003540149_python_timezone.txt |
Q:
GAE bulkloader : entity missing from the auto-generated bulkloader.yaml
I am migrating a django application to GAE,and am going to use bulkloader to upload existing data.
The model is quite simple, basically there are two models:
class Tag(db.Model):
name = db.StringProperty (required=True)
class Entry(db.... | GAE bulkloader : entity missing from the auto-generated bulkloader.yaml | I am migrating a django application to GAE,and am going to use bulkloader to upload existing data.
The model is quite simple, basically there are two models:
class Tag(db.Model):
name = db.StringProperty (required=True)
class Entry(db.Model):
# some properties ...
# ...
tags = db.ListProperty(... | [
"Try running that GQL in the data store viewer in your control panel. \n"
] | [
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0003540363_google_app_engine_python.txt |
Q:
Does anyone know of a script to convert pygtk to tk
I have a fairly large work project that uses pygtk for the GUI and I need reduce the dependencies and convert to tkinter.
Does anyone know of a script to convert exisiting pygtk code to tkinter?
A:
Ok for anyone in the same boat as me, I just found PyGtk2Tk wh... | Does anyone know of a script to convert pygtk to tk | I have a fairly large work project that uses pygtk for the GUI and I need reduce the dependencies and convert to tkinter.
Does anyone know of a script to convert exisiting pygtk code to tkinter?
| [
"Ok for anyone in the same boat as me, I just found PyGtk2Tk which is a PyGtk to Tkinter Wrapper that runs PyGtk based code unchanged using Tkinter (Tk).\n"
] | [
2
] | [] | [] | [
"pygtk",
"python",
"tkinter"
] | stackoverflow_0003539735_pygtk_python_tkinter.txt |
Q:
Cannot create new Django model object within Ajax post request
This is kind of "I already lost x hours debugging this" kind of problem/question :(
Following jQuery js code is initiating POST request upon button click
$("#btn_create_tag").click(function(evt) {
$.post("/tag/createAjax", {
tagname: $("#txt_tag_n... | Cannot create new Django model object within Ajax post request | This is kind of "I already lost x hours debugging this" kind of problem/question :(
Following jQuery js code is initiating POST request upon button click
$("#btn_create_tag").click(function(evt) {
$.post("/tag/createAjax", {
tagname: $("#txt_tag_name").val()
},
function(data) {
}
);
});
Django ... | [
"This sounds very strange. Can you double check your database settings? Ensure that you are using the correct database inside settings.py? Also write an unit test to exercise the code using Django's test client. In your test method remember to send the HTTP_X_REQUESTED_WITH header for is_ajax() to work. \n",
"If... | [
1,
1,
0
] | [] | [] | [
"django",
"javascript",
"jquery",
"orm",
"python"
] | stackoverflow_0003537399_django_javascript_jquery_orm_python.txt |
Q:
Python error "IOError: [Errno 2] No such file or directory" but file is there
I am trying to read a csv file and I am getting the error above but the file is there. The line giving the error is
infilequery = file('D:\x88_2.csv','rb')
and I get the error below.
Traceback (most recent call last):
File "C:\Pyth... | Python error "IOError: [Errno 2] No such file or directory" but file is there | I am trying to read a csv file and I am getting the error above but the file is there. The line giving the error is
infilequery = file('D:\x88_2.csv','rb')
and I get the error below.
Traceback (most recent call last):
File "C:\Python26\usrapply_onemol2.py", line 14, in
infilequery = file('D:\x88_2.csv','rb')... | [
"Try\n'D:\\\\x88_2.csv'\n\nThe \\x88 is interpreted as the character at code point 0x88. Alternatively you could use raw string\nr'D:\\x88_2.csv'\n\nor forward slash\n'D:/x88_2.csv'\n\n"
] | [
7
] | [] | [] | [
"file",
"io",
"python"
] | stackoverflow_0003541109_file_io_python.txt |
Q:
Why is this pickled data not unpickling after transfer over a network?
logexample.py logs over the network using logging.handlers.DatagramHandler, which pickles(protocol 1) the data it sends.
logserver.py is supposed to unpickle and print to screen, but instead it raises an error. If I use pickle.loads then KeyErr... | Why is this pickled data not unpickling after transfer over a network? | logexample.py logs over the network using logging.handlers.DatagramHandler, which pickles(protocol 1) the data it sends.
logserver.py is supposed to unpickle and print to screen, but instead it raises an error. If I use pickle.loads then KeyError: '\x00' and if I use cPickle.loads its an EOFError
The files are here - h... | [
"There is an example in the docs of how to use DataGramHandler - it shows that the datagram may be sent over multiple packets, which need to be reassembled at the receiving end. The first four bytes of the first packet are the length - you are passing this into pickle.loads as well as the pickled data. Use the ex... | [
0
] | [] | [] | [
"pickle",
"python"
] | stackoverflow_0003540842_pickle_python.txt |
Q:
Is it possible to run linux on hand-held tablets?
I want to run a django app on a hand-held device. It'll need to run Python (obviously) and will write its data to an SQLite database.
Are there any tablets available that will let me do this? Specifically, if I bought an Android tablet, would I have to/be able to ... | Is it possible to run linux on hand-held tablets? | I want to run a django app on a hand-held device. It'll need to run Python (obviously) and will write its data to an SQLite database.
Are there any tablets available that will let me do this? Specifically, if I bought an Android tablet, would I have to/be able to install linux instead, or would I be able to run it und... | [
"If you want Linux probably Meego is the best choice. There is no hardware for it yet, I believe, but there is hardware for the predecessor Maemo.\nRunning Django on Android is not possible, AFAIK. If you have a network connection the Django server yould be anywhere and you would just need a smartphone/tablet with ... | [
1,
0
] | [] | [] | [
"android",
"django",
"python"
] | stackoverflow_0003540805_android_django_python.txt |
Q:
os.walk() caching/speeding up
I have a prototype server[0] that's doing an os.walk()[1] for each query a client[0] makes.
I'm currently looking into ways of:
caching this data in memory,
speeding up queries, and
hopefully allowing for expansion into storing metadata and data persistence later on.
I find SQL co... | os.walk() caching/speeding up | I have a prototype server[0] that's doing an os.walk()[1] for each query a client[0] makes.
I'm currently looking into ways of:
caching this data in memory,
speeding up queries, and
hopefully allowing for expansion into storing metadata and data persistence later on.
I find SQL complicated for tree structures, so I... | [
"You don't need to persist a tree structure -- in fact, your code is busily dismantling the natural tree structure of the directory tree into a linear sequence, so why would you want to restart from a tree next time?\nLooks like what you need is just an ordered sequence:\ni X result of os.path.join for X\n\nwh... | [
3,
3,
0
] | [] | [] | [
"database",
"embedded_database",
"nosql",
"python"
] | stackoverflow_0003537279_database_embedded_database_nosql_python.txt |
Q:
PyArg_ParseTuple and a callback function pointer
I have code like the following:
PyObject *callback;
PyObject *paths;
// Process and convert arguments
if (!PyArg_ParseTuple(args, "OO:schedule", &paths, &callback))
return NULL;
What exactly happens inside PyArg_ParseTuple? My guess is ... | PyArg_ParseTuple and a callback function pointer | I have code like the following:
PyObject *callback;
PyObject *paths;
// Process and convert arguments
if (!PyArg_ParseTuple(args, "OO:schedule", &paths, &callback))
return NULL;
What exactly happens inside PyArg_ParseTuple? My guess is that callback gets the function pointer I passed to ar... | [
"PyArg_ParseTuple doesn't care about the type of an \"O\" arg. No conversion is done. No new object is created. The address of the object is dropped into the PyObject * C variable that you have specified. It does exactly the same to each of your two args.\nI can't imagine what is the relevance of PyObject_Hash. If ... | [
1,
0
] | [] | [] | [
"c",
"callback",
"python",
"python_c_extension"
] | stackoverflow_0003532434_c_callback_python_python_c_extension.txt |
Q:
MySQL database: lua or python
Under preferences(Menu)/general (Tab)/ Interactive GRT Shell Language: lua or python.
What is the difference?
I use MySQL for database and involve mostly binary.
A:
mysql is a database server -- it doesn't have a menu. I think you mean mysql workbench which is a visual database des... | MySQL database: lua or python | Under preferences(Menu)/general (Tab)/ Interactive GRT Shell Language: lua or python.
What is the difference?
I use MySQL for database and involve mostly binary.
| [
"mysql is a database server -- it doesn't have a menu. I think you mean mysql workbench which is a visual database design tool. That option allows you to use lua scripting or python scripting to help you on the design of your database -- it is unrelated to what happens on the mysql server. There are some examples o... | [
5
] | [] | [] | [
"lua",
"mysql",
"python"
] | stackoverflow_0003541364_lua_mysql_python.txt |
Q:
Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)
My present task is to dissect tcpdump data that includes P2P messages and I am having trouble with the piece data I acquire and write to a file on my x86 machine. My suspicion is I have a simple endian-ness issue wit... | Python method for storing list of bytes in network (big-endian) byte order to file (little-endian) | My present task is to dissect tcpdump data that includes P2P messages and I am having trouble with the piece data I acquire and write to a file on my x86 machine. My suspicion is I have a simple endian-ness issue with the bytes I write to to file.
I have a list of bytes holding a piece of P2P video read and processed ... | [
"To save yourself some work you might like to use a bytearray (Python 2.6 and later):\nb = [14, 254, 23, 35]\nf = open(\"file\", 'ab')\nf.write(bytearray(b))\n\nThis does all the converting of your 0-255 values into bytes without the need for all the looping.\nI can't see what your problem is otherwise without more... | [
2,
1,
0
] | [] | [] | [
"binary",
"byte",
"endianness",
"file_io",
"python"
] | stackoverflow_0003405972_binary_byte_endianness_file_io_python.txt |
Q:
How to find out if there is data to be read from stdin on Windows in Python?
This code
select.select([sys.stdin], [], [], 1.0)
does exactly what I want on Linux, but not in Windows.
I've used kbhit() in msvcrt before to see if data is available on stdin for reading, but in this case it always returns 0. Addition... | How to find out if there is data to be read from stdin on Windows in Python? | This code
select.select([sys.stdin], [], [], 1.0)
does exactly what I want on Linux, but not in Windows.
I've used kbhit() in msvcrt before to see if data is available on stdin for reading, but in this case it always returns 0. Additionally msvcrt.getch() returns '\xff' whereas sys.stdin.read(1) returns '\x01'. It s... | [
"In some rare situations, you might care what stdin is connected to. Mostly, you don't care -- you just read stdin.\nIn someprocess | python myprogram.py, stdin is connected to a pipe; in this case, the stdout of the previous process. You simply read from sys.stdin and you're reading from the other process. [Not... | [
2,
1
] | [] | [] | [
"python"
] | stackoverflow_0000323829_python.txt |
Q:
Client Server Socket Programing in Python
I have the Client Server Socket program on python.
In both the Client and Server I use the loopback address.
But kindly assist how to use this code and apply on different Client Server machines
Eg (Server IP 192.168.1.4 & Client IP 192.168.1.5)
# Server program
from sock... | Client Server Socket Programing in Python | I have the Client Server Socket program on python.
In both the Client and Server I use the loopback address.
But kindly assist how to use this code and apply on different Client Server machines
Eg (Server IP 192.168.1.4 & Client IP 192.168.1.5)
# Server program
from socket import *
host = "localhost"
port = 21567
bu... | [
"Instead of 'localhost', use '192.168.1.5' (the client's address) in the server code, '192.168.1.4' (the server's address) in the client code.\nNormally a server wouldn't need to know the client's address beforehand, but UDP's knottier than TCP (the more usual, stream-oriented approach to socket communication) in m... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0003541611_python.txt |
Q:
Using Numpy arrays as lookup tables
I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were.
What is the best (most Numpythonic) way to match up the ... | Using Numpy arrays as lookup tables | I have a 2D array of Numpy data read from a .csv file. Each row represents a data point with the final column containing a a 'key' which corresponds uniquely to 'key' in another Numpy array - the 'lookup table' as it were.
What is the best (most Numpythonic) way to match up the lines in the first table with the values ... | [
"Some example data:\nimport numpy as np\n\nlookup = np.array([[ 1. , 3.14 , 4.14 ],\n [ 2. , 2.71818, 3.7 ],\n [ 3. , 42. , 43. ]])\n\na = np.array([[ 1, 11],\n [ 1, 12],\n [ 2, 21],\n [ 3, 31]])\n\nBu... | [
10,
5
] | [] | [] | [
"numpy",
"python"
] | stackoverflow_0003522946_numpy_python.txt |
Q:
python regular expresssion for a string
consider this string
prison break: proof of innocence (2006) {abduction (#1.10)}
i just want to know whether there is (# floating point value )} in the string or not
i tried few regular expressions like
re.search('\(\#+\f+\)\}',xyz)
and
re.search('\(\#+(\d\.\d)+\)\}',xy... | python regular expresssion for a string | consider this string
prison break: proof of innocence (2006) {abduction (#1.10)}
i just want to know whether there is (# floating point value )} in the string or not
i tried few regular expressions like
re.search('\(\#+\f+\)\}',xyz)
and
re.search('\(\#+(\d\.\d)+\)\}',xyz)
nothing worked though...can someone sugge... | [
"Try r'\\(#\\d+\\.\\d+\\)\\}'\nThe (, ), ., and } are all special metacharacters, that's why they're preceded by \\, so they're matched literally instead.\nYou also need to apply the + repetition at the right element. Here it's attached to the \\d -- the shorthand for digit character class -- to mean that only the ... | [
3,
3
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0003541963_python_regex.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.