text
stringlengths 4
1.08k
|
|---|
how can i convert literal escape sequences in a string to the corresponding bytes?,"""""""\\xc3\\x85a"""""".encode('utf-8').decode('unicode_escape').encode('latin-1')"
|
python counting with str and int,"count1 = int(config.get('Counter', 'count1'))"
|
how to generate all permutations of a list in python,"[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]"
|
how to sort multidimensional array by column?,"sorted(a, key=lambda x: x[1])"
|
how to set the current working directory in python?,os.chdir(path)
|
splitting a string based on tab in the file,"re.split('\\t+', yas.rstrip('\t'))"
|
python reversing an utf-8 string,b = a.decode('utf8')[::-1].encode('utf8')
|
python continuously parse console input,sys.stdin.read(1)
|
building a matrix with a generator,"[[0, -1, -2], [1, 0, -1], [2, 1, 0]]"
|
how to pause and wait for command input in a python script,variable = input('input something!: ')
|
passing newline within string into a python script from the command line,"print(string.replace('\\n', '\n'))"
|
split a string `s` into integers,l = (int(x) for x in s.split())
|
how to index nested lists in python?,[tup[0] for tup in A]
|
python imaging library save function syntax,im.save('my_image.png')
|
compare lists with other lists for elements in preserved order,return set(zip(*[lst[i:] for i in range(n)]))
|
find monday's date with python,today - datetime.timedelta(days=today.weekday())
|
how do i draw a grid onto a plot in python?,plt.grid(True)
|
how to convert a boolean array to an int array,y = x.astype(int)
|
django orm way of going through multiple many-to-many relationship,Toy.objects.filter(toy_owners__parents=parent)
|
how to use matplotlib tight layout with figure?,plt.show()
|
efficient way to convert a list to dictionary,"dict(map(lambda s: s.split(':'), ['A:1', 'B:2', 'C:3', 'D:4']))"
|
how to display the value of the bar on each bar with pyplot.barh()?,plt.show()
|
python: filter list of list with another list,result = [x for x in list_a if x[0] in list_b]
|
how to remove all the punctuation in a string? (python),"out = ''.join(c for c in asking if c not in ('!', '.', ':'))"
|
how to check if one of the following items is in a list?,S1.intersection(S2)
|
convert each list in list `main_list` into a tuple,"map(list, zip(*main_list))"
|
is it possible to plot timelines with matplotlib?,ax.xaxis.set_ticks_position('bottom')
|
how do you calculate the greatest number of repetitions in a list?,"print(max(result, key=lambda a: a[1]))"
|
how do you get a directory listing sorted by creation date in python?,files.sort(key=lambda x: os.path.getmtime(x))
|
parse a file `sample.xml` using expat parsing in python 3,"parser.ParseFile(open('sample.xml', 'rb'))"
|
how to filter a dictionary in python?,"{i: 'updated' for i, j in list(d.items()) if j != 'None'}"
|
efficiently change a key of a python dict,"a_send = dict((k[0], v) for k, v in list(a.items()))"
|
how to reliably open a file in the same directory as a python script,"f = open(os.path.join(__location__, 'bundled-resource.jpg'))"
|
how to create an ec2 instance using boto3,"ec2.create_instances(ImageId='<ami-image-id>', MinCount=1, MaxCount=5)"
|
how to get yesterday in python,datetime.datetime.now() - datetime.timedelta(days=1)
|
convert a list of integers into a single integer,"r = int(''.join(map(str, x)))"
|
how to get alpha value of a png image with pil?,alpha = img.convert('RGBA').split()[-1]
|
get biggest 3 values from each column of the pandas dataframe `data`,"data.apply(lambda x: sorted(x, 3))"
|
how to pull a random record using django's orm?,MyModel.objects.order_by('?').first()
|
"sum the column `positions` along the other columns `stock`, `same1`, `same2` in a pandas data frame `df`","df.groupby(['stock', 'same1', 'same2'], as_index=False)['positions'].sum()"
|
matplotlib problems plotting logged data and setting its x/y bounds,plt.show()
|
how do i display real-time graphs in a simple ui for a python program?,plt.show()
|
remove the first word in a python string?,"print(re.sub('^\\W*\\w+\\W*', '', text))"
|
clear terminal screen on windows,os.system('cls')
|
can i put a tuple into an array in python?,"a = [('b', i, 'ff') for i in range(1, 5)]"
|
how do i turn a dataframe into a series of lists?,pd.Series(df.T.to_dict('list'))
|
how to find if directory exists in python,print(os.path.exists('/home/el/myfile.txt'))
|
replace repeated instances of a character '*' with a single instance in a string 'text',"re.sub('\\*\\*+', '*', text)"
|
how to make a related field mandatory in django?,raise ValidationError('At least one address is required.')
|
group/count list of dictionaries based on value,"Counter({'BlahBlah': 1, 'Blah': 1})"
|
python 2.7: test if characters in a string are all chinese characters,all('\u4e00' <= c <= '\u9fff' for c in name.decode('utf-8'))
|
best way to abstract season/show/episode data,raise self.__class__.__name__
|
what is the most pythonic way to pop a random element from a list?,random.shuffle(lst)
|
how to get the difference of two querysets in django,set(alllists).difference(set(subscriptionlists))
|
how to use unicode characters in a python string,print('\u25b2'.encode('utf-8'))
|
show explorer's properties dialog for a file in windows,time.sleep(5)
|
"regular expression syntax for ""match nothing""?",re.compile('a^')
|
python pandas: check if any value is nan in dataframe,df.isnull().values.any()
|
"print a string after a specific substring ', ' in string `my_string `","print(my_string.split(', ', 1)[1])"
|
parse xml file into python object,"[(ch.tag, ch.text) for e in tree.findall('file') for ch in e.getchildren()]"
|
python saving multiple figures into one pdf file,pdf.close()
|
how to remove parentheses only around single words in a string,"re.sub('\\((\\w+)\\)', '\\1', s)"
|
arbitrary number of arguments in a python function,return args[-1] + mySum(args[:-1])
|
cleanest way to get a value from a list element,"print(re.search('\\bLOG_ADDR\\s+(\\S+)', line).group(1))"
|
how to import a module given the full path?,sys.path.append('/foo/bar/mock-0.3.1')
|
python - fastest way to check if a string contains specific characters in any of the items in a list,any(e in lestring for e in lelist)
|
python convert fraction to decimal,float(a)
|
can i run a python script as a service?,sys.exit(1)
|
expanding a block of numbers in python,"L = ['1', '2', '3', '7-10', '15', '20-25']"
|
conditionally fill a column of a pandas df with values of a different df,"df1.merge(df2, how='left', on='word')"
|
regex matching 5-digit substrings not enclosed with digits,"re.findall('(?<!\\d)\\d{5}(?!\\d)', s)"
|
django order by highest number of likes,Article.objects.annotate(like_count=Count('likes')).order_by('-like_count')
|
django string to date format,"datetime.datetime.strptime(s, '%Y-%m-%d').date()"
|
how do i get the whole content between two xml tags in python?,"tostring(element).split('>', 1)[1]"
|
a simple way to remove multiple spaces in a string in python,"re.sub('\\s\\s+', ' ', s)"
|
how to set background color in a chart in xlsxwriter,"chart.add_series({'values': '=Sheet1!$C$1:$C$5', 'fill': {'color': 'yellow'}})"
|
x11 forwarding with paramiko,ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
how to reverse the elements in a sublist?,L[:] = new_list
|
printing multiples of numbers,"print(list(range(n, (m + 1) * n, n)))"
|
how to format list and dictionary comprehensions,"{k: v for k, v in enumerate(range(10)) if v % 2 == 0}"
|
how to unzip an iterator?,"a = zip(list(range(10)), list(range(10)))"
|
what is the difference between a string and a byte string?,"""""""tornos"""""".decode('utf-8')"
|
how to add group labels for bar charts in matplotlib?,fig.savefig('label_group_bar_example.png')
|
how to size my imshow?,plt.show()
|
get a random key `country` and value `capital` form a dictionary `d`,"country, capital = random.choice(list(d.items()))"
|
python matplotlib: position colorbar in data coordinates,plt.show()
|
pygtk color for drag_highlight,gtk.main()
|
regular expression to remove line breaks,"re.sub('(?<=[a-z])\\r?\\n', ' ', textblock)"
|
how to remove the space between subplots in matplotlib.pyplot?,"fig.subplots_adjust(wspace=0, hspace=0)"
|
getting user input,filename = input('Enter a file name: ')
|
convert a string to an array,testarray = ast.literal_eval(teststr)
|
sending custom pyqt signals?,QtCore.SIGNAL('finished(PyQt_PyObject)')
|
what is the best way of counting distinct values in a dataframe and group by a different column?,df.groupby('state').DRUNK_DR.value_counts()
|
numpy: how to find the unique local minimum of sub matrixes in matrix a?,"[np.unravel_index(np.argmin(a), (2, 2)) for a in A2]"
|
split a list into nested lists on a value,"[[1, 4], [6, 9], [3, 9, 4]]"
|
python: how to get rid of spaces in str(dict)?,"str({'a': 1, 'b': 'as df'}).replace(': ', ':').replace(', ', ',')"
|
find all the indexes in a numpy 2d array where the value is 1,zip(*np.where(a == 1))
|
some built-in to pad a list in python,"list(pad([1, 2, 3], 7, ''))"
|
how to set rmse cost function in tensorflow,"tf.sqrt(tf.reduce_mean(tf.square(tf.sub(targets, outputs))))"
|
pandas: mean of columns with the same names,df = df.reset_index()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.