intent
stringlengths
4
183
snippet
stringlengths
2
1k
how to use os.umask() in python
os.close(fh2)
how to build and fill pandas dataframe from for loop?
pd.DataFrame(d)
list of ints into a list of tuples python
print(zip(my_list[0::2], my_list[1::2]))
add a path `/path/to/2014_07_13_test` to system path
sys.path.append('/path/to/2014_07_13_test')
string formatting in python: can i use %s for all types?
"""Integer: {}; Float: {}; String: {}""".format(a, b, c)
python . how to get rid of '\r' in string?
line.strip()
can i set user-defined variable in python mysqldb?
cursor.execute('SELECT @X:=@X+1 FROM some_table')
python: value of dictionary is list of strings
ast.literal_eval(reclist)
how to save the pandas dataframe/series data as a figure?
fig.savefig('asdf.png')
extract date from a string 'monkey 20/01/1980 love banana'
dparser.parse('monkey 20/01/1980 love banana', fuzzy=True)
numpy int array: find indices of multiple target ints
np.where(np.in1d(values, searchvals))
list duplicated elements in two lists `lista` and `listb`
list(set(listA) & set(listB))
convert pandas dataframe `df` to a dictionary using `id` field as the key
df.set_index('id').to_dict()
how to change fontsize in excel using python
worksheet.write(1, 0, label='Formatted value', style=style)
strip html from strings in python
re.sub('<[^<]+?>', '', text)
using selenium in python to click/select a radio button
browser.find_elements_by_css("input[type='radio'][value='SRF']").click
driver python for postgresql
session.commit()
get value at index `[2, 0]` in dataframe `df`
df.iloc[2, 0]
convert binary string to numpy array
np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')
transpose a matrix in python
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
remove identical items from list `my_list` and sort it alphabetically
sorted(set(my_list))
how to convert from boolean array to int array in python
new_data = np.vectorize(boolstr_to_floatstr)(data).astype(float)
using pyodbc on ubuntu to insert a image field on sql server
cur.execute('SET TEXTSIZE 2147483647 SELECT myimage FROM testing WHERE id = 1')
unescaping characters in a string with python
"""\\u003Cp\\u003E""".decode('unicode-escape')
how to find duplicate elements in array using for loop in python?
[i for i in y if y[i] == 1]
indirect inline in django admin
admin.site.register(User, UserAdmin)
anaphoric list comprehension in python
[s for s in (square(x) for x in range(12)) if s > 50]
parsing json with python: blank fields
entries['extensions'].get('telephone')
restart a computer after `900` seconds using subprocess
subprocess.call(['shutdown', '/r', '/t', '900'])
numpy: unexpected result when dividing a vertical array by one of its own elements
x = np.random.rand(5, 1)
regular expression syntax for "match nothing"?
re.compile('$^')
applying functions to groups in pandas dataframe
df.groupby('type').apply(foo)
extracting a number from a 1-word string
[int(s) for s in I.split() if s.isdigit()]
creating a matrix of options using itertools
itertools.product([False, True], repeat=5)
converting integer to list in python
map(int, str(num))
python print unicode doesn't show correct symbols
print(myunicode.encode('utf-8'))
how can i programmatically authenticate a user in django?
return HttpResponseRedirect('/splash/')
how do i remove whitespace from the end of a string in python?
""" xyz """.rstrip()
how to clear os.environ value for only one variable in python
os.environ.pop('PYTHONHOME')
python sort multidimensional array based on 2nd element of subarray
sorted(lst, key=operator.itemgetter(1), reverse=True)
in python 2.4, how can i execute external commands with csh instead of bash?
os.system("zsh -c 'echo $0'")
reading tab delimited csv into numpy array with different data types
np.genfromtxt(txt, delimiter='\t', dtype='str')
replace only first occurence of string `test` from a string `longlongteststringtest`
'longlongTESTstringTEST'.replace('TEST', '?', 1)
how to annotate text along curved lines in python?
plt.xlabel('X')
how to close a tkinter window by pressing a button?
window.destroy()
how to retrieve row and column names from data frame?
cmat.stack().to_frame('item').query('.3 < item < .9')
get keys from a dictionary 'd' where the value is '1'.
print([key for key, value in list(d.items()) if value == 1])
convert nan values to 'n/a' while reading rows from a csv `read_csv` with pandas
df = pd.read_csv('my.csv', na_values=['n/a'])
finding index of the same elements in a list
[i for i in range(len(word)) if word[i] == letter]
delete all occureces of `8` in each string `s` in list `lst`
print([s.replace('8', '') for s in lst])
how do i include unicode strings in python doctests?
mylen('\xe1\xe9\xed\xf3\xfa')
how can i create stacked line graph with matplotlib?
plt.show()
remove nan from pandas series
s.dropna()
django: grab a set of objects from id list (and sort by timestamp)
objects = Model.objects.filter(id__in=object_ids).order_by('-timestamp')
how to create a password entry field using tkinter
myEntry.config(show='*')
getting a dictionary value where part of the key is in a string
{i: functools.reduce(dict.__getitem__, keys, d[i]) for i in d}
python combining two logics of map()
map(partial(f, x), y) == map(f, [x] * len(y), y)
replace part of a string in python?
stuff.replace(' and ', '/')
format a string `u'andr\xc3\xa9'` that has unicode characters
"""""".join(chr(ord(c)) for c in 'Andr\xc3\xa9')
python matplotlib - how to specify values on y axis?
plt.plot(x, y)
creating dictionary from space separated key=value string in python
{k: v.strip('"') for k, v in re.findall('(\\S+)=(".*?"|\\S+)', s)}
regular expression "^(.+)\\n((?:\\n.+)+)" matching a multiline block of text
re.compile('^(.+)\\n((?:\\n.+)+)', re.MULTILINE)
redirect prints to log file
logging.info('hello')
stack bar plot in matplotlib and add label to each section (and suggestions)
plt.show()
opposite of melt in python pandas
origin.pivot(index='label', columns='type')['value']
replace duplicate values across columns in pandas
pd.Series(['M', '0', 'M', '0']).duplicated()
can a python method check if it has been called from within itself?
foo()
reading a csv into pandas where one column is a json string
df = pandas.read_csv(f1, converters={'stats': CustomParser}, header=0)
return a random word from a word list in python
return random.choice(words)
sending a file over tcp sockets in python
s.send('Hello server!')
merging a python script's subprocess' stdout and stderr while keeping them distinguishable
tsk = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
how to format print output into fixed width?
"""{0: >5}""".format('ss')
a list as a key for pyspark's reducebykey
rdd.map(lambda k_v: (tuple(k_v[0]), k_v[1])).groupByKey()
get the directory path of absolute file path in python
os.path.dirname(fullpath)
how to delete everything after a certain character in a string?
s = s.split('.zip', 1)[0] + '.zip'
sort a multidimensional list by a variable number of keys
a.sort(key=operator.itemgetter(2, 3))
how do i fill two (or more) numpy arrays from a single iterable of tuples?
arr.sort(order=['f0', 'f1'])
removing the first folder in a path
os.path.join(*x.split(os.path.sep)[2:])
convert generator object to a dictionary
{i: (i * 2) for i in range(10)}
python - fastest way to check if a string contains specific characters in any of the items in a list
[(e in lestring) for e in lelist if e in lestring]
regex for removing data in parenthesis
item = re.sub(' ?\\(\\w+\\)', '', item)
can you create a python list from a string, while keeping characters in specific keywords together?
['x', 'y', 'z', 'car', 'bus', 'a', 'b', 'c', 'car', '!']
get list of string elements in string `data` delimited by commas, putting `0` in place of empty strings
[(int(x) if x else 0) for x in data.split(',')]
how to remove duplicates from a dataframe?
df = pd.DataFrame({'a': [1, 2, 3, 3, 3], 'b': [1, 2, None, 1, None]})
python pandas: drop rows of a timeserie based on time range
pd.concat([df[:start_remove], df[end_remove:]])
removing backslashes from string
print("\\I don't know why ///I don't have the right answer\\".strip('/'))
how do i step through/debug a python web application?
pdb.set_trace()
python: one-liner to perform an operation upon elements in a 2d array (list of lists)?
[list(map(int, x)) for x in values]
how to count the total number of lines in a text file using python
count = sum(1 for line in myfile if line.rstrip('\n'))
two combination lists from one list
print([[l[:i], l[i:]] for i in range(1, len(l))])
grouping pandas dataframe by n days starting in the begining of the day
df['dateonly'] = df['time'].apply(lambda x: x.date())
python/matplotlib - is there a way to make a discontinuous axis?
ax.set_xlim(0, 1)
empty a list `lst`
lst[:] = []
how can i get an array of alternating values in python?
np.resize([1, -1], 10)
splitting a string with multiple delimiters in python
re.split('[,;]+', 'This,is;a,;string')
how to create a numpy array of all true or all false?
array([[True, True], [True, True]], dtype=bool)
sort list of date strings
sorted(d, key=lambda x: datetime.datetime.strptime(x, '%m-%Y'))
draw a line correlating zones between multiple subplots in matplotlib
plt.show()
create tuples containing elements that are at the same index of list `lst` and list `lst2`
[(i, j) for i, j in zip(lst, lst2)]
how do you programmatically set an attribute in python?
setattr(x, attr, 'magic')