text
stringlengths 4
1.08k
|
|---|
get the ASCII value of a character as an int,ord()
|
decode JSON string `u` to a dictionary,json.load(u)
|
"Delete mulitple columns `columnheading1`, `columnheading2` in pandas data frame `yourdf`","yourdf.drop(['columnheading1', 'columnheading2'], axis=1, inplace=True)"
|
get a list of of elements resulting from splitting user input by commas and stripping white space from each resulting string `s`,"[s.strip() for s in input().split(',')]"
|
create a list containing the digits values from binary string `x` as elements,[int(d) for d in str(bin(x))[2:]]
|
get the max string length in list `i`,max(len(word) for word in i)
|
get the maximum string length in nested list `i`,"len(max(i, key=len))"
|
execute os command `my_cmd`,os.system(my_cmd)
|
sort list `mylist` alphabetically,mylist.sort(key=lambda x: x.lower())
|
sort list `mylist` in alphabetical order,mylist.sort(key=str.lower)
|
sort a list of strings 'mylist'.,mylist.sort()
|
sort a list of strings `list`,list.sort()
|
Set multi index on columns 'Company' and 'date' of data frame `df` in pandas.,"df.set_index(['Company', 'date'], inplace=True)"
|
get the attribute `x` from object `your_obj`,"getattr(your_obj, x)"
|
remove first word in string `s`,"s.split(' ', 1)[1]"
|
save xlsxwriter file in 'app/smth1/smth2/Expenses01.xlsx' path and assign to variable `workbook`,workbook = xlsxwriter.Workbook('app/smth1/smth2/Expenses01.xlsx')
|
save xlsxwriter file to 'C:/Users/Steven/Documents/demo.xlsx' path,workbook = xlsxwriter.Workbook('C:/Users/Steven/Documents/demo.xlsx')
|
change legend size to 'x-small' in upper-left location,"pyplot.legend(loc=2, fontsize='x-small')"
|
change legend font size with matplotlib.pyplot to 6,"plot.legend(loc=2, prop={'size': 6})"
|
split list `l` into `n` sized lists,"[l[i:i + n] for i in range(0, len(l), n)]"
|
split a list `l` into evenly sized chunks `n`,"[l[i:i + n] for i in range(0, len(l), n)]"
|
check if character '-' exists in a dataframe `df` cell 'a',df['a'].str.contains('-')
|
"remove all non -word, -whitespace, or -apostrophe characters from string `doesn't this mean it -technically- works?`","re.sub(""[^\\w' ]"", '', ""doesn't this mean it -technically- works?"")"
|
find all digits between two characters `\xab` and `\xbb`in a string `text`,"print(re.findall('\\d+', '\n'.join(re.findall('\xab([\\s\\S]*?)\xbb', text))))"
|
plot data of column 'index' versus column 'A' of dataframe `monthly_mean` after resetting its index,"monthly_mean.reset_index().plot(x='index', y='A')"
|
"get the output of a subprocess command `echo ""foo""` in command line","subprocess.check_output('echo ""foo""', shell=True)"
|
Encode each value to 'UTF8' in the list `EmployeeList`,[x.encode('UTF8') for x in EmployeeList]
|
combine two columns `foo` and `bar` in a pandas data frame,"pandas.concat([df['foo'].dropna(), df['bar'].dropna()]).reindex_like(df)"
|
generate a list of consecutive integers from 0 to 8,list(range(9))
|
convert list `myintegers` into a unicode string,""""""""""""".join(chr(i) for i in myintegers)"
|
inherit from class `Executive`,"super(Executive, self).__init__(*args)"
|
Remove the string value `item` from a list of strings `my_sequence`,[item for item in my_sequence if item != 'item']
|
randomly select an item from list `foo`,random.choice(foo)
|
"check if all of the following items in list `['a', 'b']` are in a list `['a', 'b', 'c']`","set(['a', 'b']).issubset(['a', 'b', 'c'])"
|
"Check if all the items in a list `['a', 'b']` exists in another list `l`","set(['a', 'b']).issubset(set(l))"
|
to convert a list of tuples `list_of_tuples` into list of lists,[list(t) for t in zip(*list_of_tuples)]
|
group a list `list_of_tuples` of tuples by values,zip(*list_of_tuples)
|
merge pandas dataframe `x` with columns 'a' and 'b' and dataframe `y` with column 'y',"pd.merge(y, x, on='k')[['a', 'b', 'y']]"
|
"Split string with comma (,) and remove whitespace from a string 'my_string'","[item.strip() for item in my_string.split(',')]"
|
Get all object attributes of object `obj`,print((obj.__dict__))
|
Get all object attributes of an object,dir()
|
Get all object attributes of an object,dir()
|
pygobject center window `window`,window.set_position(Gtk.WindowPosition.CENTER)
|
change the size of the sci notation to '30' above the y axis in matplotlib `plt`,"plt.rc('font', **{'size': '30'})"
|
check if datafram `df` has any NaN vlaues,df.isnull().values.any()
|
unpack the arguments out of list `params` to function `some_func`,some_func(*params)
|
decode encodeuricomponent in GAE,urllib.parse.unquote(h.path.encode('utf-8')).decode('utf-8')
|
get proportion of rows in dataframe `trace_df` whose values for column `ratio` are greater than 0,(trace_df['ratio'] > 0).mean()
|
convert a set of tuples `queryresult` to a string `emaillist`,emaillist = '\n'.join(item[0] for item in queryresult)
|
convert a set of tuples `queryresult` to a list of strings,[item[0] for item in queryresult]
|
convert a list of tuples `queryresult` to a string from the first indexes.,emaillist = '\n'.join([item[0] for item in queryresult])
|
get the widget which has currently the focus in tkinter instance `window2`,"print(('focus object class:', window2.focus_get().__class__))"
|
Initialize a list `a` with `10000` items and each item's value `0`,a = [0] * 10000
|
Keep only unique words in list of words `words` and join into string,"print(' '.join(sorted(set(words), key=words.index)))"
|
generate 6 random numbers between 1 and 50,"random.sample(range(1, 50), 6)"
|
generate six unique random numbers in the range of 1 to 49.,"random.sample(range(1, 50), 6)"
|
lowercase keys and values in dictionary `{'My Key': 'My Value'}`,"{k.lower(): v.lower() for k, v in list({'My Key': 'My Value'}.items())}"
|
lowercase all keys and values in dictionary `{'My Key': 'My Value'}`,"dict((k.lower(), v) for k, v in {'My Key': 'My Value'}.items())"
|
"Convert each key,value pair in a dictionary `{'My Key': 'My Value'}` to lowercase","dict((k.lower(), v.lower()) for k, v in {'My Key': 'My Value'}.items())"
|
sorting the lists in list of lists `data`,[sorted(item) for item in data]
|
SQLite get a list of column names from cursor object `cursor`,"names = list(map(lambda x: x[0], cursor.description))"
|
get the absolute path of a running python script,os.path.abspath(__file__)
|
sort 2d array `matrix` by row with index 1,"sorted(matrix, key=itemgetter(1))"
|
Get all indexes of a letter `e` from a string `word`,"[index for index, letter in enumerate(word) if letter == 'e']"
|
decode utf-8 code `x` into a raw unicode literal,print(str(x).decode('raw_unicode_escape'))
|
split string 'abcdefg' into a list of characters,"re.findall('\\w', 'abcdefg')"
|
check whether a file `fname` exists,os.path.isfile(fname)
|
check whether file `file_path` exists,os.path.exists(file_path)
|
"check whether a file ""/etc/password.txt"" exists",print(os.path.isfile('/etc/password.txt'))
|
"check whether a file ""/etc"" exists",print(os.path.isfile('/etc'))
|
"check whether a path ""/does/not/exist"" exists",print(os.path.exists('/does/not/exist'))
|
"check whether a file ""/does/not/exist"" exists",print(os.path.isfile('/does/not/exist'))
|
"check whether a path ""/etc"" exists",print(os.path.exists('/etc'))
|
"check whether a path ""/etc/password.txt"" exists",print(os.path.exists('/etc/password.txt'))
|
"split string ""a;bcd,ef g"" on delimiters ';' and ','","""""""a;bcd,ef g"""""".replace(';', ' ').replace(',', ' ').split()"
|
get a list each value `i` in the implicit tuple `range(3)`,list(i for i in range(3))
|
add field names as headers in csv constructor `writer`,writer.writeheader()
|
flatten a tuple `l`,"[(a, b, c) for a, (b, c) in l]"
|
convert 3652458 to string represent a 32bit hex number,"""""""0x{0:08X}"""""".format(3652458)"
|
convert a python dictionary `d` to a list of tuples,"[(v, k) for k, v in list(d.items())]"
|
convert dictionary of pairs `d` to a list of tuples,"[(v, k) for k, v in d.items()]"
|
convert python 2 dictionary `a` to a list of tuples where the value is the first tuple element and the key is the second tuple element,"[(v, k) for k, v in a.items()]"
|
convert a python dictionary 'a' to a list of tuples,"[(k, v) for k, v in a.items()]"
|
"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']]"
|
convert the elements of list `L` from hex byte strings to hex integers,"[int(x, 16) for x in L]"
|
"assign values to two variables, `var1` and `var2` from user input response to `'Enter two numbers here: ` split on whitespace","var1, var2 = input('Enter two numbers here: ').split()"
|
Filter a json from a key-value pair as `{'fixed_key_1': 'foo2'}` in Django,Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
|
create a list containing a four elements long tuples of permutations of binary values,"itertools.product(list(range(2)), repeat=4)"
|
get yesterday's date as a string in `YYYY-MM-DD` format using timedelta,(datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
|
"Get the dot product of matrix `[1,0,0,1,0,0]` and matrix `[[0,1],[1,1],[1,0],[1,0],[1,1],[0,1]]`","np.dot([1, 0, 0, 1, 0, 0], [[0, 1], [1, 1], [1, 0], [1, 0], [1, 1], [0, 1]])"
|
convert date strings in pandas dataframe column`df['date']` to pandas timestamps using the format '%d%b%Y',"df['date'] = pd.to_datetime(df['date'], format='%d%b%Y')"
|
Importing file `file` from folder '/path/to/application/app/folder',"sys.path.insert(0, '/path/to/application/app/folder')
|
import file"
|
do a `left` merge of dataframes `x` and `y` on the column `state` and sort by `index`,"x.reset_index().merge(y, how='left', on='state', sort=False).sort('index')"
|
Create a default empty json object if no json is available in request parameter `mydata`,"json.loads(request.POST.get('mydata', '{}'))"
|
"get a list of tuples of every three consecutive items in list `[1, 2, 3, 4, 5, 6, 7, 8, 9]`","list(zip(*((iter([1, 2, 3, 4, 5, 6, 7, 8, 9]),) * 3)))"
|
"slice list `[1, 2, 3, 4, 5, 6, 7]` into lists of two elements each","list(grouper(2, [1, 2, 3, 4, 5, 6, 7]))"
|
Sort list `keys` based on its elements' dot-seperated numbers,"keys.sort(key=lambda x: map(int, x.split('.')))"
|
Sort a list of integers `keys` where each value is in string format,keys.sort(key=lambda x: [int(y) for y in x.split('.')])
|
convert a 3d array `img` of dimensions 4x2x3 to a 2d array of dimensions 3x8,"img.transpose(2, 0, 1).reshape(3, -1)"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.