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
1,762,484
def f_1762484(stocks_list): return
[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']
def check(candidate):
[ "\n stocks_list = ['AAPL', 'MSFT', 'GOOG', 'MSFT', 'MSFT']\n assert(candidate(stocks_list) == [1,3,4])\n", "\n stocks_list = ['AAPL', 'MSXT', 'GOOG', 'MSAT', 'SFT']\n assert(candidate(stocks_list) == [])\n" ]
f_1762484
find the index of an element 'MSFT' in a list `stocks_list`
[]
[]
3,464,359
def f_3464359(ax, labels): return
ax.set_xticklabels(labels, rotation=45)
import matplotlib.pyplot as plt def check(candidate):
[ "\n fig, ax = plt.subplots()\n ax.plot([1, 2, 3, 4], [1, 4, 2, 3])\n ret = candidate(ax, [f\"#{i}\" for i in range(7)])\n assert [tt.get_rotation() == 45.0 for tt in ret]\n" ]
f_3464359
rotate the xtick `labels` of matplotlib plot `ax` by `45` degrees to make long labels readable
[ "matplotlib" ]
[ { "function": "ax.set_xticklabels", "text": "matplotlib.axes.Axes.set_xticklabels Axes.set_xticklabels(labels, *, fontdict=None, minor=False, **kwargs)[source]\n \nSet the xaxis' labels with list of string labels. Warning This method should only be used after fixing the tick positions using Axes.set_xtic...
875,968
def f_875968(s): return
re.sub('[^\\w]', ' ', s)
import re def check(candidate):
[ "\n s = \"how much for the maple syrup? $20.99? That's ridiculous!!!\"\n assert candidate(s) == 'how much for the maple syrup 20 99 That s ridiculous '\n" ]
f_875968
remove symbols from a string `s`
[ "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 ...
34,750,084
def f_34750084(s): return
re.findall("'\\\\[0-7]{1,3}'", s)
import re def check(candidate):
[ "\n assert candidate(r\"char x = '\\077';\") == [\"'\\\\077'\"]\n" ]
f_34750084
Find octal characters matches from a string `s` using regex
[ "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...
13,209,288
def f_13209288(input): return
re.split(r'[ ](?=[A-Z]+\b)', input)
import re def check(candidate):
[ "\n assert candidate('HELLO there HOW are YOU') == ['HELLO there', 'HOW are', 'YOU']\n", "\n assert candidate('hELLO there HoW are YOU') == ['hELLO there HoW are', 'YOU']\n", "\n assert candidate('7 is a NUMBER') == ['7 is a', 'NUMBER']\n", "\n assert candidate('NUMBER 7') == ['NUMBER 7']\n" ]
f_13209288
split string `input` based on occurrences of regex pattern '[ ](?=[A-Z]+\\b)'
[ "re" ]
[ { "function": "re.split", "text": "re.split(pattern, string, maxsplit=0, flags=0) \nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit ...
13,209,288
def f_13209288(input): return
re.split('[ ](?=[A-Z])', input)
import re def check(candidate):
[ "\n assert candidate('HELLO there HOW are YOU') == ['HELLO there', 'HOW are', 'YOU']\n", "\n assert candidate('hELLO there HoW are YOU') == ['hELLO there', 'HoW are', 'YOU']\n", "\n assert candidate('7 is a NUMBER') == ['7 is a', 'NUMBER']\n", "\n assert candidate('NUMBER 7') == ['NUMBER 7']\n" ]
f_13209288
Split string `input` at every space followed by an upper-case letter
[ "re" ]
[ { "function": "re.split", "text": "re.split(pattern, string, maxsplit=0, flags=0) \nSplit string by the occurrences of pattern. If capturing parentheses are used in pattern, then the text of all groups in the pattern are also returned as part of the resulting list. If maxsplit is nonzero, at most maxsplit ...
24,642,040
def f_24642040(url, files, headers, data): return
requests.post(url, files=files, headers=headers, data=data)
import requests from unittest.mock import Mock def check(candidate):
[ "\n requests.post = Mock()\n try:\n candidate('https://www.google.com', ['a.txt'], {'accept': 'text/json'}, {'name': 'abc'})\n except:\n assert False\n" ]
f_24642040
send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`
[ "requests" ]
[]
4,290,716
def f_4290716(filename, bytes_): return
open(filename, 'wb').write(bytes_)
def check(candidate):
[ "\n bytes_ = b'68 65 6c 6c 6f'\n candidate(\"tmpfile\", bytes_)\n\n with open(\"tmpfile\", 'rb') as fr:\n assert fr.read() == bytes_\n" ]
f_4290716
write bytes `bytes_` to a file `filename` in python 3
[]
[]
33,078,554
def f_33078554(lst, dct): return
[dct[k] for k in lst]
def check(candidate):
[ "\n assert candidate(['c', 'd', 'a', 'b', 'd'], {'a': '3', 'b': '3', 'c': '5', 'd': '3'}) == ['5', '3', '3', '3', '3'] \n", "\n assert candidate(['c', 'd', 'a', 'b', 'd'], {'a': 3, 'b': 3, 'c': 5, 'd': 3}) == [5, 3, 3, 3, 3] \n", "\n assert candidate(['c', 'd', 'a', 'b'], {'a': 3, 'b': 3, 'c': 5, 'd': ...
f_33078554
get a list from a list `lst` with values mapped into a dictionary `dct`
[]
[]
15,247,628
def f_15247628(x): return
x['name'][x.duplicated('name')]
import pandas as pd def check(candidate):
[ "\n assert candidate(pd.DataFrame([{'name': 'willy', 'age': 10}, {'name': 'wilson', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == [] \n", "\n assert candidate(pd.DataFrame([{'name': 'willy', 'age': 10}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == ['willy'] \n", "\n a...
f_15247628
find duplicate names in column 'name' of the dataframe `x`
[ "pandas" ]
[ { "function": "x.duplicated", "text": "pandas.DataFrame.duplicated DataFrame.duplicated(subset=None, keep='first')[source]\n \nReturn boolean Series denoting duplicate rows. Considering certain columns is optional. Parameters ", "title": "pandas.reference.api.pandas.dataframe.duplicated" } ]
783,897
def f_783897(): return
round(1.923328437452, 3)
def check(candidate):
[ "\n assert candidate() == 1.923\n" ]
f_783897
truncate float 1.923328437452 to 3 decimal places
[]
[]
22,859,493
def f_22859493(li): return
sorted(li, key=lambda x: datetime.strptime(x[1], '%d/%m/%Y'), reverse=True)
from datetime import datetime def check(candidate):
[ "\n assert candidate([['name', '01/03/2012', 'job'], ['name', '02/05/2013', 'job'], ['name', '03/08/2014', 'job']]) == [['name', '03/08/2014', 'job'], ['name', '02/05/2013', 'job'], ['name', '01/03/2012', 'job']] \n", "\n assert candidate([['name', '01/03/2012', 'job'], ['name', '02/05/2012', 'job'], ['name...
f_22859493
sort list `li` in descending order based on the date value in second element of each list in list `li`
[ "datetime" ]
[ { "function": "datetime.strptime", "text": "classmethod datetime.strptime(date_string, format) \nReturn a datetime corresponding to date_string, parsed according to format. This is equivalent to: datetime(*(time.strptime(date_string, format)[0:6]))\n ValueError is raised if the date_string and format can’t...
29,394,552
def f_29394552(ax):
return
ax.set_rlabel_position(135)
import matplotlib.pyplot as plt def check(candidate):
[ "\n ax = plt.subplot(111, polar=True)\n candidate(ax)\n assert ax.properties()['rlabel_position'] == 135.0\n" ]
f_29394552
place the radial ticks in plot `ax` at 135 degrees
[ "matplotlib" ]
[ { "function": "ax.set_rlabel_position", "text": "set_rlabel_position(value)[source]\n \nUpdate the theta position of the radius labels. Parameters \n \nvaluenumber\n\n\nThe angular position of the radius labels in degrees.", "title": "matplotlib.projections_api#matplotlib.projections.polar.PolarAxes.se...
3,320,406
def f_3320406(my_path): return
os.path.isabs(my_path)
import os def check(candidate):
[ "\n assert candidate('.') == False \n", "\n assert candidate('/') == True \n", "\n assert candidate('/usr') == True\n" ]
f_3320406
check if path `my_path` is an absolute path
[ "os" ]
[ { "function": "os.isabs", "text": "os.path.isabs(path) \nReturn True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter. Changed in version 3.6: Accepts a path-like object.", "title": "py...
2,212,433
def f_2212433(yourdict): return
len(list(yourdict.keys()))
def check(candidate):
[ "\n assert candidate({'a': 1, 'b': 2, 'c': 3}) == 3 \n", "\n assert candidate({'a': 2, 'c': 3}) == 2\n" ]
f_2212433
get number of keys in dictionary `yourdict`
[]
[]
2,212,433
def f_2212433(yourdictfile): return
len(set(open(yourdictfile).read().split()))
def check(candidate):
[ "\n with open('dict.txt', 'w') as fw:\n for w in [\"apple\", \"banana\", \"tv\", \"apple\", \"phone\"]:\n fw.write(f\"{w}\\n\")\n assert candidate('dict.txt') == 4\n" ]
f_2212433
count the number of keys in dictionary `yourdictfile`
[]
[]
20,067,636
def f_20067636(df): return
df.groupby('id').first()
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({\n 'id': [1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 6, 6, 6, 7, 7], \n 'value': ['first', 'second', 'second', 'first', 'second', 'first', 'third', 'fourth', 'fifth', 'second', 'fifth', 'first', 'first', 'second', 'third', 'fourth', 'fifth']\n })\n assert candidate(df).to_dict...
f_20067636
pandas dataframe `df` get first row of each group by 'id'
[ "pandas" ]
[ { "function": "dataframe.groupby", "text": "pandas.DataFrame.groupby DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=NoDefault.no_default, observed=False, dropna=True)[source]\n \nGroup DataFrame using a mapper or by a Series of columns. A groupby operatio...
40,924,332
def f_40924332(df): return
pd.concat([df[0].apply(pd.Series), df[1]], axis=1)
import numpy as np import pandas as pd def check(callerFunction):
[ "\n assert callerFunction(pd.DataFrame([[[8, 10, 12], 'A'], [[7, 9, 11], 'B']])).equals(pd.DataFrame([[8,10,12,'A'], [7,9,11,'B']], columns=[0,1,2,1]))\n", "\n assert callerFunction(pd.DataFrame([[[8, 10, 12], 'A'], [[7, 11], 'B']])).equals(pd.DataFrame([[8.0,10.0,12.0,'A'], [7.0,11.0,np.nan,'B']], columns=...
f_40924332
split a list in first column into multiple columns keeping other columns as well in pandas data frame `df`
[ "numpy", "pandas" ]
[ { "function": "pandas.concat", "text": "pandas.concat pandas.concat(objs, axis=0, join='outer', ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True)[source]\n \nConcatenate pandas objects along a particular axis with optional set logic along the other axes...
30,759,776
def f_30759776(data): return
re.findall('src="js/([^"]*\\bjquery\\b[^"]*)"', data)
import re def check(candidate):
[ "\n data = '<script type=\"text/javascript\" src=\"js/jquery-1.9.1.min.js\"/><script type=\"text/javascript\" src=\"js/jquery-migrate-1.2.1.min.js\"/><script type=\"text/javascript\" src=\"js/jquery-ui.min.js\"/><script type=\"text/javascript\" src=\"js/abc_bsub.js\"/><script type=\"text/javascript\" src=\"js/ab...
f_30759776
extract attributes 'src="js/([^"]*\\bjquery\\b[^"]*)"' from string `data`
[ "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...
25,388,796
def f_25388796(): return
sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])
def check(candidate):
[ "\n assert candidate() == 4\n" ]
f_25388796
Sum integers contained in strings in list `['', '3.4', '', '', '1.0']`
[]
[]
804,995
def f_804995(): return
subprocess.Popen(['c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_804995
Call a subprocess with arguments `c:\\Program Files\\VMware\\VMware Server\\vmware-cmd.bat` that may contain spaces
[ "subprocess" ]
[ { "function": "subprocess.Popen", "text": "class subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=None, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=Fal...
26,441,253
def f_26441253(q):
return q
for n in [1,3,4,2]: q.put((-n, n))
from queue import PriorityQueue def check(candidate):
[ "\n q = PriorityQueue()\n q = candidate(q)\n expected = [4, 3, 2, 1]\n for i in range(0, len(expected)):\n assert q.get()[1] == expected[i]\n" ]
f_26441253
reverse a priority queue `q` in python without using classes
[ "queue" ]
[ { "function": "q.put", "text": "Queue.put(item, block=True, timeout=None) \nPut item into the queue. If optional args block is true and timeout is None (the default), block if necessary until a free slot is available. If timeout is a positive number, it blocks at most timeout seconds and raises the Full ex...
18,897,261
def f_18897261(df): return
df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([1, 3, 4, 5, 7, 9], columns = ['group'])\n a = candidate(df)\n assert 'AxesSubplot' in str(type(a))\n" ]
f_18897261
make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`
[ "pandas" ]
[ { "function": "dataframe.plot", "text": "pandas.Series.plot Series.plot(*args, **kwargs)[source]\n \nMake plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters ", "title": "pandas.reference.api.pandas.series.plot" } ]
373,194
def f_373194(data): return
re.findall('([a-fA-F\\d]{32})', data)
import re def check(candidate):
[ "\n assert candidate('6f96cfdfe5ccc627cadf24b41725caa4 gorilla') == ['6f96cfdfe5ccc627cadf24b41725caa4']\n" ]
f_373194
find all matches of regex pattern '([a-fA-F\\d]{32})' in string `data`
[ "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...
518,021
def f_518021(my_list): return
len(my_list)
def check(candidate):
[ "\n assert candidate([]) == 0\n", "\n assert candidate([1]) == 1\n", "\n assert candidate([1, 2]) == 2\n" ]
f_518021
Get the length of list `my_list`
[]
[]
518,021
def f_518021(l): return
len(l)
import numpy as np def check(candidate):
[ "\n assert candidate([]) == 0\n", "\n assert candidate(np.array([1])) == 1\n", "\n assert candidate(np.array([1, 2])) == 2\n" ]
f_518021
Getting the length of array `l`
[ "numpy" ]
[]
518,021
def f_518021(s): return
len(s)
import numpy as np def check(candidate):
[ "\n assert candidate([]) == 0\n", "\n assert candidate(np.array([1])) == 1\n", "\n assert candidate(np.array([1, 2])) == 2\n" ]
f_518021
Getting the length of array `s`
[ "numpy" ]
[]
518,021
def f_518021(my_tuple): return
len(my_tuple)
def check(candidate):
[ "\n assert candidate(()) == 0\n", "\n assert candidate(('aa', 'wfseg', '')) == 3\n", "\n assert candidate(('apple',)) == 1\n" ]
f_518021
Getting the length of `my_tuple`
[]
[]
518,021
def f_518021(my_string): return
len(my_string)
def check(candidate):
[ "\n assert candidate(\"sedfgbdjofgljnh\") == 15\n", "\n assert candidate(\" \") == 13\n", "\n assert candidate(\"vsdh4'cdf'\") == 10\n" ]
f_518021
Getting the length of `my_string`
[]
[]
40,452,956
def f_40452956(): return
b'\\a'.decode('unicode-escape')
def check(candidate):
[ "\n assert candidate() == '\\x07'\n" ]
f_40452956
remove escape character from string "\\a"
[]
[]
8,687,018
def f_8687018(): return
"""obama""".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')
def check(candidate):
[ "\n assert candidate() == 'oabmb'\n" ]
f_8687018
replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.
[]
[]
303,200
def f_303200():
return
shutil.rmtree('/folder_name')
import os import shutil from unittest.mock import Mock def check(candidate):
[ "\n shutil.rmtree = Mock()\n os.walk = Mock(return_value = [])\n candidate()\n assert os.walk('/') == []\n" ]
f_303200
remove directory tree '/folder_name'
[ "os", "shutil" ]
[ { "function": "shutil.rmtree", "text": "shutil.rmtree(path, ignore_errors=False, onerror=None) \nDelete an entire directory tree; path must point to a directory (but not a symbolic link to a directory). If ignore_errors is true, errors resulting from failed removals will be ignored; if false or omitted, su...
13,740,672
def f_13740672(data):
return data
def weekday(i): if i >=1 and i <= 5: return True else: return False data['weekday'] = data['my_dt'].apply(lambda x: weekday(x))
import pandas as pd def check(candidate):
[ "\n data = pd.DataFrame([1, 2, 3, 4, 5, 6, 7], columns = ['my_dt'])\n data = candidate(data)\n assert data['weekday'][5] == False\n assert data['weekday'][6] == False\n for i in range (0, 5):\n assert data['weekday'][i]\n" ]
f_13740672
create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`
[ "pandas" ]
[ { "function": "dataframe.apply", "text": "pandas.DataFrame.apply DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)[source]\n \nApply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0)...
20,950,650
def f_20950650(x): return
sorted(x, key=x.get, reverse=True)
from collections import Counter def check(candidate):
[ "\n x = Counter({'blue': 1, 'red': 2, 'green': 3})\n assert candidate(x) == ['green', 'red', 'blue']\n", "\n x = Counter({'blue': 1.234, 'red': 1.35, 'green': 1.789})\n assert candidate(x) == ['green', 'red', 'blue']\n", "\n x = Counter({'blue': \"b\", 'red': \"r\", 'green': \"g\"})\n assert c...
f_20950650
reverse sort Counter `x` by values
[ "collections" ]
[]
20,950,650
def f_20950650(x): return
sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)
from collections import Counter def check(candidate):
[ "\n x = Counter({'blue': 1, 'red': 2, 'green': 3})\n assert candidate(x) == [('green', 3), ('red', 2), ('blue', 1)]\n", "\n x = Counter({'blue': 1.234, 'red': 1.35, 'green': 1.789})\n assert candidate(x) == [('green', 1.789), ('red', 1.35), ('blue', 1.234)]\n", "\n x = Counter({'blue': \"b\", 're...
f_20950650
reverse sort counter `x` by value
[ "collections" ]
[]
9,775,297
def f_9775297(a, b): return
np.vstack((a, b))
import numpy as np def check(candidate):
[ "\n a = np.array([[1, 2, 3], [4, 5, 6]])\n b = np.array([[9, 8, 7], [6, 5, 4]])\n assert np.array_equal(candidate(a, b), np.array([[1, 2, 3], [4, 5, 6], [9, 8, 7], [6, 5, 4]]))\n", "\n a = np.array([[1, 2.45, 3], [4, 0.55, 612]])\n b = np.array([[988, 8, 7], [6, 512, 4]])\n assert np.array_equal...
f_9775297
append a numpy array 'b' to a numpy array 'a'
[ "numpy" ]
[ { "function": "numpy.vstack", "text": "numpy.vstack numpy.vstack(tup)[source]\n \nStack arrays in sequence vertically (row wise). This is equivalent to concatenation along the first axis after 1-D arrays of shape (N,) have been reshaped to (1,N). Rebuilds arrays divided by vsplit. This function makes most...
21,887,754
def f_21887754(a, b): return
np.concatenate((a, b), axis=0)
import numpy as np def check(candidate):
[ "\n a = np.array([[1, 5, 9], [2, 6, 10]])\n b = np.array([[3, 7, 11], [4, 8, 12]])\n assert np.array_equal(candidate(a, b), np.array([[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]))\n", "\n a = np.array([[1, 2.45, 3], [4, 0.55, 612]])\n b = np.array([[988, 8, 7], [6, 512, 4]])\n assert np.array...
f_21887754
numpy concatenate two arrays `a` and `b` along the first axis
[ "numpy" ]
[ { "function": "numpy.concatenate", "text": "numpy.concatenate numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting=\"same_kind\")\n \nJoin a sequence of arrays along an existing axis. Parameters ", "title": "numpy.reference.generated.numpy.concatenate" } ]
21,887,754
def f_21887754(a, b): return
np.concatenate((a, b), axis=1)
import numpy as np def check(candidate):
[ "\n a = np.array([[1, 5, 9], [2, 6, 10]])\n b = np.array([[3, 7, 11], [4, 8, 12]])\n assert np.array_equal(candidate(a, b), np.array([[1, 5, 9, 3, 7, 11], [2, 6, 10, 4, 8, 12]]))\n", "\n a = np.array([[1, 2.45, 3], [4, 0.55, 612]])\n b = np.array([[988, 8, 7], [6, 512, 4]])\n assert np.array_equ...
f_21887754
numpy concatenate two arrays `a` and `b` along the second axis
[ "numpy" ]
[ { "function": "numpy.concatenate", "text": "numpy.concatenate numpy.concatenate((a1, a2, ...), axis=0, out=None, dtype=None, casting=\"same_kind\")\n \nJoin a sequence of arrays along an existing axis. Parameters ", "title": "numpy.reference.generated.numpy.concatenate" } ]
21,887,754
def f_21887754(a, b): return
np.r_[(a[None, :], b[None, :])]
import numpy as np def check(candidate):
[ "\n a = np.array([[1, 5, 9], [2, 6, 10]])\n b = np.array([[3, 7, 11], [4, 8, 12]])\n assert np.array_equal(candidate(a, b), np.array([[[1, 5, 9], [2, 6, 10]], [[3, 7, 11], [4, 8, 12]]]))\n", "\n a = np.array([[1, 2.45, 3], [4, 0.55, 612]])\n b = np.array([[988, 8, 7], [6, 512, 4]])\n assert np.a...
f_21887754
numpy concatenate two arrays `a` and `b` along the first axis
[ "numpy" ]
[ { "function": "numpy.r_", "text": "numpy.r_ numpy.r_ = <numpy.lib.index_tricks.RClass object>\n \nTranslates slice objects to concatenation along the first axis. This is a simple way to build up arrays quickly. There are two use cases. If the index expression contains comma separated arrays, then stack t...
21,887,754
def f_21887754(a, b): return
np.array((a, b))
import numpy as np def check(candidate):
[ "\n a = np.array([[1, 5, 9], [2, 6, 10]])\n b = np.array([[3, 7, 11], [4, 8, 12]])\n assert np.array_equal(candidate(a, b), np.array([[[1, 5, 9], [2, 6, 10]], [[3, 7, 11], [4, 8, 12]]]))\n", "\n a = np.array([[1, 2.45, 3], [4, 0.55, 612]])\n b = np.array([[988, 8, 7], [6, 512, 4]])\n assert np.a...
f_21887754
numpy concatenate two arrays `a` and `b` along the first axis
[ "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" } ]
2,805,231
def f_2805231(): return
socket.getaddrinfo('google.com', 80)
import socket def check(candidate):
[ "\n res = candidate()\n assert all([(add[4][1] == 80) for add in res])\n" ]
f_2805231
fetch address information for host 'google.com' ion port 80
[ "socket" ]
[ { "function": "socket.getaddrinfo", "text": "socket.getaddrinfo(host, port, family=0, type=0, proto=0, flags=0) \nTranslate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. host is a domain name, a string representa...
17,552,997
def f_17552997(df): return
df.xs('sat', level='day', drop_level=False)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'year':[2008,2008,2008,2008,2009,2009,2009,2009], \n 'flavour':['strawberry','strawberry','banana','banana',\n 'strawberry','strawberry','banana','banana'],\n 'day':['sat','sun','sat','sun','sat','sun','sat','sun'],\n ...
f_17552997
add a column 'day' with value 'sat' to dataframe `df`
[ "pandas" ]
[ { "function": "df.xs", "text": "pandas.DataFrame.xs DataFrame.xs(key, axis=0, level=None, drop_level=True)[source]\n \nReturn cross-section from the Series/DataFrame. This method takes a key argument to select data at a particular level of a MultiIndex. Parameters ", "title": "pandas.reference.api.pa...
4,356,842
def f_4356842(): return
HttpResponse('Unauthorized', status=401)
from django.http import HttpResponse from django.conf import settings if not settings.configured: settings.configure(DEBUG=True) def check(candidate):
[ "\n assert candidate().status_code == 401\n" ]
f_4356842
return a 401 unauthorized in django
[ "django" ]
[ { "function": "HttpResponse", "text": "class HttpResponse", "title": "django.ref.request-response#django.http.HttpResponse" } ]
13,598,363
def f_13598363(): return
Flask('test', template_folder='wherever')
from flask import Flask def check(candidate):
[ "\n __name__ == \"test\"\n assert candidate().template_folder == \"wherever\"\n" ]
f_13598363
Flask set folder 'wherever' as the default template folder
[ "flask" ]
[ { "function": "Flask", "text": "class flask.Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None) \nThe flask object implements a WSGI...
3,398,589
def f_3398589(c2):
return c2
c2.sort(key=lambda row: row[2])
def check(candidate):
[ "\n c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]]\n candidate(c2)\n assert c2[0] == [7,8,9]\n", "\n c2 = [[14.343, 25.24, 46], [1, 22, 53.45], [7, 8.65, 9]]\n candidate(c2)\n assert c2[0] == [7,8.65,9]\n" ]
f_3398589
sort a list of lists 'c2' such that third row comes first
[]
[]
3,398,589
def f_3398589(c2):
return c2
c2.sort(key=lambda row: (row[2], row[1], row[0]))
def check(candidate):
[ "\n c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]]\n candidate(c2)\n assert c2[0] == [7,8,9]\n", "\n c2 = [[14.343, 25.24, 46], [1, 22, 53.45], [7, 8.65, 9]]\n candidate(c2)\n assert c2[0] == [7,8.65,9]\n" ]
f_3398589
sort a list of lists 'c2' in reversed row order
[]
[]
3,398,589
def f_3398589(c2):
return c2
c2.sort(key=lambda row: (row[2], row[1]))
def check(candidate):
[ "\n c2 = [[14, 25, 46], [1, 22, 53], [7, 8, 9]]\n candidate(c2)\n assert c2[0] == [7,8,9]\n", "\n c2 = [[14.343, 25.24, 46], [1, 22, 53.45], [7, 8.65, 9]]\n candidate(c2)\n assert c2[0] == [7,8.65,9]\n" ]
f_3398589
Sorting a list of lists `c2`, each by the third and second row
[]
[]
10,960,463
def f_10960463(): return
matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})
import matplotlib def check(candidate):
[ "\n try:\n candidate()\n except:\n assert False\n" ]
f_10960463
set font `Arial` to display non-ascii characters in matplotlib
[ "matplotlib" ]
[ { "function": "matplotlib.rc", "text": "matplotlib.pyplot.rc matplotlib.pyplot.rc(group, **kwargs)[source]\n \nSet the current rcParams. group is the grouping for the rc, e.g., for lines.linewidth the group is lines, for axes.facecolor, the group is axes, and so on. Group may also be a list or tuple of gr...
20,576,618
def f_20576618(df): return
df['date'].apply(lambda x: x.toordinal())
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame(\n {\n \"group\": [\"A\", \"A\", \"A\", \"A\", \"A\"],\n \"date\": pd.to_datetime([\"2020-01-02\", \"2020-01-13\", \"2020-02-01\", \"2020-02-23\", \"2020-03-05\"]),\n \"value\": [10, 20, 16, 31, 56],\n }) \n data_series = candidate(df).to...
f_20576618
Convert DateTime column 'date' of pandas dataframe 'df' to ordinal
[ "pandas" ]
[ { "function": "dataframe.apply", "text": "pandas.DataFrame.apply DataFrame.apply(func, axis=0, raw=False, result_type=None, args=(), **kwargs)[source]\n \nApply a function along an axis of the DataFrame. Objects passed to the function are Series objects whose index is either the DataFrame’s index (axis=0)...
31,793,195
def f_31793195(df): return
df.index.get_loc('bob')
import pandas as pd import numpy as np def check(candidate):
[ "\n df = pd.DataFrame(data=np.asarray([[1,2,3],[4,5,6],[7,8,9]]), index=['alice', 'bob', 'charlie'])\n index = candidate(df)\n assert index == 1\n" ]
f_31793195
Get the integer location of a key `bob` in a pandas data frame `df`
[ "numpy", "pandas" ]
[ { "function": "df.get_loc", "text": "pandas.Index.get_loc Index.get_loc(key, method=None, tolerance=None)[source]\n \nGet integer location, slice or boolean mask for requested label. Parameters ", "title": "pandas.reference.api.pandas.index.get_loc" } ]
10,487,278
def f_10487278(my_dict):
return my_dict
my_dict.update({'third_key': 1})
def check(candidate):
[ "\n my_dict = {'a':1, 'b':2}\n assert candidate(my_dict) == {'a':1, 'b':2, 'third_key': 1}\n", "\n my_dict = {'c':1, 'd':2}\n assert candidate(my_dict) == {'c':1, 'd':2, 'third_key': 1}\n" ]
f_10487278
add an item with key 'third_key' and value 1 to an dictionary `my_dict`
[]
[]
10,487,278
def f_10487278():
return my_list
my_list = []
def check(candidate):
[ "\n assert candidate() == []\n" ]
f_10487278
declare an array `my_list`
[]
[]
10,487,278
def f_10487278(my_list):
return my_list
my_list.append(12)
def check(candidate):
[ "\n assert candidate([1,2]) == [1, 2, 12] \n", "\n assert candidate([5,6]) == [5, 6, 12]\n" ]
f_10487278
Insert item `12` to a list `my_list`
[]
[]
10,155,684
def f_10155684(myList):
return myList
myList.insert(0, 'wuggah')
def check(candidate):
[ "\n assert candidate([1,2]) == ['wuggah', 1, 2]\n", "\n assert candidate([]) == ['wuggah'] \n" ]
f_10155684
add an entry 'wuggah' at the beginning of list `myList`
[]
[]
3,519,125
def f_3519125(hex_str): return
bytes.fromhex(hex_str.replace('\\x', ''))
def check(candidate):
[ "\n assert candidate(\"\\\\xF3\\\\xBE\\\\x80\\\\x80\") == b'\\xf3\\xbe\\x80\\x80'\n" ]
f_3519125
convert a hex-string representation `hex_str` to actual bytes
[]
[]
40,144,769
def f_40144769(df): return
df[df.columns[-1]]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[1, 2, 3],[4,5,6]], columns=[\"a\", \"b\", \"c\"])\n assert candidate(df).tolist() == [3,6]\n", "\n df = pd.DataFrame([[\"Hello\", \"world!\"],[\"Hi\", \"world!\"]], columns=[\"a\", \"b\"])\n assert candidate(df).tolist() == [\"world!\", \"world!\"]\n" ]
f_40144769
select the last column of dataframe `df`
[ "pandas" ]
[ { "function": "dataframe.columns", "text": "pandas.DataFrame.columns DataFrame.columns\n \nThe column labels of the DataFrame.", "title": "pandas.reference.api.pandas.dataframe.columns" } ]
30,787,901
def f_30787901(df): return
df.loc[df['Letters'] == 'C', 'Letters'].values[0]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([[\"a\", 1],[\"C\", 6]], columns=[\"Letters\", \"Numbers\"])\n assert candidate(df) == 'C'\n", "\n df = pd.DataFrame([[None, 1],[\"C\", 789]], columns=[\"Letters\", \"Names\"])\n assert candidate(df) == 'C'\n" ]
f_30787901
get the first value from dataframe `df` where column 'Letters' is equal to 'C'
[ "pandas" ]
[ { "function": "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 interpre...
18,730,044
def f_18730044(): return
np.column_stack(([1, 2, 3], [4, 5, 6]))
import numpy as np def check(candidate):
[ "\n assert np.all(candidate() == np.array([[1, 4], [2, 5], [3, 6]]))\n" ]
f_18730044
converting two lists `[1, 2, 3]` and `[4, 5, 6]` into a matrix
[ "numpy" ]
[ { "function": "numpy.column_stack", "text": "numpy.column_stack numpy.column_stack(tup)[source]\n \nStack 1-D arrays as columns into a 2-D array. Take a sequence of 1-D arrays and stack them as columns to make a single 2-D array. 2-D arrays are stacked as-is, just like with hstack. 1-D arrays are turned i...
402,504
def f_402504(i): return
type(i)
def check(candidate):
[ "\n assert candidate(\"hello\") is str\n", "\n assert candidate(123) is int\n", "\n assert candidate(\"123\") is str\n", "\n assert candidate(123.4) is float\n" ]
f_402504
get the type of `i`
[]
[]
402,504
def f_402504(v): return
type(v)
def check(candidate):
[ "\n assert candidate(\"hello\") is str\n", "\n assert candidate(123) is int\n", "\n assert candidate(\"123\") is str\n", "\n assert candidate(123.4) is float\n" ]
f_402504
determine the type of variable `v`
[]
[]
402,504
def f_402504(v): return
type(v)
def check(candidate):
[ "\n assert candidate(\"hello\") is str\n", "\n assert candidate(123) is int\n", "\n assert candidate(\"123\") is str\n", "\n assert candidate(123.4) is float\n" ]
f_402504
determine the type of variable `v`
[]
[]
402,504
def f_402504(variable_name): return
type(variable_name)
def check(candidate):
[ "\n assert candidate(\"hello\") is str\n", "\n assert candidate(123) is int\n", "\n assert candidate(\"123\") is str\n", "\n assert candidate(123.4) is float\n" ]
f_402504
get the type of variable `variable_name`
[]
[]
2,300,756
def f_2300756(g): return
next(itertools.islice(g, 5, 5 + 1))
import itertools def check(candidate):
[ "\n test = [1, 2, 3, 4, 5, 6, 7]\n assert(candidate(test) == 6)\n" ]
f_2300756
get the 5th item of a generator `g`
[ "itertools" ]
[ { "function": "itertools.islice", "text": "itertools.islice(iterable, stop) \nitertools.islice(iterable, start, stop[, step]) \nMake an iterator that returns selected elements from the iterable. If start is non-zero, then elements from the iterable are skipped until start is reached. Afterward, elements a...
20,056,548
def f_20056548(word): return
'"{}"'.format(word)
def check(candidate):
[ "\n assert candidate('Some Random Word') == '\"Some Random Word\"'\n" ]
f_20056548
return a string `word` with string format
[]
[]
8,546,245
def f_8546245(list): return
""" """.join(list)
def check(candidate):
[ "\n test = ['hello', 'good', 'morning']\n assert candidate(test) == \"hello good morning\"\n" ]
f_8546245
join a list of strings `list` using a space ' '
[]
[]
2,276,416
def f_2276416():
return y
y = [[] for n in range(2)]
def check(candidate):
[ "\n assert(candidate() == [[], []])\n" ]
f_2276416
create list `y` containing two empty lists
[]
[]
3,925,614
def f_3925614(filename):
return data
data = [line.strip() for line in open(filename, 'r')]
def check(candidate):
[ "\n file1 = open(\"myfile.txt\", \"w\")\n L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"]\n file1.writelines(L)\n file1.close()\n assert candidate('myfile.txt') == ['This is Delhi', 'This is Paris', 'This is London']\n" ]
f_3925614
read a file `filename` into a list `data`
[]
[]
22,187,233
def f_22187233(): return
"""""".join([char for char in 'it is icy' if char != 'i'])
def check(candidate):
[ "\n assert candidate() == 't s cy'\n" ]
f_22187233
delete all occurrences of character 'i' in string 'it is icy'
[]
[]
22,187,233
def f_22187233(): return
re.sub('i', '', 'it is icy')
import re def check(candidate):
[ "\n assert candidate() == 't s cy'\n" ]
f_22187233
delete all instances of a character 'i' in a string 'it is icy'
[ "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 ...
22,187,233
def f_22187233(): return
"""it is icy""".replace('i', '')
def check(candidate):
[ "\n assert candidate() == 't s cy'\n" ]
f_22187233
delete all characters "i" in string "it is icy"
[]
[]
13,413,590
def f_13413590(df): return
df.dropna(subset=[1])
import numpy as np import pandas as pd def check(candidate):
[ "\n data = {0:[3.0, 4.0, 2.0], 1:[2.0, 3.0, np.nan], 2:[np.nan, 3.0, np.nan]}\n df = pd.DataFrame(data)\n d = {0:[3.0, 4.0], 1:[2.0, 3.0], 2:[np.nan, 3.0]}\n res = pd.DataFrame(d)\n assert candidate(df).equals(res)\n" ]
f_13413590
Drop rows of pandas dataframe `df` having NaN in column at index "1"
[ "numpy", "pandas" ]
[ { "function": "df.dropna", "text": "pandas.DataFrame.dropna DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)[source]\n \nRemove missing values. See the User Guide for more on which values are considered missing, and how to work with missing data. Parameters ", "title": "pa...
598,398
def f_598398(myList): return
[x for x in myList if x.n == 30]
import numpy as np import pandas as pd def check(candidate):
[ "\n class Data: \n def __init__(self, a, n): \n self.a = a\n self.n = n\n \n myList = [Data(i, 10*(i%4)) for i in range(20)]\n assert candidate(myList) == [myList[i] for i in [3, 7, 11, 15, 19]]\n" ]
f_598398
get elements from list `myList`, that have a field `n` value 30
[ "numpy", "pandas" ]
[]
10,351,772
def f_10351772(intstringlist):
return nums
nums = [int(x) for x in intstringlist]
def check(candidate):
[ "\n assert candidate(['1', '2', '3', '4', '5']) == [1, 2, 3, 4, 5]\n", "\n assert candidate(['001', '200', '3', '4', '5']) == [1, 200, 3, 4, 5]\n" ]
f_10351772
converting list of strings `intstringlist` to list of integer `nums`
[]
[]
493,386
def f_493386(): return
sys.stdout.write('.')
import sys def check(candidate):
[ "\n assert candidate() == 1\n" ]
f_493386
print "." without newline
[ "sys" ]
[ { "function": "sys.write", "text": "sys — System-specific parameters and functions This module provides access to some variables used or maintained by the interpreter and to functions that interact strongly with the interpreter. It is always available. \nsys.abiflags \nOn POSIX systems where Python was bu...
6,569,528
def f_6569528(): return
int(round(2.52 * 100))
def check(candidate):
[ "\n assert candidate() == 252\n" ]
f_6569528
round off the float that is the product of `2.52 * 100` and convert it to an int
[]
[]
3,964,681
def f_3964681():
return files
os.chdir('/mydir') files = [] for file in glob.glob('*.txt'): files.append(file)
import os import glob from unittest.mock import Mock def check(candidate):
[ "\n samples = ['abc.txt']\n os.chdir = Mock()\n glob.glob = Mock(return_value = samples)\n assert candidate() == samples\n" ]
f_3964681
Find all files `files` in directory '/mydir' with extension '.txt'
[ "glob", "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...
3,964,681
def f_3964681(): return
[file for file in os.listdir('/mydir') if file.endswith('.txt')]
import os from unittest.mock import Mock def check(candidate):
[ "\n samples = ['abc.txt', 'f.csv']\n os.listdir = Mock(return_value = samples)\n assert candidate() == ['abc.txt']\n" ]
f_3964681
Find all files in directory "/mydir" with extension ".txt"
[ "os" ]
[ { "function": "os.listdir", "text": "os.listdir(path='.') \nReturn a list containing the names of the entries in the directory given by path. The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory. If a file is removed from or added t...
3,964,681
def f_3964681(): return
[file for (root, dirs, files) in os.walk('/mydir') for file in files if file.endswith('.txt')]
import os from unittest.mock import Mock def check(candidate):
[ "\n name = '/mydir'\n samples = [(name, [], ['abc.txt', 'f.csv'])]\n os.walk = Mock(return_value = samples)\n assert candidate() == ['abc.txt']\n" ]
f_3964681
Find all files in directory "/mydir" with extension ".txt"
[ "os" ]
[ { "function": "os.walk", "text": "os.walk(top, topdown=True, onerror=None, followlinks=False) \nGenerate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames...
20,865,487
def f_20865487(df): return
df.plot(legend=False)
import os import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([1, 2, 3, 4, 5], columns = ['Vals'])\n res = candidate(df)\n assert 'AxesSubplot' in str(type(res))\n assert res.legend_ is None\n" ]
f_20865487
plot dataframe `df` without a legend
[ "os", "pandas" ]
[ { "function": "df.plot", "text": "pandas.DataFrame.plot DataFrame.plot(*args, **kwargs)[source]\n \nMake plots of Series or DataFrame. Uses the backend specified by the option plotting.backend. By default, matplotlib is used. Parameters ", "title": "pandas.reference.api.pandas.dataframe.plot" } ]
13,368,659
def f_13368659(): return
['192.168.%d.%d'%(i, j) for i in range(256) for j in range(256)]
def check(candidate):
[ "\n addrs = candidate()\n assert len(addrs) == 256*256\n assert addrs == [f'192.168.{i}.{j}' for i in range(256) for j in range(256)]\n" ]
f_13368659
loop through the IP address range "192.168.x.x"
[]
[]
4,065,737
def f_4065737(x): return
sum(1 << i for i, b in enumerate(x) if b)
def check(candidate):
[ "\n assert candidate([1,2,3]) == 7\n", "\n assert candidate([1,2,None,3,None]) == 11\n" ]
f_4065737
Sum the corresponding decimal values for binary values of each boolean element in list `x`
[]
[]
8,691,311
def f_8691311(line1, line2, line3, target):
return
target.write('%r\n%r\n%r\n' % (line1, line2, line3))
def check(candidate):
[ "\n file_name = 'abc.txt'\n lines = ['fgh', 'ijk', 'mnop']\n f = open(file_name, 'a')\n candidate(lines[0], lines[1], lines[2], f)\n f.close()\n with open(file_name, 'r') as f:\n f_lines = f.readlines()\n for i in range (0, len(lines)):\n assert lines[i] in f_lines[i]\n" ]
f_8691311
write multiple strings `line1`, `line2` and `line3` in one line in a file `target`
[]
[]
10,632,111
def f_10632111(data): return
[y for x in data for y in (x if isinstance(x, list) else [x])]
def check(candidate):
[ "\n data = [[1, 2], [3]]\n assert candidate(data) == [1, 2, 3]\n", "\n data = [[1, 2], [3], []]\n assert candidate(data) == [1, 2, 3]\n", "\n data = [1,2,3]\n assert candidate(data) == [1, 2, 3]\n" ]
f_10632111
Convert list of lists `data` into a flat list
[]
[]
15,392,730
def f_15392730(): return
'foo\nbar'.encode('unicode_escape')
def check(candidate):
[ "\n assert candidate() == b'foo\\\\nbar'\n" ]
f_15392730
Print new line character as `\n` in a string `foo\nbar`
[]
[]
1,010,961
def f_1010961(s): return
"""""".join(s.rsplit(',', 1))
def check(candidate):
[ "\n assert candidate('abc, def, klm') == 'abc, def klm'\n" ]
f_1010961
remove last comma character ',' in string `s`
[]
[]
23,855,976
def f_23855976(x): return
(x[1:] + x[:-1]) / 2
import numpy as np def check(candidate):
[ "\n x = np.array([ 1230., 1230., 1227., 1235., 1217., 1153., 1170.])\n xm = np.array([1230. , 1228.5, 1231. , 1226. , 1185. , 1161.5])\n assert np.array_equal(candidate(x), xm)\n" ]
f_23855976
calculate the mean of each element in array `x` with the element previous to it
[ "numpy" ]
[]
23,855,976
def f_23855976(x): return
x[:-1] + (x[1:] - x[:-1]) / 2
import numpy as np def check(candidate):
[ "\n x = np.array([ 1230., 1230., 1227., 1235., 1217., 1153., 1170.])\n xm = np.array([1230. , 1228.5, 1231. , 1226. , 1185. , 1161.5])\n assert np.array_equal(candidate(x), xm)\n" ]
f_23855976
get an array of the mean of each two consecutive values in numpy array `x`
[ "numpy" ]
[]
6,375,343
def f_6375343():
return arr
arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')
import numpy import codecs import numpy as np def check(candidate):
[ "\n with open ('new.txt', 'a', encoding='utf-8') as f:\n f.write('ट')\n f.write('ज')\n arr = candidate()\n assert arr[0] == 'टज'\n" ]
f_6375343
load data containing `utf-8` from file `new.txt` into numpy array `arr`
[ "codecs", "numpy" ]
[ { "function": "numpy.fromiter", "text": "numpy.fromiter numpy.fromiter(iter, dtype, count=- 1, *, like=None)\n \nCreate a new 1-dimensional array from an iterable object. Parameters ", "title": "numpy.reference.generated.numpy.fromiter" }, { "function": "codecs.open", "text": "codecs.open...
1,547,733
def f_1547733(l):
return l
l = sorted(l, key=itemgetter('time'), reverse=True)
from operator import itemgetter def check(candidate):
[ "\n l = [ {'time':33}, {'time':11}, {'time':66} ]\n assert candidate(l) == [{'time':66}, {'time':33}, {'time':11}]\n" ]
f_1547733
reverse sort list of dicts `l` by value for key `time`
[ "operator" ]
[ { "function": "operator.itemgetter", "text": "operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand’s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgette...
1,547,733
def f_1547733(l):
return l
l = sorted(l, key=lambda a: a['time'], reverse=True)
def check(candidate):
[ "\n l = [ {'time':33}, {'time':11}, {'time':66} ]\n assert candidate(l) == [{'time':66}, {'time':33}, {'time':11}]\n" ]
f_1547733
Sort a list of dictionary `l` based on key `time` in descending order
[]
[]
37,080,612
def f_37080612(df): return
df.loc[df[0].str.contains('(Hel|Just)')]
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame([['Hello', 'World'], ['Just', 'Wanted'], ['To', 'Say'], ['I\\'m', 'Tired']])\n df1 = candidate(df)\n assert df1[0][0] == 'Hello'\n assert df1[0][1] == 'Just'\n" ]
f_37080612
get rows of dataframe `df` that match regex '(Hel|Just)'
[ "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...
14,716,342
def f_14716342(your_string): return
re.search('\\[(.*)\\]', your_string).group(1)
import re def check(candidate):
[ "\n assert candidate('[uranus]') == 'uranus'\n", "\n assert candidate('hello[world] !') == 'world'\n" ]
f_14716342
find the string in `your_string` between two special characters "[" and "]"
[ "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...
18,684,076
def f_18684076(): return
[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]
import pandas def check(candidate):
[ "\n assert candidate() == ['20130226', '20130227', '20130228', '20130301', '20130302']\n" ]
f_18684076
create a list of date string in 'yyyymmdd' format with Python Pandas from '20130226' to '20130302'
[ "pandas" ]
[ { "function": "d.strftime", "text": "pandas.Timestamp.strftime Timestamp.strftime(format)\n \nReturn a string representing the given POSIX timestamp controlled by an explicit format string. Parameters \n \nformat:str\n\n\nFormat string to convert Timestamp to string. See strftime documentation for more i...
1,666,700
def f_1666700(): return
"""The big brown fox is brown""".count('brown')
def check(candidate):
[ "\n assert candidate() == 2\n" ]
f_1666700
count number of times string 'brown' occurred in string 'The big brown fox is brown'
[]
[]
18,979,111
def f_18979111(request_body): return
json.loads(request_body)
import json def check(candidate):
[ "\n x = \"\"\"{\n \"Name\": \"Jennifer Smith\",\n \"Contact Number\": 7867567898,\n \"Email\": \"jen123@gmail.com\",\n \"Hobbies\":[\"Reading\", \"Sketching\", \"Horse Riding\"]\n }\"\"\"\n assert candidate(x) == {'Hobbies': ['Reading', 'Sketching', 'Horse Riding'], 'Name': 'Jennifer Smith', 'E...
f_18979111
decode json string `request_body` to python dict
[ "json" ]
[ { "function": "json.loads", "text": "json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) \nDeserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table. The other ar...
7,243,750
def f_7243750(url, file_name): return
urllib.request.urlretrieve(url, file_name)
import urllib def check(candidate):
[ "\n file_name = 'g.html'\n candidate('https://asia.nikkei.com/Business/Tech/Semiconductors/U.S.-chip-tool-maker-Synopsys-expands-in-Vietnam-amid-China-tech-war', file_name)\n with open (file_name, 'r') as f:\n lines = f.readlines()\n if len(lines) == 0: assert False\n else: assert True...
f_7243750
download the file from url `url` and save it under file `file_name`
[ "urllib" ]
[ { "function": "urllib.urlretrieve", "text": "urllib.request.urlretrieve(url, filename=None, reporthook=None, data=None) \nCopy a network object denoted by a URL to a local file. If the URL points to a local file, the object will not be copied unless filename is supplied. Return a tuple (filename, headers) ...
743,806
def f_743806(text): return
text.split()
def check(candidate):
[ "\n assert candidate('The quick brown fox') == ['The', 'quick', 'brown', 'fox']\n", "\n assert candidate('hello!') == ['hello!']\n", "\n assert candidate('hello world !') == ['hello', 'world', '!']\n" ]
f_743806
split string `text` by space
[]
[]
743,806
def f_743806(text): return
text.split(',')
def check(candidate):
[ "\n assert candidate('The quick brown fox') == ['The quick brown fox']\n", "\n assert candidate('The,quick,brown,fox') == ['The', 'quick', 'brown', 'fox']\n" ]
f_743806
split string `text` by ","
[]
[]
743,806
def f_743806(line): return
line.split()
def check(candidate):
[ "\n assert candidate('The quick brown fox') == ['The', 'quick', 'brown', 'fox']\n" ]
f_743806
Split string `line` into a list by whitespace
[]
[]
35,044,115
def f_35044115(s): return
[re.sub('(?<!\\d)\\.(?!\\d)', ' ', i) for i in s]
import re def check(candidate):
[ "\n assert candidate('h.j.k') == ['h', ' ', 'j', ' ', 'k']\n" ]
f_35044115
replace dot characters '.' associated with ascii letters in list `s` with space ' '
[ "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 ...