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
638,048
def f_638048(list_of_pairs): return
sum([pair[0] for pair in list_of_pairs])
def check(candidate):
[ "\n assert candidate([(5, 9), (-1, -2), (4, 2)]) == 8\n" ]
f_638048
sum the first value in each tuple in a list of tuples `list_of_pairs` in python
[]
[]
14,950,260
def f_14950260(): return
ast.literal_eval("{'code1':1,'code2':1}")
import ast def check(candidate):
[ "\n d = candidate()\n exp_result = {'code1' : 1, 'code2': 1}\n for key in d:\n if key not in exp_result:\n assert False\n else:\n assert d[key] == exp_result[key]\n" ]
f_14950260
convert unicode string u"{'code1':1,'code2':1}" into dictionary
[ "ast" ]
[ { "function": "ast.literal_eval", "text": "ast.literal_eval(node_or_string) \nSafely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dic...
11,416,772
def f_11416772(mystring): return
[word for word in mystring.split() if word.startswith('$')]
def check(candidate):
[ "\n str = \"$abc def $efg $hij klm $\"\n exp_result = ['$abc', '$efg', '$hij', '$']\n assert sorted(candidate(str)) == sorted(exp_result)\n" ]
f_11416772
find all words in a string `mystring` that start with the `$` sign
[]
[]
11,331,982
def f_11331982(text):
return text
text = re.sub('^https?:\\/\\/.*[\\r\\n]*', '', text, flags=re.MULTILINE)
import re def check(candidate):
[ "\n assert candidate(\"https://www.wikipedia.org/ click at\") == \"\"\n" ]
f_11331982
remove any url within string `text`
[ "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,945,274
def f_34945274(A): return
np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([[0, 0, 1, 3, 4], [0, 0, 3, 0, 1]])\n assert np.array_equal(candidate(A), B)\n" ]
f_34945274
replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros
[ "numpy" ]
[ { "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...
15,819,980
def f_15819980(a): return
np.mean(a, axis=1)
import numpy as np def check(candidate):
[ "\n A = np.array([[6, 8, 1, 3, 4], [-1, 0, 3, 5, 1]])\n B = np.array([4.4, 1.6])\n assert np.array_equal(candidate(A), B)\n" ]
f_15819980
calculate mean across dimension in a 2d array `a`
[ "numpy" ]
[ { "function": "numpy.mean", "text": "numpy.mean numpy.mean(a, axis=None, dtype=None, out=None, keepdims=<no value>, *, where=<no value>)[source]\n \nCompute the arithmetic mean along the specified axis. Returns the average of the array elements. The average is taken over the flattened array by default, ot...
19,894,365
def f_19894365(): return
subprocess.call(['/usr/bin/Rscript', '--vanilla', '/pathto/MyrScript.r'])
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
running r script '/pathto/MyrScript.r' from python
[ "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...
19,894,365
def f_19894365(): return
subprocess.call('/usr/bin/Rscript --vanilla /pathto/MyrScript.r', shell=True)
from unittest.mock import Mock import subprocess def check(candidate):
[ "\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_19894365
run r script '/usr/bin/Rscript --vanilla /pathto/MyrScript.r'
[ "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...
33,058,590
def f_33058590(df): return
df.fillna(df.mean(axis=0))
import pandas as pd import numpy as np def check(candidate):
[ "\n df = pd.DataFrame([[1,2,3],[4,5,6],[7.0,np.nan,9.0]], columns=[\"c1\",\"c2\",\"c3\"]) \n res = pd.DataFrame([[1,2,3],[4,5,6],[7.0,3.5,9.0]], columns=[\"c1\",\"c2\",\"c3\"])\n assert candidate(df).equals(res)\n" ]
f_33058590
replacing nan in the dataframe `df` with row average
[ "numpy", "pandas" ]
[ { "function": "df.fillna", "text": "pandas.DataFrame.fillna DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None)[source]\n \nFill NA/NaN values using the specified method. Parameters ", "title": "pandas.reference.api.pandas.dataframe.fillna" }, { "fun...
12,400,256
def f_12400256(): return
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
import time def check(candidate):
[ "\n assert candidate() == \"2012-09-13 06:22:50\"\n" ]
f_12400256
Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'
[ "time" ]
[ { "function": "time.strftime", "text": "time.strftime(format[, t]) \nConvert a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument. If t is not provided, the current time as returned by localtime() is used. format must be a string....
23,359,886
def f_23359886(a): return
a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]
import numpy as np def check(candidate):
[ "\n a = np.array([[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]])\n res = np.array([[0, 1, 2]])\n assert np.array_equal(candidate(a), res)\n" ]
f_23359886
selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1
[ "numpy" ]
[ { "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,383,082
def f_4383082(words): return
re.split(' +', words)
import regex as re def check(candidate):
[ "\n s = \"hello world sample text\"\n res = [\"hello\", \"world\", \"sample\", \"text\"]\n assert candidate(s) == res\n" ]
f_4383082
separate words delimited by one or more spaces into a list
[ "regex" ]
[ { "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 ...
14,637,696
def f_14637696(words): return
len(max(words, key=len))
def check(candidate):
[ "\n assert candidate([\"hello\", \"world\", \"sample\", \"text\", \"superballer\"]) == 11\n" ]
f_14637696
length of longest element in list `words`
[]
[]
3,933,478
def f_3933478(result): return
result[0]['from_user']
def check(candidate):
[ "\n Contents = [{\"hi\": 7, \"bye\": 4, \"from_user\": 0}, {1: 2, 3: 4, 5: 6}]\n assert candidate(Contents) == 0\n" ]
f_3933478
get the value associated with unicode key 'from_user' of first dictionary in list `result`
[]
[]
39,112,645
def f_39112645(): return
[line.split() for line in open('File.txt')]
def check(candidate):
[ "\n with open('File.txt','w') as fw:\n fw.write(\"hi hello cat dog\")\n assert candidate() == [['hi', 'hello', 'cat', 'dog']]\n" ]
f_39112645
Retrieve each line from a file 'File.txt' as a list
[]
[]
1,031,851
def f_1031851(a): return
dict((v, k) for k, v in a.items())
def check(candidate):
[ "\n a = {\"one\": 1, \"two\": 2}\n assert candidate(a) == {1: \"one\", 2: \"two\"}\n" ]
f_1031851
swap keys with values in a dictionary `a`
[]
[]
8,577,137
def f_8577137(): return
open('path/to/FILE_NAME.ext', 'w')
import os def check(candidate):
[ "\n path1 = os.path.join(\"\", \"path\")\n os.mkdir(path1)\n path2 = os.path.join(\"path\", \"to\")\n os.mkdir(path2)\n candidate()\n assert os.path.exists('path/to/FILE_NAME.ext')\n" ]
f_8577137
Open a file `path/to/FILE_NAME.ext` in write mode
[ "os" ]
[ { "function": "open", "text": "os.open(path, flags, mode=0o777, *, dir_fd=None) \nOpen the file path and set various flags according to flags and possibly its mode according to mode. When computing mode, the current umask value is first masked out. Return the file descriptor for the newly opened file. The ...
17,926,273
def f_17926273(df): return
df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()
import pandas as pd def check(candidate):
[ "\n data = [[1, 1, 1], [1, 1, 1], [1, 1, 2], [1, 2, 3], [1, 2, 3], [1, 2, 3], \n [2, 1, 1], [2, 1, 2], [2, 1, 3], [2, 2, 3], [2, 2, 3], [2, 2, 3]]\n expected = [[1, 1, 2], [1, 2, 1], [2, 1, 3], [2, 2, 1]]\n df = pd.DataFrame(data, columns = ['col1', 'col2', 'col3'])\n expected_df = pd.DataFra...
f_17926273
count distinct values in a column 'col3' of a pandas dataframe `df` group by objects in 'col1' and 'col2'
[ "pandas" ]
[ { "function": "pandas.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 o...
3,735,814
def f_3735814(dict1): return
any(key.startswith('EMP$$') for key in dict1)
def check(candidate):
[ "\n assert candidate({'EMP$$': 1, 'EMP$$112': 4}) == True\n", "\n assert candidate({'EMP$$': 1, 'EM$$112': 4}) == True\n", "\n assert candidate({'EMP$33': 0}) == False\n" ]
f_3735814
Check if any key in the dictionary `dict1` starts with the string `EMP$$`
[]
[]
3,735,814
def f_3735814(dict1): return
[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]
def check(candidate):
[ "\n assert sorted(candidate({'EMP$$': 1, 'EMP$$112': 4})) == [1, 4]\n", "\n assert sorted(candidate({'EMP$$': 1, 'EM$$112': 4})) == [1]\n", "\n assert sorted(candidate({'EMP$33': 0})) == []\n" ]
f_3735814
create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'
[]
[]
26,097,916
def f_26097916(sf):
return df
df = pd.DataFrame({'email': sf.index, 'list': sf.values})
import pandas as pd def check(candidate):
[ "\n dict = {'email1': [1.0, 5.0, 7.0], 'email2': [4.2, 3.6, -0.9]}\n sf = pd.Series(dict)\n k = [['email1', [1.0, 5.0, 7.0]], ['email2', [4.2, 3.6, -0.9]]]\n df1 = pd.DataFrame(k, columns=['email', 'list'])\n df2 = candidate(sf)\n assert pd.DataFrame.equals(df1, df2)\n" ]
f_26097916
convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`
[ "pandas" ]
[]
4,048,964
def f_4048964(list): return
'\t'.join(map(str, list))
def check(candidate):
[ "\n assert candidate(['hello', 'world', '!']) == 'hello\\tworld\\t!'\n", "\n assert candidate([]) == \"\"\n", "\n assert candidate([\"mconala\"]) == \"mconala\"\n", "\n assert candidate([\"MCoNaLa\"]) == \"MCoNaLa\"\n" ]
f_4048964
concatenate elements of list `list` by tabs ` `
[]
[]
3,182,716
def f_3182716(): return
'\xd0\xbf\xd1\x80\xd0\xb8'.encode('raw_unicode_escape')
def check(candidate):
[ "\n assert candidate() == b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8'\n" ]
f_3182716
print unicode string '\xd0\xbf\xd1\x80\xd0\xb8' with utf-8
[]
[]
3,182,716
def f_3182716(): return
'Sopet\xc3\xb3n'.encode('latin-1').decode('utf-8')
def check(candidate):
[ "\n assert candidate() == \"Sopetón\"\n" ]
f_3182716
Encode a latin character in string `Sopet\xc3\xb3n` properly
[]
[]
35,622,945
def f_35622945(s): return
re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)
import re def check(candidate):
[ "\n assert candidate(\"ncnnnne\") == ['nnnn']\n", "\n assert candidate(\"nn\") == []\n", "\n assert candidate(\"ask\") == []\n" ]
f_35622945
regex, find "n"s only in the middle of string `s`
[ "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...
5,306,756
def f_5306756(): return
'{0:.0f}%'.format(1.0 / 3 * 100)
def check(candidate):
[ "\n assert(candidate() == \"33%\")\n" ]
f_5306756
display the float `1/3*100` as a percentage
[]
[]
2,878,084
def f_2878084(mylist):
return mylist
mylist.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n ...
f_2878084
sort a list of dictionary `mylist` by the key `title`
[]
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: x['title'])
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n ...
f_2878084
sort a list `l` of dicts by dict value 'title'
[]
[]
2,878,084
def f_2878084(l):
return l
l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))
def check(candidate):
[ "\n input = [\n {'title':'New York Times', 'title_url':'New_York_Times','id':4}, \n {'title':'USA Today','title_url':'USA_Today','id':6}, \n {'title':'Apple News','title_url':'Apple_News','id':2}\n ]\n res = [\n {'title': 'Apple News', 'title_url': 'Apple_News', 'id': 2}, \n ...
f_2878084
sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.
[]
[]
9,323,159
def f_9323159(l1, l2): return
heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))
import heapq def check(candidate):
[ "\n l1 = [99, 86, 90, 70, 86, 95, 56, 98, 80, 81]\n l2 = [21, 11, 21, 1, 26, 40, 4, 50, 34, 37]\n res = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n assert candidate(l1, l2) == res\n" ]
f_9323159
find 10 largest differences between each respective elements of list `l1` and list `l2`
[ "heapq" ]
[ { "function": "heapq.nlargest", "text": "heapq.nlargest(n, iterable, key=None) \nReturn a list with the n largest elements from the dataset defined by iterable. key, if provided, specifies a function of one argument that is used to extract a comparison key from each element in iterable (for example, key=st...
29,877,663
def f_29877663(soup): return
soup.find_all('span', {'class': 'starGryB sp'})
import bs4 def check(candidate):
[ "\n html = '''<span class=\"starBig sp\">4.1</span>\n <span class=\"starGryB sp\">2.9</span>\n <span class=\"sp starGryB\">2.9</span>\n <span class=\"sp starBig\">22</span>'''\n soup = bs4.BeautifulSoup(html, features=\"html5lib\")\n res = '''[<span class=\"starGryB sp\"...
f_29877663
BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'
[ "bs4" ]
[]
24,189,150
def f_24189150(df, engine):
return
df.to_sql('test', engine)
import pandas as pd from sqlalchemy import create_engine def check(candidate):
[ "\n engine = create_engine('sqlite://', echo=False)\n df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})\n candidate(df, engine)\n result = pd.read_sql('SELECT name FROM test', engine)\n assert result.equals(df)\n" ]
f_24189150
write records in dataframe `df` to table 'test' in schema 'a_schema' with `engine`
[ "pandas", "sqlalchemy" ]
[ { "function": "df.to_sql", "text": "pandas.DataFrame.to_sql DataFrame.to_sql(name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)[source]\n \nWrite records stored in a DataFrame to a SQL database. Databases supported by SQLAlchemy [1] are support...
30,766,151
def f_30766151(s): return
re.sub('[^(){}[\]]', '', s)
import re def check(candidate):
[ "\n assert candidate(\"(a(vdwvndw){}]\") == \"((){}]\"\n", "\n assert candidate(\"12345\") == \"\"\n" ]
f_30766151
Extract brackets from 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 ...
1,143,379
def f_1143379(L): return
list(dict((x[0], x) for x in L).values())
def check(candidate):
[ "\n L = [['14', '65', 76], ['2', '5', 6], ['7', '12', 33], ['14', '22', 46]]\n res = [['14', '22', 46], ['2', '5', 6], ['7', '12', 33]]\n assert(candidate(L) == res)\n", "\n assert candidate([\"a\", \"aa\", \"abc\", \"bac\"]) == [\"abc\", \"bac\"]\n" ]
f_1143379
remove duplicate elements from list 'L'
[]
[]
12,330,522
def f_12330522(file): return
[line.rstrip('\n') for line in file]
def check(candidate):
[ "\n res = ['1', '2', '3']\n f = open(\"myfile.txt\", \"a\")\n f.write(\"1\\n2\\n3\")\n f.close()\n f = open(\"myfile.txt\", \"r\")\n assert candidate(f) == res\n" ]
f_12330522
read a file `file` without newlines
[]
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
[]
364,621
def f_364621(testlist): return
[i for (i, x) in enumerate(testlist) if (x == 1)]
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist) == [0, 5, 7]\n", "\n testlist = [0, -1]\n assert candidate(testlist) == []\n" ]
f_364621
get the position of item 1 in `testlist`
[]
[]
364,621
def f_364621(testlist, element): return
testlist.index(element)
def check(candidate):
[ "\n testlist = [1,2,3,5,3,1,2,1,6]\n assert candidate(testlist, 1) == 0\n", "\n testlist = [1,2,3,5,3,1,2,1,6]\n try:\n candidate(testlist, 14)\n except:\n assert True\n" ]
f_364621
get the position of item `element` in list `testlist`
[]
[]
13,145,368
def f_13145368(lis): return
max(lis, key=lambda item: item[1])[0]
def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
find the first element of the tuple with the maximum second element in a list of tuples `lis`
[]
[]
13,145,368
def f_13145368(lis): return
max(lis, key=itemgetter(1))[0]
from operator import itemgetter def check(candidate):
[ "\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n" ]
f_13145368
get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`
[ "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...
2,689,189
def f_2689189():
return
time.sleep(1)
import time def check(candidate):
[ "\n t1 = time.time()\n candidate()\n t2 = time.time()\n assert t2 - t1 > 1\n" ]
f_2689189
Make a delay of 1 second
[ "time" ]
[ { "function": "time.sleep", "text": "time.sleep(secs) \nSuspend execution of the calling thread for the given number of seconds. The argument may be a floating point number to indicate a more precise sleep time. The actual suspension time may be less than that requested because any caught signal will termi...
12,485,244
def f_12485244(L): return
""", """.join('(' + ', '.join(i) + ')' for i in L)
def check(candidate):
[ "\n L = [(\"abc\", \"def\"), (\"hij\", \"klm\")]\n assert candidate(L) == '(abc, def), (hij, klm)'\n" ]
f_12485244
convert list of tuples `L` to a string
[]
[]
755,857
def f_755857():
return b
b = models.CharField(max_length=7, default='0000000', editable=False)
from django.db import models def check(candidate):
[ "\n assert candidate().get_default() == '0000000'\n" ]
f_755857
Django set default value of field `b` equal to '0000000'
[ "django" ]
[ { "function": "models.CharField", "text": "class CharField(max_length=None, **options)", "title": "django.ref.models.fields#django.db.models.CharField" } ]
16,193,578
def f_16193578(list5): return
sorted(list5, key = lambda x: (degrees(x), x))
from math import degrees def check(candidate):
[ "\n list5 = [4, 1, 2, 3, 9, 5]\n assert candidate(list5) == [1, 2, 3, 4, 5, 9]\n" ]
f_16193578
Sort lis `list5` in ascending order based on the degrees value of its elements
[ "math" ]
[ { "function": "math.degrees", "text": "math.degrees(x) \nConvert angle x from radians to degrees.", "title": "python.library.math#math.degrees" } ]
16,041,405
def f_16041405(l): return
(n for n in l)
def check(candidate):
[ "\n generator = candidate([1,2,3,5])\n assert str(type(generator)) == \"<class 'generator'>\"\n assert [x for x in generator] == [1, 2, 3, 5]\n" ]
f_16041405
convert a list `l` into a generator object
[]
[]
18,837,607
def f_18837607(oldlist, removelist): return
[v for i, v in enumerate(oldlist) if i not in removelist]
def check(candidate):
[ "\n assert candidate([\"asdf\",\"ghjk\",\"qwer\",\"tyui\"], [1,3]) == ['asdf', 'qwer']\n", "\n assert candidate([1,2,3,4,5], [0,4]) == [2,3,4]\n" ]
f_18837607
remove elements from list `oldlist` that have an index number mentioned in list `removelist`
[]
[]
4,710,067
def f_4710067(): return
open('yourfile.txt', 'w')
def check(candidate):
[ "\n fw = candidate()\n assert fw.name == \"yourfile.txt\"\n assert fw.mode == 'w'\n" ]
f_4710067
Open a file `yourfile.txt` in write mode
[]
[]
7,373,219
def f_7373219(obj, attr): return
getattr(obj, attr)
def check(candidate):
[ "\n class Student:\n student_id = \"\"\n student_name = \"\"\n\n def __init__(self, student_id=101, student_name=\"Adam\"):\n self.student_id = student_id\n self.student_name = student_name\n\n student = Student()\n\n assert(candidate(student, 'student_name') == \...
f_7373219
get attribute 'attr' from object `obj`
[]
[]
8,171,751
def f_8171751(): return
reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))
from functools import reduce def check(candidate):
[ "\n assert candidate() == ('aa', 'bb', 'cc')\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple
[ "functools" ]
[ { "function": "reduce", "text": "functools.reduce(function, iterable[, initializer]) \nApply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+...
8,171,751
def f_8171751(): return
list(map(lambda a: a[0], (('aa',), ('bb',), ('cc',))))
def check(candidate):
[ "\n assert candidate() == ['aa', 'bb', 'cc']\n" ]
f_8171751
convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line
[]
[]
28,986,489
def f_28986489(df):
return df
df['range'].replace(',', '-', inplace=True)
import pandas as pd def check(candidate):
[ "\n df = pd.DataFrame({'range' : [\",\", \"(50,290)\", \",,,\"]})\n res = pd.DataFrame({'range' : [\"-\", \"(50,290)\", \",,,\"]})\n assert candidate(df).equals(res)\n" ]
f_28986489
replace a characters in a column of a dataframe `df`
[ "pandas" ]
[ { "function": "pandas.dataframe.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 wi...
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])
def check(candidate):
[ "\n assert [a for a in candidate()] == [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n" ]
f_19339
unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`
[]
[]
19,339
def f_19339(original): return
([a for (a, b) in original], [b for (a, b) in original])
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n assert candidate(original) == (['a', 'b', 'c', 'd'], [1, 2, 3, 4])\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n assert candidate(original2) == ([[], [], 5, 6], [1, 2, 3, 4])\n" ]
f_19339
unzip list `original`
[]
[]
19,339
def f_19339(original): return
((a for (a, b) in original), (b for (a, b) in original))
def check(candidate):
[ "\n original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]\n result = candidate(original)\n assert [a for gen in result for a in gen] == ['a','b','c','d',1,2,3,4]\n", "\n original2 = [([], 1), ([], 2), (5, 3), (6, 4)]\n result2 = candidate(original2)\n assert [a for gen in result2 for a in gen] == ...
f_19339
unzip list `original` and return a generator
[]
[]
19,339
def f_19339(): return
zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])
def check(candidate):
[ "\n assert list(candidate()) == [('a', 'b', 'c', 'd', 'e')]\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`
[]
[]
19,339
def f_19339(): return
list(zip_longest(('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)))
from itertools import zip_longest def check(candidate):
[ "\n assert(candidate() == [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)])\n" ]
f_19339
unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None
[ "itertools" ]
[ { "function": "itertools.zip_longest", "text": "itertools.zip_longest(*iterables, fillvalue=None) \nMake an iterator that aggregates elements from each of the iterables. If the iterables are of uneven length, missing values are filled-in with fillvalue. Iteration continues until the longest iterable is exh...
1,960,516
def f_1960516(): return
json.dumps('3.9')
import json def check(candidate):
[ "\n data = candidate()\n assert json.loads(data) == '3.9'\n" ]
f_1960516
encode `Decimal('3.9')` to a JSON string
[ "json" ]
[ { "function": "json.dumps", "text": "json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) \nSerialize obj to a JSON formatted str using this conversion table. The arguments have the same meani...
1,024,847
def f_1024847(d):
return d
d['mynewkey'] = 'mynewvalue'
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'mynewkey': 'mynewvalue'}\n" ]
f_1024847
Add key "mynewkey" to dictionary `d` with value "mynewvalue"
[]
[]
1,024,847
def f_1024847(data):
return data
data.update({'a': 1, })
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
1,024,847
def f_1024847(data):
return data
data.update(dict(a=1))
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
1,024,847
def f_1024847(data):
return data
data.update(a=1)
def check(candidate):
[ "\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n", "\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n" ]
f_1024847
Add key 'a' to dictionary `data` with value 1
[]
[]
35,837,346
def f_35837346(matrix): return
max([max(i) for i in matrix])
def check(candidate):
[ "\n assert candidate([[1,2,3],[4,5,6],[7,8,9]]) == 9\n", "\n assert candidate([[1.3,2.8],[4.2,10],[7.9,8.1,5]]) == 10\n" ]
f_35837346
find maximal value in matrix `matrix`
[]
[]
20,457,038
def f_20457038(answer):
return answer
answer = str(round(answer, 2))
def check(candidate):
[ "\n assert candidate(2.34351) == \"2.34\"\n", "\n assert candidate(99.375) == \"99.38\"\n", "\n assert candidate(4.1) == \"4.1\"\n", "\n assert candidate(3) == \"3\"\n" ]
f_20457038
Round number `answer` to 2 precision after the decimal point
[]
[]
2,890,896
def f_2890896(s):
return ip
ip = re.findall('[0-9]+(?:\\.[0-9]+){3}', s)
import re def check(candidate):
[ "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131</body></html>\") == [\"165.91.15.131\"]\n", "\n assert candidate(\"<html><head><title>Current IP Check</title></head><body>Current IP Address: 165.91.15.131 and this is not a IP Address: 165.91.1...
f_2890896
extract ip address `ip` from an html string `s`
[ "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...
29,836,836
def f_29836836(df): return
df.groupby('A').filter(lambda x: len(x) > 1)
import pandas as pd def check(candidate):
[ "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4]], columns=['A', 'B'])) is True\n", "\n assert candidate(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])).equals(pd.DataFrame([[1, 2], [1, 4], [1, 6]], columns=['A', 'B'])) is True\...
f_29836836
filter dataframe `df` by values in column `A` that appear more than once
[ "pandas" ]
[ { "function": "pandas.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 o...
2,545,397
def f_2545397(myfile): return
[x for x in myfile if x != '']
def check(candidate):
[ "\n with open('./tmp.txt', 'w') as fw: \n for s in [\"hello\", \"world\", \"!!!\"]:\n fw.write(f\"{s}\\n\")\n\n with open('./tmp.txt', 'r') as myfile:\n lines = candidate(myfile)\n assert isinstance(lines, list)\n assert len(lines) == 3\n assert lines[0].strip() =...
f_2545397
append each line in file `myfile` into a list
[]
[]
2,545,397
def f_2545397():
return lst
lst = list(map(int, open('filename.txt').readlines()))
import pandas as pd def check(candidate):
[ "\n with open('./filename.txt', 'w') as fw: \n for s in [\"1\", \"2\", \"100\"]:\n fw.write(f\"{s}\\n\")\n\n assert candidate() == [1, 2, 100]\n" ]
f_2545397
Get a list of integers `lst` from a file `filename.txt`
[ "pandas" ]
[]
35,420,052
def f_35420052(plt, mappable, ax3):
return plt
plt.colorbar(mappable=mappable, cax=ax3)
import numpy as np import matplotlib.pyplot as plt from obspy.core.trace import Trace from obspy.imaging.spectrogram import spectrogram def check(candidate):
[ "\n spl1 = Trace(data=np.arange(0, 10))\n fig = plt.figure()\n ax1 = fig.add_axes([0.1, 0.75, 0.7, 0.2]) #[left bottom width height]\n ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.60], sharex=ax1)\n ax3 = fig.add_axes([0.83, 0.1, 0.03, 0.6])\n\n #make time vector\n t = np.arange(spl1.stats.npts) / spl1...
f_35420052
add color bar with image `mappable` to plot `plt`
[ "matplotlib", "numpy", "obspy" ]
[ { "function": "plt.colorbar", "text": "matplotlib.pyplot.colorbar matplotlib.pyplot.colorbar(mappable=None, cax=None, ax=None, **kw)[source]\n \nAdd a colorbar to a plot. Parameters ", "title": "matplotlib._as_gen.matplotlib.pyplot.colorbar" } ]
29,903,025
def f_29903025(df): return
Counter(' '.join(df['text']).split()).most_common(100)
import pandas as pd from collections import Counter def check(candidate):
[ "\n df = pd.DataFrame({\"text\": [\n 'Python is a high-level, general-purpose programming language.', \n 'Its design philosophy emphasizes code readability with the use of significant indentation. Python is dynamically-typed and garbage-collected.'\n ]})\n assert candidate(df) == [('Python', 2),(...
f_29903025
count most frequent 100 words in column 'text' of dataframe `df`
[ "collections", "pandas" ]
[ { "function": "Counter.most_common", "text": "most_common([n]) \nReturn a list of the n most common elements and their counts from the most common to the least. If n is omitted or None, most_common() returns all elements in the counter. Elements with equal counts are ordered in the order first encountered:...
7,378,180
def f_7378180(): return
list(itertools.combinations((1, 2, 3), 2))
import itertools def check(candidate):
[ "\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\n" ]
f_7378180
generate all 2-element subsets of tuple `(1, 2, 3)`
[ "itertools" ]
[ { "function": "itertools.combinations", "text": "itertools.combinations(iterable, r) \nReturn r length subsequences of elements from the input iterable. The combination tuples are emitted in lexicographic ordering according to the order of the input iterable. So, if the input iterable is sorted, the combin...
4,530,069
def f_4530069(): return
datetime.now(pytz.utc)
import pytz import time from datetime import datetime, timezone def check(candidate):
[ "\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\n" ]
f_4530069
get a value of datetime.today() in the UTC time zone
[ "datetime", "pytz", "time" ]
[ { "function": "datetime.now", "text": "classmethod datetime.now(tz=None) \nReturn the current local date and time. If optional argument tz is None or not specified, this is like today(), but, if possible, supplies more precision than can be gotten from going through a time.time() timestamp (for example, th...
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x != []]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Get a new list `list2`by removing empty list from a list of lists `list1`
[]
[]
4,842,956
def f_4842956(list1):
return list2
list2 = [x for x in list1 if x]
def check(candidate):
[ "\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n", "\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n" ]
f_4842956
Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`
[]
[]
9,262,278
def f_9262278(data): return
HttpResponse(data, content_type='application/json')
import os import json from django.http import HttpResponse from django.conf import settings if not settings.configured: settings.configure(DEBUG=True) def check(candidate):
[ "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"})).content == b'{\"Sample-Key\": \"Sample-Value\"}'\n", "\n if settings.DEBUG:\n assert candidate(json.dumps({\"Sample-Key\": \"Sample-Value\"}))['content-type'] == 'application/json'\n" ]
f_9262278
Django response with JSON `data`
[ "django", "json", "os" ]
[ { "function": "HttpResponse", "text": "class HttpResponse", "title": "django.ref.request-response#django.http.HttpResponse" } ]
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)\\[.*?\\]', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
get all text that is not enclosed within square brackets in string `example_str`
[ "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...
17,284,947
def f_17284947(example_str): return
re.findall('(.*?)(?:\\[.*?\\]|$)', example_str)
import re def check(candidate):
[ "\n list_elems = candidate(\"Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]\")\n assert \"\".join(list_elems).strip() == 'Josie Smith Mugsy Dog Smith'\n" ]
f_17284947
Use a regex to get all text in a string `example_str` that is not surrounded by square brackets
[ "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...
14,182,339
def f_14182339(): return
re.findall('\\(.+?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'
[ "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...
14,182,339
def f_14182339(): return
re.findall('\\((.*?)\\)|(\\w)', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\n" ]
f_14182339
match regex '\\((.*?)\\)|(\\w)' with string '(zyx)bc'
[ "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...
14,182,339
def f_14182339(): return
re.findall('\\(.*?\\)|\\w', '(zyx)bc')
import re def check(candidate):
[ "\n assert candidate() == ['(zyx)', 'b', 'c']\n" ]
f_14182339
match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`
[ "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...
7,126,916
def f_7126916(elements):
return elements
elements = ['%{0}%'.format(element) for element in elements]
def check(candidate):
[ "\n elements = ['abc', 'def', 'ijk', 'mno']\n assert candidate(elements) == ['%abc%', '%def%', '%ijk%', '%mno%']\n", "\n elements = [1, 2, 3, 4, 500]\n assert candidate(elements) == ['%1%', '%2%', '%3%', '%4%', '%500%']\n" ]
f_7126916
formate each string cin list `elements` into pattern '%{0}%'
[]
[]
3,595,685
def f_3595685(): return
subprocess.Popen(['background-process', 'arguments'])
import subprocess from unittest.mock import Mock def check(candidate):
[ "\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n" ]
f_3595685
Open a background process 'background-process' with arguments 'arguments'
[ "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...
18,453,566
def f_18453566(mydict, mykeys): return
[mydict[x] for x in mykeys]
def check(candidate):
[ "\n mydict = {'one': 1, 'two': 2, 'three': 3}\n mykeys = ['three', 'one']\n assert candidate(mydict, mykeys) == [3, 1]\n", "\n mydict = {'one': 1.0, 'two': 2.0, 'three': 3.0}\n mykeys = ['one']\n assert candidate(mydict, mykeys) == [1.0]\n" ]
f_18453566
get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'
[]
[]
12,692,135
def f_12692135(): return
dict([('Name', 'Joe'), ('Age', 22)])
def check(candidate):
[ "\n assert candidate() == {'Name': 'Joe', 'Age': 22}\n" ]
f_12692135
convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary
[]
[]
14,401,047
def f_14401047(data): return
data.mean(axis=1).reshape(data.shape[0], -1)
import numpy as np def check(candidate):
[ "\n data = np.array([[1, 2, 3, 4, 4, 3, 7, 1], [6, 2, 3, 4, 3, 4, 4, 1]])\n expected_res = np.array([[3.125], [3.375]])\n assert np.array_equal(candidate(data), expected_res)\n" ]
f_14401047
average each two columns of array `data`
[ "numpy" ]
[ { "function": "numpy.ndarray.mean", "text": "numpy.ndarray.mean method ndarray.mean(axis=None, dtype=None, out=None, keepdims=False, *, where=True)\n \nReturns the average of the array elements along given axis. Refer to numpy.mean for full documentation. See also numpy.mean\n\nequivalent function", ...
18,886,596
def f_18886596(s): return
s.replace('"', '\"')
def check(candidate):
[ "\n s = 'This sentence has some \"quotes\" in it'\n assert candidate(s) == 'This sentence has some \\\"quotes\\\" in it'\n" ]
f_18886596
double backslash escape all double quotes in string `s`
[]
[]
5,932,059
def f_5932059(s): return
re.split('(\\W+)', s)
import re def check(candidate):
[ "\n s = \"this is a\\nsentence\"\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n" ]
f_5932059
split a string `s` into a list of words and whitespace
[ "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 ...
9,938,130
def f_9938130(df): return
df.plot(kind='barh', stacked=True)
import pandas as pd def check(candidate):
[ "\n data = [[1, 3], [2, 5], [4, 8]]\n df = pd.DataFrame(data, columns = ['a', 'b'])\n assert str(candidate(df)).split('(')[0] == 'AxesSubplot'\n" ]
f_9938130
plotting stacked barplots on a panda data frame `df`
[ "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" } ]
35,945,473
def f_35945473(myDictionary): return
{i[1]: i[0] for i in list(myDictionary.items())}
def check(candidate):
[ "\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\n" ]
f_35945473
reverse the keys and values in a dictionary `myDictionary`
[]
[]
30,729,735
def f_30729735(myList): return
[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]
def check(candidate):
[ "\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\n" ]
f_30729735
finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.
[]
[]
1,303,243
def f_1303243(obj): return
isinstance(obj, str)
def check(candidate):
[ "\n assert candidate('python3') == True\n", "\n assert candidate(1.23) == False\n" ]
f_1303243
check if object `obj` is a string
[]
[]
1,303,243
def f_1303243(o): return
isinstance(o, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
[]
1,303,243
def f_1303243(o): return
(type(o) is str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if object `o` is a string
[]
[]
1,303,243
def f_1303243(obj_to_test): return
isinstance(obj_to_test, str)
def check(candidate):
[ "\n assert candidate(\"hello\") == True\n", "\n assert candidate(123) == False\n", "\n assert candidate([]) == False\n", "\n assert candidate({\"aa\", \"v\"}) == False\n", "\n assert candidate(\"123\") == True\n" ]
f_1303243
check if `obj_to_test` is a string
[]
[]
8,177,079
def f_8177079(list1, list2):
return
list2.extend(list1)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, ...
f_8177079
append list `list1` to `list2`
[]
[]
8,177,079
def f_8177079(mylog, list1):
return
list1.extend(mylog)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, ...
f_8177079
append list `mylog` to `list1`
[]
[]
8,177,079
def f_8177079(a, c):
return
c.extend(a)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, ...
f_8177079
append list `a` to `c`
[]
[]
8,177,079
def f_8177079(mylog, list1):
return
for line in mylog: list1.append(line)
def check(candidate):
[ "\n a, b = [1, 2, 3], [4, 5, 6]\n candidate(a, b)\n assert b == [4, 5, 6, 1, 2, 3]\n", "\n a, c = [1, 2, 3], [7, 8, 9]\n candidate(a, c)\n assert c == [7, 8, 9, 1, 2, 3] \n", "\n b = [4, 5, 6, 1, 2, 3]\n c = [7, 8, 9, 1, 2, 3] \n candidate(b, c)\n assert c == [7, 8, 9, 1, 2, 3, 4, ...
f_8177079
append items in list `mylog` to `list1`
[]
[]
4,126,227
def f_4126227(a, b):
return
b.append((a[0][0], a[0][2]))
def check(candidate):
[ "\n a = [(1,2,3),(4,5,6)]\n b = [(0,0)]\n candidate(a, b)\n assert(b == [(0, 0), (1, 3)])\n" ]
f_4126227
append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`
[]
[]
34,902,378
def f_34902378(app):
return
app.config['SECRET_KEY'] = 'Your_secret_string'
from flask import Flask def check(candidate):
[ "\n app = Flask(\"test\")\n candidate(app)\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\n" ]
f_34902378
Initialize `SECRET_KEY` in flask config with `Your_secret_string `
[ "flask" ]
[ { "function": "flask.Flask.config", "text": "config \nThe configuration dictionary as Config. This behaves exactly like a regular dictionary but supports additional methods to load a config from files.", "title": "flask.api.index#flask.Flask.config" } ]
22,799,300
def f_22799300(out): return
pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)
import numpy as np import pandas as pd from scipy import stats def check(candidate):
[ "\n df = pd.DataFrame(dict(x=np.random.randn(100), y=np.repeat(list(\"abcd\"), 25)))\n out = df.groupby(\"y\").x.apply(stats.ttest_1samp, 0)\n test = pd.DataFrame(out.tolist())\n test.columns = ['out-1', 'out-2']\n test.index = out.index\n res = candidate(out)\n assert(test.equals(res))\n" ]
f_22799300
unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'
[ "numpy", "pandas", "scipy" ]
[ { "function": "pandas.dataframe", "text": "pandas.DataFrame classpandas.DataFrame(data=None, index=None, columns=None, dtype=None, copy=None)[source]\n \nTwo-dimensional, size-mutable, potentially heterogeneous tabular data. Data structure also contains labeled axes (rows and columns). Arithmetic operatio...