intent
stringlengths
4
183
snippet
stringlengths
2
1k
dropping a single (sub-) column from a multiindex
df.drop('a', level=1, axis=1)
creating list of random numbers in python
print('{.5f}'.format(randomList[index]))
python: how to build a dict from plain list of keys and values
dict(zip(i, i))
how to decode url to path in python, django
urllib.parse.unquote(url)
can i extend within a list of lists in python?
[[1, 100313, 0, 0, 1], [2, 100313, 0, 0, 1], [1, 100314, 0, 1, 0], [3, 100315]]
select all rows in dataframe `df` where the values of column 'columnx' is bigger than or equal to `x` and smaller than or equal to `y`
df[(x <= df['columnX']) & (df['columnX'] <= y)]
how to exclude a character from a regex group?
re.compile('[^a-zA-Z0-9-]+')
permanently set the current directory to the 'c:/users/name/desktop'
os.chdir('C:/Users/Name/Desktop')
display a grayscale image from array of pixels `imagearray`
imshow(imageArray, cmap='Greys_r')
how does a descriptor with __set__ but without __get__ work?
myinst.__dict__['attr']
organizing list of tuples
[(1, 4), (4, 8), (8, 10)]
how can i print over the current line in a command line application?
sys.stdout.flush()
how can i make a scatter plot colored by density in matplotlib?
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
how do you convert yyyy-mm-ddthh:mm:ss.000z time format to mm/dd/yyyy time format in python?
print(d.strftime('%m/%d/%Y'))
sending a mail from flask-mail (smtpsenderrefused 530)
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
display a decimal in scientific notation
"""{:.2E}""".format(Decimal('40800000000.00000000000000'))
convert a list to a dictionary in python
b = {a[i]: a[i + 1] for i in range(0, len(a), 2)}
how to sort a dataframe in python pandas by two or more columns?
df.sort_values(['a', 'b'], ascending=[True, False])
how can i exit fullscreen mode in pygame?
pygame.display.set_mode(size, FULLSCREEN)
python pickle/unpickle a list to/from a file 'afile'
pickle.load(open('afile', 'rb'))
replace the single quote (') character from a string
"""""".join([c for c in string if c != "'"])
how to convert hex string to integer in python?
int('0x000000001', 16)
writing nicely formatted text in python
f.write('%-40s %6s %10s %2s\n' % (filename, type, size, modified))
how to write a python script that can communicate with the input and output of a swift executable?
process.stdin.flush()
get a list of last trailing words from another list of strings`original_list`
new_list = [x.split()[-1] for x in Original_List]
python: convert unicode string to mm/dd/yyyy
datetime.datetime.strptime('Mar232012', '%b%d%Y').strftime('%m/%d/%Y')
display a image file `pathtofile`
Image.open('pathToFile').show()
how do i save data from a modelform to database in django?
obj.save()
is it possible to add a string as a legend item in matplotlib
plt.show()
extracting first n columns of a numpy matrix
a[:, :2]
python - converting hex to int/char
[ord(c) for c in s.decode('hex')]
how to call a function from another file?
print(function())
check if string contains a certain amount of words of another string
print([(s, s in st1) for s in re.findall(pat, st2)])
saving dictionary whose keys are tuples with json, python
json.dumps({str(k): v for k, v in data.items()})
row-wise indexing in numpy
i = np.array([[0], [1]])
pytz - converting utc and timezone to local time
pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)
how to use regular expression to separate numbers and characters in strings like "30m1000n20m"
re.findall('([0-9]+)([A-Z])', '20M10000N80M')
get random sample from list while maintaining ordering of items?
rand_smpl = [mylist[i] for i in sorted(random.sample(range(len(mylist)), 4))]
python regular expression match whole word
re.search('\\bis\\b', your_string)
named tuples in a list
a = [mynamedtuple(*el) for el in a]
how to modify a variable inside a lambda function?
myFunc(lambda a, b: iadd(a, b))
create a list that contain each line of a file
my_list = [line.split(',') for line in open('filename.txt')]
how to serve static files in flask
app.run()
no minor grid lines on the x-axis only
axes.xaxis.grid(False, which='minor')
get a list of indices of non zero elements in a list `a`
[i for i, e in enumerate(a) if e != 0]
how can i send variables to jinja template from a flask decorator?
return render_template('template.html')
regex punctuation split [python]
re.split('\\W+', 'Words, words, words.')
how to convert an ordereddict into a regular dict in python3
dict(OrderedDict([('method', 'constant'), ('data', '1.225')]))
how to use one app to satisfy multiple urls in django
urlpatterns = patterns('', ('', include('myapp.urls')))
convert dictionary of pairs `d` to a list of tuples
[(v, k) for k, v in d.items()]
remove items from a list while iterating
somelist = [x for x in somelist if not determine(x)]
return multiple lists from comprehension in python
x, y = zip(*[(i, -1 * j) for i, j in enumerate(range(10))])
python: how to remove values from 2 lists based on what's in 1 list
ind = [i for i in range(len(yVar)) if yVar[i] < 100]
how to count the number of words in a sentence?
len(s.split())
standard way to open a folder window in linux?
os.system('xdg-open "%s"' % foldername)
fill missing indices in pandas
x.resample('D').fillna(0)
python sorting - a list of objects
somelist.sort(key=lambda x: x.resultType)
python regular expression to replace everything but specific words
print(re.sub('(.+?)(going|you|$)', subit, s))
get a utf-8 string literal representation of byte string `x`
"""x = {}""".format(x.decode('utf8')).encode('utf8')
find all the occurrences of a character in a string
[x.start() for x in re.finditer('\\|', str)]
python: confusions with urljoin
urljoin('http://some/more/', '/thing')
how can i concatenate a series onto a dataframe with pandas?
pd.concat([students, pd.DataFrame(marks)], axis=1)
distance between numpy arrays, columnwise
arr2.T[numpy.array(zip(list(range(0, 3)), list(range(1, 4))))]
how do i make python to wait for a pressed key
input('Press Enter to continue...')
does anybody know of a good example of functional testing a python tkinter application?
Mainscreen()
taking a screenshot with pyglet [fix'd]
pyglet.app.run()
deploy flask app as windows service
app.run(host='192.168.1.6')
throw an exception with message 'this is the exception you expect to handle'
raise Exception('This is the exception you expect to handle')
fors in python list comprehension
[y for y in x for x in data]
finding index of an item closest to the value in a list that's not entirely sorted
min(list(range(len(a))), key=lambda i: abs(a[i] - 11.5))
python - how to sort a list of lists by the fourth element in each list?
unsorted_list.sort(key=lambda x: x[3])
trimming a string " hello\n" by space
' Hello\n'.strip(' ')
python "extend" for a dictionary
a.update(b)
delete items from list `my_list` if the item exist in list `to_dell`
my_list = [[x for x in sublist if x not in to_del] for sublist in my_list]
anchor or lock text to a marker in matplotlib
plt.show()
sql alchemy - how to delete from a model instance?
session.delete(instance)
get a relative path of file 'my_file' into variable `fn`
fn = os.path.join(os.path.dirname(__file__), 'my_file')
get a list `mylist` from 1 to 10
myList = [i for i in range(10)]
pandas groupby: how to get a union of strings
df.groupby('A')['C'].apply(lambda x: '{%s}' % ', '.join(x))
python: passing a function name as an argument in a function
var = dork1
convert string '2011221' into a datetime object using format '%y%w%w'
datetime.strptime('2011221', '%Y%W%w')
pyramid on app engine gets "invalidresponseerror: header values must be str, got 'unicode'
self.redirect('/home.view')
howto determine file owner on windows using python without pywin32
subprocess.call('dir /q', shell=True)
how can i parse a comma delimited string into a list (caveat)?
['test, a', 'foo,bar",baz', 'bar \xc3\xa4 baz']
download a remote image and save it to a django model
imgfile = models.ImageField(upload_to='images/%m/%d')
convert js date object 'tue, 22 nov 2011 06:00:00 gmt' to python datetime
datetime.strptime('Tue, 22 Nov 2011 06:00:00 GMT', '%a, %d %b %Y %H:%M:%S %Z')
is there a way to use two if conditions in list comprehensions in python
[i for i in my_list if not i.startswith(('91', '18'))]
creating a dictionary with list of lists in python
inlinkDict[docid] = adoc[1:] if adoc[1:] else 0
random strings in python
return ''.join(random.choice(string.lowercase) for i in range(length))
how to create a python dictionary with double quotes as default quote format?
print('{%s}' % ', '.join([('"%s": "%s"' % (k, v)) for k, v in list(pairs.items())]))
how to compress with 7zip instead of zip, code changing
subprocess.call(['7z', 'a', filename + '.7z', '*.*'])
how to convert a python set to a numpy array?
numpy.array(list(c))
how do i move the last item in a list to the front in python?
a = a[-1:] + a[:-1]
django - get distinct dates from timestamp
return qs.values('date').annotate(Sum('amount')).order_by('date')
splitting a string based on a certain set of words
result.extend(re.split('_(?:f?or|and)_', s))
set environment variable in python script
os.environ['LD_LIBRARY_PATH'] = 'my_path'
declare an array with element 'i'
intarray = array('i')
how to check for palindrome using python logic
str(n) == str(n)[::-1]
combining rows in pandas
df.groupby(df.index).sum()
check for a valid domain name in a string?
"""[a-zA-Z\\d-]{,63}(\\.[a-zA-Z\\d-]{,63})*"""