text stringlengths 4 1.08k |
|---|
how to split a unicode string into list,list(stru.decode('utf-8')) |
python: sort a list of lists by an item in the sublist,"sorted(a, key=lambda x: x[1], reverse=True)" |
repeat every character for 7 times in string 'map',""""""""""""".join(map(lambda x: x * 7, 'map'))" |
how to draw a line outside of an axis in matplotlib (in figure coordinates)?,"ax.plot(x, y, label='a')" |
is there a way to control a webcam focus in pygame?,os.system('v4l2-ctl -d 0 -c focus_absolute=250') |
"create a dictionary `{'spam': 5, 'ham': 6}` into another dictionary `d` field 'dict3'","d['dict3'] = {'spam': 5, 'ham': 6}" |
how can i make this timer run forever?,time.sleep(30.0) |
check if all lists in list `l` have three elements of integer 1,all(x.count(1) == 3 for x in L) |
filter a django model `mymodel` to have charfield length of max `255`,MyModel.objects.extra(where=['CHAR_LENGTH(text) > 254']) |
showing the stack trace from a running python application,"os.kill(pid, signal.SIGUSR1)" |
can i change socks proxy within a function using socksipy?,sck.setproxy() |
how can i turn 000000000001 into 1?,"int('08', 10)" |
how to change the stdin encoding on python,sys.stdout = codecs.getwriter('utf-8')(sys.stdout) |
printing a list using python,"print('[', ', '.join(repr(i) for i in list), ']')" |
changing the values of the diagonal of a matrix in numpy,"A.ravel()[i:max(0, A.shape[1] - i) * A.shape[1]:A.shape[1] + 1]" |
creating a json response using django and python,return JsonResponse({'foo': 'bar'}) |
how to convert hex string to hex number?,"print('%x' % int('2a', 16))" |
convert decimal integer 8 to a list of its binary values as elements,[int(x) for x in list('{0:0b}'.format(8))] |
sort a list `unsorted_list` based on another sorted list `presorted_list`,"sorted(unsorted_list, key=presorted_list.index)" |
convert pandas group by object to multi-indexed dataframe with indices 'name' and 'destination',"df.set_index(['Name', 'Destination'])" |
scatter plot and color mapping in python,"plt.scatter(x, y, c=t, cmap='jet')" |
convert generator object to a dictionary,"dict((i, i * 2) for i in range(10))" |
numpy list comprehension syntax,"[[X[i, j] for j in range(X.shape[1])] for i in range(x.shape[0])]" |
sorting dictionary keys based on their values,"[k for k, v in sorted(list(mydict.items()), key=lambda k_v: k_v[1][1])]" |
"combine two lists `[1, 2, 3, 4]` and `['a', 'b', 'c', 'd']` into a dictionary","dict(zip([1, 2, 3, 4], ['a', 'b', 'c', 'd']))" |
parse and format the date from the github api in python,"date.strftime('%A %b %d, %Y at %H:%M GMT')" |
order a list by all item's digits in python,"sorted(myList, key=dist)" |
how do i use user input to invoke a function in python?,"{'func1': func1, 'func2': func2, 'func3': func3}.get(choice)()" |
set colorbar range in matplotlib,plt.show() |
reset the indexes of a pandas data frame,df2 = df.reset_index() |
python selenium: find object attributes using xpath,"browser.find_elements_by_xpath(""//*[@type='submit']/@value"").text" |
python: split string with multiple delimiters,"re.split('; |, |\\*|\n', a)" |
how to override template in django-allauth?,"TEMPLATE_DIRS = os.path.join(BASE_DIR, 'cms', 'templates', 'allauth')," |
summing across rows of pandas dataframe,"df.groupby(['stock', 'same1', 'same2'])['positions'].sum().reset_index()" |
how can i create the empty json object in python,data = json.loads(request.POST['mydata']) if 'mydata' in request.POST else {} |
how can i check if a date is the same day as datetime.today()?,yourdatetime.date() < datetime.today().date() |
reading a file in python,"reader = csv.reader(open('filename'), delimiter='\t')" |
convert a string to integer with decimal in python,int(s.split('.')[0]) |
sort list of lists `l` by the second item in each list,L.sort(key=operator.itemgetter(1)) |
how do i write a python http server to listen on multiple ports?,server.serve_forever() |
calculate the date six months from the current date,print((datetime.date.today() + datetime.timedelta(((6 * 365) / 12))).isoformat()) |
numpy list comprehension syntax,"[[X[i, j] for i in range(X.shape[0])] for j in range(x.shape[1])]" |
send data 'http/1.0 200 ok\r\n\r\n' to socket `connection`,connection.send('HTTP/1.0 200 OK\r\n\r\n') |
change timezone of date-time column in pandas and add as hierarchical index,"dataframe.tz_localize('UTC', level=0)" |
how to select increasing elements of a list of tuples?,"a = [a[i] for i in range(1, len(a)) if a[i][1] > a[i - 1][1]]" |
how to add multiple values to a dictionary key in python?,a[key].append(1) |
matplotlib 3d scatter plot with colorbar,"p = ax.scatter(xs, ys, zs, c=cs, marker=m)" |
circular pairs from array?,"[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 1)]" |
python requests multipart http post,"requests.post(url, headers=headers, files=files, data=data)" |
django csrf check failing with an ajax post request,"request_csrf_token = request.META.get('HTTP_X_CSRFTOKEN', '')" |
pandas convert 'na' to nan,pd.read_csv('test') |
how to apply linregress in pandas bygroup,"grouped.apply(lambda x: linregress(x['col_X'], x['col_Y']))" |
split a string `s` at line breaks `\r\n`,"[map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]" |
get the indices of tuples in list of tuples `l` where the first value is 53,"[i for i, v in enumerate(L) if v[0] == 53]" |
how to properly get url for the login view in template?,"url('^login/$', views.login, name='login')," |
inserting json into mysql using python,db.execute('INSERT INTO json_col VALUES (' + json_value + ')') |
"python, checksum of a dict","from functools import reduce |
reduce(lambda x, y: x ^ y, [hash(item) for item in list(d.items())])" |
plotting unix timestamps in matplotlib,ax.xaxis.set_major_formatter(xfmt) |
sort list `alist` in ascending order based on each of its elements' attribute `foo`,alist.sort(key=lambda x: x.foo) |
count rows that match string and numeric with pandas,df.MUT.str.extract('A:(T)|A:(G)|A:(C)|A:(-)') |
update and create a multi-dimensional dictionary in python,d['js'].append({'other': 'thing'}) |
how do i add custom field to python log format string?,"logging.info('Log message', extra={'app_name': 'myapp'})" |
multiple lines of x tick labels in matplotlib,ax.set_xticklabels(xlbls) |
"numpy, how to get a sub matrix with boolean slicing","np.array(m2)[:, (1)] > 10" |
keeping nans with pandas dataframe inequalities,df.isnull() |
turning string with embedded brackets into a dictionary,"print(dict(re.findall('\\{(\\S+)\\s+\\{*(.*?)\\}+', x)))" |
split three-digit integer to three-item list of each digit in python,[int(char) for char in str(634)] |
how to work with surrogate pairs in python?,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')" |
how do i change the range of the x-axis with datetimes in matplotlib?,fig.autofmt_xdate() |
how do i convert unicode code to string in python?,print(text.decode('unicode-escape')) |
using nx.write_gexf in python for graphs that have dict data on nodes and edges,"G.add_edge(0, 1, likes=['milk', 'oj'])" |
slice assignment with a string in a list,my_list[0] = 'cake' |
numpy indexerror: too many indices for array when indexing matrix with another,"matrix([[1, 2, 3], [7, 8, 9], [10, 11, 12]])" |
"how do i serialize a python dictionary into a string, and then back to a dictionary?",json.loads(_) |
python sum of ascii values of all characters in a string,"sum(map(ord, string))" |
how to change the 'tag' when logging to syslog from 'unknown'?,log.info('FooBar') |
removing backslashes from a string in python,"result.replace('\\', '')" |
django - csrf verification failed,"return render(request, 'contact.html', {form: form})" |
how can i increase the frequency of xticks/ labels for dates on a bar plot?,plt.show() |
how to split sub-lists into sub-lists k times? (python),"split_list([1, 2, 3, 4, 5, 6, 7, 8], 2)" |
find maximum value of a column and return the corresponding row values using pandas,df = df.reset_index() |
"python server ""only one usage of each socket address is normally permitted""","s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)" |
trying to count words in a string,"re.split('[^0-9A-Za-z]+', strs)" |
what is the most pythonic way to avoid specifying the same value in a string,"""""""hello {name}, how are you {name}, welcome {name}"""""".format(name='john')" |
converting a string into dictionary python,json.loads(s) |
histogram equalization for python,"plt.imshow(im2, cmap=plt.get_cmap('gray'))" |
python: find the absolute path of an imported module,os.path.abspath(math.__file__) |
using terminal command to search through files for a specific string within a python script,os.chdir('..') |
how do i convert a string 2 bytes long to an integer in python,"struct.unpack('h', pS[0:2])" |
plotting seismic wiggle traces using matplotlib,plt.show() |
how to plot multiple histograms on same plot with seaborn,"plt.hist([x, y], color=['r', 'b'], alpha=0.5)" |
max in a list with two conditions,"max((t for t in yourlist if t[2] >= 100), key=itemgetter(1))" |
scatter plot in matplotlib,matplotlib.pyplot.show() |
python regular expressions - how to capture multiple groups from a wildcard expression?,"re.findall('\\w', 'abcdefg')" |
how to generate random number of given decimal point between 2 number in python?,"decimal.Decimal('%d.%d' % (random.randint(0, i), random.randint(0, j)))" |
how to use the pipe operator as part of a regular expression?,"re.findall('[^ ]*.(?:cnn|espn).[^ ]*', u1)" |
how to close a program using python?,os.system('TASKKILL /F /IM firefox.exe') |
drop the rows in pandas timeseries `df` from the row containing index `start_remove` to the row containing index `end_remove`,df.loc[(df.index < start_remove) | (df.index > end_remove)] |
get parent of current directory from python script,d = os.path.dirname(os.getcwd()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.