text stringlengths 185 26.5k |
|---|
<s>[INST] Extracting text from HTML file using Python I'd like to extract the text from an HTML file using Python. I want essentially the same output I would get if I copied the text from a browser and pasted it into notepad.
I'd like something more robust than using regular expressions that may fail on poorly forme... |
<s>[INST] How Python web frameworks, WSGI and CGI fit together I have a Bluehost account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in .htaccess:
Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py
Now, whenever I look up web programm... |
<s>[INST] How can I get the source code of a Python function? Suppose I have a Python function as defined below:
def foo(arg1,arg2):
#do something with args
a = arg1 + arg2
return a
I can get the name of the function using foo.func_name. How can I programmatically get its source code, as I typed above?
[/... |
<s>[INST] How to invoke the super constructor in Python? class A:
def __init__(self):
print "world"
class B(A):
def __init__(self):
print "hello"
B()
hello
In all other languages I've worked with the super constructor is invoked implicitly. How does one invoke it in Python? I would expect super(self) but thi... |
<s>[INST] Is "x < y < z" faster than "x < y and y < z"? From this page, we know that:
Chained comparisons are faster than using the and operator.
Write x < y < z instead of x < y and y < z.
However, I got a different result testing the following code snippets:
$ python -m timeit "x = 1.2" "y = 1.3" "z = 1.8" "x < y... |
<s>[INST] Reducing Django Memory Usage. Low hanging fruit? My memory usage increases over time and restarting Django is not kind to users.
I am unsure how to go about profiling the memory usage but some tips on how to start measuring would be useful.
I have a feeling that there are some simple steps that could produce ... |
<s>[INST] Check if multiple strings exist in another string How can I check if any of the strings in an array exists in another string?
Like:
a = ['a', 'b', 'c']
str = "a123"
if a in str:
print "some of the strings found in str"
else:
print "no strings found in str"
That code doesn't work, it's just to show what I... |
<s>[INST] Why does ~True result in -2? In Python console:
~True
Gives me:
-2
Why? Can someone explain this particular case to me in binary?
[/INST] What is int(True)? It is 1.
1 is:
00000001
and ~1 is:
11111110
Which is -2 in Two's complement1
1 Flip all the bits, add 1 to the resulting number and interpret the re... |
<s>[INST] Python -- return, return None, and no return at all Consider three functions:
def my_func1():
print "Hello World"
return None
def my_func2():
print "Hello World"
return
def my_func3():
print "Hello World"
They all appear to return None. Are there any differences between how the returned value of ... |
<s>[INST] In practice, what are the main uses for the new "yield from" syntax in Python 3.3? I'm having a hard time wrapping my brain around PEP 380.
What are the situations where "yield from" is useful?
What is the classic use case?
Why is it compared to micro-threads?
[ update ]
Now I understand the cause of my di... |
<s>[INST] django import error - No module named core.management Ok, I see plenty of these errors around. I have tried everything I know to do and have yet to figure this out.
I am working on a development server running python 2.5 and Django 1.3. Django 1.3 was installed using python setup.py install after unpacking th... |
<s>[INST] How to use Python to login to a webpage and retrieve cookies for later usage? I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to... |
<s>[INST] Standard way to embed version into python package? Is there a standard way to associate version string with a python package in such way that I could do the following?
import foo
print foo.version
I would imagine there's some way to retrieve that data without any extra hardcoding, since minor/major strings a... |
<s>[INST] Ruby equivalent of virtualenv? Is there something similar to the Python utility virtualenv?
Basically it allows you to install Python packages into a sandboxed environment, so easy_install django doesn't go in your system-wide site-packages directory, it would go in the virtualenv-created directory.
For examp... |
<s>[INST] Python strftime - date without leading 0? When using Python strftime, is there a way to remove the first 0 of the date if it's before the 10th, ie. so 01 is 1? Can't find a %thingy for that?
Thanks!
[/INST] Actually I had the same problem and I realized that, if you add a hyphen between the % and the letter,... |
<s>[INST] How to get a random number between a float range? (Python) randrange(start, stop) only takes integer arguments... So how would I get a random number between two float values?
[/INST] Use random.uniform(a, b):
>>> random.uniform(1.5, 1.9)
1.8733202628557872
</s> |
<s>[INST] Creating a range of dates in Python I want to create a list of dates, starting with today, and going back an arbitrary number of days, say, in my example 100 days. Is there a better way to do it than this?
import datetime
a = datetime.datetime.today()
numdays = 100
dateList = []
for x in range (0, numdays):
... |
<s>[INST] How to remove convexity defects in a Sudoku square? I was doing a fun project: Solving a Sudoku from an input image using OpenCV (as in Google goggles etc). And I have completed the task, but at the end I found a little problem for which I came here.
I did the programming using Python API of OpenCV 2.3.1.
Bel... |
<s>[INST] Python if not == vs if != What is the difference between these two lines of code:
if not x == 'val':
and
if x != 'val':
Is one more efficient than the other?
Would it be better to use
if x == 'val':
pass
else:
[/INST] Using dis to look at the bytecode generated for the two versions:
not ==
4 ... |
<s>[INST] Why do you have to call .iteritems() when iterating over a dictionary in python? Why do you have to call iteritems() to iterate over key, value pairs in a dictionary? ie
dic = {'one':'1', 'two':'2'}
for k, v in dic.iteritems():
print k, v
Why isn't that the default behavior of iterating over a dictionary... |
<s>[INST] Define css class in django Forms Assume I have a form
class SampleClass(forms.Form):
name = forms.CharField(max_length=30)
age = forms.IntegerField()
django_hacker = forms.BooleanField(required=False)
Is there a way for me to define css classes on each field such that I can then use jQuery based ... |
<s>[INST] Python format timedelta to string I'm a Python newbie (2 weeks) and I'm having trouble formatting a datetime.timedelta object.
Here's what I'm trying to do:
I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to... |
<s>[INST] How do I modify a text file in Python? I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?
[/INST] Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can app... |
<s>[INST] Best programming aids for a quadriplegic programmer Before you jump to conclusions, yes, this is programming related. It covers a situation that comes under the heading of, "There, but for the grace of God, go you or I." This is brand new territory for me so I'm asking for some serious help here.
A young man,... |
<s>[INST] Can't pickle <type 'instancemethod'> when using python's multiprocessing Pool.map() I'm trying to use multiprocessing's Pool.map() function to divide out work simultaneously. When I use the following code, it works fine:
import multiprocessing
def f(x):
return x*x
def go():
pool = multiprocessing.Po... |
<s>[INST] Why do you need explicitly have the "self" argument into a Python method? When defining a method on a class in Python, it looks something like this:
class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
But in some other languages, such as C#, you have a reference to the ... |
<s>[INST] Using Python 3 in virtualenv Using virtualenv, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.
I used brew install python3 to install it on my Mac. Now, how do I create a virtualenv that uses the new version?
e.g. sudo virtualenv envPython3
If I try:
virt... |
<s>[INST] Print in one line dynamically I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
for item in range(1,100):
print item
The result is:
1
2
3
4
.
.
.
How get this to instead look like:
1 2 3 4 5 ...
Even better, is... |
<s>[INST] Python: Run function from the command line I have below code in my file:
def hello():
return 'Hi :)'
How would I run this from the command line?
[/INST] With the -c (command) argument (assuming your file is named foo.py):
$ python -c 'import foo; print foo.hello()'
Alternatively, if you don't care abou... |
<s>[INST] How do I get the path of the current executed file in Python? This may seem like a newbie question, but it is not. Some common approaches don't work in all cases:
sys.argv[0]
This means using path = os.path.abspath(os.path.dirname(sys.argv[0])), but this does not work if you are running from another Python sc... |
<s>[INST] Python code to pick out all possible combinations from a list? I have a list with 15 numbers in, and I need to write some code that produces all 32,768 combinations of those numbers.
I've found some code (by googling) that apparently does what I'm looking for, but I found the code fairly opaque and am wary o... |
<s>[INST] Python vs Cpython What's all this fuss about Python and CPython (Jython,IronPython), I don't get it:
python.org mentions that CPython is:
The "traditional" implementation of Python (nicknamed CPython)
yet another Stack Overflow question mentions that:
CPython is the default byte-code interpreter of Python,... |
<s>[INST] How do I copy a string to the clipboard on Windows using Python? I'm kind of new to Python and I'm trying to make a basic Windows application that builds a string out of user input then adds it to the clipboard. How do I copy a string to the clipboard using Python?
[/INST] Actually, pywin32 and ctypes seem ... |
<s>[INST] Cross-platform way of getting temp directory in Python Is there a cross-platform way of getting the path to the temp directory in Python 2.6?
For example, under Linux that would be /tmp, while under XP C:\Documents and settings\[user]\Application settings\Temp.
Thanks!
[/INST] That would be the tempfile mo... |
<s>[INST] How do I check if a string is unicode or ascii? What do I have to do in Python to figure out which encoding?
[/INST] In Python 3, all strings are sequences of Unicode characters. There is a bytes type that holds raw bytes.
In Python 2, a string may be of type str or of type unicode. You can tell which using ... |
<s>[INST] Can I force pip to reinstall the current version? I've come across situations where a current version of a package seems not to be working and requires reinstallation. But pip install -U won't touch a package that is already up-to-date. I see how to force a reinstallation by first uninstalling (with pip unins... |
<s>[INST] Iterate over model instance field names and values in template I'm trying to create a basic template to display the selected instance's field values, along with their names. Think of it as just a standard output of the values of that instance in table format, with the field name (verbose_name specifically if... |
<s>[INST] How can I explicitly free memory in Python? I wrote a Python program that acts on a large input file to create a few million objects representing triangles. The algorithm is:
read an input file
process the file and create a list of triangles, represented by their vertices
output the vertices in the OFF form... |
<s>[INST] Proper way to handle multiple forms on one page in Django I have a template page expecting two forms. If I just use one form, things are fine as in this typical example:
if request.method == 'POST':
form = AuthorForm(request.POST,)
if form.is_valid():
form.save()
# do something.
else:... |
<s>[INST] How should I log while using multiprocessing in Python? Right now I have a central module in a framework that spawns multiple processes using the Python 2.6 multiprocessing module. Because it uses multiprocessing, there is module-level multiprocessing-aware log, LOG = multiprocessing.get_logger(). Per the doc... |
<s>[INST] Get loop count inside a Python FOR loop In a Python for loop that iterates over a list we can write:
for item in list:
print item
and it neatly goes through all the elements in the list. Is there a way to know within the loop how many times I've been looping so far? For instance, I want to take a list an... |
<s>[INST] Loading all modules in a folder in Python Could someone provide me with a good way of importing a whole directory of modules?
I have a structure like this:
/Foo
bar.py
spam.py
eggs.py
I tried just converting it to a package by adding __init__.py and doing from Foo import * but it didn't work the ... |
<s>[INST] Python: How to get a value of datetime.today() that is "timezone aware"? I am trying to subtract one date value from the value of datetime.today() to calculate how long ago something was. But it complains:
TypeError: can't subtract offset-naive and offset-aware datetimes
The value datetime.today() doesn't se... |
<s>[INST] Is there a standardized method to swap two variables in Python? In Python, I've seen two variable values swapped using this syntax:
left, right = right, left
Is this considered the standard way to swap two variable values or is there some other means by which two variables are by convention most usually swap... |
<s>[INST] How does Python compare string and int? The following snippet is annotated with the output (as seen on ideone.com):
print "100" < "2" # True
print "5" > "9" # False
print "100" < 2 # False
print 100 < "2" # True
print 5 > "9" # False
print "5" > 9 # True
Can some... |
<s>[INST] Efficient way to shift a list in python What is the most efficient way to shift a list in python?
Right now I have something like this:
>>> def shift(l, n):
... return l[n:] + l[:n]
...
>>> l = [1,2,3,4]
>>> shift(l,1)
[2, 3, 4, 1]
>>> shift(l,2)
[3, 4, 1, 2]
>>> shift(l,0)
[1, 2, 3, 4]
>>> shift(l,-1)
... |
<s>[INST] Is there a way to detach matplotlib plots so that the computation can continue? After these instructions in the Python interpreter one gets a window with a plot:
from matplotlib.pyplot import *
plot([1,2,3])
show()
# other code
Unfortunately, I don't know how to continue to interactively explore the figure c... |
<s>[INST] Get last n lines of a file with Python, similar to tail I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item on the bottom.
So I need a tail() method that can read n lines from the bott... |
<s>[INST] What is the difference between encode/decode? I've never been sure that I understand the difference between str/unicode decode and encode.
I know that str().decode() is for when you have a string of bytes that you know has a certain character encoding, given that encoding name it will return a unicode string.... |
<s>[INST] error: command 'gcc' failed with exit status 1 while installing eventlet I wanted to install eventlet on my system in order to have "Herd" for software deployment.. but the terminal is showing a gcc error:
root@agrover-OptiPlex-780:~# easy_install -U eventlet
Searching for eventlet
Reading http://pypi.p... |
<s>[INST] Converting datetime.date to UTC timestamp in Python I am dealing with dates in Python and I need to convert them to UTC timestamps to be used
inside Javascript. The following code does not work:
>>> d = datetime.date(2011,01,01)
>>> datetime.datetime.utcfromtimestamp(time.mktime(d.timetuple()))
datetime.datet... |
<s>[INST] Initialize a datetime object with seconds since epoch The time module can be initialized using seconds since epoch:
>>> import time
>>> t1=time.gmtime(1284286794)
>>> t1
time.struct_time(tm_year=2010, tm_mon=9, tm_mday=12, tm_hour=10, tm_min=19,
tm_sec=54, tm_wday=6, tm_yday=255, tm_isdst=0)... |
<s>[INST] Python multiprocessing.Pool: when to use apply, apply_async or map? I have not seen clear examples with use-cases for Pool.apply, Pool.apply_async and Pool.map. I am mainly using Pool.map; what are the advantages of others?
[/INST] Back in the old days of Python, to call a function with arbitrary arguments, ... |
<s>[INST] Python: Why is functools.partial necessary? Partial application is cool. What functionality does functools.partial offer that you can't get through lambdas?
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>>> incr2 = functools.p... |
<s>[INST] Getting the index of the returned max or min item using max()/min() on a list I'm using Python's max and min functions on lists for a minimax algorithm, and I need the index of the value returned by max() or min(). In other words, I need to know which move produced the max (at a first player's turn) or min (s... |
<s>[INST] When should I use uuid.uuid1() vs. uuid.uuid4() in python? I understand the differences between the two from the docs.
uuid1():
Generate a UUID from a host ID, sequence number, and the current time
uuid4():
Generate a random UUID.
So uuid1 uses machine/sequence/time info to generate a UUID. What are the pros... |
<s>[INST] Why can tuples contain mutable items? If a tuple is immutable then why can it contain mutable items?
It is seemingly a contradiction that when a mutable item such as a list does get modified, the tuple it belongs to maintains being immutable.
[/INST] That's because tuples don't contain lists, strings or numb... |
<s>[INST] What is the most efficient way to loop through dataframes with pandas? I want to perform my own complex operations on financial data in dataframes in a sequential manner.
For example I am using the following MSFT CSV file taken from Yahoo Finance:
Date,Open,High,Low,Close,Volume,Adj Close
2011-10-19,27.37,27... |
<s>[INST] Retrieving the output of subprocess.call() How can I get the output of a process run using subprocess.call()?
Passing a StringIO.StringIO object to stdout gives this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.6/lib/py... |
<s>[INST] BaseException.message deprecated in Python 2.6 I get a warning that BaseException.message is deprecated in Python 2.6 when I use the following user-defined exception:
class MyException(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return repr(self... |
<s>[INST] Shuffle an array with python, randomize array item order with python What's the easiest way to shuffle an array with python?
[/INST] import random
random.shuffle(array)
</s> |
<s>[INST] Failed to install Python Cryptography package with PIP and setup.py When I try to install the Cryptography package for Python through either pip install cryptography or by downloading the package from their site and running python setup.py, I get the following error:
D:\Anaconda\Scripts\pip-script.py run on ... |
<s>[INST] Pandas writing dataframe to CSV file I have a dataframe in pandas which I would like to write to a CSV file. I am doing this using:
df.to_csv('out.csv')
And getting the error:
UnicodeEncodeError: 'ascii' codec can't encode character u'\u03b1' in position 20: ordinal not in range(128)
Is there any way to get... |
<s>[INST] Deleting DataFrame row in Pandas based on column value I have the following DataFrame:
daysago line_race rating rw wrating
line_date
2007-03-31 62 11 56 1.000000 56.000000
2007-03-10 83 11 67 1.0... |
<s>[INST] Create an empty list in python with certain size I want to create an empty list (or whatever is the best way) that can hold 10 elements.
After that I want to assign values in that list, for example this is supposed to display 0 to 9:
s1 = list();
for i in range(0,9):
s1[i] = i
print s1
But when I run th... |
<s>[INST] How to check if a string in Python is in ASCII? I want to I check whether a string is in ASCII or not.
I am aware of ord(), however when I try ord('é'), I have TypeError: ord() expected a character, but string of length 2 found. I understood it is caused by the way I built Python (as explained in ord()'s doc... |
<s>[INST] Use of "global" keyword in Python What I understand from reading the documentation is that Python has a separate namespace for functions, and if I want to use a global variable in that function, I need to use global.
I'm using Python 2.7 and I tried this little test
>>> sub = ['0', '0', '0', '0']
>>> def getJ... |
<s>[INST] Assign output of os.system to a variable and prevent it from being displayed on the screen I want to assign the output of a command I run using os.system to a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for var is 0, w... |
<s>[INST] How do I add a placeholder on a CharField in Django? Take this very simple form for example.
class SearchForm(Form):
q = forms.CharField(label='search')
This gets rendered in the template:
<input type="text" name="q" id="id_q" />
However, I want to add the 'placeholder' attribute to this field with a val... |
<s>[INST] How to convert 2D float numpy array to 2D int numpy array? How to convert real numpy array to int numpy array?
Tried using map directly to array but it did not work.
[/INST] Use the astype method.
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
ar... |
<s>[INST] read subprocess stdout line by line My python script uses subprocess to call a linux utility that is very noisy. I want to store all of the output to a log file and show some of it to the user. I thought the following would work, but the output doesn't show up in my application until the utility has produce... |
<s>[INST] Is there a way to perform "if" in python's lambda In python 2.6, I want to do:
f = lambda x: if x==2 print x else raise Exception()
f(2) #should print "2"
f(3) #should throw an exception
This clearly isn't the syntax. Is it possible to perform an if in lambda and if so how to do it?
thanks
[/INST] The synta... |
<s>[INST] Clearing Python lists Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:
old_list = []
old_list = list()
The reason I ask is that I just saw this in some running code:
del old_list[ 0:len(old_list) ]
[/INST] Clearing a list in place will... |
<s>[INST] A simple way to remove multiple spaces in a string in Python Suppose this is the string:
The fox jumped over the log.
It would result in:
The fox jumped over the log.
What is the simplest, 1-2 liner that can do this? Without splitting and going into lists...
[/INST] foo is your string:
" ".join(foo.... |
<s>[INST] Can I install Python windows packages into virtualenvs? Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects' dependencies aren't all thrown together into a common pile.
But if I want to install a package on Windows that's packaged as a .exe installer, how ... |
<s>[INST] Convert base-2 binary number string to int I'd simply like to convert a base-2 binary number string into an int, something like this:
>>> '11111111'.fromBinaryToInt()
255
Is there a way to do this in Python?
[/INST] You use the built-in [int() function][1], and pass it the base of the input number, i.e. 2 ... |
<s>[INST] Using python map and other functional tools This is quite n00bish, but I'm trying to learn/understand functional programming in python. The following code:
foos = [1.0,2.0,3.0,4.0,5.0]
bars = [1,2,3]
def maptest(foo, bar):
print foo, bar
map(maptest, foos, bars)
produces:
1.0 1
2.0 2
3.0 3
4.0 None
5.0... |
<s>[INST] How to find all occurrences of an element in a list? index() will just give the first occurrence of an item in a list. Is there a neat trick which returns all indices in a list?
[/INST] You can use a list comprehension:
indices = [i for i, x in enumerate(my_list) if x == "whatever"]
</s> |
<s>[INST] How to check whether a variable is a class or not? I was wondering how to check whether a variable is a class (not an instance!) or not.
I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.
For example, in the following code
... |
<s>[INST] What is `related_name` used for in Django? What is the related_name argument useful for on ManyToManyField and ForeignKey fields? For example, given the following code, what is the effect of related_name='maps'?
class Map(db.Model):
members = models.ManyToManyField(User, related_name='maps',
... |
<s>[INST] Cron and virtualenv I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed.
I have seen examples here and elsewhere that show running management commands from within virtualenv's like:
0 3 * * * source /home/user/project/env/bin/activate && /home/user/proj... |
<s>[INST] Python - When to use file vs open What's the difference between file and open in Python? When should I use which one? (Say I'm in 2.5)
[/INST] You should always use open().
As the documentation states:
When opening a file, it's preferable
to use open() instead of invoking this
constructor directly. fi... |
<s>[INST] Safest way to convert float to integer in python? Python's math module contain handy functions like floor & ceil. These functions take a floating point number and return the nearest integer below or above it. However these functions return the answer as a floating point number. For example:
import math
f=math... |
<s>[INST] What's the best practice using a settings file in Python? I have a command line script that I run with a lot of arguments. I have now come to a point where I have too many arguments, and I want to have some arguments in dictionary form too.
So in order to simplify things I would like to run the script with a ... |
<s>[INST] Alphabet range python Instead of making a list of alphabet like this:
alpha = ['a', 'b', 'c', 'd'.........'z']
Is there any way that we can group it to a range or something? For example, for numbers it can be grouped using range()
range(1, 10)
[/INST] >>> import string
>>> string.ascii_lowercase
'abcdefghi... |
<s>[INST] PyCharm shows unresolved references error for valid code I am using PyCharm to work on a project. The project is opened and configured with an interpreter, and can run successfully. The remote interpreter paths are mapped properly. This seems to be the correct configuration, but PyCharm is highlighting my ... |
<s>[INST] How to print an error in Python? try:
something here
except:
print 'the whatever error occurred.'
How can I print the error in my except: block?
[/INST] except Exception,e: print str(e)
</s> |
<s>[INST] Why are pandas merges in python faster than data.table merges in R? I recently came across the pandas library for python, which according to this benchmark performs very fast in-memory merges. It's even faster than the data.table package in R (my language of choice for analysis).
Why is pandas so much faster... |
<s>[INST] Ubuntu running `pip install` gives error 'The following required packages can not be built: * freetype' When performing pip install -r requirements.txt, I get the following error during the stage where it is installing matplotlib:
REQUIRED DEPENDENCIES AND EXTENSIONS
numpy: yes [not found. pi... |
<s>[INST] How to check which version of Numpy I'm using? How can I check which version of Numpy I'm using? I'm using Mac OS X 10.6.1 Snow Leopard.
[/INST] import numpy
numpy.version.version
</s> |
<s>[INST] How do I look inside a Python object? I'm starting to code in various projects using Python (including Django web development and Panda3D game development).
To help me understand what's going on, I would like to basically 'look' inside the Python objects to see how they tick - like their methods and properti... |
<s>[INST] Most efficient way to reverse a numpy array Believe it or not, after profiling my current code, the repetitive operation of numpy array reversion ate a giant chunk of the running time. What I have right now is the common view-based method:
reversed_arr = arr[::-1]
Is there any other way to do it more efficie... |
<s>[INST] What does -> mean in Python function definitions? I've recently noticed something interesting when looking at Python 3.3 grammar specification:
funcdef: 'def' NAME parameters ['->' test] ':' suite
The optional 'arrow' block was absent in Python 2 and I couldn't find any information regarding its meaning in P... |
<s>[INST] How to delete an item in a list if it exists? I am getting new_tag from a form text field with self.response.get("new_tag") and selected_tags from checkbox fields with
self.response.get_all("selected_tags")
I combine them like this:
tag_string = new_tag
new_tag_list = f1.striplist(tag_string.split(",") + se... |
<s>[INST] Change the name of a key in dictionary I want to change the key of an entry in a Python dictionary.
Is there a straightforward way to do this?
[/INST] Easily done in 2 steps:
dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]
Or in 1 step:
dictionary[new_key] = dictionary.pop(old_key)
which ... |
<s>[INST] Get a filtered list of files in a directory I am trying to get a list of files in a directory using Python, but I do not want a list of ALL the files.
What I essentially want is the ability to do something like the following but using Python and not executing ls.
ls 145592*.jpg
If there is no built-in method... |
<s>[INST] How do I fix PyDev "Undefined variable from import" errors? I've got a Python project using PyDev in Eclipse, and PyDev keeps generating false errors for my code. I have a module settings that defines a settings object. I import that in module b and assign an attribute with:
from settings import settings
se... |
<s>[INST] Maximum recursion depth? I have this tail recursive function here:
def fib(n, sum):
if n < 1:
return sum
else:
return fib(n-1, sum+n)
c = 998
print(fib(c, 0))
It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" RuntimeError. Is this ... |
<s>[INST] What is the '@=' symbol for in Python? I know @ is for decorators, but what is @= for in Python? Is it just reservation for some future idea?
This is just one of my many questions while reading tokenizer.py.
[/INST] From the documentation:
The @ (at) operator is intended to be used for matrix multiplication... |
<s>[INST] How do I find the time difference between two datetime objects in python? How do I tell the time difference in minutes between two datetime objects?
[/INST] >>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> c = b - a
datetime.timedelta(0, 8, 562000)
>>> divmod(c.days * 8... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.