text
stringlengths 4
1.08k
|
|---|
changing permission of file `path` to `stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH`,"os.chmod(path, stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)"
|
argparse associate zero or more arguments with flag 'file',"parser.add_argument('file', nargs='*')"
|
get a list of booleans `z` that shows wether the corresponding items in list `x` and `y` are equal,"z = [(i == j) for i, j in zip(x, y)]"
|
create a list which indicates whether each element in `x` and `y` is identical,[(x[i] == y[i]) for i in range(len(x))]
|
create an empty data frame `df2` with index from another data frame `df1`,df2 = pd.DataFrame(index=df1.index)
|
unpack first and second bytes of byte string `pS` into integer,"struct.unpack('h', pS[0:2])"
|
print list `t` into a table-like shape,"print('\n'.join(' '.join(map(str, row)) for row in t))"
|
check if a checkbox is checked in selenium python webdriver,driver.find_element_by_name('<check_box_name>').is_selected()
|
determine if checkbox with id '<check_box_id>' is checked in selenium python webdriver,driver.find_element_by_id('<check_box_id>').is_selected()
|
"replace `0` with `2` in the list `[0, 1, 0, 3]`","[(a if a else 2) for a in [0, 1, 0, 3]]"
|
Produce a string that is suitable as Unicode literal from string 'M\\N{AMPERSAND}M\\N{APOSTROPHE}s','M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.encode().decode('unicode-escape')
|
Parse a unicode string `M\\N{AMPERSAND}M\\N{APOSTROPHE}s`,'M\\N{AMPERSAND}M\\N{APOSTROPHE}s'.decode('unicode-escape')
|
convert Unicode codepoint to utf8 hex,"chr(int('fd9b', 16)).encode('utf-8')"
|
use upper case letters to print hex value `value`,print('0x%X' % value)
|
get a list `cleaned` that contains all non-empty elements in list `your_list`,cleaned = [x for x in your_list if x]
|
create a slice object using string `string_slice`,slice(*[(int(i.strip()) if i else None) for i in string_slice.split(':')])
|
Find all the tags `a` and `div` from Beautiful Soup object `soup`,"soup.find_all(['a', 'div'])"
|
get the name of function `func` as a string,print(func.__name__)
|
convert dictionary `adict` into string,""""""""""""".join('{}{}'.format(key, val) for key, val in sorted(adict.items()))"
|
convert dictionary `adict` into string,""""""""""""".join('{}{}'.format(key, val) for key, val in list(adict.items()))"
|
copy list `old_list` as `new_list`,new_list = old_list[:]
|
copy list `old_list` as `new_list`,new_list = list(old_list)
|
copy list `old_list` as `new_list`,new_list = copy.copy(old_list)
|
deep copy list `old_list` as `new_list`,new_list = copy.deepcopy(old_list)
|
make a copy of list `old_list`,[i for i in old_list]
|
remove frame of legend in plot `plt`,plt.legend(frameon=False)
|
Print a emoji from a string `\\ud83d\\ude4f` having surrogate pairs,"""""""\\ud83d\\ude4f"""""".encode('utf-16', 'surrogatepass').decode('utf-16')"
|
calling a function named 'myfunction' in the module,globals()['myfunction']()
|
"Check the status code of url ""http://www.stackoverflow.com""",urllib.request.urlopen('http://www.stackoverflow.com').getcode()
|
Check the status code of url `url`,"r = requests.head(url)
|
return (r.status_code == 200)"
|
"Checking if website ""http://www.stackoverflow.com"" is up",print(urllib.request.urlopen('http://www.stackoverflow.com').getcode())
|
"Selenium `driver` click a hyperlink with the pattern ""a[href^='javascript']""","driver.find_element_by_css_selector(""a[href^='javascript']"").click()"
|
"store data frame `df` to file `file_name` using pandas, python",df.to_pickle(file_name)
|
calculate the mean of columns with same name in dataframe `df`,"df.groupby(by=df.columns, axis=1).mean()"
|
sort list `bar` by each element's attribute `attrb1` and attribute `attrb2` in reverse order,"bar.sort(key=lambda x: (x.attrb1, x.attrb2), reverse=True)"
|
get alpha value `alpha` of a png image `img`,alpha = img.split()[-1]
|
BeautifulSoup find tag 'div' with styling 'width=300px;' in HTML string `soup`,"soup.findAll('div', style='width=300px;')"
|
Execute SQL statement `sql` with values of dictionary `myDict` as parameters,"cursor.execute(sql, list(myDict.values()))"
|
Convert CSV file `Result.csv` to Pandas dataframe using separator ' ',"df.to_csv('Result.csv', index=False, sep=' ')"
|
update the `globals()` dictionary with the contents of the `vars(args)` dictionary,globals().update(vars(args))
|
find all substrings in `mystring` beginning and ending with square brackets,"re.findall('\\[(.*?)\\]', mystring)"
|
"Format all floating variables `var1`, `var2`, `var3`, `var1` to print to two decimal places.","print('%.2f kg = %.2f lb = %.2f gal = %.2f l' % (var1, var2, var3, var4))"
|
Remove all items from a dictionary `d` where the values are less than `1`,"d = dict((k, v) for k, v in d.items() if v > 0)"
|
Filter dictionary `d` to have items with value greater than 0,"d = {k: v for k, v in list(d.items()) if v > 0}"
|
convert a string of date strings `date_stngs ` to datetime objects and put them in a dataframe,pd.to_datetime(pd.Series(date_stngs))
|
"get value at index `[2, 0]` in dataframe `df`","df.iloc[2, 0]"
|
change the font size on plot `matplotlib` to 22,matplotlib.rcParams.update({'font.size': 22})
|
converting dictionary `d` into a dataframe `pd` with keys as data for column 'Date' and the corresponding values as data for column 'DateValue',"pd.DataFrame(list(d.items()), columns=['Date', 'DateValue'])"
|
create a dataframe containing the multiplication of element-wise in dataframe `df` and dataframe `df2` using index name and column labels of dataframe `df`,"pd.DataFrame(df.values * df2.values, columns=df.columns, index=df.index)"
|
extract floating number from string 'Current Level: 13.4 db.',"re.findall('\\d+\\.\\d+', 'Current Level: 13.4 db.')"
|
extract floating point numbers from a string 'Current Level: -13.2 db or 14.2 or 3',"re.findall('[-+]?\\d*\\.\\d+|\\d+', 'Current Level: -13.2 db or 14.2 or 3')"
|
pair each element in list `it` 3 times into a tuple,"zip(it, it, it)"
|
lowercase a python dataframe string in column 'x' if it has missing values in dataframe `df`,df['x'].str.lower()
|
"append dict `{'f': var6, 'g': var7, 'h': var8}` to value of key `e` in dict `jsobj['a']['b']`","jsobj['a']['b']['e'].append({'f': var6, 'g': var7, 'h': var8})"
|
Concat a list of strings `lst` using string formatting,""""""""""""".join(lst)"
|
sum values greater than 0 in dictionary `d`,sum(v for v in list(d.values()) if v > 0)
|
run flask application `app` in debug mode.,app.run(debug=True)
|
"drop rows whose index value in list `[1, 3]` in dataframe `df`","df.drop(df.index[[1, 3]], inplace=True)"
|
replace nan values in a pandas data frame with the average of columns,"df.apply(lambda x: x.fillna(x.mean()), axis=0)"
|
extract attribute `my_attr` from each object in list `my_list`,[o.my_attr for o in my_list]
|
python get time stamp on file `file` in '%m/%d/%Y' format,"time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))"
|
check if dictionary `subset` is a subset of dictionary `superset`,all(item in list(superset.items()) for item in list(subset.items()))
|
Convert integer elements in list `wordids` to strings,[str(wi) for wi in wordids]
|
Reset the indexes of a pandas data frame,df2 = df.reset_index()
|
format datetime in `dt` as string in format `'%m/%d/%Y`,dt.strftime('%m/%d/%Y')
|
format floating point number `TotalAmount` to be rounded off to two decimal places and have a comma thousands' seperator,"print('Total cost is: ${:,.2f}'.format(TotalAmount))"
|
sum the values in each row of every two adjacent columns in dataframe `df`,"df.groupby(np.arange(len(df.columns)) // 2 + 1, axis=1).sum().add_prefix('s')"
|
create list `randomList` with 10 random floating point numbers between 0.0 and 1.0,randomList = [random.random() for _ in range(10)]
|
find href value that has string 'follow?page' inside it,"print(soup.find('a', href=re.compile('.*follow\\?page.*')))"
|
immediately see output of print statement that doesn't end in a newline,sys.stdout.flush()
|
get a random key `country` and value `capital` form a dictionary `d`,"country, capital = random.choice(list(d.items()))"
|
split string `Word to Split` into a list of characters,list('Word to Split')
|
Create a list containing words that contain vowel letter followed by the same vowel in file 'file.text',"[w for w in open('file.txt') if not re.search('[aeiou]{2}', w)]"
|
Validate IP address using Regex,"pat = re.compile('^\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}$')"
|
execute file 'filename.py',"exec(compile(open('filename.py').read(), 'filename.py', 'exec'))"
|
SQLAlchemy count the number of rows with distinct values in column `name` of table `Tag`,session.query(Tag).distinct(Tag.name).group_by(Tag.name).count()
|
remove null columns in a dataframe `df`,"df = df.dropna(axis=1, how='all')"
|
check if all lists in list `L` have three elements of integer 1,all(x.count(1) == 3 for x in L)
|
Get a list comparing two lists of tuples `l1` and `l2` if any first value in `l1` matches with first value in `l2`,[x[0] for x in l1 if any(x[0] == y[0] for y in l2)]
|
clear the textbox `text` in tkinter,"tex.delete('1.0', END)"
|
Convert long int `myNumber` into date and time represented in the the string format '%Y-%m-%d %H:%M:%S',datetime.datetime.fromtimestamp(myNumber).strftime('%Y-%m-%d %H:%M:%S')
|
Spawn a process to run python script `myscript.py` in C++,system('python myscript.py')
|
sort a list `your_list` of class objects by their values for the attribute `anniversary_score`,your_list.sort(key=operator.attrgetter('anniversary_score'))
|
sort list `your_list` by the `anniversary_score` attribute of each object,your_list.sort(key=lambda x: x.anniversary_score)
|
"convert a tensor with list of constants `[1, 2, 3]` into a numpy array in tensorflow","print(type(tf.Session().run(tf.constant([1, 2, 3]))))"
|
convert list `a` from being consecutive sequences of tuples into a single sequence of elements,list(itertools.chain(*a))
|
Set value for key `a` in dict `count` to `0` if key `a` does not exist or if value is `none`,"count.setdefault('a', 0)"
|
Do group by on `cluster` column in `df` and get its mean,df.groupby(['cluster']).mean()
|
get number in list `myList` closest in value to number `myNumber`,"min(myList, key=lambda x: abs(x - myNumber))"
|
check if any of the items in `search` appear in `string`,any(x in string for x in search)
|
search for occurrences of regex pattern `pattern` in string `url`,print(pattern.search(url).group(1))
|
factorize all string values in dataframe `s` into floats,(s.factorize()[0] + 1).astype('float')
|
Get a list `C` by subtracting values in one list `B` from corresponding values in another list `A`,"C = [(a - b) for a, b in zip(A, B)]"
|
"derive the week start for the given week number and year ‘2011, 4, 0’","datetime.datetime.strptime('2011, 4, 0', '%Y, %U, %w')"
|
"convert a list of strings `['1', '-1', '1']` to a list of numbers","map(int, ['1', '-1', '1'])"
|
"create datetime object from ""16sep2012""","datetime.datetime.strptime('16Sep2012', '%d%b%Y')"
|
update fields in Django model `Book` with arguments in dictionary `d` where primary key is equal to `pk`,Book.objects.filter(pk=pk).update(**d)
|
update the fields in django model `Book` using dictionary `d`,Book.objects.create(**d)
|
print a digit `your_number` with exactly 2 digits after decimal,print('{0:.2f}'.format(your_number))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.