text
stringlengths
4
1.08k
how to find row of 2d array in 3d numpy array,"np.argwhere(np.all(arr == [[0, 3], [3, 0]], axis=(1, 2)))"
evaluate a nested dictionary `myobject.id.number` to get `number` if `myobject` is present with getattr,"getattr(getattr(myobject, 'id', None), 'number', None)"
"python, print all floats to 2 decimal places in output","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))"
how to group similar items in a list?,"[list(g) for _, g in itertools.groupby(test, lambda x: x.partition('_')[0])]"
how to extract numbers from filename in python?,[int(x) for x in regex.findall(filename)]
how to run scrapy from within a python script,reactor.run()
plot on top of seaborn clustermap,plt.show()
print first key value in an ordered counter,c.most_common(1)
sort list `l` based on the value of variable 'resulttype' for each object in list `l`,"sorted(L, key=operator.itemgetter('resultType'))"
how to retrieve sql result column value using column name in python?,"print('%s, %s' % (row['name'], row['category']))"
convert string to numpy array,"np.array(map(int, '100110'))"
sum one number to every element in a list (or array) in python,"map(lambda x: x + 1, L)"
save json output from a url 'http://search.twitter.com/search.json?q=hi' to file 'hi.json' in python 2,"urllib.request.urlretrieve('http://search.twitter.com/search.json?q=hi', 'hi.json')"
pandas: join with outer product,demand.ix['Com'].apply(lambda x: x * areas['Com']).stack()
how to insert string to each token of a list of strings?,l = [i.split() for i in l]
"matplotlib, define size of a grid on a plot",plt.show()
sum the length of lists in list `x` that are more than 1 item in length,sum(len(y) for y in x if len(y) > 1)
representing a multi-select field for weekdays in a django model,"Entry.objects.extra(where=['weekdays & %s'], params=[WEEKDAYS.fri])"
how to bind self events in tkinter text widget after it will binded by text widget?,root.mainloop()
how can i split a string and form a multi-level nested dictionary?,"from functools import reduce
reduce(lambda res, cur: {cur: res}, reversed('foo/bar/baz'.split('/')), 1)"
how to plot a gradient color line in matplotlib?,plt.show()
all combinations of a list of lists,list(itertools.product(*a))
printing each item of a variable on a separate line in python,"print('\n'.join(map(str, ports)))"
deleting columns in a csv with python,"wtr.writerow((r[0], r[1], r[3], r[4]))"
how to share the global app object in flask?,app = Flask(__name__)
"convert date string 'january 11, 2010' into day of week","datetime.datetime.strptime('January 11, 2010', '%B %d, %Y').strftime('%A')"
"how do you determine if an ip address is private, in python?",ip.iptype()
parse html table with python beautifulsoup,"soup.find_all('td', attrs={'bgcolor': '#FFFFCC'})"
the most efficient way to remove first n elements in a python list?,"[6, 7, 8, 9]"
django filter jsonfield list of dicts,Test.objects.filter(actions__contains=[{'fixed_key_3': [{'key1': 'foo2'}]}])
passing on named variable arguments in python,"methodB('argvalue', **kwargs)"
reshape array in numpy,"data = np.transpose(data, (0, 3, 1, 2))"
python cant find module in the same folder,sys.path.append('/path/to/2014_07_13_test')
find average of every three columns in pandas dataframe,"res = df.resample('Q', axis=1).mean()"
python global variable with thread,time.sleep(1)
fill in time data in pandas,"a.resample('15S', loffset='5S')"
how to iterate over a range of keys in a dictionary?,list(d.keys())
find the last substring after a character,"""""""foo:bar:baz:spam:eggs"""""".rsplit(':', 3)"
retrieve the path from a flask request,request.url
python regex for hyphenated words,"re.findall('\\w+(?:-\\w+)+', text)"
"create a matrix from a list `[1, 2, 3]`","x = scipy.matrix([1, 2, 3]).transpose()"
"pandas lookup, mapping one column in a dataframe to another in a different dataframe","df1 = df1.merge(df2[['weeknum', 'datetime']], on=['weeknum'])"
how do you set up a flask application with sqlalchemy for testing?,SQLALCHEMY_DATABASE_URI = 'postgresql://user:pw@localhost/somedb'
iterating over a dictionary `d` using for loops,"for (key, value) in d.items():
pass"
iterating over a dictionary to create a list,"['blue', 'blue', 'red', 'red', 'green']"
how to pass django rest framework response to html?,"return Response(data, template_name='articles.html')"
determine if checkbox with id '<check_box_id>' is checked in selenium python webdriver,driver.find_element_by_id('<check_box_id>').is_selected()
get index of the top n values of a list in python,"sorted(list(range(len(a))), key=lambda i: a[i], reverse=True)[:2]"
how to print like printf in python3?,print('Hi')
how to delete an item in a list if it exists?,some_list.remove(thing)
request url `url` using http header `{'referer': my_referer}`,"requests.get(url, headers={'referer': my_referer})"
"remove string ""1"" from string `string`","string.replace('1', '')"
return a random word from a word list in python,random.choice(list(open('/etc/dictionaries-common/words')))
merging 2 lists in multiple ways - python,"itertools.permutations([0, 0, 0, 0, 1, 1, 1, 1])"
create a new 2 dimensional array containing two random rows from array `a`,"A[(np.random.randint(A.shape[0], size=2)), :]"
reverse a string in python without using reversed or [::-1],""""""""""""".join(reverse('hello'))"
divide elements in list `a` from elements at the same index in list `b`,"[(x / y) for x, y in zip(a, b)]"
group a pandas data frame by monthly frequenct `m` using groupby,df.groupby(pd.TimeGrouper(freq='M'))
why would i ever use anything else than %r in python string formatting?,"'Repr:%r Str:%s' % ('foo', 'foo')"
get the name of function `func` as a string,print(func.__name__)
how to write custom python logging handler?,logger.setLevel(logging.DEBUG)
how can i open files in external programs in python?,webbrowser.open(filename)
best way to return a value from a python script,sys.exit(0)
parsing string containing unicode character names,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape')
a better way to assign list into a var,starf = [int(i) for i in starf]
call bash command 'tar c my_dir | md5sum' with pipe,"subprocess.call('tar c my_dir | md5sum', shell=True)"
erase the contents of a file `filename`,"open('filename', 'w').close()"
sort a pandas data frame by column `peak` in ascending and `weeks` in descending order,"df.sort(['Peak', 'Weeks'], ascending=[True, False], inplace=True)"
how can i add values in the list using for loop in python?,a = int(eval(input('Enter number of players: ')))
django models - how to filter out duplicate values by pk after the fact?,q = Model.objects.filter(Q(field1=f1) | Q(field2=f2)).distinct()
how to find the indexes of matches in two lists,"[i for i, (a, b) in enumerate(zip(vec1, vec2)) if a == b]"
typeerror in django with python 2.7,"MEDIA_ROOT = os.path.join(os.path.dirname(file), 'media').replace('\\\\', '//')"
how to get the length of words in a sentence?,s.split()
"simple, cross platform midi library for python","MyMIDI.addNote(track, channel, pitch, time, duration, volume)"
pandas : assign result of groupby to dataframe to a new column,df.groupby('adult')['weight'].transform('idxmax')
how do i print this list vertically?,print(' '.join(i))
when should i commit with sqlalchemy using a for loop?,db.session.commit()
json datetime between python and javascript,json.dump(datetime.now().strftime('%Y-%m-%dT%H:%M:%S'))
find the full path of current directory,full_path = os.path.realpath(__file__)
passing a list of strings from python to rust,"['blah', 'blah', 'blah', 'blah']"
how can i find script's directory with python?,return os.path.dirname(os.path.realpath(sys.argv[0]))
how can i create an array/list of dictionaries in python?,dictlist = [dict() for x in range(n)]
how to filter model results for multiple values for a many to many field in django,"Group.objects.filter(member__in=[1, 2])"
replace special characters in url 'http://spam.com/go/' using the '%xx' escape,urllib.parse.quote('http://spam.com/go/')
sorting numpy array on multiple columns in python,"rows_list.sort(key=operator.itemgetter(0, 1, 2))"
pythonic way to eval all octal values in a string as integers,"re.sub('\\b0+(?!\\b)', '', '012 + 2 + 0 - 01 + 204 - 0')"
generate a string of numbers separated by comma which is divisible by `4` with remainder `1` or `2`.,""""""","""""".join(str(i) for i in range(100) if i % 4 in (1, 2))"
how do i output a config value in a sphinx .rst file?,rst_epilog = '.. |my_conf_val| replace:: %d' % my_config_value
numpy: efficiently add rows of a matrix,"np.dot(I, np.ones((7,), int))"
changing figure size with subplots,"f, axs = plt.subplots(2, 2, figsize=(15, 15))"
plot histogram in python,plt.show()
how can i color python logging output?,logging.info('some info')
how to convert decimal to binary list in python,list('{0:0b}'.format(8))
split each string in list `mylist` on the tab character,myList = [i.split('\t')[0] for i in myList]
how to efficiently convert matlab engine arrays to numpy ndarray?,np.array(x._data).reshape(x.size[::-1]).T
pandas: how to plot a barchar with dataframes with labels?,"df.set_index(['timestamp', 'objectId'])['result'].unstack()"
convert `i` to string,str(i)
customize x-axis in matplotlib,"plt.xticks(ticks, labels)"