task_id
int64
19.3k
41.9M
prompt
stringlengths
17
68
suffix
stringclasses
37 values
canonical_solution
stringlengths
6
153
test_start
stringlengths
22
198
test
listlengths
1
7
entry_point
stringlengths
7
10
intent
stringlengths
19
200
library
listlengths
0
3
docs
listlengths
0
3
2,011,048
def f_2011048(filepath): return
os.stat(filepath).st_size
import os def check(candidate):
[ "\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"hello world!\")\n assert candidate(\"tmp.txt\") == 12\n", "\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"\")\n assert candidate(\"tmp.txt\") == 0\n", "\n with open(\"tmp.txt\", 'w') as fw: fw.write('\\n')\n assert candidate(\"tmp.txt\") == 1...
f_2011048
Get the characters count in a file `filepath`
[ "os" ]
[ { "function": "os.stat", "text": "os.stat(path, *, dir_fd=None, follow_symlinks=True) \nGet the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes – directly or indirectly through the PathLike interface ...
2,600,191
def f_2600191(l): return
l.count('a')
def check(candidate):
[ "\n assert candidate(\"123456asf\") == 1\n", "\n assert candidate(\"123456gyjnccfgsf\") == 0\n", "\n assert candidate(\"aA\"*10) == 10\n" ]
f_2600191
count the occurrences of item "a" in list `l`
[]
[]
2,600,191
def f_2600191(l): return
Counter(l)
from collections import Counter def check(candidate):
[ "\n assert dict(candidate(\"123456asf\")) == {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, 'a': 1, 's': 1, 'f': 1}\n", "\n assert candidate(\"123456gyjnccfgsf\") == {'1': 1,'2': 1,'3': 1,'4': 1,'5': 1,'6': 1,'g': 2,'y': 1,'j': 1,'n': 1,'c': 2,'f': 2,'s': 1}\n", "\n assert candidate(\"aA\"*10) == {'a...
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[ { "function": "Counter", "text": "class collections.Counter([iterable-or-mapping]) \nA Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value inclu...
2,600,191
def f_2600191(l): return
[[x, l.count(x)] for x in set(l)]
from collections import Counter def check(candidate):
[ "\n assert sorted(candidate(\"123456asf\")) == [['1', 1],['2', 1],['3', 1],['4', 1],['5', 1],['6', 1],['a', 1],['f', 1],['s', 1]]\n", "\n assert sorted(candidate(\"aA\"*10)) == [['A', 10], ['a', 10]]\n" ]
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[ { "function": "l.count", "text": "count(x) \nCount the number of deque elements equal to x. New in version 3.2.", "title": "python.library.collections#collections.deque.count" } ]
2,600,191
def f_2600191(l): return
dict(((x, l.count(x)) for x in set(l)))
from collections import Counter def check(candidate):
[ "\n assert candidate(\"123456asf\") == {'4': 1, 'a': 1, '1': 1, 's': 1, '6': 1, 'f': 1, '3': 1, '5': 1, '2': 1}\n", "\n assert candidate(\"aA\"*10) == {'A': 10, 'a': 10}\n", "\n assert candidate([1, 6]) == {1: 1, 6: 1}\n" ]
f_2600191
count the occurrences of items in list `l`
[ "collections" ]
[]
2,600,191
def f_2600191(l): return
l.count('b')
def check(candidate):
[ "\n assert candidate(\"123456abbbsf\") == 3\n", "\n assert candidate(\"123456gyjnccfgsf\") == 0\n", "\n assert candidate(\"Ab\"*10) == 10\n" ]
f_2600191
count the occurrences of item "b" in list `l`
[]
[]
12,842,997
def f_12842997(srcfile, dstdir):
return
shutil.copy(srcfile, dstdir)
import shutil from unittest.mock import Mock def check(candidate):
[ "\n shutil.copy = Mock()\n try:\n candidate('opera.txt', '/')\n except:\n return False \n" ]
f_12842997
copy file `srcfile` to directory `dstdir`
[ "shutil" ]
[ { "function": "shutil.copy", "text": "shutil.copy(src, dst, *, follow_symlinks=True) \nCopies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to t...
1,555,968
def f_1555968(x): return
max(k for k, v in x.items() if v != 0)
def check(candidate):
[ "\n assert candidate({'a': 1, 'b': 2, 'c': 2000}) == 'c'\n", "\n assert candidate({'a': 0., 'b': 0, 'c': 200.02}) == 'c'\n", "\n assert candidate({'key1': -100, 'key2': 0.}) == 'key1'\n", "\n x = {1:\"g\", 2:\"a\", 5:\"er\", -4:\"dr\"}\n assert candidate(x) == 5\n" ]
f_1555968
find the key associated with the largest value in dictionary `x` whilst key is non-zero value
[]
[]
17,021,863
def f_17021863(file):
return
file.seek(0)
def check(candidate):
[ "\n with open ('a.txt', 'w') as f:\n f.write('kangaroo\\nkoala\\noxford\\n')\n f = open('a.txt', 'r')\n f.read()\n candidate(f)\n assert f.readline() == 'kangaroo\\n'\n" ]
f_17021863
Put the curser at beginning of the file
[]
[]
38,152,389
def f_38152389(df):
return df
df['c'] = np.where(df['a'].isnull, df['b'], df['a'])
import numpy as np import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'a': [1,2,3], 'b': [0,0,0]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [1,2,3], 'b': [0,0,0], 'c': [0,0,0]}))\n", "\n df = pd.DataFrame({'a': [0,2,3], 'b': [4,5,6]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [0,2,3], 'b': [4,5,6], 'c': [4,5,6]}))\n" ]
f_38152389
combine values from column 'b' and column 'a' of dataframe `df` into column 'c' of datafram `df`
[ "numpy", "pandas" ]
[ { "function": "numpy.where", "text": "numpy.where numpy.where(condition, [x, y, ]/)\n \nReturn elements chosen from x or y depending on condition. Note When only condition is provided, this function is a shorthand for np.asarray(condition).nonzero(). Using nonzero directly should be preferred, as it beha...
4,175,686
def f_4175686(d):
return d
del d['ele']
def check(candidate):
[ "\n assert candidate({\"ale\":1, \"ele\": 2}) == {\"ale\": 1}\n" ]
f_4175686
remove key 'ele' from dictionary `d`
[]
[]
11,574,195
def f_11574195(): return
['it'] + ['was'] + ['annoying']
def check(candidate):
[ "\n assert candidate() == ['it', 'was', 'annoying']\n" ]
f_11574195
merge list `['it']` and list `['was']` and list `['annoying']` into one list
[]
[]
587,647
def f_587647(x): return
str(int(x) + 1).zfill(len(x))
def check(candidate):
[ "\n assert candidate(\"001\") == \"002\"\n", "\n assert candidate(\"100\") == \"101\"\n" ]
f_587647
increment a value with leading zeroes in a number `x`
[]
[]
17,315,881
def f_17315881(df): return
all(df.index[:-1] <= df.index[1:])
import pandas as pd def check(candidate):
[ "\n df1 = pd.DataFrame({'a': [1,2], 'bb': [0,2]})\n assert candidate(df1) == True\n", "\n df2 = pd.DataFrame({'a': [1,2,3,4,5], 'bb': [0,3,5,7,9]})\n shuffled = df2.sample(frac=3, replace=True)\n assert candidate(shuffled) == False\n", "\n df = pd.DataFrame([[1, 2], [5, 4]], columns=['a', 'b']...
f_17315881
check if a pandas dataframe `df`'s index is sorted
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" } ]
16,296,643
def f_16296643(t): return
list(t)
def check(candidate):
[ "\n assert candidate((0, 1, 2)) == [0,1,2]\n", "\n assert candidate(('a', [], 100)) == ['a', [], 100]\n" ]
f_16296643
Convert tuple `t` to list
[]
[]
16,296,643
def f_16296643(t): return
tuple(t)
def check(candidate):
[ "\n assert candidate([0,1,2]) == (0, 1, 2)\n", "\n assert candidate(['a', [], 100]) == ('a', [], 100)\n" ]
f_16296643
Convert list `t` to tuple
[]
[]
16,296,643
def f_16296643(level1):
return level1
level1 = map(list, level1)
def check(candidate):
[ "\n t = ((1, 2), (3, 4))\n t = candidate(t)\n assert list(t) == [[1, 2], [3, 4]]\n" ]
f_16296643
Convert tuple `level1` to list
[]
[]
3,880,399
def f_3880399(dataobject, logFile): return
pprint.pprint(dataobject, logFile)
import pprint def check(candidate):
[ "\n f = open('kkk.txt', 'w')\n candidate('hello', f)\n f.close()\n with open('kkk.txt', 'r') as f:\n assert 'hello' in f.readline()\n" ]
f_3880399
send the output of pprint object `dataobject` to file `logFile`
[ "pprint" ]
[ { "function": "pprint.pprint", "text": "pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) \nPrints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpre...
21,800,169
def f_21800169(df): return
df.loc[df['BoolCol']]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n" ]
f_21800169
get index of rows in column 'BoolCol'
[ "pandas" ]
[ { "function": "pandas.dataframe.loc", "text": "pandas.DataFrame.loc propertyDataFrame.loc\n \nAccess a group of rows and columns by label(s) or a boolean array. .loc[] is primarily label based, but may also be used with a boolean array. Allowed inputs are: A single label, e.g. 5 or 'a', (note that 5 is i...
21,800,169
def f_21800169(df): return
df.iloc[np.flatnonzero(df['BoolCol'])]
import numpy as np import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n" ]
f_21800169
Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True
[ "numpy", "pandas" ]
[ { "function": "numpy.flatnonzero", "text": "numpy.flatnonzero numpy.flatnonzero(a)[source]\n \nReturn indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ", "title": "numpy.reference.generated.numpy.flatnonzero" }, { "function"...
21,800,169
def f_21800169(df): return
df[df['BoolCol'] == True].index.tolist()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n" ]
f_21800169
from dataframe `df` get list of indexes of rows where column 'BoolCol' values match True
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" }, { "function": "pandas.index.tolist()", "text": "pandas.Index.tolist Index.tolist()[source]\n \n...
21,800,169
def f_21800169(df): return
df[df['BoolCol']].index.tolist()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n" ]
f_21800169
get index of rows in dataframe `df` which column 'BoolCol' matches value True
[ "pandas" ]
[ { "function": "pandas.index.tolist", "text": "pandas.Index.tolist Index.tolist()[source]\n \nReturn a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp/Timedelta/Interval/Period) Returns \n list\n See also numpy.ndarray....
299,446
def f_299446(owd):
return
os.chdir(owd)
import os from unittest.mock import Mock def check(candidate):
[ "\n os.chdir = Mock()\n try:\n candidate('/')\n except:\n assert False\n" ]
f_299446
change working directory to the directory `owd`
[ "os" ]
[ { "function": "os.chdir", "text": "os.chdir(path) \nChange the current working directory to path. This function can support specifying a file descriptor. The descriptor must refer to an opened directory, not an open file. This function can raise OSError and subclasses such as FileNotFoundError, PermissionE...
14,695,134
def f_14695134(c, testfield):
return
c.execute("INSERT INTO test VALUES (?, 'bar')", (testfield,))
import sqlite3 def check(candidate):
[ "\n conn = sqlite3.connect('dev.db')\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE test (x VARCHAR(10), y VARCHAR(10))\")\n candidate(cur, 'kang')\n cur.execute(\"SELECT * FROM test\")\n rows = cur.fetchall()\n assert len(rows) == 1\n" ]
f_14695134
insert data from a string `testfield` to sqlite db `c`
[ "sqlite3" ]
[ { "function": "c.execute", "text": "execute(sql[, parameters]) \nExecutes an SQL statement. Values may be bound to the statement using placeholders. execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you...
24,242,433
def f_24242433(): return
b'\\x89\\n'.decode('unicode_escape')
import sqlite3 def check(candidate):
[ "\n assert candidate() == '\\x89\\n'\n" ]
f_24242433
decode string "\\x89\\n" into a normal string
[ "sqlite3" ]
[]
24,242,433
def f_24242433(raw_string): return
raw_string.decode('unicode_escape')
def check(candidate):
[ "\n assert candidate(b\"Hello\") == \"Hello\"\n", "\n assert candidate(b\"hello world!\") == \"hello world!\"\n", "\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n" ]
f_24242433
convert a raw string `raw_string` into a normal string
[]
[]
24,242,433
def f_24242433(raw_byte_string): return
raw_byte_string.decode('unicode_escape')
def check(candidate):
[ "\n assert candidate(b\"Hello\") == \"Hello\"\n", "\n assert candidate(b\"hello world!\") == \"hello world!\"\n", "\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n" ]
f_24242433
convert a raw string `raw_byte_string` into a normal string
[]
[]
22,882,922
def f_22882922(s): return
[m.group(0) for m in re.finditer('(\\d)\\1*', s)]
import re def check(candidate):
[ "\n assert candidate('111234') == ['111', '2', '3', '4']\n" ]
f_22882922
split a string `s` with into all strings of repeated characters
[ "re" ]
[ { "function": "re.finditer", "text": "re.finditer(pattern, string, flags=0) \nReturn an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. ...
4,143,502
def f_4143502(): return
plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')
import numpy as np import matplotlib.pyplot as plt def check(candidate):
[ "\n assert 'matplotlib' in str(type(candidate()))\n" ]
f_4143502
scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none
[ "matplotlib", "numpy" ]
[ { "function": "plt.scatter", "text": "matplotlib.pyplot.scatter matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]\n \nA scatter plot of y vs. x with var...
4,143,502
def f_4143502(): return
plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')
import numpy as np import matplotlib.pyplot as plt def check(candidate):
[ "\n assert 'matplotlib' in str(type(candidate()[0]))\n" ]
f_4143502
do a scatter plot with empty circles
[ "matplotlib", "numpy" ]
[ { "function": "plt.plot", "text": "matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]\n \nPlot y versus x as lines and/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)\nplot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\n T...
32,063,985
def f_32063985(soup): return
soup.find('div', id='main-content').decompose()
from bs4 import BeautifulSoup def check(candidate):
[ "\n markup = \"<a>This is not div <div>This is div 1</div><div id='main-content'>This is div 2</div></a>\"\n soup = BeautifulSoup(markup,\"html.parser\")\n candidate(soup)\n assert str(soup) == '<a>This is not div <div>This is div 1</div></a>'\n" ]
f_32063985
remove a div from `soup` with a id `main-content` using beautifulsoup
[ "bs4" ]
[]
27,975,069
def f_27975069(df): return
df[df['ids'].str.contains('ball')]
import pandas as pd def check(candidate):
[ "\n f = pd.DataFrame([[\"ball1\", 1, 2], [\"hall\", 5, 4]], columns = ['ids', 'x', 'y'])\n f1 = candidate(f)\n assert f1['x'][0] == 1\n assert f1['y'][0] == 2\n" ]
f_27975069
filter rows of datafram `df` containing key word `ball` in column `ids`
[ "pandas" ]
[ { "function": "pandas.series.str.contains", "text": "pandas.Series.str.contains Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]\n \nTest if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex...
20,461,165
def f_20461165(df): return
df.reset_index(level=0, inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index'][0] == 0\n assert df['index'][1] == 1\n" ]
f_20461165
convert index at level 0 into a column in dataframe `df`
[ "pandas" ]
[ { "function": "df.reset_index", "text": "pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, ...
20,461,165
def f_20461165(df):
return
df['index1'] = df.index
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index1'][0] == 0\n assert df['index1'][1] == 1\n" ]
f_20461165
Add indexes in a data frame `df` to a column `index1`
[ "pandas" ]
[ { "function": "pandas.dataframe.index", "text": "pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.index" } ]
20,461,165
def f_20461165(df): return
df.reset_index(level=['tick', 'obs'])
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([['2016-09-13', 'C', 2, 0.0139], ['2016-07-17', 'A', 2, 0.5577]], columns = ['tick', 'tag', 'obs', 'val'])\n df = df.set_index(['tick', 'tag', 'obs'])\n df = candidate(df)\n assert df['tick']['C'] == '2016-09-13'\n" ]
f_20461165
convert pandas index in a dataframe `df` to columns
[ "pandas" ]
[ { "function": "df.reset_index", "text": "pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, ...
4,685,571
def f_4685571(b): return
[x[::-1] for x in b]
def check(candidate):
[ "\n b = [('spam',0), ('eggs',1)]\n b1 = candidate(b)\n assert b1 == [(0, 'spam'), (1, 'eggs')]\n" ]
f_4685571
Get reverse of list items from list 'b' using extended slicing
[]
[]
17,960,441
def f_17960441(a, b): return
np.array([zip(x, y) for x, y in zip(a, b)])
import numpy as np def check(candidate):
[ "\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n expected = [(9, 7), (8, 1)]\n ctr = 0\n for i in c[0]:\n assert i == expected[ctr]\n ctr += 1\n" ]
f_17960441
join each element in array `a` with element at the same index in array `b` as a tuple
[ "numpy" ]
[ { "function": "numpy.array", "text": "numpy.array numpy.array(object, dtype=None, *, copy=True, order='K', subok=False, ndmin=0, like=None)\n \nCreate an array. Parameters ", "title": "numpy.reference.generated.numpy.array" } ]
17,960,441
def f_17960441(a, b): return
np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)
import numpy as np def check(candidate):
[ "\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n e = np.array([[(9, 7), (8, 1)], [(7, 5), (6, 2)]], dtype=[('f0', '<i4'), ('f1', '<i4')])\n assert np.array_equal(c, e)\n" ]
f_17960441
zip two 2-d arrays `a` and `b`
[ "numpy" ]
[ { "function": "numpy.ndarray.reshape", "text": "numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function nu...
438,684
def f_438684(list_of_ints): return
""",""".join([str(i) for i in list_of_ints])
def check(candidate):
[ "\n list_of_ints = [8, 7, 6]\n assert candidate(list_of_ints) == '8,7,6'\n", "\n list_of_ints = [0, 1, 6]\n assert candidate(list_of_ints) == '0,1,6'\n" ]
f_438684
convert list `list_of_ints` into a comma separated string
[]
[]
8,519,922
def f_8519922(url, DATA, HEADERS_DICT, username, password): return
requests.post(url, data=DATA, headers=HEADERS_DICT, auth=(username, password))
import requests from unittest.mock import Mock def check(candidate):
[ "\n url='https://www.google.com'\n HEADERS_DICT = {'Accept':'text/json'}\n requests.post = Mock()\n try:\n candidate(url, \"{'name': 'abc'}\", HEADERS_DICT, 'admin', 'admin123')\n except:\n assert False\n" ]
f_8519922
Send a post request with raw data `DATA` and basic authentication with `username` and `password`
[ "requests" ]
[]
26,443,308
def f_26443308(): return
'abcd}def}'.rfind('}')
def check(candidate):
[ "\n assert candidate() == 8\n" ]
f_26443308
Find last occurrence of character '}' in string "abcd}def}"
[]
[]
22,365,172
def f_22365172(): return
[item for item in [1, 2, 3]]
def check(candidate):
[ "\n assert candidate() == [1,2,3]\n" ]
f_22365172
Iterate ove list `[1, 2, 3]` using list comprehension
[]
[]
12,300,912
def f_12300912(d): return
[(x['x'], x['y']) for x in d]
def check(candidate):
[ "\n data = [{'x': 1, 'y': 10}, {'x': 3, 'y': 15}, {'x': 2, 'y': 1}]\n res = candidate(data)\n assert res == [(1, 10), (3, 15), (2, 1)]\n" ]
f_12300912
extract all the values with keys 'x' and 'y' from a list of dictionaries `d` to list of tuples
[]
[]
678,236
def f_678236(): return
os.path.splitext(os.path.basename('hemanth.txt'))[0]
import os def check(candidate):
[ "\n assert candidate() == \"hemanth\"\n" ]
f_678236
get the filename without the extension from file 'hemanth.txt'
[ "os" ]
[ { "function": "os.splitext", "text": "os.path.splitext(path) \nSplit the pathname path into a pair (root, ext) such that root + ext ==\npath, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). Ch...
7,895,449
def f_7895449(): return
sum([['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']], [])
def check(candidate):
[ "\n assert candidate() == ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I']\n" ]
f_7895449
create a list containing flattened list `[['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']]`
[]
[]
31,617,845
def f_31617845(df):
return df
df = df[(df['closing_price'] >= 99) & (df['closing_price'] <= 101)]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([67, 68, 69, 70, 99, 100, 101, 102], columns = ['closing_price'])\n assert candidate(df).shape[0] == 3\n" ]
f_31617845
select rows in a dataframe `df` column 'closing_price' between two values 99 and 101
[ "pandas" ]
[]
25,698,710
def f_25698710(df): return
df.replace({'\n': '<br>'}, regex=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm<br>pqr', 'wxy<br>jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n" ]
f_25698710
replace all occurences of newlines `\n` with `<br>` in dataframe `df`
[ "pandas" ]
[ { "function": "df.replace", "text": "pandas.DataFrame.replace DataFrame.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]\n \nReplace values given in to_replace with value. Values of the DataFrame are replaced with other value...
25,698,710
def f_25698710(df): return
df.replace({'\n': '<br>'}, regex=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm<br>pqr', 'wxy<br>jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n" ]
f_25698710
replace all occurrences of a string `\n` by string `<br>` in a pandas data frame `df`
[ "pandas" ]
[ { "function": "df.replace", "text": "pandas.DataFrame.replace DataFrame.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]\n \nReplace values given in to_replace with value. Values of the DataFrame are replaced with other value...
41,923,858
def f_41923858(word): return
[(x + y) for x, y in zip(word, word[1:])]
def check(candidate):
[ "\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n", "\n assert candidate([\"hello\", \"world\", \"!\"]) == [\"helloworld\", \"world!\"]\n" ]
f_41923858
create a list containing each two adjacent letters in string `word` as its elements
[]
[]
41,923,858
def f_41923858(word): return
list(map(lambda x, y: x + y, word[:-1], word[1:]))
def check(candidate):
[ "\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n" ]
f_41923858
Get a list of pairs from a string `word` using lambda function
[]
[]
9,760,588
def f_9760588(myString): return
re.findall('(https?://[^\\s]+)', myString)
import re def check(candidate):
[ "\n assert candidate(\"This is a link http://www.google.com\") == [\"http://www.google.com\"]\n", "\n assert candidate(\"Please refer to the website: http://www.google.com\") == [\"http://www.google.com\"]\n" ]
f_9760588
extract a url from a string `myString`
[ "re" ]
[ { "function": "re.findall", "text": "re.findall(pattern, string, flags=0) \nReturn all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of gro...
9,760,588
def f_9760588(myString): return
re.search('(?P<url>https?://[^\\s]+)', myString).group('url')
import re def check(candidate):
[ "\n assert candidate(\"This is a link http://www.google.com\") == \"http://www.google.com\"\n", "\n assert candidate(\"Please refer to the website: http://www.google.com\") == \"http://www.google.com\"\n" ]
f_9760588
extract a url from a string `myString`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is differ...
5,843,518
def f_5843518(mystring): return
re.sub('[^A-Za-z0-9]+', '', mystring)
import re def check(candidate):
[ "\n assert candidate('Special $#! characters spaces 888323') == 'Specialcharactersspaces888323'\n" ]
f_5843518
remove all special characters, punctuation and spaces from a string `mystring` using regex
[ "re" ]
[ { "function": "re.sub", "text": "re.sub(pattern, repl, string, count=0, flags=0) \nReturn the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. If the pattern isn’t found, string is returned unchanged. repl can be a string or a function; if ...
36,674,519
def f_36674519(): return
pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)
import pandas as pd import datetime def check(candidate):
[ "\n actual = candidate() \n expected = [[2016, 1, 8], [2016, 2, 12],\n [2016, 3, 11], [2016, 4, 8],\n [2016, 5, 13], [2016, 6, 10],\n [2016, 7, 8], [2016, 8, 12],\n [2016, 9, 9], [2016, 10, 14],\n [2016, 11, 11], [2016, 12, 9],\n ...
f_36674519
create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'
[ "datetime", "pandas" ]
[ { "function": "pandas.date_range", "text": "pandas.date_range pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=NoDefault.no_default, inclusive=None, **kwargs)[source]\n \nReturn a fixed frequency DatetimeIndex. Returns the range of equally spaced...
508,657
def f_508657():
return matrix
matrix = [['a', 'b'], ['c', 'd'], ['e', 'f']]
def check(candidate):
[ "\n matrix = candidate()\n assert len(matrix) == 3\n assert all([len(row)==2 for row in matrix])\n" ]
f_508657
Create multidimensional array `matrix` with 3 rows and 2 columns in python
[]
[]
1,007,481
def f_1007481(mystring): return
mystring.replace(' ', '_')
def check(candidate):
[ "\n assert candidate(' ') == '_'\n", "\n assert candidate(' _ ') == '___'\n", "\n assert candidate('') == ''\n", "\n assert candidate('123123') == '123123'\n", "\n assert candidate('\\_ ') == '\\__'\n" ]
f_1007481
replace spaces with underscore in string `mystring`
[]
[]
1,249,786
def f_1249786(my_string): return
""" """.join(my_string.split())
def check(candidate):
[ "\n assert candidate('hello world ') == 'hello world'\n", "\n assert candidate('') == ''\n", "\n assert candidate(' ') == ''\n", "\n assert candidate(' hello') == 'hello'\n", "\n assert candidate(' h e l l o ') == 'h e l l o'\n" ]
f_1249786
split string `my_string` on white spaces
[]
[]
4,444,923
def f_4444923(filename): return
os.path.splitext(filename)[0]
import os def check(candidate):
[ "\n assert candidate('/Users/test/hello.txt') == '/Users/test/hello'\n", "\n assert candidate('hello.txt') == 'hello'\n", "\n assert candidate('hello') == 'hello'\n", "\n assert candidate('.gitignore') == '.gitignore'\n" ]
f_4444923
get filename without extension from file `filename`
[ "os" ]
[ { "function": "os.splitext", "text": "os.path.splitext(path) \nSplit the pathname path into a pair (root, ext) such that root + ext ==\npath, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). Ch...
13,728,486
def f_13728486(l): return
[sum(l[:i]) for i, _ in enumerate(l)]
def check(candidate):
[ "\n assert candidate([1,2,3]) == [0,1,3]\n", "\n assert candidate([]) == []\n", "\n assert candidate([1]) == [0]\n" ]
f_13728486
get a list containing the sum of each element `i` in list `l` plus the previous elements
[]
[]
9,743,134
def f_9743134(): return
"""Docs/src/Scripts/temp""".replace('/', '/\x00/').split('\x00')
def check(candidate):
[ "\n assert candidate() == ['Docs/', '/src/', '/Scripts/', '/temp']\n", "\n assert candidate() != ['Docs', 'src', 'Scripts', 'temp']\n" ]
f_9743134
split a string `Docs/src/Scripts/temp` by `/` keeping `/` in the result
[]
[]
20,546,419
def f_20546419(r): return
np.random.shuffle(np.transpose(r))
import numpy as np def check(candidate):
[ "\n a1 = np.array([[ 1, 20], [ 2, 30]])\n candidate(a1)\n assert np.array_equal(a1, np.array([[ 1, 20],[ 2, 30]])) or np.array_equal(a1, np.array([[ 20, 1], [ 30, 2]]))\n", "\n a2 = np.array([[ 1], [ 2]])\n candidate(a2) \n assert np.array_equal(a2,np.array([[ 1], [ 2]]) )\...
f_20546419
shuffle columns of an numpy array 'r'
[ "numpy" ]
[ { "function": "numpy.shuffle", "text": "numpy.random.shuffle random.shuffle(x)\n \nModify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. Note Ne...
32,675,861
def f_32675861(df):
return df
df['D'] = df['B']
import pandas as pd def check(candidate):
[ "\n df_1 = pd.DataFrame({'A': [1,2,3], 'B': ['a', 'b', 'c']})\n candidate(df_1)\n assert (df_1['D'] == df_1['B']).all()\n", "\n df_2 = pd.DataFrame({'A': [1,2,3], 'B': [1, 'A', 'B']})\n candidate(df_2)\n assert (df_2['D'] == df_2['B']).all()\n", "\n df_3 = pd.DataFrame({'B': [1]})\n cand...
f_32675861
copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'
[ "pandas" ]
[]
14,227,561
def f_14227561(data): return
list(data['A']['B'].values())[0]['maindata'][0]['Info']
import json def check(candidate):
[ "\n s1 = '{\"A\":{\"B\":{\"unknown\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT\"}]}}}}'\n data = json.loads(s1)\n assert candidate(data) == 'TEXT'\n", "\n s2 = '{\"A\":{\"B\":{\"sample1\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT!\"}]}}}}'\n data = json.loads(s2)\n assert candidate(data) == ...
f_14227561
find a value within nested json 'data' where the key inside another key 'B' is unknown.
[ "json" ]
[]
14,858,916
def f_14858916(string, predicate): return
all(predicate(x) for x in string)
def check(candidate):
[ "\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aab', predicate) == False\n", "\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aa', predica...
f_14858916
check characters of string `string` are true predication of function `predicate`
[]
[]
574,236
def f_574236(): return
os.statvfs('/').f_files - os.statvfs('/').f_ffree
import os def check(candidate):
[ "\n assert candidate() == (os.statvfs('/').f_files - os.statvfs('/').f_ffree)\n" ]
f_574236
determine number of files on a drive with python
[ "os" ]
[ { "function": "os.statvfs", "text": "os.statvfs(path) \nPerform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail...
7,011,291
def f_7011291(cursor): return
cursor.fetchone()[0]
import sqlite3 def check(candidate):
[ "\n conn = sqlite3.connect('main')\n cursor = conn.cursor()\n cursor.execute(\"CREATE TABLE student (name VARCHAR(10))\")\n cursor.execute(\"INSERT INTO student VALUES('abc')\")\n cursor.execute(\"SELECT * FROM student\")\n assert candidate(cursor) == 'abc'\n" ]
f_7011291
how to get a single result from a SQLite query from `cursor`
[ "sqlite3" ]
[ { "function": "cursor.fetchone", "text": "fetchone() \nFetches the next row of a query result set, returning a single sequence, or None when no more data is available.", "title": "python.library.sqlite3#sqlite3.Cursor.fetchone" } ]
6,378,889
def f_6378889(user_input):
return user_list
user_list = [int(number) for number in user_input.split(',')]
def check(candidate):
[ "\n assert candidate('0') == [0]\n", "\n assert candidate('12') == [12]\n", "\n assert candidate('12,33,223') == [12, 33, 223]\n" ]
f_6378889
convert string `user_input` into a list of integers `user_list`
[]
[]
6,378,889
def f_6378889(user): return
[int(s) for s in user.split(',')]
def check(candidate):
[ "\n assert candidate('0') == [0]\n", "\n assert candidate('12') == [12]\n", "\n assert candidate('12,33,223') == [12, 33, 223]\n" ]
f_6378889
Get a list of integers by splitting a string `user` with comma
[]
[]
5,212,870
def f_5212870(list): return
sorted(list, key=lambda x: (x[0], -x[1]))
def check(candidate):
[ "\n list = [(9, 0), (9, 1), (9, -1), (8, 5), (4, 5)]\n assert candidate(list) == [(4, 5), (8, 5), (9, 1), (9, 0), (9, -1)]\n" ]
f_5212870
Sorting a Python list `list` by the first item ascending and last item descending
[]
[]
403,421
def f_403421(ut, cmpfun):
return ut
ut.sort(key=cmpfun, reverse=True)
def check(candidate):
[ "\n assert candidate([], lambda x: x) == []\n", "\n assert candidate(['a', 'b', 'c'], lambda x: x) == ['c', 'b', 'a']\n", "\n assert candidate([2, 1, 3], lambda x: -x) == [1, 2, 3]\n" ]
f_403421
sort a list of objects `ut`, based on a function `cmpfun` in descending order
[]
[]
403,421
def f_403421(ut):
return ut
ut.sort(key=lambda x: x.count, reverse=True)
class Tag: def __init__(self, name, count): self.name = name self.count = count def __str__(self): return f"[{self.name}]-[{self.count}]" def check(candidate):
[ "\n result = candidate([Tag(\"red\", 1), Tag(\"blue\", 22), Tag(\"black\", 0)])\n assert (result[0].name == \"blue\") and (result[0].count == 22)\n assert (result[1].name == \"red\") and (result[1].count == 1)\n assert (result[2].name == \"black\") and (result[2].count == 0)\n" ]
f_403421
reverse list `ut` based on the `count` attribute of each object
[]
[]
3,944,876
def f_3944876(i): return
'ME' + str(i)
def check(candidate):
[ "\n assert candidate(100) == \"ME100\"\n", "\n assert candidate(0.22) == \"ME0.22\"\n", "\n assert candidate(\"text\") == \"MEtext\"\n" ]
f_3944876
cast an int `i` to a string and concat to string 'ME'
[]
[]
40,903,174
def f_40903174(df): return
df.sort_values(['System_num', 'Dis'])
import pandas as pd def check(candidate):
[ "\n df1 = pd.DataFrame([[6, 1, 1], [5, 1, 1], [4, 1, 1], [3, 2, 1], [2, 2, 1], [1, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans1 = pd.DataFrame([[4, 1, 1], [5, 1, 1], [6, 1, 1], [1, 2, 1], [2, 2, 1], [3, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans1.equals(candidate(df...
f_40903174
Sorting data in Pandas DataFrame `df` with columns 'System_num' and 'Dis'
[ "pandas" ]
[ { "function": "df.sort_values", "text": "pandas.DataFrame.sort_values DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)[source]\n \nSort by the values along either axis. Parameters ", "title": "pandas.reference.api.pan...
4,454,298
def f_4454298(infile, outfile):
return
open(outfile, 'w').write('#test firstline\n' + open(infile).read())
import filecmp def check(candidate):
[ "\n open('test1.txt', 'w').write('test1')\n candidate('test1.txt', 'test1_out.txt')\n open('test1_ans.txt', 'w').write('#test firstline\\ntest1')\n assert filecmp.cmp('test1_out.txt', 'test1_ans.txt') == True\n", "\n open('test2.txt', 'w').write('\\ntest2\\n')\n candidate('test2.txt', 'test2_out...
f_4454298
prepend the line '#test firstline\n' to the contents of file 'infile' and save as the file 'outfile'
[ "filecmp" ]
[]
19,729,928
def f_19729928(l):
return l
l.sort(key=lambda t: len(t[1]), reverse=True)
def check(candidate):
[ "\n assert candidate([(\"a\", [1]), (\"b\", [1,2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"b\", [1,2]), (\"a\", [1])]\n", "\n assert candidate([(\"a\", [1]), (\"b\", [2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"a\", [1]), (\"b\", [2])]\n", "\n assert candidate([(\"a\", [1]), (...
f_19729928
sort a list `l` by length of value in tuple
[]
[]
31,371,879
def f_31371879(s): return
re.findall('\\b(\\w+)d\\b', s)
import re def check(candidate):
[ "\n assert candidate(\"this is good\") == [\"goo\"]\n", "\n assert candidate(\"this is interesting\") == []\n", "\n assert candidate(\"good bad dd\") == [\"goo\", \"ba\", \"d\"]\n" ]
f_31371879
split string `s` by words that ends with 'd'
[ "re" ]
[ { "function": "re.findall", "text": "Pattern.findall(string[, pos[, endpos]]) \nSimilar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search().", "title": "python.library.re#re.Pattern.findall" } ]
9,012,008
def f_9012008(): return
bool(re.search('ba[rzd]', 'foobarrrr'))
import re def check(candidate):
[ "\n assert candidate() == True\n" ]
f_9012008
return `True` if string `foobarrrr` contains regex `ba[rzd]`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is differ...
7,961,363
def f_7961363(t): return
list(set(t))
def check(candidate):
[ "\n assert candidate([1,2,3]) == [1,2,3]\n", "\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n", "\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n", "\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n", "\n assert candidate([1.0, 1]) == [1.0] \n", ...
f_7961363
Removing duplicates in list `t`
[]
[]
7,961,363
def f_7961363(source_list): return
list(set(source_list))
def check(candidate):
[ "\n assert candidate([1,2,3]) == [1,2,3]\n", "\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n", "\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n", "\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n", "\n assert candidate([1.0, 1]) == [1.0] \n", ...
f_7961363
Removing duplicates in list `source_list`
[]
[]
7,961,363
def f_7961363(): return
list(OrderedDict.fromkeys('abracadabra'))
from collections import OrderedDict def check(candidate):
[ "\n assert candidate() == ['a', 'b', 'r', 'c', 'd']\n" ]
f_7961363
Removing duplicates in list `abracadabra`
[ "collections" ]
[ { "function": "collections.OrderedDict", "text": "class collections.OrderedDict([items]) \nReturn an instance of a dict subclass that has methods specialized for rearranging dictionary order. New in version 3.1. \npopitem(last=True) \nThe popitem() method for ordered dictionaries returns and removes a ...
5,183,533
def f_5183533(a): return
numpy.array(a).reshape(-1).tolist()
import numpy def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3,4,5,6]\n", "\n assert candidate(['a', 'aa', 'abc']) == ['a', 'aa', 'abc']\n" ]
f_5183533
Convert array `a` into a list
[ "numpy" ]
[ { "function": "numpy.ndarray.reshape", "text": "numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function nu...
5,183,533
def f_5183533(a): return
numpy.array(a)[0].tolist()
import numpy def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3]\n", "\n assert candidate(['a', 'aa', 'abc']) == 'a'\n" ]
f_5183533
Convert the first row of numpy matrix `a` to a list
[ "numpy" ]
[ { "function": "numpy.ndarray.tolist", "text": "numpy.ndarray.tolist method ndarray.tolist()\n \nReturn the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via th...
5,999,747
def f_5999747(soup): return
soup.find(text='Address:').findNext('td').contents[0]
from bs4 import BeautifulSoup def check(candidate):
[ "\n assert candidate(BeautifulSoup(\"<td><b>Address:</b></td><td>My home address</td>\")) == \"My home address\"\n", "\n assert candidate(BeautifulSoup(\"<td><b>Address:</b></td><td>This is my home address</td><td>Not my home address</td>\")) == \"This is my home address\"\n", "\n assert candidate(Beau...
f_5999747
In `soup`, get the content of the sibling of the `td` tag with text content `Address:`
[ "bs4" ]
[]
4,284,648
def f_4284648(l): return
""" """.join([('%d@%d' % t) for t in l])
def check(candidate):
[ "\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n", "\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n", "\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n" ]
f_4284648
convert elements of each tuple in list `l` into a string separated by character `@`
[]
[]
4,284,648
def f_4284648(l): return
""" """.join([('%d@%d' % (t[0], t[1])) for t in l])
def check(candidate):
[ "\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n", "\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n", "\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n" ]
f_4284648
convert each tuple in list `l` to a string with '@' separating the tuples' elements
[]
[]
29,696,641
def f_29696641(teststr): return
[i for i in teststr if re.search('\\d+[xX]', i)]
import re def check(candidate):
[ "\n assert candidate(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']) == ['2x Sec String', '5X fifth']\n", "\n assert candidate(['1x', '2', '3X', '4x random', '5X random']) == ['1x', '3X', '4x random', '5X random']\n", "\n assert candidate(['1x', '2', '3X', '4xrandom', '5Xra...
f_29696641
Get all matches with regex pattern `\\d+[xX]` in list of string `teststr`
[ "re" ]
[ { "function": "re.search", "text": "re.search(pattern, string, flags=0) \nScan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is differ...
15,315,452
def f_15315452(df): return
df['A'][(df['B'] > 50) & (df['C'] == 900)]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'A': [7, 7, 4, 4, 7, 7, 3, 9, 6, 3], 'B': [20, 80, 90, 30, 80, 60, 80, 40, 40 ,10], 'C': [300, 700, 100, 900, 200, 800, 900, 100, 100, 600]})\n assert candidate(df).to_dict() == {6: 3}\n", "\n df1 = pd.DataFrame({'A': [9, 9, 5, 8, 7, 9, 2, 2, 5, 7], 'B': [40, 70, 70, 80, 50, 30, 80...
f_15315452
select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`
[ "pandas" ]
[]
4,642,501
def f_4642501(o): return
sorted(o.items())
import pandas as pd def check(candidate):
[ "\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [(1, \"abc\"), (2, \"pqr\"), (5, \"klm\")]\n", "\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [(-1.009, 'pow'), (4.221, 'uwv')]\n", "\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) ==...
f_4642501
Sort dictionary `o` in ascending order based on its keys and items
[ "pandas" ]
[]
4,642,501
def f_4642501(d): return
sorted(d)
def check(candidate):
[ "\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [1, 2, 5]\n", "\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [-1.009, 4.221]\n", "\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) == ['#wwq', '35', 'Rwc', 'as2q']\n" ]
f_4642501
get sorted list of keys of dict `d`
[]
[]
4,642,501
def f_4642501(d): return
sorted(d.items())
def check(candidate):
[ "\n d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}\n assert candidate(d) == [('a', [1, 2, 3]), ('b', ['blah', 'bhasdf', 'asdf']), ('c', ['one', 'two']), ('d', ['asdf', 'wer', 'asdf', 'zxcv'])]\n" ]
f_4642501
sort dictionaries `d` by keys
[]
[]
642,154
def f_642154(): return
int('1')
def check(candidate):
[ "\n assert candidate() == 1\n", "\n assert candidate() + 1 == 2\n" ]
f_642154
convert string "1" into integer
[]
[]
642,154
def f_642154(T1): return
[list(map(int, x)) for x in T1]
def check(candidate):
[ "\n T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16'))\n assert candidate(T1) == [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]\n" ]
f_642154
convert items in `T1` to integers
[]
[]
3,777,301
def f_3777301():
return
subprocess.call(['./test.sh'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n" ]
f_3777301
call a shell script `./test.sh` using subprocess
[ "subprocess" ]
[ { "function": "subprocess.call", "text": "subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) \nRun the command described by args. Wait for command to complete, then return the returncode attribute. Code needing to capture stdout or stde...
3,777,301
def f_3777301():
return
subprocess.call(['notepad'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n" ]
f_3777301
call a shell script `notepad` using subprocess
[ "subprocess" ]
[ { "function": "subprocess.call", "text": "subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False, cwd=None, timeout=None, **other_popen_kwargs) \nRun the command described by args. Wait for command to complete, then return the returncode attribute. Code needing to capture stdout or stde...
7,946,798
def f_7946798(l1, l2): return
[val for pair in zip(l1, l2) for val in pair]
def check(candidate):
[ "\n assert candidate([1,2,3], [10,20,30]) == [1,10,2,20,3,30]\n", "\n assert candidate([1,2,3], ['c','b','a']) == [1,'c',2,'b',3,'a']\n", "\n assert candidate([1,2,3], ['c','b']) == [1,'c',2,'b']\n" ]
f_7946798
combine lists `l1` and `l2` by alternating their elements
[]
[]
8,908,287
def f_8908287(): return
base64.b64encode(b'data to be encoded')
import base64 def check(candidate):
[ "\n assert candidate() == b'ZGF0YSB0byBiZSBlbmNvZGVk'\n" ]
f_8908287
encode string 'data to be encoded'
[ "base64" ]
[ { "function": "base64.b64encode", "text": "base64.b64encode(s, altchars=None) \nEncode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + ...
8,908,287
def f_8908287(): return
'data to be encoded'.encode('ascii')
def check(candidate):
[ "\n assert candidate() == b'data to be encoded'\n" ]
f_8908287
encode a string `data to be encoded` to `ascii` encoding
[]
[]
7,856,296
def f_7856296(): return
list(csv.reader(open('text.txt', 'r'), delimiter='\t'))
import csv def check(candidate):
[ "\n with open('text.txt', 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter='\t')\n spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])\n spamwriter.writerow(['hello', 'world', '!'])\n\n assert candidate() == [['Spam', 'Lovely Spam', 'Wonderful Spam'], [...
f_7856296
parse tab-delimited CSV file 'text.txt' into a list
[ "csv" ]
[ { "function": "csv.reader", "text": "csv.reader(csvfile, dialect='excel', **fmtparams) \nReturn a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called — file objects an...
9,035,479
def f_9035479(my_object, my_str): return
getattr(my_object, my_str)
def check(candidate):
[ "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert candidate(s, \"name\") == \"abc\"\n", "\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert (candidate(s, \"grade\") - 9...
f_9035479
Get attribute `my_str` of object `my_object`
[]
[]
5,558,418
def f_5558418(LD): return
dict(zip(LD[0], zip(*[list(d.values()) for d in LD])))
import collections def check(candidate):
[ "\n employees = [{'name' : 'apple', 'id': 60}, {'name' : 'orange', 'id': 65}]\n exp_result = {'name': ('apple', 'orange'), 'id': (60, 65)}\n actual_result = candidate(employees)\n for key in actual_result:\n assert collections.Counter(list(exp_result[key])) == collections.Counter(list(actual_resu...
f_5558418
group a list of dicts `LD` into one dict by key
[ "collections" ]
[]