intent
stringlengths 4
183
| snippet
stringlengths 2
1k
|
---|---|
convert variable name to string? | list(globals().keys())[2] |
custom sort an alphanumeric list `l` | sorted(l, key=lambda x: x.replace('0', 'Z')) |
python: script to detect data hazards | line1 = ['ld a8,0x8910', 'mul a3,a2,8', 'shl a3,a3,4', 'add a3,a3,a8'] |
dynamically change widget background color in tkinter | root.mainloop() |
fetch all elements in a dictionary `parent_dict`, falling between two keys 2 and 4 | dict((k, v) for k, v in parent_dict.items() if 2 < k < 4) |
alias for dictionary operation in python | {frozenset([1, 2, 3]): 4, frozenset([1]): 5} |
python matplotlib: plot with 2-dimensional arguments : how to specify options? | plt.show() |
remove special characters from string | unicodedata.normalize('NFKD', source).encode('ascii', 'ignore') |
run flask application `app` in debug mode. | app.run(debug=True) |
python dictionary values sorting | OrderedDict(sorted(list(d.items()), key=d.get)) |
multiprocessing queue in python | procs.append(multiprocessing.Process(target=worker)) |
how do i format a number with a variable number of digits in python? | """One hundred and twenty three with three leading zeros {0:06}.""".format(123) |
concatenate dataframe `df_1` to dataframe `df_2` sorted by values of the column 'y' | pd.concat([df_1, df_2.sort_values('y')]) |
how do i get the modified date/time of a file in python? | os.stat(filepath).st_mtime |
tkinter: how to use after method | root.mainloop() |
get only digits from a string `strs` | """""".join([c for c in strs if c.isdigit()]) |
how to print negative zero in python | print(('%.0f\xb0%.0f\'%.0f"' % (deg, fabs(min), fabs(sec))).encode('utf-8')) |
regular expression matching all but 'aa' and 'bb' for string `string` | re.findall('-(?!aa-|bb-)([^-]+)', string) |
how do you extract a column from a multi-dimensional array? | a = [[1, 2], [2, 3], [3, 4]] |
how can i convert a python dictionary to a list of tuples? | [(k, v) for k, v in a.items()] |
convert letters to lower case | re.sub('[AEIOU]+', lambda m: m.group(0).lower(), 'SOME TEXT HERE') |
how to create an integer array within a recursion? | return foo(n - 1) + [1] |
how do i get the full xml or html content of an element using elementtree? | """""".join([t.text] + [xml.tostring(e) for e in t.getchildren()]) |
is there a way to make the tkinter text widget read only? | text.configure(state='disabled') |
unique plot marker for each plot in matplotlib | plt.show() |
check if any item from list `b` is in list `a` | print(any(x in a for x in b)) |
request http url `url` | r = requests.get(url) |
python max length of j-th item across sublists of a list | [max(len(b) for b in a) for a in zip(*x)] |
how to remove a key from a python dictionary? | my_dict.pop('key', None) |
reading data into numpy array from text file | data = numpy.genfromtxt(yourFileName, skiprows=n) |
calling an external command "some_command with args" | os.system('some_command with args') |
pull a value with key 'name' from a json object `item` | print(item['name']) |
subtract all items in a list against each other | [(1, 1), (2, 2), (3, 4), (1, 1), (2, 3), (1, 2)] |
django: ordered list of model instances from different models? | MediaItem.objects.all().order_by('upload_date').select_subclasses() |
how do i sort a list of strings in python? | mylist.sort(key=lambda x: x.lower()) |
sort a list of dictionary provided an order | sorted(list_of_dct, key=lambda x: order.index(list(x.values())[0])) |
python: how to remove all duplicate items from a list | x = list(set(x)) |
in python, how can i find the index of the first item in a list that is not some value? | return next((i for i, v in enumerate(L) if v != x), -1) |
convert string to dict using list comprehension in python | dict([x.split('=') for x in s.split()]) |
django get all records of related models | Activity.objects.filter(list__topic__user=my_user) |
python: how can i run python functions in parallel? | p.start() |
how can i resize the root window in tkinter? | root.geometry('500x500') |
create sub matrix of a list of lists `[[2, 3, 4], [2, 3, 4], [2, 3, 4]]` (without numpy) | [[2, 3, 4], [2, 3, 4], [2, 3, 4]] |
how can i split a string into tokens? | ['x', '+', '13', '.', '5', '*', '10', 'x', '-', '4', 'e', '1'] |
how to subquery in queryset in django? | people2 = Person.objects.filter(employee__company='Private') |
how can i make an animation with contourf()? | plt.show() |
how can i insert data into a mysql database? | db.close() |
how to iterate over columns of pandas dataframe to run regression | df1.ix[0, 1] |
taking the floor of a float | int(3.1415) |
datetime objects format | print(mydate.strftime('%Y-%m-%d')) |
calcuate mean for selected rows for selected columns in pandas data frame | df[['b', 'c']].iloc[[2, 4]].mean(axis=0) |
how to change the color of a single bar if condition is true matplotlib | plt.show() |
how to open a url in python | webbrowser.open('http://example.com') |
how to get the url address from upper function in scrapy? | yield Request(url=url, callback=self.parse, meta={'page': 1}) |
zip lists in python | zip(a, b, c) |
sorting the content of a dictionary by the value and by the key | sorted(list(d.items()), key=lambda x: x[::-1]) |
python dict comprehension with two ranges | {k: v for k, v in zip(range(1, 5), count(7))} |
plot a (polar) color wheel based on a colormap using python/matplotlib | display_axes.set_rlim([-1, 1]) |
how do you read tensorboard files programmatically? | ea.Scalars('Loss') |
how to send a session message to an anonymous user in a django site? | request.session['message'] = 'Some Error Message' |
how to i disable and re-enable console logging in python? | logging.critical('This is a critical error message') |
open the file 'words.txt' in 'ru' mode | f = open('words.txt', 'rU') |
merge two or more lists with given order of merging | list(ordered_merge([[3, 4], [1, 5], [2, 6]], [1, 2, 0, 0, 1, 2])) |
qdialog not opening from main window (pyqt) | self.pushButton.clicked.connect(self.showDial) |
specific shuffling list in python | ['e', 'b', 'f', 'c', 'a', 'd'] |
python pandas - how to flatten a hierarchical index in columns | [' '.join(col).strip() for col in df.columns.values] |
python regex search and split | re.split('(d(d)d)', 'aaa bbb ccc ddd eee fff', 1) |
how to calculate cointegrations of two lists? | b = [5.23, 6.1, 8.3, 4.98] |
remove dictionary from list `a` if the value associated with its key 'link' is in list `b` | a = [x for x in a if x['link'] not in b] |
how to exclude a character from a regex group? | re.compile('[^a-zA-Z0-9-]') |
how do i parse a vcard to a python dictionary? | vobj.adr |
pandas: joining items with same index | df.assign(id=df.groupby([0]).cumcount()).set_index(['id', 0]).unstack(level=1) |
pandas to_csv call is prepending a comma | df.to_csv('c:\\data\\t.csv') |
pupil detection in opencv & python | contour = cv2.convexHull(contour) |
obtain the current day of the week in a 3 letter format from a datetime object | datetime.datetime.now().strftime('%a') |
reverse a string in python | l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
create ntfs junction point in python | kdll.CreateSymbolicLinkA('d:\testdir', 'd:\testdir_link', 1) |
twitter streaming api with tweepy rejects oauth | auth.set_access_token(access_token, access_token_secret) |
regular expression to match a dot | re.findall('(\\w+[.]\\w+)@', s) |
is there a numpy function to return the first index of something in an array? | array[itemindex[0][1]][itemindex[1][1]] |
how do i watch a file for changes using python? | os.stat(filename).st_mtime |
how to create only one table with sqlalchemy? | Base.metadata.tables['ticket_daily_history'].create(bind=engine) |
python: how to make a list of n numbers and randomly select any number? | mylist = list(range(10)) |
how to attach debugger to a python subproccess? | ForkedPdb().set_trace() |
comparing values in two lists in python | z = [(i == j) for i, j in zip(x, y)] |
check if string contains a certain amount of words of another string | re.findall('(?=(\\b\\w+\\s\\b\\w+))', st) |
replacing 'abc' and 'ab' values in column 'brandname' of dataframe `df` with 'a' | df['BrandName'].replace(['ABC', 'AB'], 'A') |
how to encode integer in to base64 string in python 3 | base64.b64encode('1'.encode()) |
matplotlib: two y-axis scales, how to align gridlines? | plt.show() |
multiplying a tuple by a scalar | tuple([(10 * x) for x in img.size]) |
json load/dump in python | the_dump = json.dumps(['foo', {'bar': ['baz', None, 1.0, 2]}]) |
sorting a text file alphabetically (python) | lines.sort() |
select value from list of tuples where condition | results = [t[1] for t in mylist if t[0] == 10] |
subprocess run command 'start command -flags arguments' through the shell | subprocess.call('start command -flags arguments', shell=True) |
how can i replace all the nan values with zero's in a column of a pandas dataframe | df.fillna(0) |
in django, filter `task.objects` based on all entities in ['a', 'p', 'f'] | Task.objects.exclude(prerequisites__status__in=['A', 'P', 'F']) |
plotting a 3d surface from a list of tuples in matplotlib | plt.show() |
python: how can i include the delimiter(s) in a string split? | ['(', 'two', 'plus', 'three', ')', 'plus', 'four'] |
python regex replace | new_string = re.sub('"(\\d+),(\\d+)"', '\\1.\\2', original_string) |
login to a site using python and opening the login site in the browser | webbrowser.open('http://somesite.com/adminpanel/index.php') |