text
stringlengths 4
1.08k
|
|---|
make a list of integers from 0 to `5` where each second element is a duplicate of the previous element,"print([u for v in [[i, i] for i in range(5)] for u in v])"
|
"create a list of integers with duplicate values `[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]`","[0, 0, 1, 1, 2, 2, 3, 3, 4, 4]"
|
create a list of integers from 1 to 5 with each value duplicated,[(i // 2) for i in range(10)]
|
remove first and last lines of string `s`,s[s.find('\n') + 1:s.rfind('\n')]
|
create dict of squared int values in range of 100,{(x ** 2) for x in range(100)}
|
"zip lists `[1, 2], [3, 4], [5, 6]` in a list","zip(*[[1, 2], [3, 4], [5, 6]])"
|
"zip lists in a list [[1, 2], [3, 4], [5, 6]]","zip(*[[1, 2], [3, 4], [5, 6]])"
|
request page 'https://www.mysite.com/' with credentials of username 'username' and password 'pwd',"requests.get('https://www.mysite.com/', auth=('username', 'pwd'))"
|
get a new string from the 3rd character to the end of the string `x`,x[2:]
|
get a new string including the first two characters of string `x`,x[:2]
|
get a new string including all but the last character of string `x`,x[:(-2)]
|
get a new string including the last two characters of string `x`,x[(-2):]
|
get a new string with the 3rd to the second-to-last characters of string `x`,x[2:(-2)]
|
reverse a string `some_string`,some_string[::(-1)]
|
"select alternate characters of ""H-e-l-l-o- -W-o-r-l-d""",'H-e-l-l-o- -W-o-r-l-d'[::2]
|
select a substring of `s` beginning at `beginning` of length `LENGTH`,s = s[beginning:(beginning + LENGTH)]
|
terminate the program,sys.exit()
|
terminate the program,quit()
|
"Terminating a Python script with error message ""some error message""",sys.exit('some error message')
|
"encode value of key `City` in dictionary `data` as `ascii`, ignoring non-ascii characters","data['City'].encode('ascii', 'ignore')"
|
get current CPU and RAM usage,"psutil.cpu_percent()
|
psutil.virtual_memory()"
|
get current RAM usage of current program,"pid = os.getpid()
|
py = psutil.Process(pid)
|
memoryUse = (py.memory_info()[0] / (2.0 ** 30))"
|
print cpu and memory usage,"print((psutil.cpu_percent()))
|
print((psutil.virtual_memory()))"
|
read a ragged csv file `D:/Temp/tt.csv` using `names` parameter in pandas,"pd.read_csv('D:/Temp/tt.csv', names=list('abcdef'))"
|
get first non-null value per each row from dataframe `df`,df.stack().groupby(level=0).first()
|
print two numbers `10` and `20` using string formatting,"""""""{0} {1}"""""".format(10, 20)"
|
"replace placeholders in string '{1} {ham} {0} {foo} {1}' with arguments `(10, 20, foo='bar', ham='spam')`","""""""{1} {ham} {0} {foo} {1}"""""".format(10, 20, foo='bar', ham='spam')"
|
create list `changed_list ` containing elements of list `original_list` whilst converting strings containing digits to integers,changed_list = [(int(f) if f.isdigit() else f) for f in original_list]
|
get a dictionary with keys from one list `keys` and values from other list `data`,"dict(zip(keys, zip(*data)))"
|
convert string `apple` from iso-8859-1/latin1 to utf-8,apple.decode('iso-8859-1').encode('utf8')
|
Exclude column names when writing dataframe `df` to a csv file `filename.csv`,"df.to_csv('filename.csv', header=False)"
|
"Escape character '}' in string '{0}:<15}}{1}:<15}}{2}:<8}}' while using function `format` with arguments `('1', '2', '3')`","print('{0}:<15}}{1}:<15}}{2}:<8}}'.format('1', '2', '3'))"
|
get dictionary with max value of key 'size' in list of dicts `ld`,"max(ld, key=lambda d: d['size'])"
|
"format parameters 'b' and 'a' into plcaeholders in string ""{0}\\w{{2}}b{1}\\w{{2}}quarter""","""""""{0}\\w{{2}}b{1}\\w{{2}}quarter"""""".format('b', 'a')"
|
django create a foreign key column `user` and link it to table 'User',"user = models.ForeignKey('User', unique=True)"
|
write a regex pattern to match even number of letter `A`,re.compile('^([^A]*)AA([^A]|AA)*$')
|
join Numpy array `b` with Numpy array 'a' along axis 0,"b = np.concatenate((a, a), axis=0)"
|
custom sort an alphanumeric list `l`,"sorted(l, key=lambda x: x.replace('0', 'Z'))"
|
plot logarithmic axes with matplotlib,ax.set_yscale('log')
|
"Access environment variable ""HOME""",os.environ['HOME']
|
"get value of environment variable ""HOME""",os.environ['HOME']
|
print all environment variables,print(os.environ)
|
get all environment variables,os.environ
|
get value of the environment variable 'KEY_THAT_MIGHT_EXIST',print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
|
get value of the environment variable 'KEY_THAT_MIGHT_EXIST' with default value `default_value`,"print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))"
|
get value of the environment variable 'HOME' with default value '/home/username/',"print(os.environ.get('HOME', '/home/username/'))"
|
create a dictionary containing each string in list `my_list` split by '=' as a key/value pairs,print(dict([s.split('=') for s in my_list]))
|
find the index of element closest to number 11.5 in list `a`,"min(enumerate(a), key=lambda x: abs(x[1] - 11.5))"
|
"find element `a` that contains string ""TEXT A"" in file `root`","e = root.xpath('.//a[contains(text(),""TEXT A"")]')"
|
Find the`a` tag in html `root` which starts with the text `TEXT A` and assign it to `e`,"e = root.xpath('.//a[starts-with(text(),""TEXT A"")]')"
|
find the element that holds string 'TEXT A' in file `root`,"e = root.xpath('.//a[text()=""TEXT A""]')"
|
create list `c` containing items from list `b` whose index is in list `index`,c = [b[i] for i in index]
|
get the dot product of two one dimensional numpy arrays,"np.dot(a[:, (None)], b[(None), :])"
|
multiplication of two 1-dimensional arrays in numpy,"np.outer(a, b)"
|
execute a file './abc.py' with arguments `arg1` and `arg2` in python shell,"subprocess.call(['./abc.py', arg1, arg2])"
|
Replace NaN values in column 'value' with the mean of data in column 'group' of dataframe `df`,df[['value']].fillna(df.groupby('group').transform('mean'))
|
separate each character in string `s` by '-',"re.sub('(.)(?=.)', '\\1-', s)"
|
concatenate '-' in between characters of string `str`,"re.sub('(?<=.)(?=.)', '-', str)"
|
get the indexes of the x and y axes in Numpy array `np` where variable `a` is equal to variable `value`,"i, j = np.where(a == value)"
|
print letter that appears most frequently in string `s`,print(collections.Counter(s).most_common(1)[0])
|
find float number proceeding sub-string `par` in string `dir`,"float(re.findall('(?:^|_)' + par + '(\\d+\\.\\d*)', dir)[0])"
|
Get all the matches from a string `abcd` if it begins with a character `a`,"re.findall('[^a]', 'abcd')"
|
get a list of variables from module 'adfix.py' in current module.,print([item for item in dir(adfix) if not item.startswith('__')])
|
get the first element of each tuple in a list `rows`,[x[0] for x in rows]
|
get a list `res_list` of the first elements of each tuple in a list of tuples `rows`,res_list = [x[0] for x in rows]
|
duplicate data in pandas dataframe `x` for 5 times,"pd.concat([x] * 5, ignore_index=True)"
|
Get a repeated pandas data frame object `x` by `5` times,pd.concat([x] * 5)
|
sort json `ips_data` by a key 'data_two',"sorted_list_of_keyvalues = sorted(list(ips_data.items()), key=item[1]['data_two'])"
|
read json `elevations` to pandas dataframe `df`,pd.read_json(elevations)
|
"generate a random number in 1 to 7 with a given distribution [0.1, 0.05, 0.05, 0.2, 0.4, 0.2]","numpy.random.choice(numpy.arange(1, 7), p=[0.1, 0.05, 0.05, 0.2, 0.4, 0.2])"
|
Return rows of data associated with the maximum value of column 'Value' in dataframe `df`,df.loc[df['Value'].idxmax()]
|
find recurring patterns in a string '42344343434',"re.findall('^(.+?)((.+)\\3+)$', '42344343434')[0][:-1]"
|
convert binary string to numpy array,"np.fromstring('\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@', dtype='>f4')"
|
"insert variables `(var1, var2, var3)` into sql statement 'INSERT INTO table VALUES (?, ?, ?)'","cursor.execute('INSERT INTO table VALUES (?, ?, ?)', (var1, var2, var3))"
|
"Execute a sql statement using variables `var1`, `var2` and `var3`","cursor.execute('INSERT INTO table VALUES (%s, %s, %s)', (var1, var2, var3))"
|
"pandas split strings in column 'stats' by ',' into columns in dataframe `df`","df['stats'].str[1:-1].str.split(',', expand=True).astype(float)"
|
"split string in column 'stats' by ',' into separate columns in dataframe `df`","df['stats'].str[1:-1].str.split(',').apply(pd.Series).astype(float)"
|
Unpack column 'stats' in dataframe `df` into a series of columns,df['stats'].apply(pd.Series)
|
wait for shell command `p` evoked by subprocess.Popen to complete,p.wait()
|
encode string `s` to utf-8 code,s.encode('utf8')
|
parse string '01-Jan-1995' into a datetime object using format '%d-%b-%Y',"datetime.datetime.strptime('01-Jan-1995', '%d-%b-%Y')"
|
copy a file from `src` to `dst`,"copyfile(src, dst)"
|
"copy file ""/dir/file.ext"" to ""/new/dir/newname.ext""","shutil.copy2('/dir/file.ext', '/new/dir/newname.ext')"
|
copy file '/dir/file.ext' to '/new/dir',"shutil.copy2('/dir/file.ext', '/new/dir')"
|
print a list of integers `list_of_ints` using string formatting,"print(', '.join(str(x) for x in list_of_ints))"
|
multiply column 'A' and column 'B' by column 'C' in datafram `df`,"df[['A', 'B']].multiply(df['C'], axis='index')"
|
convert string 'a' to hex,hex(ord('a'))
|
Get the sum of values to the power of their indices in a list `l`,"sum(j ** i for i, j in enumerate(l, 1))"
|
remove extra white spaces & tabs from a string `s`,""""""" """""".join(s.split())"
|
replace comma in string `s` with empty string '',"s = s.replace(',', '')"
|
"Resample dataframe `frame` to resolution of 1 hour `1H` for timeseries index, summing values in the column `radiation` averaging those in column `tamb`","frame.resample('1H').agg({'radiation': np.sum, 'tamb': np.mean})"
|
create a pandas dataframe `df` from elements of a dictionary `nvalues`,"df = pd.DataFrame.from_dict({k: v for k, v in list(nvalues.items()) if k != 'y3'})"
|
Flask get value of request variable 'firstname',first_name = request.args.get('firstname')
|
Flask get posted form data 'firstname',first_name = request.form.get('firstname')
|
get a list of substrings consisting of the first 5 characters of every string in list `buckets`,[s[:5] for s in buckets]
|
sort list `the_list` by the length of string followed by alphabetical order,"the_list.sort(key=lambda item: (-len(item), item))"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.