text stringlengths 4 1.08k |
|---|
remove all whitespace in a string `sentence`,"pattern = re.compile('\\s+') |
sentence = re.sub(pattern, '', sentence)" |
python load json file with utf-8 bom header,"json.load(codecs.open('sample.json', 'r', 'utf-8-sig'))" |
crop image with corrected distortion in opencv (python),"img = cv2.imread('Undistorted.jpg', 0)" |
fabric - sudo -u,"sudo('python manage.py collectstatic --noinput', user='www-data')" |
how to solve a pair of nonlinear equations using python?,"print(equations((x, y)))" |
(django) how to get month name?,today.strftime('%B') |
python 2.7: making a dictionary object from a specially-formatted list object,"{f[i + 1]: [f[i], f[i + 2]] for i in range(0, len(f), 3)}" |
convert pandas dataframe to csv string,df.to_csv() |
python: how do i convert an array of strings to an array of numbers?,desired_array = [int(numeric_string) for numeric_string in current_array] |
python 3: how do i get a string literal representation of a byte string?,('x = %s' % '\\u041c\\u0438\\u0440').encode('utf-8') |
sorted() with lambda function,lambda x: int(x.partition('/')[0][2:]) |
add tuple to a list of tuples,"[(10, 21, 32), (13, 24, 35), (16, 27, 38)]" |
"remove item ""b"" in list `a`",a.remove('b') |
generate random decimal,decimal.Decimal(random.randrange(10000)) / 100 |
delete none values from python dict,"result.update((k, v) for k, v in user.items() if v is not None)" |
clicking on a link via selenium in python,link.click() |
how to convert this list into a dictionary,"dict([(e[0], int(e[1])) for e in lst])" |
how to zip two lists of lists in python?,"[list(itertools.chain(*x)) for x in zip(L1, L2)]" |
how to zip two lists of lists in python?,"Lmerge = [(i1 + i2) for i1, i2 in zip(L1, L2)]" |
django - how to create a file and save it to a model's filefield?,"self.license_file.save(new_name, new_contents)" |
how to modify choices of modelmultiplechoicefield,self.fields['author'].queryset = choices |
set colorbar range in matplotlib,plt.show() |
generate random upper-case ascii string of 12 characters length,print(''.join(choice(ascii_uppercase) for i in range(12))) |
update json file,json_file.write('{}\n'.format(json.dumps(new_data))) |
"return a subplot axes positioned by the grid definition `1,1,1` using matpotlib","fig.add_subplot(1, 1, 1)" |
send html e-mail in app engine / python?,message.send() |
how to add title to subplots in matplotlib?,plt.show() |
"dropping rows from dataframe based on a ""not in"" condtion",df = df[~df.datecolumn.isin(a)] |
how to find the first index of any of a set of characters in a string,min(s.find(i) if i in s else None for i in a) |
extract data with backslash and double quote - python csv reader,"data = csv.reader(f, delimiter=',', quotechar='""')" |
smartest way to join two lists into a formatted string,"c = ', '.join('{}={}'.format(*t) for t in zip(a, b))" |
crop image with corrected distortion in opencv (python),"cv2.imshow('Crop', desired_result)" |
3d plot with matplotlib,ax.set_xlabel('X') |
get all indexes of a list `a` where each value is greater than `2`,[i for i in range(len(a)) if a[i] > 2] |
finding consecutive consonants in a word,"re.findall('[bcdfghjklmnpqrstvwxyz]+', 'CONCERTATION', re.IGNORECASE)" |
"convert a list of hex byte strings `['bb', 'a7', 'f6', '9e']` to a list of hex integers","[int(x, 16) for x in ['BB', 'A7', 'F6', '9E']]" |
take screenshot in python on mac os x,os.system('screencapture screen.png') |
how to join list of strings?,""""""" """""".join(L)" |
is there any pool for threadingmixin and forkingmixin for socketserver?,python - mserver |
attach debugger pdb to class `forkedpdb`,ForkedPdb().set_trace() |
python how to scan string and and use upper() between two characters?,"print(re.sub('(</?\\w+>)', lambda up: up.group(1).upper(), '<tag>input</tag>'))" |
python: uniqueness for list of lists,"list(map(list, set(map(lambda i: tuple(i), testdata))))" |
notebook widget in tkinter,root.mainloop() |
django create a foreign key column `user` and link it to table 'user',"user = models.ForeignKey('User', unique=True)" |
how to add timeout to twisted defer,reactor.run() |
numpy with python: convert 3d array to 2d,"img.transpose(2, 0, 1).reshape(3, -1)" |
how to rename all folders?,"os.rename(dir, dir + '!')" |
concatenate '-' in between characters of string `str`,"re.sub('(?<=.)(?=.)', '-', str)" |
how to prevent numbers being changed to exponential form in python matplotlib figure,ax.get_xaxis().get_major_formatter().set_scientific(False) |
how can i convert a python dictionary to a list of tuples?,"[(v, k) for k, v in a.items()]" |
removing trailing zeros in python,int('0000') |
sort a pandas data frame according to column `peak` in ascending and `weeks` in descending order,"df.sort_values(['Peak', 'Weeks'], ascending=[True, False], inplace=True)" |
is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) |
python - remove any element from a list of strings that is a substring of another element,"set(['looked', 'resting', 'spit'])" |
make an http post request with data `post_data`,"post_response = requests.post(url='http://httpbin.org/post', json=post_data)" |
using a python dictionary as a key (non-nested),tuple(sorted(a.items())) |
play a sound with python,"winsound.PlaySound('sound.wav', winsound.SND_FILENAME)" |
double iteration in list comprehension,[x for b in a for x in b] |
how to decode encodeuricomponent in gae (python)?,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8') |
how to split python list into chunks of equal size?,"[l[i:i + 3] for i in range(0, len(l), 3)]" |
python- insert a character into a string,""""""",+"""""".join(c.rsplit('+', 1))" |
how to make pyqt window state to maximised in pyqt,self.showMaximized() |
how to get the width of a string in pixels?,"width, height = dc.GetTextExtent('Text to measure')" |
google app engine: how can i programmatically access the properties of my model class?,p.properties()[s].get_value_for_datastore(p) |
how to add items into a numpy array,"array([[1, 3, 4, 1], [1, 2, 3, 2], [1, 2, 1, 3]])" |
how to use the mv command in python with subprocess,"subprocess.call('mv /home/somedir/subdir/* somedir/', shell=True)" |
is there a quick way to get the r equivalent of ls() in python?,"['__builtins__', '__doc__', '__loader__', '__name__', '__package__']" |
how do i remove \n from my python dictionary?,"x = line.rstrip('\n').split(',')" |
list of ip addresses in python to a list of cidr,"cidrs = netaddr.ip_range_to_cidrs(ip_start, ip_end)" |
pivoting a pandas dataframe while deduplicating additional columns,"df.pivot_table('baz', ['foo', 'extra'], 'bar').reset_index()" |
index confusion in numpy arrays,"A[np.ix_([0, 2], [0, 1], [1, 2])]" |
how do you remove the column name row from a pandas dataframe?,"df.to_csv('filename.csv', header=False)" |
replace periods `.` that are not followed by periods or spaces with a period and a space `. `,"re.sub('\\.(?=[^ .])', '. ', para)" |
get value of key `post code` associated with first index of key `places` of dictionary `data`,print(data['places'][0]['post code']) |
how do i sort a list of strings in python?,"mylist = ['b', 'C', 'A'] |
mylist.sort()" |
how to find range overlap in python?,"list(range(max(x[0], y[0]), min(x[-1], y[-1]) + 1))" |
options for building a python web based application,app.run() |
"slice in python, is a copy or just a pointer","a.__setitem__(slice(0, 1), [1])" |
sqlalchemy add child in one-to-many relationship,"parent = relationship('Parent', backref=backref('children', lazy='noload'))" |
is there a more pythonic way of exploding a list over a function's arguments?,foo(*i) |
python dict to numpy structured array,"numpy.array([[key, val] for key, val in result.items()], dtype)" |
how to apply itertools.product to elements of a list of lists?,list(itertools.product(*arrays)) |
"zip a list of tuples `[(1, 4), (2, 5), (3, 6)]` into a list of tuples according to original tuple index","zip(*[(1, 4), (2, 5), (3, 6)])" |
unpack the binary data represented by the hexadecimal string '4081637ef7d0424a' to a float,"struct.unpack('d', binascii.unhexlify('4081637ef7d0424a'))" |
how to loop backwards in python?,"list(range(10, 0, -1))" |
how to replace nans by preceding values in pandas dataframe?,"df.fillna(method='ffill', inplace=True)" |
how do i right-align numeric data in python?,"""""""a string {0:>5}"""""".format(foo)" |
how can i get the output of a matplotlib plot as an svg?,plt.savefig('test.svg') |
how to find the minimum value in a numpy matrix?,arr[arr > 0].min() |
find indices of a value in 2d matrix,"[(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row]" |
count all elements in list of arbitrary nested list without recursion,"print(element_count([[[[[[[[1, 2, 3]]]]]]]]))" |
print each first value from a list of tuples `mytuple` with string formatting,"print(', ,'.join([str(i[0]) for i in mytuple]))" |
count the number of items in a generator/iterator `it`,sum(1 for i in it) |
sort items in dictionary `d` using the first part of the key after splitting the key,"sorted(list(d.items()), key=lambda name_num: (name_num[0].rsplit(None, 1)[0], name_num[1]))" |
convert a list of dictionaries `d` to pandas data frame,pd.DataFrame(d) |
"map list of tuples into a dictionary, python",myDict[item[1]] += item[2] |
looping over all member variables of a class in python,"['blah', 'bool143', 'bool2', 'foo', 'foobar2000']" |
how can i increase the frequency of xticks/ labels for dates on a bar plot?,plt.xticks(rotation='25') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.