{"task_id":3283984,"prompt":"def f_3283984():\n\treturn ","suffix":"","canonical_solution":"bytes.fromhex('4a4b4c').decode('utf-8')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == \"JKL\"\n"],"entry_point":"f_3283984","intent":"decode a hex string '4a4b4c' to UTF-8.","library":[],"docs":[]} {"task_id":3844801,"prompt":"def f_3844801(myList):\n\treturn ","suffix":"","canonical_solution":"all(x == myList[0] for x in myList)","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3]) == False\n","\n assert candidate([1,1,1,1,1,1]) == True\n","\n assert candidate([1]) == True\n","\n assert candidate(['k','k','k','k','k']) == True\n","\n assert candidate([None,'%$#ga',3]) == False\n"],"entry_point":"f_3844801","intent":"check if all elements in list `myList` are identical","library":[],"docs":[]} {"task_id":4302166,"prompt":"def f_4302166():\n\treturn ","suffix":"","canonical_solution":"'%*s : %*s' % (20, 'Python', 20, 'Very Good')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == ' Python : Very Good'\n"],"entry_point":"f_4302166","intent":"format number of spaces between strings `Python`, `:` and `Very Good` to be `20`","library":[],"docs":[]} {"task_id":7555335,"prompt":"def f_7555335(d):\n\treturn ","suffix":"","canonical_solution":"d.decode('cp1251').encode('utf8')","test_start":"\ndef check(candidate):","test":["\n assert candidate('hello world!'.encode('cp1251')) == b'hello world!'\n","\n assert candidate('%*(^O*'.encode('cp1251')) == b'%*(^O*'\n","\n assert candidate(''.encode('cp1251')) == b''\n","\n assert candidate('hello world!'.encode('cp1251')) != 'hello world!'\n"],"entry_point":"f_7555335","intent":"convert a string `d` from CP-1251 to UTF-8","library":[],"docs":[]} {"task_id":2544710,"prompt":"def f_2544710(kwargs):\n\treturn ","suffix":"","canonical_solution":"{k: v for k, v in list(kwargs.items()) if v is not None}","test_start":"\ndef check(candidate):","test":["\n assert candidate({i: None for i in range(10)}) == {}\n","\n assert candidate({i: min(i,4) for i in range(6)}) == {0:0,1:1,2:2,3:3,4:4,5:4}\n","\n assert candidate({'abc': 'abc'})['abc'] == 'abc'\n","\n assert candidate({'x': None, 'yy': 234}) == {'yy': 234}\n"],"entry_point":"f_2544710","intent":"get rid of None values in dictionary `kwargs`","library":[],"docs":[]} {"task_id":2544710,"prompt":"def f_2544710(kwargs):\n\treturn ","suffix":"","canonical_solution":"dict((k, v) for k, v in kwargs.items() if v is not None)","test_start":"\ndef check(candidate):","test":["\n assert candidate({i: None for i in range(10)}) == {}\n","\n assert candidate({i: min(i,4) for i in range(6)}) == {0:0,1:1,2:2,3:3,4:4,5:4}\n","\n assert candidate({'abc': 'abc'})['abc'] == 'abc'\n","\n assert candidate({'x': None, 'yy': 234}) == {'yy': 234}\n"],"entry_point":"f_2544710","intent":"get rid of None values in dictionary `kwargs`","library":[],"docs":[]} {"task_id":14971373,"prompt":"def f_14971373():\n\treturn ","suffix":"","canonical_solution":"subprocess.check_output('ps -ef | grep something | wc -l', shell=True)","test_start":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n output = b' PID TTY TIME CMD\\n 226 pts\/1 00:00:00 bash\\n 285 pts\/1 00:00:00 python3\\n 352 pts\/1 00:00:00 ps\\n'\n subprocess.check_output = Mock(return_value = output)\n assert candidate() == output\n"],"entry_point":"f_14971373","intent":"capture final output of a chain of system commands `ps -ef | grep something | wc -l`","library":["subprocess"],"docs":[{"function":"subprocess.check_output","text":"subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs) \nRun command with arguments and return its output. If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute. This is equivalent to: run(..., check=True, stdout=PIPE).stdout\n The arguments shown above are merely some common ones. The full function signature is largely the same as that of run() - most arguments are passed directly through to that interface. One API deviation from run() behavior exists: passing input=None will behave the same as input=b'' (or input='', depending on other arguments) rather than using the parent\u2019s standard input file handle. By default, this function will return the data as encoded bytes. The actual encoding of the output data may depend on the command being invoked, so the decoding to text will often need to be handled at the application level. This behaviour may be overridden by setting text, encoding, errors, or universal_newlines to True as described in Frequently Used Arguments and run(). To also capture standard error in the result, use stderr=subprocess.STDOUT: >>> subprocess.check_output(\n... \"ls non_existent_file; exit 0\",\n... stderr=subprocess.STDOUT,\n... shell=True)\n'ls: non_existent_file: No such file or directory\\n'\n New in version 3.1. Changed in version 3.3: timeout was added. Changed in version 3.4: Support for the input keyword argument was added. Changed in version 3.6: encoding and errors were added. See run() for details. New in version 3.7: text was added as a more readable alias for universal_newlines.","title":"python.library.subprocess#subprocess.check_output"}]} {"task_id":6726636,"prompt":"def f_6726636():\n\treturn ","suffix":"","canonical_solution":"\"\"\"\"\"\".join(['a', 'b', 'c'])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == \"abc\"\n","\n assert candidate() == 'a' + 'b' + 'c'\n"],"entry_point":"f_6726636","intent":"concatenate a list of strings `['a', 'b', 'c']`","library":[],"docs":[]} {"task_id":18079563,"prompt":"def f_18079563(s1, s2):\n\treturn ","suffix":"","canonical_solution":"pd.Series(list(set(s1).intersection(set(s2))))","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n x1, x2 = pd.Series([1,2]), pd.Series([1,3])\n assert candidate(x1, x2).equals(pd.Series([1]))\n","\n x1, x2 = pd.Series([1,2]), pd.Series([1,3, 10, 4, 5, 9])\n assert candidate(x1, x2).equals(pd.Series([1]))\n","\n x1, x2 = pd.Series([1,2]), pd.Series([1,2, 10])\n assert candidate(x1, x2).equals(pd.Series([1, 2]))\n"],"entry_point":"f_18079563","intent":"find intersection data between series `s1` and series `s2`","library":["pandas"],"docs":[{"function":"pandas.series","text":"Series Constructor \nSeries([data, index, dtype, name, copy, ...]) One-dimensional ndarray with axis labels (including time series). Attributes Axes \nSeries.index The index (axis labels) of the Series. ","title":"pandas.reference.series"}]} {"task_id":8315209,"prompt":"def f_8315209(client):\n\t","suffix":"\n\treturn ","canonical_solution":"client.send('HTTP\/1.0 200 OK\\r\\n')","test_start":"\nimport socket\nfrom unittest.mock import Mock\nimport mock\n\ndef check(candidate):","test":["\n with mock.patch('socket.socket') as mock_socket:\n mock_socket.return_value.recv.return_value = ''\n mock_socket.bind(('', 8080))\n mock_socket.listen(5)\n mock_socket.accept = Mock(return_value = mock_socket)\n mock_socket.send = Mock()\n try:\n candidate(mock_socket)\n except:\n assert False\n"],"entry_point":"f_8315209","intent":"sending http headers to `client`","library":["socket"],"docs":[{"function":"client.send","text":"socket.send(bytes[, flags]) \nSend data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Returns the number of bytes sent. Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data. For further information on this topic, consult the Socket Programming HOWTO. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the method now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale).","title":"python.library.socket#socket.socket.send"}]} {"task_id":26153795,"prompt":"def f_26153795(when):\n\treturn ","suffix":"","canonical_solution":"datetime.datetime.strptime(when, '%Y-%m-%d').date()","test_start":"\nimport datetime\n\ndef check(candidate):","test":["\n assert candidate('2013-05-07') == datetime.date(2013, 5, 7)\n","\n assert candidate('2000-02-29') == datetime.date(2000, 2, 29)\n","\n assert candidate('1990-01-08') == datetime.date(1990, 1, 8)\n","\n assert candidate('1990-1-08') == datetime.date(1990, 1, 8)\n","\n assert candidate('1990-1-8') == datetime.date(1990, 1, 8)\n","\n assert candidate('1990-01-8') == datetime.date(1990, 1, 8)\n"],"entry_point":"f_26153795","intent":"Format a datetime string `when` to extract date only","library":["datetime"],"docs":[{"function":"datetime.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\u2019t be parsed by time.strptime() or if it returns a value which isn\u2019t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.","title":"python.library.datetime#datetime.datetime.strptime"}]} {"task_id":172439,"prompt":"def f_172439(inputString):\n\treturn ","suffix":"","canonical_solution":"inputString.split('\\n')","test_start":"\ndef check(candidate):","test":["\n assert candidate('line a\\nfollows by line b\t...bye\\n') == ['line a', 'follows by line b\t...bye', '']\n","\n assert candidate('no new line in this sentence. ') == ['no new line in this sentence. ']\n","\n assert candidate('a\tbfs hhhdf\tsfdas') == ['a\tbfs hhhdf\tsfdas']\n","\n assert candidate('') == ['']\n"],"entry_point":"f_172439","intent":"split a multi-line string `inputString` into separate strings","library":[],"docs":[]} {"task_id":172439,"prompt":"def f_172439():\n\treturn ","suffix":"","canonical_solution":"' a \\n b \\r\\n c '.split('\\n')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == [' a ', ' b \\r', ' c ']\n"],"entry_point":"f_172439","intent":"Split a multi-line string ` a \\n b \\r\\n c ` by new line character `\\n`","library":[],"docs":[]} {"task_id":13954222,"prompt":"def f_13954222(b):\n\treturn ","suffix":"","canonical_solution":"\"\"\":\"\"\".join(str(x) for x in b)","test_start":"\ndef check(candidate):","test":["\n assert candidate(['x','y','zzz']) == 'x:y:zzz'\n","\n assert candidate(['111','22','3']) == '111:22:3'\n","\n assert candidate(['']) == ''\n","\n assert candidate([':',':']) == ':::'\n","\n assert candidate([',','#','#$%']) == ',:#:#$%'\n","\n assert candidate(['a','b','c']) != 'abc'\n"],"entry_point":"f_13954222","intent":"concatenate elements of list `b` by a colon \":\"","library":[],"docs":[]} {"task_id":13567345,"prompt":"def f_13567345(a):\n\treturn ","suffix":"","canonical_solution":"a.sum(axis=1)","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n a1 = np.array([[i for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a1), np.array([3, 3, 3, 3, 3]))\n","\n a2 = np.array([[i+j for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a2), np.array([ 3, 6, 9, 12, 15]))\n","\n a3 = np.array([[i*j for i in range(3)] for j in range(5)])\n assert np.array_equal(candidate(a3), np.array([ 0, 3, 6, 9, 12]))\n"],"entry_point":"f_13567345","intent":"Calculate sum over all rows of 2D numpy array `a`","library":["numpy"],"docs":[{"function":"a.sum","text":"numpy.sum numpy.sum(a, axis=None, dtype=None, out=None, keepdims=, initial=, where=)[source]\n \nSum of array elements over a given axis. Parameters ","title":"numpy.reference.generated.numpy.sum"}]} {"task_id":29784889,"prompt":"def f_29784889():\n\t","suffix":"\n\treturn ","canonical_solution":"warnings.simplefilter('always')","test_start":"\nimport warnings \n\ndef check(candidate):","test":["\n candidate() \n assert any([(wf[0] == 'always') for wf in warnings.filters])\n"],"entry_point":"f_29784889","intent":"enable warnings using action 'always'","library":["warnings"],"docs":[{"function":"warnings.simplefilter","text":"warnings.simplefilter(action, category=Warning, lineno=0, append=False) \nInsert a simple entry into the list of warnings filter specifications. The meaning of the function parameters is as for filterwarnings(), but regular expressions are not needed as the filter inserted always matches any message in any module as long as the category and line number match.","title":"python.library.warnings#warnings.simplefilter"}]} {"task_id":13550423,"prompt":"def f_13550423(l):\n\treturn ","suffix":"","canonical_solution":"' '.join(map(str, l))","test_start":"\ndef check(candidate):","test":["\n assert candidate(['x','y','zzz']) == 'x y zzz'\n","\n assert candidate(['111','22','3']) == '111 22 3'\n","\n assert candidate(['']) == ''\n","\n assert candidate([':',':']) == ': :'\n","\n assert candidate([',','#','#$%']) == ', # #$%'\n","\n assert candidate(['a','b','c']) != 'abc'\n"],"entry_point":"f_13550423","intent":"concatenate items of list `l` with a space ' '","library":[],"docs":[]} {"task_id":698223,"prompt":"def f_698223():\n\treturn ","suffix":"","canonical_solution":"time.strptime('30\/03\/09 16:31:32.123', '%d\/%m\/%y %H:%M:%S.%f')","test_start":"\nimport time \n\ndef check(candidate):","test":["\n answer = time.strptime('30\/03\/09 16:31:32.123', '%d\/%m\/%y %H:%M:%S.%f')\n assert candidate() == answer\n false_1 = time.strptime('30\/03\/09 17:31:32.123', '%d\/%m\/%y %H:%M:%S.%f')\n assert candidate() != false_1\n false_2 = time.strptime('20\/03\/09 17:31:32.123', '%d\/%m\/%y %H:%M:%S.%f')\n assert candidate() != false_2\n"],"entry_point":"f_698223","intent":"parse a time string '30\/03\/09 16:31:32.123' containing milliseconds in it","library":["time"],"docs":[{"function":"time.strptime","text":"time.strptime(string[, format]) \nParse a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime(). The format parameter uses the same directives as those used by strftime(); it defaults to \"%a %b %d %H:%M:%S %Y\" which matches the formatting returned by ctime(). If string cannot be parsed according to format, or if it has excess data after parsing, ValueError is raised. The default values used to fill in any missing data when more accurate values cannot be inferred are (1900, 1, 1, 0, 0, 0, 0, 1, -1). Both string and format must be strings. For example: >>> import time","title":"python.library.time#time.strptime"}]} {"task_id":6633523,"prompt":"def f_6633523(my_string):\n\t","suffix":"\n\treturn my_float","canonical_solution":"my_float = float(my_string.replace(',', ''))","test_start":"\ndef check(candidate):","test":["\n assert (candidate('1,234.00') - 1234.0) < 1e-6\n","\n assert (candidate('0.00') - 0.00) < 1e-6\n","\n assert (candidate('1,000,000.00') - 1000000.00) < 1e-6\n","\n assert (candidate('1,000,000.00') - 999999.98) > 1e-6\n","\n assert (candidate('1') - 1.00) < 1e-6\n"],"entry_point":"f_6633523","intent":"convert a string `my_string` with dot and comma into a float number `my_float`","library":[],"docs":[]} {"task_id":6633523,"prompt":"def f_6633523():\n\treturn ","suffix":"","canonical_solution":"float('123,456.908'.replace(',', ''))","test_start":"\ndef check(candidate):","test":["\n assert (candidate() - 123456.908) < 1e-6\n assert (candidate() - 123456.9) > 1e-6\n assert (candidate() - 1234.908) > 1e-6\n assert type(candidate()) == float\n assert int(candidate()) == 123456\n"],"entry_point":"f_6633523","intent":"convert a string `123,456.908` with dot and comma into a floating number","library":[],"docs":[]} {"task_id":3108285,"prompt":"def f_3108285():\n\t","suffix":"\n\treturn ","canonical_solution":"sys.path.append('\/path\/to\/whatever')","test_start":"\nimport sys \n\ndef check(candidate):","test":["\n original_paths = [sp for sp in sys.path]\n candidate()\n assert '\/path\/to\/whatever' in sys.path\n"],"entry_point":"f_3108285","intent":"set python path '\/path\/to\/whatever' in python script","library":["sys"],"docs":[{"function":"sys.append","text":"sys \u2014 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 built with the standard configure script, this contains the ABI flags as specified by PEP 3149. Changed in version 3.8: Default flags became an empty string (m flag for pymalloc has been removed). New in version 3.2. \n ","title":"python.library.sys"}]} {"task_id":2195340,"prompt":"def f_2195340():\n\treturn ","suffix":"","canonical_solution":"re.split('(\\\\W+)', 'Words, words, words.')","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate() == ['Words', ', ', 'words', ', ', 'words', '.', '']\n assert candidate() == ['Words', ', '] + ['words', ', ', 'words', '.', '']\n"],"entry_point":"f_2195340","intent":"split string 'Words, words, words.' using a regex '(\\\\W+)'","library":["re"],"docs":[{"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 splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}]} {"task_id":17977584,"prompt":"def f_17977584():\n\treturn ","suffix":"","canonical_solution":"open('Output.txt', 'a')","test_start":"\ndef check(candidate):","test":["\n f = candidate()\n assert str(f.__class__) == \"\"\n assert f.name == 'Output.txt'\n assert f.mode == 'a'\n"],"entry_point":"f_17977584","intent":"open a file `Output.txt` in append mode","library":[],"docs":[]} {"task_id":22676,"prompt":"def f_22676():\n\treturn ","suffix":"","canonical_solution":"urllib.request.urlretrieve('https:\/\/github.com\/zorazrw\/multilingual-conala\/blob\/master\/dataset\/test\/es_test.json', 'mp3.mp3')","test_start":"\nimport urllib \n\ndef check(candidate):","test":["\n results = candidate()\n assert len(results) == 2\n assert results[0] == \"mp3.mp3\"\n assert results[1].values()[0] == \"GitHub.com\"\n"],"entry_point":"f_22676","intent":"download a file \"http:\/\/www.example.com\/songs\/mp3.mp3\" over HTTP and save to \"mp3.mp3\"","library":["urllib"],"docs":[{"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) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen(). The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be -1 on older FTP servers which do not return a file size in response to a retrieval request. The following example illustrates the most common usage scenario: >>> import urllib.request","title":"python.library.urllib.request#urllib.request.urlretrieve"}]} {"task_id":22676,"prompt":"def f_22676(url):\n\t","suffix":"\n\treturn html","canonical_solution":"html = urllib.request.urlopen(url).read()","test_start":"\nimport urllib \n\ndef check(candidate):","test":["\n html = candidate(\"https:\/\/github.com\/zorazrw\/multilingual-conala\/blob\/master\/dataset\/test\/es_test.json\")\n assert b\"zorazrw\/multilingual-conala\" in html\n"],"entry_point":"f_22676","intent":"download a file 'http:\/\/www.example.com\/' over HTTP","library":["urllib"],"docs":[{"function":"urllib.request.urlopen","text":"urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None) \nOpen the URL url, which can be either a string or a Request object. data must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details. urllib.request module uses HTTP\/1.1 and includes Connection:close header in its HTTP requests. The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This actually only works for HTTP, HTTPS and FTP connections. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details. The optional cafile and capath parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations(). The cadefault parameter is ignored. This function always returns an object which can work as a context manager and has the properties url, headers, and status. See urllib.response.addinfourl for more detail on these properties. For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute \u2014 the reason phrase returned by server \u2014 instead of the response headers as it is specified in the documentation for HTTPResponse. For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object. Raises URLError on protocol errors. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy. The legacy urllib.urlopen function from Python 2.6 and earlier has been discontinued; urllib.request.urlopen() corresponds to the old urllib2.urlopen. Proxy handling, which was done by passing a dictionary parameter to urllib.urlopen, can be obtained by using ProxyHandler objects.\nThe default opener raises an auditing event urllib.Request with arguments fullurl, data, headers, method taken from the request object. Changed in version 3.2: cafile and capath were added. Changed in version 3.2: HTTPS virtual hosts are now supported if possible (that is, if ssl.HAS_SNI is true). New in version 3.2: data can be an iterable object. Changed in version 3.3: cadefault was added. Changed in version 3.4.3: context was added. Deprecated since version 3.6: cafile, capath and cadefault are deprecated in favor of context. Please use ssl.SSLContext.load_cert_chain() instead, or let ssl.create_default_context() select the system\u2019s trusted CA certificates for you.","title":"python.library.urllib.request#urllib.request.urlopen"}]} {"task_id":22676,"prompt":"def f_22676(url):\n\treturn ","suffix":"","canonical_solution":"requests.get(url)","test_start":"\nimport requests \n\ndef check(candidate):","test":["\n assert candidate(\"https:\/\/github.com\/\").url == \"https:\/\/github.com\/\"\n","\n assert candidate(\"https:\/\/google.com\/\").url == \"https:\/\/www.google.com\/\"\n"],"entry_point":"f_22676","intent":"download a file `url` over HTTP","library":["requests"],"docs":[]} {"task_id":22676,"prompt":"def f_22676(url):\n\t","suffix":"\n\treturn ","canonical_solution":"\n\tresponse = requests.get(url, stream=True)\n\twith open('10MB', 'wb') as handle:\n\t\tfor data in response.iter_content():\n\t\t\thandle.write(data)\n\t","test_start":"\nimport requests \n\ndef check(candidate):","test":["\n candidate(\"https:\/\/github.com\/\")\n with open(\"10MB\", 'rb') as fr: \n all_data = [data for data in fr]\n assert all_data[: 2] == [b'\\n', b'\\n']\n"],"entry_point":"f_22676","intent":"download a file `url` over HTTP and save to \"10MB\"","library":["requests"],"docs":[]} {"task_id":15405636,"prompt":"def f_15405636(parser):\n\treturn ","suffix":"","canonical_solution":"parser.add_argument('--version', action='version', version='%(prog)s 2.0')","test_start":"\nimport argparse \n\ndef check(candidate):","test":["\n parser = argparse.ArgumentParser()\n output = candidate(parser)\n assert output.option_strings == ['--version']\n assert output.dest == 'version'\n assert output.nargs == 0\n"],"entry_point":"f_15405636","intent":"argparse add argument with flag '--version' and version action of '%(prog)s 2.0' to parser `parser`","library":["argparse"],"docs":[{"function":"parser.add_argument","text":"ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]) \nDefine how a single command-line argument should be parsed. Each parameter has its own more detailed description below, but in short they are: \nname or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. ","title":"python.library.argparse#argparse.ArgumentParser.add_argument"}]} {"task_id":17665809,"prompt":"def f_17665809(d):\n\treturn ","suffix":"","canonical_solution":"{i: d[i] for i in d if i != 'c'}","test_start":"\ndef check(candidate):","test":["\n assert candidate({'a': 1 , 'b': 2, 'c': 3}) == {'a': 1 , 'b': 2}\n","\n assert candidate({'c': None}) == {}\n","\n assert candidate({'a': 1 , 'b': 2, 'c': 3}) != {'a': 1 , 'b': 2, 'c': 3}\n","\n assert candidate({'c': 1, 'cc': 2, 'ccc':3}) == {'cc': 2, 'ccc':3}\n","\n assert 'c' not in candidate({'c':i for i in range(10)})\n"],"entry_point":"f_17665809","intent":"remove key 'c' from dictionary `d`","library":[],"docs":[]} {"task_id":41861705,"prompt":"def f_41861705(split_df, csv_df):\n\treturn ","suffix":"","canonical_solution":"pd.merge(split_df, csv_df, on=['key'], suffixes=('_left', '_right'))","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n split_df = pd.DataFrame({'key': ['foo', 'bar'], 'value': [1, 2]})\n csv_df = pd.DataFrame({'key': ['foo', 'baz'], 'value': [3, 4]})\n result = pd.DataFrame({'key': ['foo'], 'value_left': [1],'value_right': [3]})\n assert all(candidate(csv_df, split_df) == result)\n"],"entry_point":"f_41861705","intent":"Create new DataFrame object by merging columns \"key\" of dataframes `split_df` and `csv_df` and rename the columns from dataframes `split_df` and `csv_df` with suffix `_left` and `_right` respectively","library":["pandas"],"docs":[{"function":"pandas.merge","text":"pandas.merge pandas.merge(left, right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]\n \nMerge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. When performing a cross merge, no column specifications to merge on are allowed. Warning If both key columns contain rows where the key is a null value, those rows will be matched against each other. This is different from usual SQL join behaviour and can lead to unexpected results. Parameters ","title":"pandas.reference.api.pandas.merge"}]} {"task_id":10697757,"prompt":"def f_10697757(s):\n\treturn ","suffix":"","canonical_solution":"s.split(' ', 4)","test_start":"\ndef check(candidate):","test":["\n assert candidate('1 0 A10B 100 Description: This is a description with spaces') == ['1', '0', 'A10B', '100', 'Description: This is a description with spaces']\n","\n assert candidate('this-is-a-continuous-sequence') == ['this-is-a-continuous-sequence']\n","\n assert candidate('') == ['']\n","\n assert candidate('\t') == ['\t']\n"],"entry_point":"f_10697757","intent":"Split a string `s` by space with `4` splits","library":[],"docs":[]} {"task_id":16344756,"prompt":"def f_16344756(app):\n\treturn ","suffix":"","canonical_solution":"app.run(debug=True)","test_start":"\nfrom flask import Flask\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n Flask = Mock()\n app = Flask('mai')\n try:\n candidate(app)\n except:\n return False\n"],"entry_point":"f_16344756","intent":"enable debug mode on Flask application `app`","library":["flask"],"docs":[{"function":"app.run","text":"run(host=None, port=None, debug=None, load_dotenv=True, **options) \nRuns the application on a local development server. Do not use run() in a production setting. It is not intended to meet security and performance requirements for a production server. Instead, see Deployment Options for WSGI server recommendations. If the debug flag is set the server will automatically reload for code changes and show a debugger in case an exception happened. If you want to run the application in debug mode, but disable the code execution on the interactive debugger, you can pass use_evalex=False as parameter. This will keep the debugger\u2019s traceback screen active, but disable code execution. It is not recommended to use this function for development with automatic reloading as this is badly supported. Instead you should be using the flask command line script\u2019s run support. Keep in Mind Flask will suppress any server error with a generic error page unless it is in debug mode. As such to enable just the interactive debugger without the code reloading, you have to invoke run() with debug=True and use_reloader=False. Setting use_debugger to True without being in debug mode won\u2019t catch any exceptions because there won\u2019t be any to catch. Parameters \n \nhost (Optional[str]) \u2013 the hostname to listen on. Set this to '0.0.0.0' to have the server available externally as well. Defaults to '127.0.0.1' or the host in the SERVER_NAME config variable if present. \nport (Optional[int]) \u2013 the port of the webserver. Defaults to 5000 or the port defined in the SERVER_NAME config variable if present. \ndebug (Optional[bool]) \u2013 if given, enable or disable debug mode. See debug. \nload_dotenv (bool) \u2013 Load the nearest .env and .flaskenv files to set environment variables. Will also change the working directory to the directory containing the first file found. \noptions (Any) \u2013 the options to be forwarded to the underlying Werkzeug server. See werkzeug.serving.run_simple() for more information. Return type \nNone Changelog Changed in version 1.0: If installed, python-dotenv will be used to load environment variables from .env and .flaskenv files. If set, the FLASK_ENV and FLASK_DEBUG environment variables will override env and debug. Threaded mode is enabled by default. Changed in version 0.10: The default port is now picked from the SERVER_NAME variable.","title":"flask.api.index#flask.Flask.run"}]} {"task_id":40133826,"prompt":"def f_40133826(mylist):\n\t","suffix":"\n\treturn ","canonical_solution":"pickle.dump(mylist, open('save.txt', 'wb'))","test_start":"\nimport pickle\n\ndef check(candidate):","test":["\n candidate([i for i in range(10)])\n data = pickle.load(open('save.txt', 'rb'))\n assert data == [i for i in range(10)]\n","\n candidate([\"hello\", \"world\", \"!\"])\n data = pickle.load(open('save.txt', 'rb'))\n assert data == [\"hello\", \"world\", \"!\"]\n"],"entry_point":"f_40133826","intent":"python save list `mylist` to file object 'save.txt'","library":["pickle"],"docs":[{"function":"pickle.dump","text":"pickle.dump(obj, file, protocol=None, *, fix_imports=True, buffer_callback=None) \nWrite the pickled representation of the object obj to the open file object file. This is equivalent to Pickler(file, protocol).dump(obj). Arguments file, protocol, fix_imports and buffer_callback have the same meaning as in the Pickler constructor. Changed in version 3.8: The buffer_callback argument was added.","title":"python.library.pickle#pickle.dump"}]} {"task_id":4490961,"prompt":"def f_4490961(P, T):\n\treturn ","suffix":"","canonical_solution":"scipy.tensordot(P, T, axes=[1, 1]).swapaxes(0, 1)","test_start":"\nimport scipy\nimport numpy as np\n\ndef check(candidate):","test":["\n P = np.array([[6, 2, 7], [1, 1, 8], [8, 7, 1], [9, 6, 4], [2, 1, 1]])\n T = np.array([[[9, 7, 2, 3], [9, 6, 8, 2], [6, 6, 2, 8]],\n [[4, 5, 5, 3], [1, 8, 3, 5], [2, 8, 1, 6]]])\n result = np.array([[[114, 96, 42, 78], [ 66, 61, 26, 69], [141, 104, 74, 46], [159, 123, 74, 71], [ 33, 26, 14, 16]], \n [[ 40, 102, 43, 70], [ 21, 77, 16, 56], [ 41, 104, 62, 65], [ 50, 125, 67, 81], [ 11, 26, 14, 17]]])\n assert np.array_equal(candidate(P, T), result)\n"],"entry_point":"f_4490961","intent":"Multiply a matrix `P` with a 3d tensor `T` in scipy","library":["numpy","scipy"],"docs":[]} {"task_id":2173087,"prompt":"def f_2173087():\n\treturn ","suffix":"","canonical_solution":"numpy.zeros((3, 3, 3))","test_start":"\nimport numpy \nimport numpy as np\n\ndef check(candidate):","test":["\n result = np.array([[[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],\n [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]],\n [[0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]])\n assert np.array_equal(candidate(), result)\n"],"entry_point":"f_2173087","intent":"Create 3d array of zeroes of size `(3,3,3)`","library":["numpy"],"docs":[{"function":"numpy.zeros","text":"numpy.zeros numpy.zeros(shape, dtype=float, order='C', *, like=None)\n \nReturn a new array of given shape and type, filled with zeros. Parameters ","title":"numpy.reference.generated.numpy.zeros"}]} {"task_id":6266727,"prompt":"def f_6266727(content):\n\treturn ","suffix":"","canonical_solution":"\"\"\" \"\"\".join(content.split(' ')[:-1])","test_start":"\ndef check(candidate):","test":["\n assert candidate('test') == ''\n","\n assert candidate('this is an example content') == 'this is an example'\n","\n assert candidate(' ') == ' '\n","\n assert candidate('') == ''\n","\n assert candidate('blank and tab\t') == 'blank and'\n"],"entry_point":"f_6266727","intent":"cut off the last word of a sentence `content`","library":[],"docs":[]} {"task_id":30385151,"prompt":"def f_30385151(x):\n\t","suffix":"\n\treturn x","canonical_solution":"x = np.asarray(x).reshape(1, -1)[(0), :]","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\n assert all(candidate(1.) == np.asarray(1.))\n","\n assert all(candidate(123) == np.asarray(123))\n","\n assert all(candidate('a') == np.asarray('a'))\n","\n assert all(candidate(False) == np.asarray(False))\n"],"entry_point":"f_30385151","intent":"convert scalar `x` to array","library":["numpy"],"docs":[{"function":"numpy.asarray","text":"numpy.asarray numpy.asarray(a, dtype=None, order=None, *, like=None)\n \nConvert the input to an array. Parameters ","title":"numpy.reference.generated.numpy.asarray"},{"function":"numpy.reshape","text":"numpy.reshape numpy.reshape(a, newshape, order='C')[source]\n \nGives a new shape to an array without changing its data. Parameters ","title":"numpy.reference.generated.numpy.reshape"}]} {"task_id":15856127,"prompt":"def f_15856127(L):\n\treturn ","suffix":"","canonical_solution":"sum(sum(i) if isinstance(i, list) else i for i in L)","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3,4]) == 10\n","\n assert candidate([[1],[2],[3],[4]]) == 10\n","\n assert candidate([1,1,1,1]) == 4\n","\n assert candidate([1,[2,3],[4]]) == 10\n","\n assert candidate([]) == 0\n","\n assert candidate([[], []]) == 0\n"],"entry_point":"f_15856127","intent":"sum all elements of nested list `L`","library":[],"docs":[]} {"task_id":1592158,"prompt":"def f_1592158():\n\treturn ","suffix":"","canonical_solution":"struct.unpack('!f', bytes.fromhex('470FC614'))[0]","test_start":"\nimport struct \n\ndef check(candidate):","test":["\n assert (candidate() - 36806.078125) < 1e-6\n","\n assert (candidate() - 32806.079125) > 1e-6\n"],"entry_point":"f_1592158","intent":"convert hex string '470FC614' to a float number","library":["struct"],"docs":[{"function":"struct.unpack","text":"struct.unpack(format, buffer) \nUnpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer\u2019s size in bytes must match the size required by the format, as reflected by calcsize().","title":"python.library.struct#struct.unpack"}]} {"task_id":5010536,"prompt":"def f_5010536(my_dict):\n\t","suffix":"\n\treturn my_dict","canonical_solution":"my_dict.update((x, y * 2) for x, y in list(my_dict.items()))","test_start":"\ndef check(candidate):","test":["\n assert candidate({'a': [1], 'b': 4.9}) == {'a': [1, 1], 'b': 9.8}\n","\n assert candidate({1:1}) == {1:2}\n","\n assert candidate({(1,2):[1]}) == {(1,2):[1,1]}\n","\n assert candidate({'asd':0}) == {'asd':0}\n","\n assert candidate({}) == {}\n"],"entry_point":"f_5010536","intent":"Multiple each value by `2` for all keys in a dictionary `my_dict`","library":[],"docs":[]} {"task_id":13745648,"prompt":"def f_13745648():\n\treturn ","suffix":"","canonical_solution":"subprocess.call('sleep.sh', shell=True)","test_start":"\nimport subprocess \nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n"],"entry_point":"f_13745648","intent":"running bash script 'sleep.sh'","library":["subprocess"],"docs":[{"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 stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.","title":"python.library.subprocess#subprocess.call"}]} {"task_id":44778,"prompt":"def f_44778(l):\n\treturn ","suffix":"","canonical_solution":"\"\"\",\"\"\".join(l)","test_start":"\ndef check(candidate):","test":["\n assert candidate(['a','b','c']) == 'a,b,c'\n","\n assert candidate(['a','b']) == 'a,b'\n","\n assert candidate([',',',',',']) == ',,,,,'\n","\n assert candidate([' ',' ','c']) == ' , ,c'\n","\n assert candidate([]) == ''\n"],"entry_point":"f_44778","intent":"Join elements of list `l` with a comma `,`","library":[],"docs":[]} {"task_id":44778,"prompt":"def f_44778(myList):\n\t","suffix":"\n\treturn myList","canonical_solution":"myList = ','.join(map(str, myList))","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3]) == '1,2,3'\n","\n assert candidate([1,2,'a']) == '1,2,a'\n","\n assert candidate([]) == ''\n","\n assert candidate(['frg',3253]) == 'frg,3253'\n"],"entry_point":"f_44778","intent":"make a comma-separated string from a list `myList`","library":[],"docs":[]} {"task_id":7286365,"prompt":"def f_7286365():\n\treturn ","suffix":"","canonical_solution":"list(reversed(list(range(10))))","test_start":"\ndef check(candidate):","test":["\n assert candidate() == [9,8,7,6,5,4,3,2,1,0]\n","\n assert len(candidate()) == 10\n","\n assert min(candidate()) == 0\n","\n assert type(candidate()) == list\n","\n assert type(candidate()[-2]) == int\n"],"entry_point":"f_7286365","intent":"reverse the list that contains 1 to 10","library":[],"docs":[]} {"task_id":18454570,"prompt":"def f_18454570():\n\treturn ","suffix":"","canonical_solution":"'lamp, bag, mirror'.replace('bag,', '')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 'lamp, mirror'\n assert type(candidate()) == str\n assert len(candidate()) == 13\n assert candidate().startswith('lamp')\n"],"entry_point":"f_18454570","intent":"remove substring 'bag,' from a string 'lamp, bag, mirror'","library":[],"docs":[]} {"task_id":4357787,"prompt":"def f_4357787(s):\n\treturn ","suffix":"","canonical_solution":"\"\"\".\"\"\".join(s.split('.')[::-1])","test_start":"\ndef check(candidate):","test":["\n assert candidate('apple.orange.red.green.yellow') == 'yellow.green.red.orange.apple'\n","\n assert candidate('apple') == 'apple'\n","\n assert candidate('apple.orange') == 'orange.apple'\n","\n assert candidate('123.456') == '456.123'\n","\n assert candidate('.') == '.'\n"],"entry_point":"f_4357787","intent":"Reverse the order of words, delimited by `.`, in string `s`","library":[],"docs":[]} {"task_id":21787496,"prompt":"def f_21787496(s):\n\treturn ","suffix":"","canonical_solution":"datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')","test_start":"\nimport time\nimport datetime\n\ndef check(candidate): ","test":["\n assert candidate(1236472) == '1970-01-15 07:27:52.000000'\n","\n assert candidate(0) == '1970-01-01 00:00:00.000000'\n","\n assert candidate(5.3) == '1970-01-01 00:00:05.300000'\n"],"entry_point":"f_21787496","intent":"convert epoch time represented as milliseconds `s` to string using format '%Y-%m-%d %H:%M:%S.%f'","library":["datetime","time"],"docs":[{"function":"datetime.fromtimestamp","text":"classmethod datetime.fromtimestamp(timestamp, tz=None) \nReturn the local date and time corresponding to the POSIX timestamp, such as is returned by time.time(). If optional argument tz is None or not specified, the timestamp is converted to the platform\u2019s local date and time, and the returned datetime object is naive. If tz is not None, it must be an instance of a tzinfo subclass, and the timestamp is converted to tz\u2019s time zone. fromtimestamp() may raise OverflowError, if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions, and OSError on localtime() or gmtime() failure. It\u2019s common for this to be restricted to years in 1970 through 2038. Note that on non-POSIX systems that include leap seconds in their notion of a timestamp, leap seconds are ignored by fromtimestamp(), and then it\u2019s possible to have two timestamps differing by a second that yield identical datetime objects. This method is preferred over utcfromtimestamp(). Changed in version 3.3: Raise OverflowError instead of ValueError if the timestamp is out of the range of values supported by the platform C localtime() or gmtime() functions. Raise OSError instead of ValueError on localtime() or gmtime() failure. Changed in version 3.6: fromtimestamp() may return instances with fold set to 1.","title":"python.library.datetime#datetime.datetime.fromtimestamp"},{"function":"datetime.strftime","text":"datetime.strftime(format) \nReturn a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.","title":"python.library.datetime#datetime.datetime.strftime"}]} {"task_id":21787496,"prompt":"def f_21787496():\n\treturn ","suffix":"","canonical_solution":"time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(1236472051807 \/ 1000.0))","test_start":"\nimport time\n\ndef check(candidate): ","test":["\n assert candidate() == '2009-03-08 00:27:31'\n"],"entry_point":"f_21787496","intent":"parse milliseconds epoch time '1236472051807' to format '%Y-%m-%d %H:%M:%S'","library":["time"],"docs":[{"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. ValueError is raised if any field in t is outside of the allowed range. 0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one. The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result: \nDirective Meaning Notes ","title":"python.library.time#time.strftime"}]} {"task_id":20573459,"prompt":"def f_20573459():\n\treturn ","suffix":"","canonical_solution":"(datetime.datetime.now() - datetime.timedelta(days=7)).date()","test_start":"\nimport datetime\n\ndef check(candidate): ","test":["\n assert datetime.datetime.now().date() - candidate() < datetime.timedelta(days = 7, seconds = 1)\n","\n assert datetime.datetime.now().date() - candidate() >= datetime.timedelta(days = 7)\n"],"entry_point":"f_20573459","intent":"get the date 7 days before the current date","library":["datetime"],"docs":[{"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, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz\u2019s time zone. This function is preferred over today() and utcnow().","title":"python.library.datetime#datetime.datetime.now"},{"function":"datetime.timedelta","text":"class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) \nAll arguments are optional and default to 0. Arguments may be integers or floats, and may be positive or negative. Only days, seconds and microseconds are stored internally. Arguments are converted to those units: A millisecond is converted to 1000 microseconds. A minute is converted to 60 seconds. An hour is converted to 3600 seconds. A week is converted to 7 days. and days, seconds and microseconds are then normalized so that the representation is unique, with 0 <= microseconds < 1000000 \n0 <= seconds < 3600*24 (the number of seconds in one day) -999999999 <= days <= 999999999 The following example illustrates how any arguments besides days, seconds and microseconds are \u201cmerged\u201d and normalized into those three resulting attributes: >>> from datetime import timedelta","title":"python.library.datetime#datetime.timedelta"}]} {"task_id":15352457,"prompt":"def f_15352457(column, data):\n\treturn ","suffix":"","canonical_solution":"sum(row[column] for row in data)","test_start":"\ndef check(candidate): ","test":["\n assert candidate(1, [[1,2,3], [4,5,6]]) == 7\n","\n assert candidate(0, [[1,1,1], [0,1,1]]) == 1\n","\n assert candidate(5, [[1,1,1,1,1,2], [0,1,1,1,1,1,1,1,1,1,1]]) == 3\n","\n assert candidate(0, [[1],[2],[3],[4]]) == 10\n"],"entry_point":"f_15352457","intent":"sum elements at index `column` of each list in list `data`","library":[],"docs":[]} {"task_id":15352457,"prompt":"def f_15352457(array):\n\treturn ","suffix":"","canonical_solution":"[sum(row[i] for row in array) for i in range(len(array[0]))]","test_start":"\ndef check(candidate): ","test":["\n assert candidate([[1,2,3], [4,5,6]]) == [5, 7, 9]\n","\n assert candidate([[1,1,1], [0,1,1]]) == [1, 2, 2]\n","\n assert candidate([[1,1,1,1,1,2], [0,1,1,1,1,1,1,1,1,1,1]]) == [1, 2, 2, 2, 2, 3]\n","\n assert candidate([[1],[2],[3],[4]]) == [10]\n"],"entry_point":"f_15352457","intent":"sum columns of a list `array`","library":[],"docs":[]} {"task_id":23164058,"prompt":"def f_23164058():\n\treturn ","suffix":"","canonical_solution":"base64.b64encode(bytes('your string', 'utf-8'))","test_start":"\nimport base64\n\ndef check(candidate): ","test":["\n assert candidate() == b'eW91ciBzdHJpbmc='\n"],"entry_point":"f_23164058","intent":"encode binary string 'your string' to base64 code","library":["base64"],"docs":[{"function":"base64.b64encode","text":"base64.b64encode(s, altchars=None) \nEncode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and \/ characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.","title":"python.library.base64#base64.b64encode"}]} {"task_id":11533274,"prompt":"def f_11533274(dicts):\n\treturn ","suffix":"","canonical_solution":"dict((k, [d[k] for d in dicts]) for k in dicts[0])","test_start":"\ndef check(candidate): ","test":["\n assert candidate([{'cat': 1, 'dog': 3}, {'cat' : 2, 'dog': ['happy']}]) == {'cat': [1, 2], 'dog': [3, ['happy']]}\n","\n assert candidate([{'cat': 1}, {'cat' : 2}]) != {'cat': 3}\n"],"entry_point":"f_11533274","intent":"combine list of dictionaries `dicts` with the same keys in each list to a single dictionary","library":[],"docs":[]} {"task_id":11533274,"prompt":"def f_11533274(dicts):\n\treturn ","suffix":"","canonical_solution":"{k: [d[k] for d in dicts] for k in dicts[0]}","test_start":"\ndef check(candidate): ","test":["\n assert candidate([{'cat': 1, 'dog': 3}, {'cat' : 2, 'dog': ['happy']}]) == {'cat': [1, 2], 'dog': [3, ['happy']]}\n","\n assert candidate([{'cat': 1}, {'cat' : 2}]) != {'cat': 3}\n"],"entry_point":"f_11533274","intent":"Merge a nested dictionary `dicts` into a flat dictionary by concatenating nested values with the same key `k`","library":[],"docs":[]} {"task_id":14026704,"prompt":"def f_14026704(request):\n\treturn ","suffix":"","canonical_solution":"request.args['myParam']","test_start":"\nimport multidict\n\nclass Request:\n def __init__(self, args):\n self.args = args\n\ndef check(candidate): ","test":["\n args = multidict.MultiDict([('myParam' , 'popeye')])\n request = Request(args)\n assert candidate(request) == 'popeye'\n"],"entry_point":"f_14026704","intent":"get the url parameter 'myParam' in a Flask view","library":["multidict"],"docs":[]} {"task_id":11236006,"prompt":"def f_11236006(mylist):\n\treturn ","suffix":"","canonical_solution":"[k for k, v in list(Counter(mylist).items()) if v > 1]","test_start":"\nfrom collections import Counter\n\ndef check(candidate):","test":["\n assert candidate([1,3,2,2,1,4]) == [1, 2]\n","\n assert candidate([1,3,2,2,1,4]) != [3,4]\n","\n assert candidate([]) == []\n","\n assert candidate([1,1,1,1,1]) == [1]\n","\n assert candidate([1.,1.,1.]) == [1.]\n"],"entry_point":"f_11236006","intent":"identify duplicate values in list `mylist`","library":["collections"],"docs":[{"function":"collections.Counter","text":"class collections.Counter([iterable-or-mapping]) \nA Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages. Elements are counted from an iterable or initialized from another mapping (or counter): >>> c = Counter() # a new, empty counter","title":"python.library.collections#collections.Counter"}]} {"task_id":20211942,"prompt":"def f_20211942(db):\n\treturn ","suffix":"","canonical_solution":"db.execute(\"INSERT INTO present VALUES('test2', ?, 10)\", (None,))","test_start":"\nimport sqlite3\n\ndef check(candidate):","test":["\n sqliteConnection = sqlite3.connect('dev.db')\n db = sqliteConnection.cursor()\n print(\"Database created and Successfully Connected to SQLite\")\n db.execute(\"CREATE TABLE present (name VARCHAR(5), age INTEGER, height INTEGER)\")\n try:\n candidate(db)\n except:\n assert False\n"],"entry_point":"f_20211942","intent":"Insert a 'None' value into a SQLite3 table.","library":["sqlite3"],"docs":[{"function":"db.execute","text":"execute(sql[, parameters]) \nThis is a nonstandard shortcut that creates a cursor object by calling the cursor() method, calls the cursor\u2019s execute() method with the parameters given, and returns the cursor.","title":"python.library.sqlite3#sqlite3.Connection.execute"}]} {"task_id":406121,"prompt":"def f_406121(list_of_menuitems):\n\treturn ","suffix":"","canonical_solution":"[image for menuitem in list_of_menuitems for image in menuitem]","test_start":"\nfrom collections import Counter\n\ndef check(candidate):","test":["\n assert candidate([[1,2],[3,4,5]]) == [1,2,3,4,5]\n","\n assert candidate([[],[]]) == []\n","\n assert candidate([[1,1,1], []]) == [1,1,1]\n","\n assert candidate([['1'],['2']]) == ['1','2']\n"],"entry_point":"f_406121","intent":"flatten list `list_of_menuitems`","library":["collections"],"docs":[]} {"task_id":4741537,"prompt":"def f_4741537(a, b):\n\t","suffix":"\n\treturn a","canonical_solution":"a.extend(b)","test_start":"\ndef check(candidate):","test":["\n assert candidate([1, 2, 2, 3], {4, 5, 2}) == [1, 2, 2, 3, 2, 4, 5]\n","\n assert candidate([], {4,5,2}) == [2,4,5]\n","\n assert candidate([1,2,3,4],{2}) == [1,2,3,4,2]\n","\n assert candidate([1], {'a'}) == [1, 'a']\n"],"entry_point":"f_4741537","intent":"append elements of a set `b` to a list `a`","library":[],"docs":[]} {"task_id":15851568,"prompt":"def f_15851568(x):\n\treturn ","suffix":"","canonical_solution":"x.rpartition('-')[0]","test_start":"\ndef check(candidate):","test":["\n assert candidate('djhajhdjk-dadwqd-dahdjkahsk') == 'djhajhdjk-dadwqd'\n","\n assert candidate('\/-\/') == '\/'\n","\n assert candidate('---') == '--'\n","\n assert candidate('') == ''\n"],"entry_point":"f_15851568","intent":"Split a string `x` by last occurrence of character `-`","library":[],"docs":[]} {"task_id":15851568,"prompt":"def f_15851568(x):\n\treturn ","suffix":"","canonical_solution":"x.rsplit('-', 1)[0]","test_start":"\ndef check(candidate):","test":["\n assert candidate('2022-03-01') == '2022-03'\n","\n assert candidate('2020-2022') == '2020'\n"],"entry_point":"f_15851568","intent":"get the last part of a string before the character '-'","library":[],"docs":[]} {"task_id":17438096,"prompt":"def f_17438096(filename, ftp):\n\t","suffix":"\n\treturn ","canonical_solution":"ftp.storlines('STOR ' + filename, open(filename, 'r'))","test_start":"\nimport ftplib\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n ftplib.FTP = Mock()\n ftp = ftplib.FTP(\"10.10.10.10\")\n ftp.storlines = Mock()\n file_name = 'readme.txt'\n with open (file_name, 'a') as f:\n f.write('apple')\n candidate(file_name, ftp)\n"],"entry_point":"f_17438096","intent":"upload file using FTP","library":["ftplib"],"docs":[{"function":"ftp.storlines","text":"FTP.storlines(cmd, fp, callback=None) \nStore a file in line mode. cmd should be an appropriate STOR command (see storbinary()). Lines are read until EOF from the file object fp (opened in binary mode) using its readline() method to provide the data to be stored. callback is an optional single parameter callable that is called on each line after it is sent.","title":"python.library.ftplib#ftplib.FTP.storlines"}]} {"task_id":28742436,"prompt":"def f_28742436():\n\treturn ","suffix":"","canonical_solution":"np.maximum([2, 3, 4], [1, 5, 2])","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n assert all(candidate() == np.array([2, 5, 4]))\n"],"entry_point":"f_28742436","intent":"create array containing the maximum value of respective elements of array `[2, 3, 4]` and array `[1, 5, 2]`","library":["numpy"],"docs":[{"function":"numpy.maximum","text":"numpy.maximum numpy.maximum(x1, x2, \/, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj]) = \n \nElement-wise maximum of array elements. Compare two arrays and returns a new array containing the element-wise maxima. If one of the elements being compared is a NaN, then that element is returned. If both elements are NaNs then the first is returned. The latter distinction is important for complex NaNs, which are defined as at least one of the real or imaginary parts being a NaN. The net effect is that NaNs are propagated. Parameters ","title":"numpy.reference.generated.numpy.maximum"}]} {"task_id":34280147,"prompt":"def f_34280147(l):\n\treturn ","suffix":"","canonical_solution":"l[3:] + l[:3]","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"my-string\") == \"stringmy-\"\n","\n assert candidate(\"my \") == \"my \"\n","\n assert candidate(\"n;ho0-4w606[q\") == \"o0-4w606[qn;h\"\n"],"entry_point":"f_34280147","intent":"print a list `l` and move first 3 elements to the end of the list","library":[],"docs":[]} {"task_id":4172131,"prompt":"def f_4172131():\n\treturn ","suffix":"","canonical_solution":"[int(1000 * random.random()) for i in range(10000)]","test_start":"\nimport random\n\ndef check(candidate):","test":["\n result = candidate()\n assert isinstance(result, list)\n assert all([isinstance(item, int) for item in result])\n"],"entry_point":"f_4172131","intent":"create a random list of integers","library":["random"],"docs":[{"function":"random.random","text":"random.random() \nReturn the next random floating point number in the range [0.0, 1.0).","title":"python.library.random#random.random"}]} {"task_id":6677332,"prompt":"def f_6677332():\n\treturn ","suffix":"","canonical_solution":"datetime.datetime.now().strftime('%H:%M:%S.%f')","test_start":"\nimport datetime\n\ndef check(candidate):","test":["\n time_now = datetime.datetime.now().strftime('%H:%M:%S.%f')\n assert candidate().split('.')[0] == time_now.split('.')[0]\n"],"entry_point":"f_6677332","intent":"Using %f with strftime() in Python to get microseconds","library":["datetime"],"docs":[{"function":"datetime.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, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz\u2019s time zone. This function is preferred over today() and utcnow().","title":"python.library.datetime#datetime.datetime.now"},{"function":"datetime.strftime","text":"datetime.strftime(format) \nReturn a string representing the date and time, controlled by an explicit format string. For a complete list of formatting directives, see strftime() and strptime() Behavior.","title":"python.library.datetime#datetime.datetime.strftime"}]} {"task_id":15325182,"prompt":"def f_15325182(df):\n\treturn ","suffix":"","canonical_solution":"df.b.str.contains('^f')","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\n df = pd.DataFrame([[1, 'fat'], [2, 'hip'], [3, 'foo']], columns = ['a', 'b'])\n expected = [True, False, True]\n actual = candidate(df)\n for i in range (0, len(expected)):\n assert expected[i] == actual[i]\n"],"entry_point":"f_15325182","intent":"filter rows in pandas starting with alphabet 'f' using regular expression.","library":["pandas"],"docs":[{"function":".contains","text":"pandas.Series.str.contains Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]\n \nTest if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ","title":"pandas.reference.api.pandas.series.str.contains"}]} {"task_id":583557,"prompt":"def f_583557(tab):\n\treturn ","suffix":"","canonical_solution":"'\\n'.join('\\t'.join(str(col) for col in row) for row in tab)","test_start":"\ndef check(candidate):","test":["\n assert candidate([[1,2,3],[4,5,6]]) == \"1\\t2\\t3\\n4\\t5\\t6\"\n","\n assert candidate([[1, 'x' ,3],[4.4,5,\"six\"]]) == \"1\\tx\\t3\\n4.4\\t5\\tsix\"\n","\n assert candidate([]) == \"\"\n","\n assert candidate([[],[],[]]) == \"\\n\\n\"\n"],"entry_point":"f_583557","intent":"print a 2 dimensional list `tab` as a table with delimiters","library":[],"docs":[]} {"task_id":38535931,"prompt":"def f_38535931(df, tuples):\n\treturn ","suffix":"","canonical_solution":"df.set_index(list('BC')).drop(tuples, errors='ignore').reset_index()","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[3, 4], [4, 5], [-1, -2]], columns = ['B', 'C'])\n tuples = [(3, 4), (-1, -2)]\n expected = pd.DataFrame([[4, 5]], columns = ['B', 'C'])\n actual = candidate(df, tuples)\n assert pd.DataFrame.equals(actual, expected)\n"],"entry_point":"f_38535931","intent":"pandas: delete rows in dataframe `df` based on multiple columns values","library":["pandas"],"docs":[{"function":"pandas.dataframe.set_index","text":"pandas.DataFrame.set_index DataFrame.set_index(keys, drop=True, append=False, inplace=False, verify_integrity=False)[source]\n \nSet the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays (of the correct length). The index can replace the existing index or expand on it. Parameters ","title":"pandas.reference.api.pandas.dataframe.set_index"},{"function":"pandas.dataframe.drop","text":"pandas.DataFrame.drop DataFrame.drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise')[source]\n \nDrop specified labels from rows or columns. Remove rows or columns by specifying label names and corresponding axis, or by specifying directly index or column names. When using a multi-index, labels on different levels can be removed by specifying the level. See the user guide for more information about the now unused levels. Parameters ","title":"pandas.reference.api.pandas.dataframe.drop"},{"function":"pandas.dataframe.reset_index","text":"pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ","title":"pandas.reference.api.pandas.dataframe.reset_index"}]} {"task_id":13945749,"prompt":"def f_13945749(goals, penalties):\n\treturn ","suffix":"","canonical_solution":"\"\"\"({:d} goals, ${:d})\"\"\".format(goals, penalties)","test_start":"\ndef check(candidate):","test":["\n assert candidate(0, 0) == \"(0 goals, $0)\"\n","\n assert candidate(123, 2) == \"(123 goals, $2)\"\n"],"entry_point":"f_13945749","intent":"format the variables `goals` and `penalties` using string formatting","library":[],"docs":[]} {"task_id":13945749,"prompt":"def f_13945749(goals, penalties):\n\treturn ","suffix":"","canonical_solution":"\"\"\"({} goals, ${})\"\"\".format(goals, penalties)","test_start":"\ndef check(candidate):","test":["\n assert candidate(0, 0) == \"(0 goals, $0)\"\n","\n assert candidate(123, \"???\") == \"(123 goals, $???)\"\n","\n assert candidate(\"x\", 0.0) == \"(x goals, $0.0)\"\n"],"entry_point":"f_13945749","intent":"format string \"({} goals, ${})\" with variables `goals` and `penalties`","library":[],"docs":[]} {"task_id":18524642,"prompt":"def f_18524642(L):\n\treturn ","suffix":"","canonical_solution":"[int(''.join(str(d) for d in x)) for x in L]","test_start":"\ndef check(candidate):","test":["\n assert candidate([[1,2], [2,3,4], [1,0,0]]) == [12,234,100]\n","\n assert candidate([[1], [2], [3]]) == [1,2,3]\n"],"entry_point":"f_18524642","intent":"convert list of lists `L` to list of integers","library":[],"docs":[]} {"task_id":18524642,"prompt":"def f_18524642(L):\n\t","suffix":"\n\treturn L","canonical_solution":"L = [int(''.join([str(y) for y in x])) for x in L]","test_start":"\ndef check(candidate):","test":["\n assert candidate([[1,2], [2,3,4], [1,0,0]]) == [12,234,100]\n","\n assert candidate([[1], [2], [3]]) == [1,2,3]\n","\n assert candidate([[1, 0], [0, 2], [3], [0, 0, 0, 0]]) == [10,2,3, 0]\n"],"entry_point":"f_18524642","intent":"convert a list of lists `L` to list of integers","library":[],"docs":[]} {"task_id":7138686,"prompt":"def f_7138686(lines, myfile):\n\t","suffix":"\n\treturn ","canonical_solution":"myfile.write('\\n'.join(lines))","test_start":"\ndef check(candidate):","test":["\n with open('tmp.txt', 'w') as myfile:\n candidate([\"first\", \"second\", \"third\"], myfile)\n with open('tmp.txt', 'r') as fr: \n lines = fr.readlines()\n assert lines == [\"first\\n\", \"second\\n\", \"third\"]\n"],"entry_point":"f_7138686","intent":"write the elements of list `lines` concatenated by special character '\\n' to file `myfile`","library":[],"docs":[]} {"task_id":17238587,"prompt":"def f_17238587(text):\n\t","suffix":"\n\treturn text","canonical_solution":"text = re.sub('\\\\b(\\\\w+)( \\\\1\\\\b)+', '\\\\1', text)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate(\"text\") == \"text\"\n","\n assert candidate(\"text text\") == \"text\"\n","\n assert candidate(\"texttext\") == \"texttext\"\n","\n assert candidate(\"text and text\") == \"text and text\"\n"],"entry_point":"f_17238587","intent":"Remove duplicate words from a string `text` using regex","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":26053849,"prompt":"def f_26053849(df):\n\treturn ","suffix":"","canonical_solution":"df.astype(bool).sum(axis=1)","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\n df1 = pd.DataFrame([[0,0,0], [0,1,0], [1,1,1]])\n assert candidate(df1).to_list() == [0, 1, 3]\n","\n df2 = pd.DataFrame([[0,0,0], [0,2,0], [1,10,8.9]])\n assert candidate(df1).to_list() == [0, 1, 3]\n","\n df2 = pd.DataFrame([[0,0.0,0], [0,2.0,0], [1,10,8.9]])\n assert candidate(df1).to_list() == [0, 1, 3]\n","\n df = df = pd.DataFrame([[4, 0, 0], [1, 0, 1]])\n expected = [1, 2]\n actual = candidate(df)\n for i in range(0, len(expected)):\n assert expected[i] == actual[i]\n"],"entry_point":"f_26053849","intent":"count non zero values in each column in pandas data frame `df`","library":["pandas"],"docs":[{"function":"pandas.dataframe.astype","text":"pandas.DataFrame.astype DataFrame.astype(dtype, copy=True, errors='raise')[source]\n \nCast a pandas object to a specified dtype dtype. Parameters ","title":"pandas.reference.api.pandas.dataframe.astype"},{"function":"pandas.dataframe.sum","text":"pandas.DataFrame.sum DataFrame.sum(axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)[source]\n \nReturn the sum of the values over the requested axis. This is equivalent to the method numpy.sum. Parameters ","title":"pandas.reference.api.pandas.dataframe.sum"}]} {"task_id":15534223,"prompt":"def f_15534223():\n\treturn ","suffix":"","canonical_solution":"re.search('(?.*<', line).group(0)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate(\"hahhdsf>0.0<;sgnd\") == \">0.0<\"\n","\n assert candidate(\"hahhdsf>2.34<;xbnfm\") == \">2.34<\"\n"],"entry_point":"f_18168684","intent":"search for occurrences of regex pattern '>.*<' in xml string `line`","library":["re"],"docs":[{"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 different from finding a zero-length match at some point in the string.","title":"python.library.re#re.search"}]} {"task_id":4914277,"prompt":"def f_4914277(filename):\n\treturn ","suffix":"","canonical_solution":"open(filename, 'w').close()","test_start":"\ndef check(candidate):","test":["\n filename = 'tmp.txt'\n with open(filename, 'w') as fw: fw.write(\"hello world!\")\n with open(filename, 'r') as fr: \n lines = fr.readlines()\n assert len(lines) == 1 and lines[0] == \"hello world!\"\n candidate(filename)\n with open(filename, 'r') as fr: \n lines = fr.readlines()\n assert len(lines) == 0\n"],"entry_point":"f_4914277","intent":"erase all the contents of a file `filename`","library":[],"docs":[]} {"task_id":19068269,"prompt":"def f_19068269(string_date):\n\treturn ","suffix":"","canonical_solution":"datetime.datetime.strptime(string_date, '%Y-%m-%d %H:%M:%S.%f')","test_start":"\nimport datetime \n\ndef check(candidate):","test":["\n assert candidate('2022-10-22 11:59:59.20') == datetime.datetime(2022, 10, 22, 11, 59, 59, 200000)\n","\n assert candidate('2000-01-01 11:59:59.20') == datetime.datetime(2000, 1, 1, 11, 59, 59, 200000)\n","\n assert candidate('1990-09-09 09:59:59.24') == datetime.datetime(1990, 9, 9, 9, 59, 59, 240000)\n","\n d = candidate('2022-12-14 07:06:00.25')\n assert d == datetime.datetime(2022, 12, 14, 7, 6, 0, 250000)\n"],"entry_point":"f_19068269","intent":"convert a string `string_date` into datetime using the format '%Y-%m-%d %H:%M:%S.%f'","library":["datetime"],"docs":[{"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\u2019t be parsed by time.strptime() or if it returns a value which isn\u2019t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.","title":"python.library.datetime#datetime.datetime.strptime"}]} {"task_id":20683167,"prompt":"def f_20683167(thelist):\n\treturn ","suffix":"","canonical_solution":"[index for index, item in enumerate(thelist) if item[0] == '332']","test_start":"\ndef check(candidate):","test":["\n assert candidate([[0,1,2], ['a','bb','ccc'], ['332',33,2], [33,22,332]]) == [2]\n","\n assert candidate([[0,1,2], ['332'], ['332'], ['332']]) == [1,2,3]\n","\n assert candidate([[0,1,2], [332], [332], [332]]) == []\n"],"entry_point":"f_20683167","intent":"find the index of a list with the first element equal to '332' within the list of lists `thelist`","library":[],"docs":[]} {"task_id":30693804,"prompt":"def f_30693804(text):\n\treturn ","suffix":"","canonical_solution":"re.sub('[^\\\\sa-zA-Z0-9]', '', text).lower().strip()","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'\n","\n assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'\n","\n assert candidate(' ') == ''\n"],"entry_point":"f_30693804","intent":"lower a string `text` and remove non-alphanumeric characters aside from space","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":30693804,"prompt":"def f_30693804(text):\n\treturn ","suffix":"","canonical_solution":"re.sub('(?!\\\\s)[\\\\W_]', '', text).lower().strip()","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate('ABjfK329r0&&*#5t') == 'abjfk329r05t'\n","\n assert candidate('jseguwphegoi339yup h') == 'jseguwphegoi339yup h'\n","\n assert candidate(' ') == ''\n"],"entry_point":"f_30693804","intent":"remove all non-alphanumeric characters except space from a string `text` and lower it","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":17138464,"prompt":"def f_17138464(x, y):\n\treturn ","suffix":"","canonical_solution":"plt.plot(x, y, label='H\\u2082O')","test_start":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef check(candidate):","test":["\n pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]\n assert pic.get_label() == 'H\u2082O'\n x, y = pic.get_data()\n assert all(x == np.array([1,2,3]))\n assert all(y == np.array([4,5,6]))\n","\n pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]\n assert pic.get_label() == 'H\u2082O'\n x, y = pic.get_data()\n assert all(x == np.array([6, 7, 899]))\n assert all(y == np.array([0, 1, 245]))\n"],"entry_point":"f_17138464","intent":"subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.","library":["matplotlib","numpy"],"docs":[{"function":"plt.plot","text":"matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]\n \nPlot y versus x as lines and\/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)\nplot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\n The coordinates of the points or line nodes are given by x, y. The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below. >>> plot(x, y) # plot x and y using default line style and color","title":"matplotlib._as_gen.matplotlib.pyplot.plot"}]} {"task_id":17138464,"prompt":"def f_17138464(x, y):\n\treturn ","suffix":"","canonical_solution":"plt.plot(x, y, label='$H_2O$')","test_start":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef check(candidate):","test":["\n pic = candidate(np.array([1,2,3]),np.array([4,5,6]))[0]\n assert pic.get_label() == '$H_2O$'\n x, y = pic.get_data()\n assert all(x == np.array([1,2,3]))\n assert all(y == np.array([4,5,6]))\n","\n pic = candidate(np.array([6, 7, 899]),np.array([0, 1, 245]))[0]\n assert pic.get_label() == '$H_2O$'\n x, y = pic.get_data()\n assert all(x == np.array([6, 7, 899]))\n assert all(y == np.array([0, 1, 245]))\n"],"entry_point":"f_17138464","intent":"subscript text 'H20' with '2' as subscripted in matplotlib labels for arrays 'x' and 'y'.","library":["matplotlib","numpy"],"docs":[{"function":"plt.plot","text":"matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]\n \nPlot y versus x as lines and\/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)\nplot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\n The coordinates of the points or line nodes are given by x, y. The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below. >>> plot(x, y) # plot x and y using default line style and color","title":"matplotlib._as_gen.matplotlib.pyplot.plot"}]} {"task_id":9138112,"prompt":"def f_9138112(mylist):\n\treturn ","suffix":"","canonical_solution":"[x for x in mylist if len(x) == 3]","test_start":"\ndef check(candidate):","test":["\n assert candidate([[1,2,3], 'abc', [345,53], 'avsvasf']) == [[1,2,3], 'abc']\n","\n assert candidate([[435,654.4,45,2],[34,34,757,65,32423]]) == []\n"],"entry_point":"f_9138112","intent":"loop over a list `mylist` if sublists length equals 3","library":[],"docs":[]} {"task_id":1807026,"prompt":"def f_1807026():\n\t","suffix":"\n\treturn lst","canonical_solution":"lst = [Object() for _ in range(100)]","test_start":"\nclass Object(): \n def __init__(self): \n self.name = \"object\"\n\ndef check(candidate):","test":["\n lst = candidate()\n assert all([x.name == \"object\" for x in lst])\n"],"entry_point":"f_1807026","intent":"initialize a list `lst` of 100 objects Object()","library":[],"docs":[]} {"task_id":13793321,"prompt":"def f_13793321(df1, df2):\n\treturn ","suffix":"","canonical_solution":"df1.merge(df2, on='Date_Time')","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df1 = pd.DataFrame([[1, 2, 3]], columns=[\"Date\", \"Time\", \"Date_Time\"])\n df2 = pd.DataFrame([[1, 3],[4, 9]], columns=[\"Name\", \"Date_Time\"])\n assert candidate(df1, df2).to_dict() == {'Date': {0: 1}, 'Time': {0: 2}, 'Date_Time': {0: 3}, 'Name': {0: 1}}\n"],"entry_point":"f_13793321","intent":"joining data from dataframe `df1` with data from dataframe `df2` based on matching values of column 'Date_Time' in both dataframes","library":["pandas"],"docs":[{"function":"df1.merge","text":"pandas.DataFrame.merge DataFrame.merge(right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True, indicator=False, validate=None)[source]\n \nMerge DataFrame or named Series objects with a database-style join. A named Series object is treated as a DataFrame with a single named column. The join is done on columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes on a column or columns, the index will be passed on. When performing a cross merge, no column specifications to merge on are allowed. Warning If both key columns contain rows where the key is a null value, those rows will be matched against each other. This is different from usual SQL join behaviour and can lead to unexpected results. Parameters ","title":"pandas.reference.api.pandas.dataframe.merge"}]} {"task_id":3367288,"prompt":"def f_3367288(str1):\n\treturn ","suffix":"","canonical_solution":"'first string is: %s, second one is: %s' % (str1, 'geo.tif')","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"s001\") == \"first string is: s001, second one is: geo.tif\"\n","\n assert candidate(\"\") == \"first string is: , second one is: geo.tif\"\n","\n assert candidate(\" \") == \"first string is: , second one is: geo.tif\"\n"],"entry_point":"f_3367288","intent":"use `%s` operator to print variable values `str1` inside a string","library":[],"docs":[]} {"task_id":3475251,"prompt":"def f_3475251():\n\treturn ","suffix":"","canonical_solution":"[x.strip() for x in '2.MATCHES $$TEXT$$ STRING'.split('$$TEXT$$')]","test_start":"\ndef check(candidate):","test":["\n assert candidate() == ['2.MATCHES', 'STRING']\n"],"entry_point":"f_3475251","intent":"Split a string '2.MATCHES $$TEXT$$ STRING' by a delimiter '$$TEXT$$'","library":[],"docs":[]} {"task_id":273192,"prompt":"def f_273192(directory):\n\t","suffix":"\n\treturn ","canonical_solution":"if (not os.path.exists(directory)):\n\t os.makedirs(directory)","test_start":"\nimport os \n\ndef check(candidate):","test":["\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n","\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"],"entry_point":"f_273192","intent":"check if directory `directory ` exists and create it if necessary","library":["os"],"docs":[{"function":"os.exists","text":"os.path.exists(path) \nReturn True if path refers to an existing path or an open file descriptor. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists. Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise. Changed in version 3.6: Accepts a path-like object.","title":"python.library.os.path#os.path.exists"},{"function":"os.makedirs","text":"os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. \u201c..\u201d on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.","title":"python.library.os#os.makedirs"}]} {"task_id":273192,"prompt":"def f_273192(path):\n\t","suffix":"\n\treturn ","canonical_solution":"try:\n\t os.makedirs(path)\n\texcept OSError:\n\t if (not os.path.isdir(path)):\n\t raise","test_start":"\nimport os \n\ndef check(candidate):","test":["\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n","\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"],"entry_point":"f_273192","intent":"check if a directory `path` exists and create it if necessary","library":["os"],"docs":[{"function":"os.isdir","text":"os.path.isdir(path) \nReturn True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path. Changed in version 3.6: Accepts a path-like object.","title":"python.library.os.path#os.path.isdir"},{"function":"os.makedirs","text":"os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. \u201c..\u201d on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.","title":"python.library.os#os.makedirs"}]} {"task_id":273192,"prompt":"def f_273192(path):\n\t","suffix":"\n\treturn ","canonical_solution":"try:\n\t os.makedirs(path)\n\texcept OSError as exception:\n\t if (exception.errno != errno.EEXIST):\n\t raise","test_start":"\nimport os \n\ndef check(candidate):","test":["\n candidate(\"hello\")\n assert os.path.exists(\"hello\")\n","\n candidate(\"_some_dir\")\n assert os.path.exists(\"_some_dir\")\n"],"entry_point":"f_273192","intent":"check if a directory `path` exists and create it if necessary","library":["os"],"docs":[{"function":"os.makedirs","text":"os.makedirs(name, mode=0o777, exist_ok=False) \nRecursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory. The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed. If exist_ok is False (the default), an FileExistsError is raised if the target directory already exists. Note makedirs() will become confused if the path elements to create include pardir (eg. \u201c..\u201d on UNIX systems). This function handles UNC paths correctly. Raises an auditing event os.mkdir with arguments path, mode, dir_fd. New in version 3.2: The exist_ok parameter. Changed in version 3.4.1: Before Python 3.4.1, if exist_ok was True and the directory existed, makedirs() would still raise an error if mode did not match the mode of the existing directory. Since this behavior was impossible to implement safely, it was removed in Python 3.4.1. See bpo-21082. Changed in version 3.6: Accepts a path-like object. Changed in version 3.7: The mode argument no longer affects the file permission bits of newly-created intermediate-level directories.","title":"python.library.os#os.makedirs"}]} {"task_id":18785032,"prompt":"def f_18785032(text):\n\treturn ","suffix":"","canonical_solution":"re.sub('\\\\bH3\\\\b', 'H1', text)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"hello world and H3\") == \"hello world and H1\"\n","\n assert candidate(\"hello world and H1\") == \"hello world and H1\"\n","\n assert candidate(\"hello world!\") == \"hello world!\"\n"],"entry_point":"f_18785032","intent":"Replace a separate word 'H3' by 'H1' in a string 'text'","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":1450897,"prompt":"def f_1450897():\n\treturn ","suffix":"","canonical_solution":"re.sub('\\\\D', '', 'aas30dsa20')","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate() == \"3020\"\n"],"entry_point":"f_1450897","intent":"substitute ASCII letters in string 'aas30dsa20' with empty string ''","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":1450897,"prompt":"def f_1450897():\n\treturn ","suffix":"","canonical_solution":"\"\"\"\"\"\".join([x for x in 'aas30dsa20' if x.isdigit()])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == \"3020\"\n"],"entry_point":"f_1450897","intent":"get digits only from a string `aas30dsa20` using lambda function","library":[],"docs":[]} {"task_id":14435268,"prompt":"def f_14435268(soup):\n\treturn ","suffix":"","canonical_solution":"soup.find('name').string","test_start":"\nfrom bs4 import BeautifulSoup\n\ndef check(candidate):","test":["\n content = \"LastName<\/name>FirstName<\/lastName>+90 333 12345<\/phone><\/contact>\"\n soup = BeautifulSoup(content)\n assert candidate(soup) == \"LastName\"\n","\n content = \"hello world!<\/name>\"\n soup = BeautifulSoup(content)\n assert candidate(soup) == \"hello world!\"\n"],"entry_point":"f_14435268","intent":"access a tag called \"name\" in beautifulsoup `soup`","library":["bs4"],"docs":[]} {"task_id":20180210,"prompt":"def f_20180210(A, B):\n\treturn ","suffix":"","canonical_solution":"np.concatenate((A, B))","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n A = np.array([1,2])\n B = np.array([3,4])\n assert np.allclose(candidate(A, B), np.array([1,2,3,4]))\n","\n A = np.array([[1,2]])\n B = np.array([[3,4]])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n","\n A = np.array([[1],[2]])\n B = np.array([[3],[4]])\n assert np.allclose(candidate(A, B), np.array([[1],[2],[3],[4]]))\n","\n a = np.array([[1, 3, 4], [4, 5, 6], [6, 0, -1]])\n b = np.array([[5, 6, 1], [0, 2, -1], [9, 4, 1]])\n expected = np.array([[ 1, 3, 4], [ 4, 5, 6],\n [ 6, 0, -1], [ 5, 6, 1], [ 0, 2, -1], [ 9, 4, 1]])\n assert np.array_equal(candidate(a, b), expected)\n"],"entry_point":"f_20180210","intent":"Create new matrix object by concatenating data from matrix A and matrix B","library":["numpy"],"docs":[{"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"}]} {"task_id":20180210,"prompt":"def f_20180210(A, B):\n\treturn ","suffix":"","canonical_solution":"np.vstack((A, B))","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n A = np.array([1,2])\n B = np.array([3,4])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n","\n A = np.array([[1,2]])\n B = np.array([[3,4]])\n assert np.allclose(candidate(A, B), np.array([[1,2],[3,4]]))\n","\n A = np.array([[1],[2]])\n B = np.array([[3],[4]])\n assert np.allclose(candidate(A, B), np.array([[1],[2],[3],[4]]))\n","\n a = np.array([[1, 3, 4], [4, 5, 6], [6, 0, -1]])\n b = np.array([[5, 6, 1], [0, 2, -1], [9, 4, 1]])\n expected = np.array([[ 1, 3, 4], [ 4, 5, 6],\n [ 6, 0, -1], [ 5, 6, 1], [ 0, 2, -1], [ 9, 4, 1]])\n assert np.array_equal(candidate(a, b), expected)\n"],"entry_point":"f_20180210","intent":"concat two matrices `A` and `B` in numpy","library":["numpy"],"docs":[{"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 sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r\/g\/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters ","title":"numpy.reference.generated.numpy.vstack"}]} {"task_id":2011048,"prompt":"def f_2011048(filepath):\n\treturn ","suffix":"","canonical_solution":"os.stat(filepath).st_size","test_start":"\nimport os\n\ndef check(candidate):","test":["\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"hello world!\")\n assert candidate(\"tmp.txt\") == 12\n","\n with open(\"tmp.txt\", 'w') as fw: fw.write(\"\")\n assert candidate(\"tmp.txt\") == 0\n","\n with open(\"tmp.txt\", 'w') as fw: fw.write('\\n')\n assert candidate(\"tmp.txt\") == 1\n","\n filename = 'o.txt'\n with open (filename, 'w') as f:\n f.write('a')\n assert candidate(filename) == 1\n"],"entry_point":"f_2011048","intent":"Get the characters count in a file `filepath`","library":["os"],"docs":[{"function":"os.stat","text":"os.stat(path, *, dir_fd=None, follow_symlinks=True) \nGet the status of a file or a file descriptor. Perform the equivalent of a stat() system call on the given path. path may be specified as either a string or bytes \u2013 directly or indirectly through the PathLike interface \u2013 or as an open file descriptor. Return a stat_result object. This function normally follows symlinks; to stat a symlink add the argument follow_symlinks=False, or use lstat(). This function can support specifying a file descriptor and not following symlinks. On Windows, passing follow_symlinks=False will disable following all name-surrogate reparse points, which includes symlinks and directory junctions. Other types of reparse points that do not resemble links or that the operating system is unable to follow will be opened directly. When following a chain of multiple links, this may result in the original link being returned instead of the non-link that prevented full traversal. To obtain stat results for the final path in this case, use the os.path.realpath() function to resolve the path name as far as possible and call lstat() on the result. This does not apply to dangling symlinks or junction points, which will raise the usual exceptions. Example: >>> import os","title":"python.library.os#os.stat"}]} {"task_id":2600191,"prompt":"def f_2600191(l):\n\treturn ","suffix":"","canonical_solution":"l.count('a')","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"123456asf\") == 1\n","\n assert candidate(\"123456gyjnccfgsf\") == 0\n","\n assert candidate(\"aA\"*10) == 10\n"],"entry_point":"f_2600191","intent":"count the occurrences of item \"a\" in list `l`","library":[],"docs":[]} {"task_id":2600191,"prompt":"def f_2600191(l):\n\treturn ","suffix":"","canonical_solution":"Counter(l)","test_start":"\nfrom collections import Counter \n\ndef check(candidate):","test":["\n assert dict(candidate(\"123456asf\")) == {'1': 1, '2': 1, '3': 1, '4': 1, '5': 1, '6': 1, 'a': 1, 's': 1, 'f': 1}\n","\n assert candidate(\"123456gyjnccfgsf\") == {'1': 1,'2': 1,'3': 1,'4': 1,'5': 1,'6': 1,'g': 2,'y': 1,'j': 1,'n': 1,'c': 2,'f': 2,'s': 1}\n","\n assert candidate(\"aA\"*10) == {'a': 10, 'A': 10}\n","\n y = candidate([1, 6])\n assert y[1] == 1\n assert y[6] == 1\n"],"entry_point":"f_2600191","intent":"count the occurrences of items in list `l`","library":["collections"],"docs":[{"function":"Counter","text":"class collections.Counter([iterable-or-mapping]) \nA Counter is a dict subclass for counting hashable objects. It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages. Elements are counted from an iterable or initialized from another mapping (or counter): >>> c = Counter() # a new, empty counter","title":"python.library.collections#collections.Counter"}]} {"task_id":2600191,"prompt":"def f_2600191(l):\n\treturn ","suffix":"","canonical_solution":"[[x, l.count(x)] for x in set(l)]","test_start":"\nfrom collections import Counter \n\ndef check(candidate):","test":["\n assert sorted(candidate(\"123456asf\")) == [['1', 1],['2', 1],['3', 1],['4', 1],['5', 1],['6', 1],['a', 1],['f', 1],['s', 1]]\n","\n assert sorted(candidate(\"aA\"*10)) == [['A', 10], ['a', 10]]\n"],"entry_point":"f_2600191","intent":"count the occurrences of items in list `l`","library":["collections"],"docs":[{"function":"l.count","text":"count(x) \nCount the number of deque elements equal to x. New in version 3.2.","title":"python.library.collections#collections.deque.count"}]} {"task_id":2600191,"prompt":"def f_2600191(l):\n\treturn ","suffix":"","canonical_solution":"dict(((x, l.count(x)) for x in set(l)))","test_start":"\nfrom collections import Counter \n\ndef check(candidate):","test":["\n assert candidate(\"123456asf\") == {'4': 1, 'a': 1, '1': 1, 's': 1, '6': 1, 'f': 1, '3': 1, '5': 1, '2': 1}\n","\n assert candidate(\"aA\"*10) == {'A': 10, 'a': 10}\n","\n assert candidate([1, 6]) == {1: 1, 6: 1}\n"],"entry_point":"f_2600191","intent":"count the occurrences of items in list `l`","library":["collections"],"docs":[]} {"task_id":2600191,"prompt":"def f_2600191(l):\n\treturn ","suffix":"","canonical_solution":"l.count('b')","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"123456abbbsf\") == 3\n","\n assert candidate(\"123456gyjnccfgsf\") == 0\n","\n assert candidate(\"Ab\"*10) == 10\n"],"entry_point":"f_2600191","intent":"count the occurrences of item \"b\" in list `l`","library":[],"docs":[]} {"task_id":12842997,"prompt":"def f_12842997(srcfile, dstdir):\n\t","suffix":"\n\treturn ","canonical_solution":"shutil.copy(srcfile, dstdir)","test_start":"\nimport shutil\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n shutil.copy = Mock()\n try:\n candidate('opera.txt', '\/')\n except:\n return False \n"],"entry_point":"f_12842997","intent":"copy file `srcfile` to directory `dstdir`","library":["shutil"],"docs":[{"function":"shutil.copy","text":"shutil.copy(src, dst, *, follow_symlinks=True) \nCopies the file src to the file or directory dst. src and dst should be path-like objects or strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file. If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to. copy() copies the file data and the file\u2019s permission mode (see os.chmod()). Other metadata, like the file\u2019s creation and modification times, is not preserved. To preserve all file metadata from the original, use copy2() instead. Raises an auditing event shutil.copyfile with arguments src, dst. Raises an auditing event shutil.copymode with arguments src, dst. Changed in version 3.3: Added follow_symlinks argument. Now returns path to the newly created file. Changed in version 3.8: Platform-specific fast-copy syscalls may be used internally in order to copy the file more efficiently. See Platform-dependent efficient copy operations section.","title":"python.library.shutil#shutil.copy"}]} {"task_id":1555968,"prompt":"def f_1555968(x):\n\treturn ","suffix":"","canonical_solution":"max(k for k, v in x.items() if v != 0)","test_start":"\ndef check(candidate):","test":["\n assert candidate({'a': 1, 'b': 2, 'c': 2000}) == 'c'\n","\n assert candidate({'a': 0., 'b': 0, 'c': 200.02}) == 'c'\n","\n assert candidate({'key1': -100, 'key2': 0.}) == 'key1'\n","\n x = {1:\"g\", 2:\"a\", 5:\"er\", -4:\"dr\"}\n assert candidate(x) == 5\n"],"entry_point":"f_1555968","intent":"find the key associated with the largest value in dictionary `x` whilst key is non-zero value","library":[],"docs":[]} {"task_id":17021863,"prompt":"def f_17021863(file):\n\t","suffix":"\n\treturn ","canonical_solution":"file.seek(0)","test_start":"\ndef check(candidate):","test":["\n with open ('a.txt', 'w') as f:\n f.write('kangaroo\\nkoala\\noxford\\n')\n f = open('a.txt', 'r')\n f.read()\n candidate(f)\n assert f.readline() == 'kangaroo\\n'\n"],"entry_point":"f_17021863","intent":"Put the curser at beginning of the file","library":[],"docs":[]} {"task_id":38152389,"prompt":"def f_38152389(df):\n\t","suffix":"\n\treturn df","canonical_solution":"df['c'] = np.where(df['a'].isnull, df['b'], df['a'])","test_start":"\nimport numpy as np \nimport pandas as pd \n\ndef check(candidate):","test":["\n df = pd.DataFrame({'a': [1,2,3], 'b': [0,0,0]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [1,2,3], 'b': [0,0,0], 'c': [0,0,0]}))\n","\n df = pd.DataFrame({'a': [0,2,3], 'b': [4,5,6]})\n assert np.allclose(candidate(df), pd.DataFrame({'a': [0,2,3], 'b': [4,5,6], 'c': [4,5,6]}))\n"],"entry_point":"f_38152389","intent":"combine values from column 'b' and column 'a' of dataframe `df` into column 'c' of datafram `df`","library":["numpy","pandas"],"docs":[{"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 behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters ","title":"numpy.reference.generated.numpy.where"},{"function":"pandas.dataframe.isnull","text":"pandas.DataFrame.isnull DataFrame.isnull()[source]\n \nDataFrame.isnull is an alias for DataFrame.isna. Detect missing values. Return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings '' or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Returns ","title":"pandas.reference.api.pandas.dataframe.isnull"}]} {"task_id":4175686,"prompt":"def f_4175686(d):\n\t","suffix":"\n\treturn d","canonical_solution":"del d['ele']","test_start":"\ndef check(candidate):","test":["\n assert candidate({\"ale\":1, \"ele\": 2}) == {\"ale\": 1}\n"],"entry_point":"f_4175686","intent":"remove key 'ele' from dictionary `d`","library":[],"docs":[]} {"task_id":11574195,"prompt":"def f_11574195():\n\treturn ","suffix":"","canonical_solution":"['it'] + ['was'] + ['annoying']","test_start":"\ndef check(candidate):","test":["\n assert candidate() == ['it', 'was', 'annoying']\n"],"entry_point":"f_11574195","intent":"merge list `['it']` and list `['was']` and list `['annoying']` into one list","library":[],"docs":[]} {"task_id":587647,"prompt":"def f_587647(x):\n\treturn ","suffix":"","canonical_solution":"str(int(x) + 1).zfill(len(x))","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"001\") == \"002\"\n","\n assert candidate(\"100\") == \"101\"\n"],"entry_point":"f_587647","intent":"increment a value with leading zeroes in a number `x`","library":[],"docs":[]} {"task_id":17315881,"prompt":"def f_17315881(df):\n\treturn ","suffix":"","canonical_solution":"all(df.index[:-1] <= df.index[1:])","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\n df1 = pd.DataFrame({'a': [1,2], 'bb': [0,2]})\n assert candidate(df1) == True\n","\n df2 = pd.DataFrame({'a': [1,2,3,4,5], 'bb': [0,3,5,7,9]})\n shuffled = df2.sample(frac=3, replace=True)\n assert candidate(shuffled) == False\n","\n df = pd.DataFrame([[1, 2], [5, 4]], columns=['a', 'b'])\n assert candidate(df)\n"],"entry_point":"f_17315881","intent":"check if a pandas dataframe `df`'s index is sorted","library":["pandas"],"docs":[{"function":"pandas.dataframe.index","text":"pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.","title":"pandas.reference.api.pandas.dataframe.index"}]} {"task_id":16296643,"prompt":"def f_16296643(t):\n\treturn ","suffix":"","canonical_solution":"list(t)","test_start":"\ndef check(candidate):","test":["\n assert candidate((0, 1, 2)) == [0,1,2]\n","\n assert candidate(('a', [], 100)) == ['a', [], 100]\n"],"entry_point":"f_16296643","intent":"Convert tuple `t` to list","library":[],"docs":[]} {"task_id":16296643,"prompt":"def f_16296643(t):\n\treturn ","suffix":"","canonical_solution":"tuple(t)","test_start":"\ndef check(candidate):","test":["\n assert candidate([0,1,2]) == (0, 1, 2)\n","\n assert candidate(['a', [], 100]) == ('a', [], 100)\n"],"entry_point":"f_16296643","intent":"Convert list `t` to tuple","library":[],"docs":[]} {"task_id":16296643,"prompt":"def f_16296643(level1):\n\t","suffix":"\n\treturn level1","canonical_solution":"level1 = map(list, level1)","test_start":"\ndef check(candidate):","test":["\n t = ((1, 2), (3, 4))\n t = candidate(t)\n assert list(t) == [[1, 2], [3, 4]]\n"],"entry_point":"f_16296643","intent":"Convert tuple `level1` to list","library":[],"docs":[]} {"task_id":3880399,"prompt":"def f_3880399(dataobject, logFile):\n\treturn ","suffix":"","canonical_solution":"pprint.pprint(dataobject, logFile)","test_start":"\nimport pprint \n\ndef check(candidate):","test":["\n f = open('kkk.txt', 'w')\n candidate('hello', f)\n f.close()\n with open('kkk.txt', 'r') as f:\n assert 'hello' in f.readline()\n"],"entry_point":"f_3880399","intent":"send the output of pprint object `dataobject` to file `logFile`","library":["pprint"],"docs":[{"function":"pprint.pprint","text":"pprint.pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True) \nPrints the formatted representation of object on stream, followed by a newline. If stream is None, sys.stdout is used. This may be used in the interactive interpreter instead of the print() function for inspecting values (you can even reassign print = pprint.pprint for use within a scope). indent, width, depth, compact and sort_dicts will be passed to the PrettyPrinter constructor as formatting parameters. Changed in version 3.4: Added the compact parameter. Changed in version 3.8: Added the sort_dicts parameter. >>> import pprint","title":"python.library.pprint#pprint.pprint"}]} {"task_id":21800169,"prompt":"def f_21800169(df):\n\treturn ","suffix":"","canonical_solution":"df.loc[df['BoolCol']]","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n"],"entry_point":"f_21800169","intent":"get index of rows in column 'BoolCol'","library":["pandas"],"docs":[{"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 interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. ","title":"pandas.reference.api.pandas.dataframe.loc"}]} {"task_id":21800169,"prompt":"def f_21800169(df):\n\treturn ","suffix":"","canonical_solution":"df.iloc[np.flatnonzero(df['BoolCol'])]","test_start":"\nimport numpy as np\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y['a'][0] == 2\n assert y['b'][0] == 3\n"],"entry_point":"f_21800169","intent":"Create a list containing the indexes of rows where the value of column 'BoolCol' in dataframe `df` are equal to True","library":["numpy","pandas"],"docs":[{"function":"numpy.flatnonzero","text":"numpy.flatnonzero numpy.flatnonzero(a)[source]\n \nReturn indices that are non-zero in the flattened version of a. This is equivalent to np.nonzero(np.ravel(a))[0]. Parameters ","title":"numpy.reference.generated.numpy.flatnonzero"},{"function":"pandas.dataframe.loc","text":"pandas.DataFrame.iloc propertyDataFrame.iloc\n \nPurely integer-location based indexing for selection by position. .iloc[] is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. Allowed inputs are: An integer, e.g. 5. A list or array of integers, e.g. [4, 3, 0]. A slice object with ints, e.g. 1:7. A boolean array. A callable function with one argument (the calling Series or DataFrame) and that returns valid output for indexing (one of the above). This is useful in method chains, when you don\u2019t have a reference to the calling object, but would like to base your selection on some value. .iloc will raise IndexError if a requested indexer is out-of-bounds, except slice indexers which allow out-of-bounds indexing (this conforms with python\/numpy slice semantics). See more at Selection by Position. See also DataFrame.iat\n\nFast integer location scalar accessor. DataFrame.loc\n\nPurely label-location based indexer for selection by label. Series.iloc\n\nPurely integer-location based indexing for selection by position. Examples ","title":"pandas.reference.api.pandas.dataframe.iloc"}]} {"task_id":21800169,"prompt":"def f_21800169(df):\n\treturn ","suffix":"","canonical_solution":"df[df['BoolCol'] == True].index.tolist()","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n"],"entry_point":"f_21800169","intent":"from dataframe `df` get list of indexes of rows where column 'BoolCol' values match True","library":["pandas"],"docs":[{"function":"pandas.dataframe.index","text":"pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.","title":"pandas.reference.api.pandas.dataframe.index"},{"function":"pandas.index.tolist()","text":"pandas.Index.tolist Index.tolist()[source]\n \nReturn a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp\/Timedelta\/Interval\/Period) Returns \n list\n See also numpy.ndarray.tolist\n\nReturn the array as an a.ndim-levels deep nested list of Python scalars.","title":"pandas.reference.api.pandas.index.tolist"}]} {"task_id":21800169,"prompt":"def f_21800169(df):\n\treturn ","suffix":"","canonical_solution":"df[df['BoolCol']].index.tolist()","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[True, 2, 3], [False, 5, 6]], columns = ['BoolCol', 'a', 'b'])\n y = candidate(df)\n assert y == [0]\n"],"entry_point":"f_21800169","intent":"get index of rows in dataframe `df` which column 'BoolCol' matches value True","library":["pandas"],"docs":[{"function":"pandas.index.tolist","text":"pandas.Index.tolist Index.tolist()[source]\n \nReturn a list of the values. These are each a scalar type, which is a Python scalar (for str, int, float) or a pandas scalar (for Timestamp\/Timedelta\/Interval\/Period) Returns \n list\n See also numpy.ndarray.tolist\n\nReturn the array as an a.ndim-levels deep nested list of Python scalars.","title":"pandas.reference.api.pandas.index.tolist"},{"function":"pandas.dataframe.index","text":"pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.","title":"pandas.reference.api.pandas.dataframe.index"}]} {"task_id":299446,"prompt":"def f_299446(owd):\n\t","suffix":"\n\treturn ","canonical_solution":"os.chdir(owd)","test_start":"\nimport os\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n os.chdir = Mock()\n try:\n candidate('\/')\n except:\n assert False\n"],"entry_point":"f_299446","intent":"change working directory to the directory `owd`","library":["os"],"docs":[{"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, PermissionError, and NotADirectoryError. Raises an auditing event os.chdir with argument path. New in version 3.3: Added support for specifying path as a file descriptor on some platforms. Changed in version 3.6: Accepts a path-like object.","title":"python.library.os#os.chdir"}]} {"task_id":14695134,"prompt":"def f_14695134(c, testfield):\n\t","suffix":"\n\treturn ","canonical_solution":"c.execute(\"INSERT INTO test VALUES (?, 'bar')\", (testfield,))","test_start":"\nimport sqlite3\n\ndef check(candidate):","test":["\n conn = sqlite3.connect('dev.db')\n cur = conn.cursor()\n cur.execute(\"CREATE TABLE test (x VARCHAR(10), y VARCHAR(10))\")\n candidate(cur, 'kang')\n cur.execute(\"SELECT * FROM test\")\n rows = cur.fetchall()\n assert len(rows) == 1\n"],"entry_point":"f_14695134","intent":"insert data from a string `testfield` to sqlite db `c`","library":["sqlite3"],"docs":[{"function":"c.execute","text":"execute(sql[, parameters]) \nExecutes an SQL statement. Values may be bound to the statement using placeholders. execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.","title":"python.library.sqlite3#sqlite3.Cursor.execute"}]} {"task_id":24242433,"prompt":"def f_24242433():\n\treturn ","suffix":"","canonical_solution":"b'\\\\x89\\\\n'.decode('unicode_escape')","test_start":"\nimport sqlite3\n\ndef check(candidate):","test":["\n assert candidate() == '\\x89\\n'\n"],"entry_point":"f_24242433","intent":"decode string \"\\\\x89\\\\n\" into a normal string","library":["sqlite3"],"docs":[]} {"task_id":24242433,"prompt":"def f_24242433(raw_string):\n\treturn ","suffix":"","canonical_solution":"raw_string.decode('unicode_escape')","test_start":"\ndef check(candidate):","test":["\n assert candidate(b\"Hello\") == \"Hello\"\n","\n assert candidate(b\"hello world!\") == \"hello world!\"\n","\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n"],"entry_point":"f_24242433","intent":"convert a raw string `raw_string` into a normal string","library":[],"docs":[]} {"task_id":24242433,"prompt":"def f_24242433(raw_byte_string):\n\treturn ","suffix":"","canonical_solution":"raw_byte_string.decode('unicode_escape')","test_start":"\ndef check(candidate):","test":["\n assert candidate(b\"Hello\") == \"Hello\"\n","\n assert candidate(b\"hello world!\") == \"hello world!\"\n","\n assert candidate(b\". ?? !!x\") == \". ?? !!x\"\n"],"entry_point":"f_24242433","intent":"convert a raw string `raw_byte_string` into a normal string","library":[],"docs":[]} {"task_id":22882922,"prompt":"def f_22882922(s):\n\treturn ","suffix":"","canonical_solution":"[m.group(0) for m in re.finditer('(\\\\d)\\\\1*', s)]","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate('111234') == ['111', '2', '3', '4']\n"],"entry_point":"f_22882922","intent":"split a string `s` with into all strings of repeated characters","library":["re"],"docs":[{"function":"re.finditer","text":"re.finditer(pattern, string, flags=0) \nReturn an iterator yielding match objects over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.finditer"}]} {"task_id":4143502,"prompt":"def f_4143502():\n\treturn ","suffix":"","canonical_solution":"plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')","test_start":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef check(candidate):","test":["\n assert 'matplotlib' in str(type(candidate()))\n"],"entry_point":"f_4143502","intent":"scatter a plot with x, y position of `np.random.randn(100)` and face color equal to none","library":["matplotlib","numpy"],"docs":[{"function":"plt.scatter","text":"matplotlib.pyplot.scatter matplotlib.pyplot.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, *, edgecolors=None, plotnonfinite=False, data=None, **kwargs)[source]\n \nA scatter plot of y vs. x with varying marker size and\/or color. Parameters ","title":"matplotlib._as_gen.matplotlib.pyplot.scatter"},{"function":"numpy.random.randn","text":"numpy.random.randn random.randn(d0, d1, ..., dn)\n \nReturn a sample (or samples) from the \u201cstandard normal\u201d distribution. Note This is a convenience function for users porting code from Matlab, and wraps standard_normal. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones. Note New code should use the standard_normal method of a default_rng() instance instead; please see the Quick Start. If positive int_like arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate \u201cnormal\u201d (Gaussian) distribution of mean 0 and variance 1. A single float randomly sampled from the distribution is returned if no argument is provided. Parameters ","title":"numpy.reference.random.generated.numpy.random.randn"}]} {"task_id":4143502,"prompt":"def f_4143502():\n\treturn ","suffix":"","canonical_solution":"plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')","test_start":"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef check(candidate):","test":["\n assert 'matplotlib' in str(type(candidate()[0]))\n"],"entry_point":"f_4143502","intent":"do a scatter plot with empty circles","library":["matplotlib","numpy"],"docs":[{"function":"plt.plot","text":"matplotlib.pyplot.plot matplotlib.pyplot.plot(*args, scalex=True, scaley=True, data=None, **kwargs)[source]\n \nPlot y versus x as lines and\/or markers. Call signatures: plot([x], y, [fmt], *, data=None, **kwargs)\nplot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)\n The coordinates of the points or line nodes are given by x, y. The optional parameter fmt is a convenient way for defining basic formatting like color, marker and linestyle. It's a shortcut string notation described in the Notes section below. >>> plot(x, y) # plot x and y using default line style and color","title":"matplotlib._as_gen.matplotlib.pyplot.plot"},{"function":"numpy.random.randn","text":"numpy.random.randn random.randn(d0, d1, ..., dn)\n \nReturn a sample (or samples) from the \u201cstandard normal\u201d distribution. Note This is a convenience function for users porting code from Matlab, and wraps standard_normal. That function takes a tuple to specify the size of the output, which is consistent with other NumPy functions like numpy.zeros and numpy.ones. Note New code should use the standard_normal method of a default_rng() instance instead; please see the Quick Start. If positive int_like arguments are provided, randn generates an array of shape (d0, d1, ..., dn), filled with random floats sampled from a univariate \u201cnormal\u201d (Gaussian) distribution of mean 0 and variance 1. A single float randomly sampled from the distribution is returned if no argument is provided. Parameters ","title":"numpy.reference.random.generated.numpy.random.randn"}]} {"task_id":32063985,"prompt":"def f_32063985(soup):\n\treturn ","suffix":"","canonical_solution":"soup.find('div', id='main-content').decompose()","test_start":"\nfrom bs4 import BeautifulSoup\n\ndef check(candidate):","test":["\n markup = \"This is not div
This is div 1<\/div>
This is div 2<\/div><\/a>\"\n soup = BeautifulSoup(markup,\"html.parser\")\n candidate(soup)\n assert str(soup) == 'This is not div
This is div 1<\/div><\/a>'\n"],"entry_point":"f_32063985","intent":"remove a div from `soup` with a id `main-content` using beautifulsoup","library":["bs4"],"docs":[]} {"task_id":27975069,"prompt":"def f_27975069(df):\n\treturn ","suffix":"","canonical_solution":"df[df['ids'].str.contains('ball')]","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n f = pd.DataFrame([[\"ball1\", 1, 2], [\"hall\", 5, 4]], columns = ['ids', 'x', 'y'])\n f1 = candidate(f)\n assert f1['x'][0] == 1\n assert f1['y'][0] == 2\n"],"entry_point":"f_27975069","intent":"filter rows of datafram `df` containing key word `ball` in column `ids`","library":["pandas"],"docs":[{"function":"pandas.series.str.contains","text":"pandas.Series.str.contains Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]\n \nTest if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ","title":"pandas.reference.api.pandas.series.str.contains"}]} {"task_id":20461165,"prompt":"def f_20461165(df):\n\treturn ","suffix":"","canonical_solution":"df.reset_index(level=0, inplace=True)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index'][0] == 0\n assert df['index'][1] == 1\n"],"entry_point":"f_20461165","intent":"convert index at level 0 into a column in dataframe `df`","library":["pandas"],"docs":[{"function":"df.reset_index","text":"pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ","title":"pandas.reference.api.pandas.dataframe.reset_index"}]} {"task_id":20461165,"prompt":"def f_20461165(df):\n\t","suffix":"\n\treturn ","canonical_solution":"df['index1'] = df.index","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([[384, 593], [781, 123]], columns = ['gi', 'ptt_loc'])\n candidate(df)\n assert df['index1'][0] == 0\n assert df['index1'][1] == 1\n"],"entry_point":"f_20461165","intent":"Add indexes in a data frame `df` to a column `index1`","library":["pandas"],"docs":[{"function":"pandas.dataframe.index","text":"pandas.DataFrame.index DataFrame.index\n \nThe index (row labels) of the DataFrame.","title":"pandas.reference.api.pandas.dataframe.index"}]} {"task_id":20461165,"prompt":"def f_20461165(df):\n\treturn ","suffix":"","canonical_solution":"df.reset_index(level=['tick', 'obs'])","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([['2016-09-13', 'C', 2, 0.0139], ['2016-07-17', 'A', 2, 0.5577]], columns = ['tick', 'tag', 'obs', 'val'])\n df = df.set_index(['tick', 'tag', 'obs'])\n df = candidate(df)\n assert df['tick']['C'] == '2016-09-13'\n"],"entry_point":"f_20461165","intent":"convert pandas index in a dataframe `df` to columns","library":["pandas"],"docs":[{"function":"df.reset_index","text":"pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ","title":"pandas.reference.api.pandas.dataframe.reset_index"}]} {"task_id":4685571,"prompt":"def f_4685571(b):\n\treturn ","suffix":"","canonical_solution":"[x[::-1] for x in b]","test_start":"\ndef check(candidate):","test":["\n b = [('spam',0), ('eggs',1)]\n b1 = candidate(b)\n assert b1 == [(0, 'spam'), (1, 'eggs')]\n"],"entry_point":"f_4685571","intent":"Get reverse of list items from list 'b' using extended slicing","library":[],"docs":[]} {"task_id":17960441,"prompt":"def f_17960441(a, b):\n\treturn ","suffix":"","canonical_solution":"np.array([zip(x, y) for x, y in zip(a, b)])","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n expected = [(9, 7), (8, 1)]\n ctr = 0\n for i in c[0]:\n assert i == expected[ctr]\n ctr += 1\n"],"entry_point":"f_17960441","intent":"join each element in array `a` with element at the same index in array `b` as a tuple","library":["numpy"],"docs":[{"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"}]} {"task_id":17960441,"prompt":"def f_17960441(a, b):\n\treturn ","suffix":"","canonical_solution":"np.array(list(zip(a.ravel(),b.ravel())), dtype=('i4,i4')).reshape(a.shape)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\n a = np.array([[9, 8], [7, 6]])\n b = np.array([[7, 1], [5, 2]])\n c = candidate(a, b)\n e = np.array([[(9, 7), (8, 1)], [(7, 5), (6, 2)]], dtype=[('f0', '= 99) & (df['closing_price'] <= 101)]","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([67, 68, 69, 70, 99, 100, 101, 102], columns = ['closing_price'])\n assert candidate(df).shape[0] == 3\n"],"entry_point":"f_31617845","intent":"select rows in a dataframe `df` column 'closing_price' between two values 99 and 101","library":["pandas"],"docs":[]} {"task_id":25698710,"prompt":"def f_25698710(df):\n\treturn ","suffix":"","canonical_solution":"df.replace({'\\n': '
'}, regex=True)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm
pqr', 'wxy
jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n"],"entry_point":"f_25698710","intent":"replace all occurences of newlines `\\n` with `
` in dataframe `df`","library":["pandas"],"docs":[{"function":"df.replace","text":"pandas.DataFrame.replace DataFrame.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]\n \nReplace values given in to_replace with value. Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. Parameters ","title":"pandas.reference.api.pandas.dataframe.replace"}]} {"task_id":25698710,"prompt":"def f_25698710(df):\n\treturn ","suffix":"","canonical_solution":"df.replace({'\\n': '
'}, regex=True)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame(['klm\\npqr', 'wxy\\njkl'], columns = ['val'])\n expected = pd.DataFrame(['klm
pqr', 'wxy
jkl'], columns = ['val'])\n assert pd.DataFrame.equals(candidate(df), expected)\n"],"entry_point":"f_25698710","intent":"replace all occurrences of a string `\\n` by string `
` in a pandas data frame `df`","library":["pandas"],"docs":[{"function":"df.replace","text":"pandas.DataFrame.replace DataFrame.replace(to_replace=None, value=NoDefault.no_default, inplace=False, limit=None, regex=False, method=NoDefault.no_default)[source]\n \nReplace values given in to_replace with value. Values of the DataFrame are replaced with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. Parameters ","title":"pandas.reference.api.pandas.dataframe.replace"}]} {"task_id":41923858,"prompt":"def f_41923858(word):\n\treturn ","suffix":"","canonical_solution":"[(x + y) for x, y in zip(word, word[1:])]","test_start":"\ndef check(candidate):","test":["\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n","\n assert candidate([\"hello\", \"world\", \"!\"]) == [\"helloworld\", \"world!\"]\n"],"entry_point":"f_41923858","intent":"create a list containing each two adjacent letters in string `word` as its elements","library":[],"docs":[]} {"task_id":41923858,"prompt":"def f_41923858(word):\n\treturn ","suffix":"","canonical_solution":"list(map(lambda x, y: x + y, word[:-1], word[1:]))","test_start":"\ndef check(candidate):","test":["\n assert candidate('abcdef') == ['ab', 'bc', 'cd', 'de', 'ef']\n"],"entry_point":"f_41923858","intent":"Get a list of pairs from a string `word` using lambda function","library":[],"docs":[]} {"task_id":9760588,"prompt":"def f_9760588(myString):\n\treturn ","suffix":"","canonical_solution":"re.findall('(https?:\/\/[^\\\\s]+)', myString)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"This is a link http:\/\/www.google.com\") == [\"http:\/\/www.google.com\"]\n","\n assert candidate(\"Please refer to the website: http:\/\/www.google.com\") == [\"http:\/\/www.google.com\"]\n"],"entry_point":"f_9760588","intent":"extract a url from a string `myString`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":9760588,"prompt":"def f_9760588(myString):\n\treturn ","suffix":"","canonical_solution":"re.search('(?Phttps?:\/\/[^\\\\s]+)', myString).group('url')","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"This is a link http:\/\/www.google.com\") == \"http:\/\/www.google.com\"\n","\n assert candidate(\"Please refer to the website: http:\/\/www.google.com\") == \"http:\/\/www.google.com\"\n"],"entry_point":"f_9760588","intent":"extract a url from a string `myString`","library":["re"],"docs":[{"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 different from finding a zero-length match at some point in the string.","title":"python.library.re#re.search"},{"function":"re.Match.group","text":"Match.group([group1, ...]) \nReturns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. >>> m = re.match(r\"(\\w+) (\\w+)\", \"Isaac Newton, physicist\")","title":"python.library.re#re.Match.group"}]} {"task_id":5843518,"prompt":"def f_5843518(mystring):\n\treturn ","suffix":"","canonical_solution":"re.sub('[^A-Za-z0-9]+', '', mystring)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate('Special $#! characters spaces 888323') == 'Specialcharactersspaces888323'\n"],"entry_point":"f_5843518","intent":"remove all special characters, punctuation and spaces from a string `mystring` using regex","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":36674519,"prompt":"def f_36674519():\n\treturn ","suffix":"","canonical_solution":"pd.date_range('2016-01-01', freq='WOM-2FRI', periods=13)","test_start":"\nimport pandas as pd\nimport datetime\n\ndef check(candidate):","test":["\n actual = candidate() \n expected = [[2016, 1, 8], [2016, 2, 12],\n [2016, 3, 11], [2016, 4, 8],\n [2016, 5, 13], [2016, 6, 10],\n [2016, 7, 8], [2016, 8, 12],\n [2016, 9, 9], [2016, 10, 14],\n [2016, 11, 11], [2016, 12, 9],\n [2017, 1, 13]]\n for i in range(0, len(expected)):\n d = datetime.date(expected[i][0], expected[i][1], expected[i][2])\n assert d == actual[i].date()\n"],"entry_point":"f_36674519","intent":"create a DatetimeIndex containing 13 periods of the second friday of each month starting from date '2016-01-01'","library":["datetime","pandas"],"docs":[{"function":"pandas.date_range","text":"pandas.date_range pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=NoDefault.no_default, inclusive=None, **kwargs)[source]\n \nReturn a fixed frequency DatetimeIndex. Returns the range of equally spaced time points (where the difference between any two adjacent points is specified by the given frequency) such that they all satisfy start <[=] x <[=] end, where the first one and the last one are, resp., the first and last time points in that range that fall on the boundary of freq (if given as a frequency string) or that are valid for freq (if given as a pandas.tseries.offsets.DateOffset). (If exactly one of start, end, or freq is not specified, this missing parameter can be computed given periods, the number of timesteps in the range. See the note below.) Parameters ","title":"pandas.reference.api.pandas.date_range"}]} {"task_id":508657,"prompt":"def f_508657():\n\t","suffix":"\n\treturn matrix","canonical_solution":"matrix = [['a', 'b'], ['c', 'd'], ['e', 'f']]","test_start":"\ndef check(candidate):","test":["\n matrix = candidate()\n assert len(matrix) == 3\n assert all([len(row)==2 for row in matrix])\n"],"entry_point":"f_508657","intent":"Create multidimensional array `matrix` with 3 rows and 2 columns in python","library":[],"docs":[]} {"task_id":1007481,"prompt":"def f_1007481(mystring):\n\treturn ","suffix":"","canonical_solution":"mystring.replace(' ', '_')","test_start":"\ndef check(candidate):","test":["\n assert candidate(' ') == '_'\n","\n assert candidate(' _ ') == '___'\n","\n assert candidate('') == ''\n","\n assert candidate('123123') == '123123'\n","\n assert candidate('\\_ ') == '\\__'\n"],"entry_point":"f_1007481","intent":"replace spaces with underscore in string `mystring`","library":[],"docs":[]} {"task_id":1249786,"prompt":"def f_1249786(my_string):\n\treturn ","suffix":"","canonical_solution":"\"\"\" \"\"\".join(my_string.split())","test_start":"\ndef check(candidate):","test":["\n assert candidate('hello world ') == 'hello world'\n","\n assert candidate('') == ''\n","\n assert candidate(' ') == ''\n","\n assert candidate(' hello') == 'hello'\n","\n assert candidate(' h e l l o ') == 'h e l l o'\n"],"entry_point":"f_1249786","intent":"split string `my_string` on white spaces","library":[],"docs":[]} {"task_id":4444923,"prompt":"def f_4444923(filename):\n\treturn ","suffix":"","canonical_solution":"os.path.splitext(filename)[0]","test_start":"\nimport os\n\ndef check(candidate):","test":["\n assert candidate('\/Users\/test\/hello.txt') == '\/Users\/test\/hello'\n","\n assert candidate('hello.txt') == 'hello'\n","\n assert candidate('hello') == 'hello'\n","\n assert candidate('.gitignore') == '.gitignore'\n"],"entry_point":"f_4444923","intent":"get filename without extension from file `filename`","library":["os"],"docs":[{"function":"os.splitext","text":"os.path.splitext(path) \nSplit the pathname path into a pair (root, ext) such that root + ext ==\npath, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', ''). Changed in version 3.6: Accepts a path-like object.","title":"python.library.os.path#os.path.splitext"}]} {"task_id":13728486,"prompt":"def f_13728486(l):\n\treturn ","suffix":"","canonical_solution":"[sum(l[:i]) for i, _ in enumerate(l)]","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3]) == [0,1,3]\n","\n assert candidate([]) == []\n","\n assert candidate([1]) == [0]\n"],"entry_point":"f_13728486","intent":"get a list containing the sum of each element `i` in list `l` plus the previous elements","library":[],"docs":[]} {"task_id":9743134,"prompt":"def f_9743134():\n\treturn ","suffix":"","canonical_solution":"\"\"\"Docs\/src\/Scripts\/temp\"\"\".replace('\/', '\/\\x00\/').split('\\x00')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == ['Docs\/', '\/src\/', '\/Scripts\/', '\/temp']\n","\n assert candidate() != ['Docs', 'src', 'Scripts', 'temp']\n"],"entry_point":"f_9743134","intent":"split a string `Docs\/src\/Scripts\/temp` by `\/` keeping `\/` in the result","library":[],"docs":[]} {"task_id":20546419,"prompt":"def f_20546419(r):\n\treturn ","suffix":"","canonical_solution":"np.random.shuffle(np.transpose(r))","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\n a1 = np.array([[ 1, 20], [ 2, 30]])\n candidate(a1)\n assert np.array_equal(a1, np.array([[ 1, 20],[ 2, 30]])) or np.array_equal(a1, np.array([[ 20, 1], [ 30, 2]]))\n","\n a2 = np.array([[ 1], [ 2]])\n candidate(a2) \n assert np.array_equal(a2,np.array([[ 1], [ 2]]) )\n","\n a3 = np.array([[ 1,2,3]])\n candidate(a3)\n assert np.array_equal(a3,np.array([[ 1,2,3]])) or np.array_equal(a3,np.array([[ 2,1,3]])) or np.array_equal(a3,np.array([[ 1,3,2]])) or np.array_equal(a3,np.array([[3,2,1]])) or np.array_equal(a3,np.array([[3,1,2]])) or np.array_equal(a3,np.array([[2,3,1]])) \n","\n a4 = np.zeros(shape=(5,2))\n candidate(a4)\n assert np.array_equal(a4, np.zeros(shape=(5,2)))\n"],"entry_point":"f_20546419","intent":"shuffle columns of an numpy array 'r'","library":["numpy"],"docs":[{"function":"numpy.shuffle","text":"numpy.random.shuffle random.shuffle(x)\n \nModify a sequence in-place by shuffling its contents. This function only shuffles the array along the first axis of a multi-dimensional array. The order of sub-arrays is changed but their contents remains the same. Note New code should use the shuffle method of a default_rng() instance instead; please see the Quick Start. Parameters ","title":"numpy.reference.random.generated.numpy.random.shuffle"}]} {"task_id":32675861,"prompt":"def f_32675861(df):\n\t","suffix":"\n\treturn df","canonical_solution":"df['D'] = df['B']","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df_1 = pd.DataFrame({'A': [1,2,3], 'B': ['a', 'b', 'c']})\n candidate(df_1)\n assert (df_1['D'] == df_1['B']).all()\n","\n df_2 = pd.DataFrame({'A': [1,2,3], 'B': [1, 'A', 'B']})\n candidate(df_2)\n assert (df_2['D'] == df_2['B']).all()\n","\n df_3 = pd.DataFrame({'B': [1]})\n candidate(df_3)\n assert df_3['D'][0] == 1\n","\n df_4 = pd.DataFrame({'B': []})\n candidate(df_4)\n assert len(df_4['D']) == 0\n"],"entry_point":"f_32675861","intent":"copy all values in a column 'B' to a new column 'D' in a pandas data frame 'df'","library":["pandas"],"docs":[]} {"task_id":14227561,"prompt":"def f_14227561(data):\n\treturn ","suffix":"","canonical_solution":"list(data['A']['B'].values())[0]['maindata'][0]['Info']","test_start":"\nimport json\n\ndef check(candidate):","test":["\n s1 = '{\"A\":{\"B\":{\"unknown\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT\"}]}}}}'\n data = json.loads(s1)\n assert candidate(data) == 'TEXT'\n","\n s2 = '{\"A\":{\"B\":{\"sample1\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"TEXT!\"}]}}}}'\n data = json.loads(s2)\n assert candidate(data) == 'TEXT!'\n","\n s3 = '{\"A\":{\"B\":{\"sample_weird_un\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"!\"}]}}}}'\n data = json.loads(s3)\n assert candidate(data) == '!'\n","\n s4 = '{\"A\":{\"B\":{\"sample_weird_un\":{\"1\":\"F\",\"maindata\":[{\"Info\":\"\"}]}}}}'\n data = json.loads(s4)\n assert candidate(data) == ''\n"],"entry_point":"f_14227561","intent":"find a value within nested json 'data' where the key inside another key 'B' is unknown.","library":["json"],"docs":[]} {"task_id":14858916,"prompt":"def f_14858916(string, predicate):\n\treturn ","suffix":"","canonical_solution":"all(predicate(x) for x in string)","test_start":"\ndef check(candidate):","test":["\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aab', predicate) == False\n","\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('aa', predicate) == True\n","\n def predicate(x):\n if x == 'a':\n return True\n else:\n return False\n assert candidate('', predicate) == True\n","\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('abc', predicate) == True\n","\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('Ab', predicate) == False\n","\n def predicate(x):\n if x.islower():\n return True\n else:\n return False\n assert candidate('ABCD', predicate) == False\n"],"entry_point":"f_14858916","intent":"check characters of string `string` are true predication of function `predicate`","library":[],"docs":[]} {"task_id":574236,"prompt":"def f_574236():\n\treturn ","suffix":"","canonical_solution":"os.statvfs('\/').f_files - os.statvfs('\/').f_ffree","test_start":"\nimport os \n\ndef check(candidate):","test":["\n assert candidate() == (os.statvfs('\/').f_files - os.statvfs('\/').f_ffree)\n"],"entry_point":"f_574236","intent":"determine number of files on a drive with python","library":["os"],"docs":[{"function":"os.statvfs","text":"os.statvfs(path) \nPerform a statvfs() system call on the given path. The return value is an object whose attributes describe the filesystem on the given path, and correspond to the members of the statvfs structure, namely: f_bsize, f_frsize, f_blocks, f_bfree, f_bavail, f_files, f_ffree, f_favail, f_flag, f_namemax, f_fsid. Two module-level constants are defined for the f_flag attribute\u2019s bit-flags: if ST_RDONLY is set, the filesystem is mounted read-only, and if ST_NOSUID is set, the semantics of setuid\/setgid bits are disabled or not supported. Additional module-level constants are defined for GNU\/glibc based systems. These are ST_NODEV (disallow access to device special files), ST_NOEXEC (disallow program execution), ST_SYNCHRONOUS (writes are synced at once), ST_MANDLOCK (allow mandatory locks on an FS), ST_WRITE (write on file\/directory\/symlink), ST_APPEND (append-only file), ST_IMMUTABLE (immutable file), ST_NOATIME (do not update access times), ST_NODIRATIME (do not update directory access times), ST_RELATIME (update atime relative to mtime\/ctime). This function can support specifying a file descriptor. Availability: Unix. Changed in version 3.2: The ST_RDONLY and ST_NOSUID constants were added. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.4: The ST_NODEV, ST_NOEXEC, ST_SYNCHRONOUS, ST_MANDLOCK, ST_WRITE, ST_APPEND, ST_IMMUTABLE, ST_NOATIME, ST_NODIRATIME, and ST_RELATIME constants were added. Changed in version 3.6: Accepts a path-like object. New in version 3.7: Added f_fsid.","title":"python.library.os#os.statvfs"}]} {"task_id":7011291,"prompt":"def f_7011291(cursor):\n\treturn ","suffix":"","canonical_solution":"cursor.fetchone()[0]","test_start":"\nimport sqlite3\n\ndef check(candidate):","test":["\n conn = sqlite3.connect('main')\n cursor = conn.cursor()\n cursor.execute(\"CREATE TABLE student (name VARCHAR(10))\")\n cursor.execute(\"INSERT INTO student VALUES('abc')\")\n cursor.execute(\"SELECT * FROM student\")\n assert candidate(cursor) == 'abc'\n"],"entry_point":"f_7011291","intent":"how to get a single result from a SQLite query from `cursor`","library":["sqlite3"],"docs":[{"function":"cursor.fetchone","text":"fetchone() \nFetches the next row of a query result set, returning a single sequence, or None when no more data is available.","title":"python.library.sqlite3#sqlite3.Cursor.fetchone"}]} {"task_id":6378889,"prompt":"def f_6378889(user_input):\n\t","suffix":"\n\treturn user_list","canonical_solution":"user_list = [int(number) for number in user_input.split(',')]","test_start":"\ndef check(candidate):","test":["\n assert candidate('0') == [0]\n","\n assert candidate('12') == [12]\n","\n assert candidate('12,33,223') == [12, 33, 223]\n"],"entry_point":"f_6378889","intent":"convert string `user_input` into a list of integers `user_list`","library":[],"docs":[]} {"task_id":6378889,"prompt":"def f_6378889(user):\n\treturn ","suffix":"","canonical_solution":"[int(s) for s in user.split(',')]","test_start":"\ndef check(candidate):","test":["\n assert candidate('0') == [0]\n","\n assert candidate('12') == [12]\n","\n assert candidate('12,33,223') == [12, 33, 223]\n"],"entry_point":"f_6378889","intent":"Get a list of integers by splitting a string `user` with comma","library":[],"docs":[]} {"task_id":5212870,"prompt":"def f_5212870(list):\n\treturn ","suffix":"","canonical_solution":"sorted(list, key=lambda x: (x[0], -x[1]))","test_start":"\ndef check(candidate):","test":["\n list = [(9, 0), (9, 1), (9, -1), (8, 5), (4, 5)]\n assert candidate(list) == [(4, 5), (8, 5), (9, 1), (9, 0), (9, -1)]\n"],"entry_point":"f_5212870","intent":"Sorting a Python list `list` by the first item ascending and last item descending","library":[],"docs":[]} {"task_id":403421,"prompt":"def f_403421(ut, cmpfun):\n\t","suffix":"\n\treturn ut","canonical_solution":"ut.sort(key=cmpfun, reverse=True)","test_start":"\ndef check(candidate):","test":["\n assert candidate([], lambda x: x) == []\n","\n assert candidate(['a', 'b', 'c'], lambda x: x) == ['c', 'b', 'a']\n","\n assert candidate([2, 1, 3], lambda x: -x) == [1, 2, 3]\n"],"entry_point":"f_403421","intent":"sort a list of objects `ut`, based on a function `cmpfun` in descending order","library":[],"docs":[]} {"task_id":403421,"prompt":"def f_403421(ut):\n\t","suffix":"\n\treturn ut","canonical_solution":"ut.sort(key=lambda x: x.count, reverse=True)","test_start":"\nclass Tag: \n def __init__(self, name, count): \n self.name = name \n self.count = count \n\n def __str__(self):\n return f\"[{self.name}]-[{self.count}]\"\n\ndef check(candidate):","test":["\n result = candidate([Tag(\"red\", 1), Tag(\"blue\", 22), Tag(\"black\", 0)])\n assert (result[0].name == \"blue\") and (result[0].count == 22)\n assert (result[1].name == \"red\") and (result[1].count == 1)\n assert (result[2].name == \"black\") and (result[2].count == 0)\n"],"entry_point":"f_403421","intent":"reverse list `ut` based on the `count` attribute of each object","library":[],"docs":[]} {"task_id":3944876,"prompt":"def f_3944876(i):\n\treturn ","suffix":"","canonical_solution":"'ME' + str(i)","test_start":"\ndef check(candidate):","test":["\n assert candidate(100) == \"ME100\"\n","\n assert candidate(0.22) == \"ME0.22\"\n","\n assert candidate(\"text\") == \"MEtext\"\n"],"entry_point":"f_3944876","intent":"cast an int `i` to a string and concat to string 'ME'","library":[],"docs":[]} {"task_id":40903174,"prompt":"def f_40903174(df):\n\treturn ","suffix":"","canonical_solution":"df.sort_values(['System_num', 'Dis'])","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\n df1 = pd.DataFrame([[6, 1, 1], [5, 1, 1], [4, 1, 1], [3, 2, 1], [2, 2, 1], [1, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans1 = pd.DataFrame([[4, 1, 1], [5, 1, 1], [6, 1, 1], [1, 2, 1], [2, 2, 1], [3, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans1.equals(candidate(df1).reset_index(drop = True))) == True\n","\n df2 = pd.DataFrame([[6, 3, 1], [5, 2, 1], [4, 1, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans2 = pd.DataFrame([[4, 1, 1], [5, 2, 1], [6, 3, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans2.equals(candidate(df2).reset_index(drop = True))) == True\n","\n df3 = pd.DataFrame([[1, 3, 1], [3, 3, 1], [2, 3, 1], [6, 1, 1], [4, 1, 1], [5, 2, 1], [3, 2, 1]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans3 = pd.DataFrame([[4, 1,1], [6, 1, 1], [3, 2, 1], [5, 2, 1], [1, 3, 1], [2, 3, 1], [3, 3, 1]], columns = ['Dis', 'System_num', 'Energy'])\n assert (df_ans3.equals(candidate(df3).reset_index(drop = True))) == True \n","\n df4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]], columns = ['Dis', 'System_num', 'Energy'])\n df_ans4 = pd.DataFrame([[1, 2, 3], [1, 2, 3], [4, 1, 3]])\n assert (df_ans4.equals(candidate(df4).reset_index(drop = True))) == False\n"],"entry_point":"f_40903174","intent":"Sorting data in Pandas DataFrame `df` with columns 'System_num' and 'Dis'","library":["pandas"],"docs":[{"function":"df.sort_values","text":"pandas.DataFrame.sort_values DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)[source]\n \nSort by the values along either axis. Parameters ","title":"pandas.reference.api.pandas.dataframe.sort_values"}]} {"task_id":4454298,"prompt":"def f_4454298(infile, outfile):\n\t","suffix":"\n\treturn ","canonical_solution":"open(outfile, 'w').write('#test firstline\\n' + open(infile).read())","test_start":"\nimport filecmp\n\ndef check(candidate): ","test":["\n open('test1.txt', 'w').write('test1')\n candidate('test1.txt', 'test1_out.txt')\n open('test1_ans.txt', 'w').write('#test firstline\\ntest1')\n assert filecmp.cmp('test1_out.txt', 'test1_ans.txt') == True\n","\n open('test2.txt', 'w').write('\\ntest2\\n')\n candidate('test2.txt', 'test2_out.txt')\n open('test2_ans.txt', 'w').write('#test firstline\\n\\ntest2\\n')\n assert filecmp.cmp('test2_out.txt', 'test2_ans.txt') == True\n","\n open('test3.txt', 'w').write(' \\n \\n')\n candidate('test3.txt', 'test3_out.txt')\n open('test3_ans.txt', 'w').write('#test firstline\\n \\n \\n')\n assert filecmp.cmp('test3_out.txt', 'test3_ans.txt') == True\n","\n open('test4.txt', 'w').write('hello')\n candidate('test4.txt', 'test4_out.txt')\n open('test4_ans.txt', 'w').write('hello')\n assert filecmp.cmp('test4_out.txt', 'test4_ans.txt') == False\n"],"entry_point":"f_4454298","intent":"prepend the line '#test firstline\\n' to the contents of file 'infile' and save as the file 'outfile'","library":["filecmp"],"docs":[]} {"task_id":19729928,"prompt":"def f_19729928(l):\n\t","suffix":"\n\treturn l","canonical_solution":"l.sort(key=lambda t: len(t[1]), reverse=True)","test_start":"\ndef check(candidate): ","test":["\n assert candidate([(\"a\", [1]), (\"b\", [1,2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"b\", [1,2]), (\"a\", [1])]\n","\n assert candidate([(\"a\", [1]), (\"b\", [2]), (\"c\", [1,2,3])]) == [(\"c\", [1,2,3]), (\"a\", [1]), (\"b\", [2])]\n","\n assert candidate([(\"a\", [1]), (\"b\", [2]), (\"c\", [3])]) == [(\"a\", [1]), (\"b\", [2]), (\"c\", [3])]\n"],"entry_point":"f_19729928","intent":"sort a list `l` by length of value in tuple","library":[],"docs":[]} {"task_id":31371879,"prompt":"def f_31371879(s):\n\treturn ","suffix":"","canonical_solution":"re.findall('\\\\b(\\\\w+)d\\\\b', s)","test_start":"\nimport re\n\ndef check(candidate): ","test":["\n assert candidate(\"this is good\") == [\"goo\"]\n","\n assert candidate(\"this is interesting\") == []\n","\n assert candidate(\"good bad dd\") == [\"goo\", \"ba\", \"d\"]\n"],"entry_point":"f_31371879","intent":"split string `s` by words that ends with 'd'","library":["re"],"docs":[{"function":"re.findall","text":"Pattern.findall(string[, pos[, endpos]]) \nSimilar to the findall() function, using the compiled pattern, but also accepts optional pos and endpos parameters that limit the search region like for search().","title":"python.library.re#re.Pattern.findall"}]} {"task_id":9012008,"prompt":"def f_9012008():\n\treturn ","suffix":"","canonical_solution":"bool(re.search('ba[rzd]', 'foobarrrr'))","test_start":"\nimport re\n\ndef check(candidate): ","test":["\n assert candidate() == True\n"],"entry_point":"f_9012008","intent":"return `True` if string `foobarrrr` contains regex `ba[rzd]`","library":["re"],"docs":[{"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 different from finding a zero-length match at some point in the string.","title":"python.library.re#re.search"}]} {"task_id":7961363,"prompt":"def f_7961363(t):\n\treturn ","suffix":"","canonical_solution":"list(set(t))","test_start":"\ndef check(candidate): ","test":["\n assert candidate([1,2,3]) == [1,2,3]\n","\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n","\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n","\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n","\n assert candidate([1.0, 1]) == [1.0] \n","\n assert candidate([]) == [] \n","\n assert candidate([None]) == [None] \n"],"entry_point":"f_7961363","intent":"Removing duplicates in list `t`","library":[],"docs":[]} {"task_id":7961363,"prompt":"def f_7961363(source_list):\n\treturn ","suffix":"","canonical_solution":"list(set(source_list))","test_start":"\ndef check(candidate): ","test":["\n assert candidate([1,2,3]) == [1,2,3]\n","\n assert candidate([1,1,1,1,1,1,1,1,1,1]) == [1] \n","\n assert candidate([1,2,2,2,2,2,3,3,3,3,3]) == [1,2,3]\n","\n assert (candidate([1, '1']) == [1, '1']) or (candidate([1, '1']) == ['1', 1])\n","\n assert candidate([1.0, 1]) == [1.0] \n","\n assert candidate([]) == [] \n","\n assert candidate([None]) == [None] \n"],"entry_point":"f_7961363","intent":"Removing duplicates in list `source_list`","library":[],"docs":[]} {"task_id":7961363,"prompt":"def f_7961363():\n\treturn ","suffix":"","canonical_solution":"list(OrderedDict.fromkeys('abracadabra'))","test_start":"\nfrom collections import OrderedDict\n\ndef check(candidate):","test":["\n assert candidate() == ['a', 'b', 'r', 'c', 'd']\n"],"entry_point":"f_7961363","intent":"Removing duplicates in list `abracadabra`","library":["collections"],"docs":[{"function":"collections.OrderedDict","text":"class collections.OrderedDict([items]) \nReturn an instance of a dict subclass that has methods specialized for rearranging dictionary order. New in version 3.1. \npopitem(last=True) \nThe popitem() method for ordered dictionaries returns and removes a (key, value) pair. The pairs are returned in LIFO order if last is true or FIFO order if false. \n \nmove_to_end(key, last=True) \nMove an existing key to either end of an ordered dictionary. The item is moved to the right end if last is true (the default) or to the beginning if last is false. Raises KeyError if the key does not exist: >>> d = OrderedDict.fromkeys('abcde')","title":"python.library.collections#collections.OrderedDict"}]} {"task_id":5183533,"prompt":"def f_5183533(a):\n\treturn ","suffix":"","canonical_solution":"numpy.array(a).reshape(-1).tolist()","test_start":"\nimport numpy\n\ndef check(candidate):","test":["\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3,4,5,6]\n","\n assert candidate(['a', 'aa', 'abc']) == ['a', 'aa', 'abc']\n"],"entry_point":"f_5183533","intent":"Convert array `a` into a list","library":["numpy"],"docs":[{"function":"numpy.ndarray.reshape","text":"numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).","title":"numpy.reference.generated.numpy.ndarray.reshape"},{"function":"numpy.ndarray.tolist","text":"numpy.ndarray.tolist method ndarray.tolist()\n \nReturn the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters \n none\n Returns \n \nyobject, or list of object, or list of list of object, or \u2026\n\n\nThe possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2])","title":"numpy.reference.generated.numpy.ndarray.tolist"}]} {"task_id":5183533,"prompt":"def f_5183533(a):\n\treturn ","suffix":"","canonical_solution":"numpy.array(a)[0].tolist()","test_start":"\nimport numpy\n\ndef check(candidate):","test":["\n assert candidate([[1,2,3],[4,5,6]]) == [1,2,3]\n","\n assert candidate(['a', 'aa', 'abc']) == 'a'\n"],"entry_point":"f_5183533","intent":"Convert the first row of numpy matrix `a` to a list","library":["numpy"],"docs":[{"function":"numpy.ndarray.tolist","text":"numpy.ndarray.tolist method ndarray.tolist()\n \nReturn the array as an a.ndim-levels deep nested list of Python scalars. Return a copy of the array data as a (nested) Python list. Data items are converted to the nearest compatible builtin Python type, via the item function. If a.ndim is 0, then since the depth of the nested list is 0, it will not be a list at all, but a simple Python scalar. Parameters \n none\n Returns \n \nyobject, or list of object, or list of list of object, or \u2026\n\n\nThe possibly nested list of array elements. Notes The array may be recreated via a = np.array(a.tolist()), although this may sometimes lose precision. Examples For a 1D array, a.tolist() is almost the same as list(a), except that tolist changes numpy scalars to Python scalars: >>> a = np.uint32([1, 2])","title":"numpy.reference.generated.numpy.ndarray.tolist"}]} {"task_id":5999747,"prompt":"def f_5999747(soup):\n\treturn ","suffix":"","canonical_solution":"soup.find(text='Address:').findNext('td').contents[0]","test_start":"\nfrom bs4 import BeautifulSoup\n\ndef check(candidate):","test":["\n assert candidate(BeautifulSoup(\"Address:<\/b><\/td>My home address<\/td>\")) == \"My home address\"\n","\n assert candidate(BeautifulSoup(\"Address:<\/b><\/td>This is my home address<\/td>Not my home address<\/td>\")) == \"This is my home address\"\n","\n assert candidate(BeautifulSoup(\"Address:<\/b><\/td>My home address
  • My home address in a list<\/li><\/td>\")) == \"My home address\"\n"],"entry_point":"f_5999747","intent":"In `soup`, get the content of the sibling of the `td` tag with text content `Address:`","library":["bs4"],"docs":[]} {"task_id":4284648,"prompt":"def f_4284648(l):\n\treturn ","suffix":"","canonical_solution":"\"\"\" \"\"\".join([('%d@%d' % t) for t in l])","test_start":"\ndef check(candidate):","test":["\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n","\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n","\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n"],"entry_point":"f_4284648","intent":"convert elements of each tuple in list `l` into a string separated by character `@`","library":[],"docs":[]} {"task_id":4284648,"prompt":"def f_4284648(l):\n\treturn ","suffix":"","canonical_solution":"\"\"\" \"\"\".join([('%d@%d' % (t[0], t[1])) for t in l])","test_start":"\ndef check(candidate):","test":["\n assert candidate([(1, 2), (3, 4)]) == \"1@2 3@4\"\n","\n assert candidate([(10, 11), (12, 13)]) == \"10@11 12@13\"\n","\n assert candidate([(10.2, 11.4), (12.14, 13.13)]) == \"10@11 12@13\"\n"],"entry_point":"f_4284648","intent":"convert each tuple in list `l` to a string with '@' separating the tuples' elements","library":[],"docs":[]} {"task_id":29696641,"prompt":"def f_29696641(teststr):\n\treturn ","suffix":"","canonical_solution":"[i for i in teststr if re.search('\\\\d+[xX]', i)]","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']) == ['2x Sec String', '5X fifth']\n","\n assert candidate(['1x', '2', '3X', '4x random', '5X random']) == ['1x', '3X', '4x random', '5X random']\n","\n assert candidate(['1x', '2', '3X', '4xrandom', '5Xrandom']) == ['1x', '3X', '4xrandom', '5Xrandom']\n"],"entry_point":"f_29696641","intent":"Get all matches with regex pattern `\\\\d+[xX]` in list of string `teststr`","library":["re"],"docs":[{"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 different from finding a zero-length match at some point in the string.","title":"python.library.re#re.search"}]} {"task_id":15315452,"prompt":"def f_15315452(df):\n\treturn ","suffix":"","canonical_solution":"df['A'][(df['B'] > 50) & (df['C'] == 900)]","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame({'A': [7, 7, 4, 4, 7, 7, 3, 9, 6, 3], 'B': [20, 80, 90, 30, 80, 60, 80, 40, 40 ,10], 'C': [300, 700, 100, 900, 200, 800, 900, 100, 100, 600]})\n assert candidate(df).to_dict() == {6: 3}\n","\n df1 = pd.DataFrame({'A': [9, 9, 5, 8, 7, 9, 2, 2, 5, 7], 'B': [40, 70, 70, 80, 50, 30, 80, 80, 80, 70], 'C': [300, 700, 900, 900, 200, 900, 700, 400, 300, 800]})\n assert candidate(df1).to_dict() == {2: 5, 3: 8}\n","\n df2 = pd.DataFrame({'A': [3, 4, 5, 6], 'B': [-10, 50, 20, 10], 'C': [900, 800, 900, 900]})\n assert candidate(df2).to_dict() == {}\n"],"entry_point":"f_15315452","intent":"select values from column 'A' for which corresponding values in column 'B' will be greater than 50, and in column 'C' - equal 900 in dataframe `df`","library":["pandas"],"docs":[]} {"task_id":4642501,"prompt":"def f_4642501(o):\n\treturn ","suffix":"","canonical_solution":"sorted(o.items())","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [(1, \"abc\"), (2, \"pqr\"), (5, \"klm\")]\n","\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [(-1.009, 'pow'), (4.221, 'uwv')]\n","\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) == [('#wwq', 'say'), ('35', 'kangaroo'), ('Rwc', 'koala'), ('as2q', 'piqr')]\n"],"entry_point":"f_4642501","intent":"Sort dictionary `o` in ascending order based on its keys and items","library":["pandas"],"docs":[]} {"task_id":4642501,"prompt":"def f_4642501(d):\n\treturn ","suffix":"","canonical_solution":"sorted(d)","test_start":"\ndef check(candidate):","test":["\n assert candidate({1:\"abc\", 5:\"klm\", 2:\"pqr\"}) == [1, 2, 5]\n","\n assert candidate({4.221:\"uwv\", -1.009:\"pow\"}) == [-1.009, 4.221]\n","\n assert candidate({\"as2q\":\"piqr\", \"#wwq\":\"say\", \"Rwc\":\"koala\", \"35\":\"kangaroo\"}) == ['#wwq', '35', 'Rwc', 'as2q']\n"],"entry_point":"f_4642501","intent":"get sorted list of keys of dict `d`","library":[],"docs":[]} {"task_id":4642501,"prompt":"def f_4642501(d):\n\treturn ","suffix":"","canonical_solution":"sorted(d.items())","test_start":"\ndef check(candidate):","test":["\n d = {'a': [1, 2, 3], 'c': ['one', 'two'], 'b': ['blah', 'bhasdf', 'asdf'], 'd': ['asdf', 'wer', 'asdf', 'zxcv']}\n assert candidate(d) == [('a', [1, 2, 3]), ('b', ['blah', 'bhasdf', 'asdf']), ('c', ['one', 'two']), ('d', ['asdf', 'wer', 'asdf', 'zxcv'])]\n"],"entry_point":"f_4642501","intent":"sort dictionaries `d` by keys","library":[],"docs":[]} {"task_id":642154,"prompt":"def f_642154():\n\treturn ","suffix":"","canonical_solution":"int('1')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 1\n","\n assert candidate() + 1 == 2\n"],"entry_point":"f_642154","intent":"convert string \"1\" into integer","library":[],"docs":[]} {"task_id":642154,"prompt":"def f_642154(T1):\n\treturn ","suffix":"","canonical_solution":"[list(map(int, x)) for x in T1]","test_start":"\ndef check(candidate):","test":["\n T1 = (('13', '17', '18', '21', '32'), ('07', '11', '13', '14', '28'), ('01', '05', '06', '08', '15', '16'))\n assert candidate(T1) == [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]\n"],"entry_point":"f_642154","intent":"convert items in `T1` to integers","library":[],"docs":[]} {"task_id":3777301,"prompt":"def f_3777301():\n\t","suffix":"\n\treturn ","canonical_solution":"subprocess.call(['.\/test.sh'])","test_start":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n"],"entry_point":"f_3777301","intent":"call a shell script `.\/test.sh` using subprocess","library":["subprocess"],"docs":[{"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 stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.","title":"python.library.subprocess#subprocess.call"}]} {"task_id":3777301,"prompt":"def f_3777301():\n\t","suffix":"\n\treturn ","canonical_solution":"subprocess.call(['notepad'])","test_start":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n subprocess.call = Mock()\n try:\n candidate()\n except:\n assert False\n"],"entry_point":"f_3777301","intent":"call a shell script `notepad` using subprocess","library":["subprocess"],"docs":[{"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 stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.","title":"python.library.subprocess#subprocess.call"}]} {"task_id":7946798,"prompt":"def f_7946798(l1, l2):\n\treturn ","suffix":"","canonical_solution":"[val for pair in zip(l1, l2) for val in pair]","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3], [10,20,30]) == [1,10,2,20,3,30]\n","\n assert candidate([1,2,3], ['c','b','a']) == [1,'c',2,'b',3,'a']\n","\n assert candidate([1,2,3], ['c','b']) == [1,'c',2,'b']\n"],"entry_point":"f_7946798","intent":"combine lists `l1` and `l2` by alternating their elements","library":[],"docs":[]} {"task_id":8908287,"prompt":"def f_8908287():\n\treturn ","suffix":"","canonical_solution":"base64.b64encode(b'data to be encoded')","test_start":"\nimport base64\n\ndef check(candidate):","test":["\n assert candidate() == b'ZGF0YSB0byBiZSBlbmNvZGVk'\n"],"entry_point":"f_8908287","intent":"encode string 'data to be encoded'","library":["base64"],"docs":[{"function":"base64.b64encode","text":"base64.b64encode(s, altchars=None) \nEncode the bytes-like object s using Base64 and return the encoded bytes. Optional altchars must be a bytes-like object of at least length 2 (additional characters are ignored) which specifies an alternative alphabet for the + and \/ characters. This allows an application to e.g. generate URL or filesystem safe Base64 strings. The default is None, for which the standard Base64 alphabet is used.","title":"python.library.base64#base64.b64encode"}]} {"task_id":8908287,"prompt":"def f_8908287():\n\treturn ","suffix":"","canonical_solution":"'data to be encoded'.encode('ascii')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == b'data to be encoded'\n"],"entry_point":"f_8908287","intent":"encode a string `data to be encoded` to `ascii` encoding","library":[],"docs":[]} {"task_id":7856296,"prompt":"def f_7856296():\n\treturn ","suffix":"","canonical_solution":"list(csv.reader(open('text.txt', 'r'), delimiter='\\t'))","test_start":"\nimport csv \n\ndef check(candidate):","test":["\n with open('text.txt', 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, delimiter='\t')\n spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])\n spamwriter.writerow(['hello', 'world', '!'])\n\n assert candidate() == [['Spam', 'Lovely Spam', 'Wonderful Spam'], ['hello', 'world', '!']]\n"],"entry_point":"f_7856296","intent":"parse tab-delimited CSV file 'text.txt' into a list","library":["csv"],"docs":[{"function":"csv.reader","text":"csv.reader(csvfile, dialect='excel', **fmtparams) \nReturn a reader object which will iterate over lines in the given csvfile. csvfile can be any object which supports the iterator protocol and returns a string each time its __next__() method is called \u2014 file objects and list objects are both suitable. If csvfile is a file object, it should be opened with newline=''. 1 An optional dialect parameter can be given which is used to define a set of parameters specific to a particular CSV dialect. It may be an instance of a subclass of the Dialect class or one of the strings returned by the list_dialects() function. The other optional fmtparams keyword arguments can be given to override individual formatting parameters in the current dialect. For full details about the dialect and formatting parameters, see section Dialects and Formatting Parameters. Each row read from the csv file is returned as a list of strings. No automatic data type conversion is performed unless the QUOTE_NONNUMERIC format option is specified (in which case unquoted fields are transformed into floats). A short usage example: >>> import csv","title":"python.library.csv#csv.reader"}]} {"task_id":9035479,"prompt":"def f_9035479(my_object, my_str):\n\treturn ","suffix":"","canonical_solution":"getattr(my_object, my_str)","test_start":"\ndef check(candidate):","test":["\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert candidate(s, \"name\") == \"abc\"\n","\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert (candidate(s, \"grade\") - 97.08) < 1e-6\n","\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert (candidate(s, \"grade\") - 97.07) > 1e-6\n","\n class Student:\n id = 9\n name = \"abc\"\n grade = 97.08\n\n s = Student()\n \n assert candidate(s, \"id\") == 9\n"],"entry_point":"f_9035479","intent":"Get attribute `my_str` of object `my_object`","library":[],"docs":[]} {"task_id":5558418,"prompt":"def f_5558418(LD):\n\treturn ","suffix":"","canonical_solution":"dict(zip(LD[0], zip(*[list(d.values()) for d in LD])))","test_start":"\nimport collections\n\ndef check(candidate):","test":["\n employees = [{'name' : 'apple', 'id': 60}, {'name' : 'orange', 'id': 65}]\n exp_result = {'name': ('apple', 'orange'), 'id': (60, 65)}\n actual_result = candidate(employees)\n for key in actual_result:\n assert collections.Counter(list(exp_result[key])) == collections.Counter(list(actual_result[key]))\n"],"entry_point":"f_5558418","intent":"group a list of dicts `LD` into one dict by key","library":["collections"],"docs":[]} {"task_id":638048,"prompt":"def f_638048(list_of_pairs):\n\treturn ","suffix":"","canonical_solution":"sum([pair[0] for pair in list_of_pairs])","test_start":"\ndef check(candidate):","test":["\n assert candidate([(5, 9), (-1, -2), (4, 2)]) == 8\n"],"entry_point":"f_638048","intent":"sum the first value in each tuple in a list of tuples `list_of_pairs` in python","library":[],"docs":[]} {"task_id":14950260,"prompt":"def f_14950260():\n\treturn ","suffix":"","canonical_solution":"ast.literal_eval(\"{'code1':1,'code2':1}\")","test_start":"\nimport ast\n\ndef check(candidate):","test":["\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"],"entry_point":"f_14950260","intent":"convert unicode string u\"{'code1':1,'code2':1}\" into dictionary","library":["ast"],"docs":[{"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, dicts, sets, booleans, and None. This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing. Warning It is possible to crash the Python interpreter with a sufficiently large\/complex string due to stack depth limitations in Python\u2019s AST compiler. Changed in version 3.2: Now allows bytes and set literals. Changed in version 3.9: Now supports creating empty sets with 'set()'.","title":"python.library.ast#ast.literal_eval"}]} {"task_id":11416772,"prompt":"def f_11416772(mystring):\n\treturn ","suffix":"","canonical_solution":"[word for word in mystring.split() if word.startswith('$')]","test_start":"\ndef check(candidate):","test":["\n str = \"$abc def $efg $hij klm $\"\n exp_result = ['$abc', '$efg', '$hij', '$']\n assert sorted(candidate(str)) == sorted(exp_result)\n"],"entry_point":"f_11416772","intent":"find all words in a string `mystring` that start with the `$` sign","library":[],"docs":[]} {"task_id":11331982,"prompt":"def f_11331982(text):\n\t","suffix":"\n\treturn text","canonical_solution":"text = re.sub('^https?:\\\\\/\\\\\/.*[\\\\r\\\\n]*', '', text, flags=re.MULTILINE)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"https:\/\/www.wikipedia.org\/ click at\") == \"\"\n"],"entry_point":"f_11331982","intent":"remove any url within string `text`","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":34945274,"prompt":"def f_34945274(A):\n\treturn ","suffix":"","canonical_solution":"np.where(np.in1d(A, [1, 3, 4]).reshape(A.shape), A, 0)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_34945274","intent":"replace all elements in array `A` that are not present in array `[1, 3, 4]` with zeros","library":["numpy"],"docs":[{"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 behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters ","title":"numpy.reference.generated.numpy.where"},{"function":"numpy.in1d","text":"numpy.in1d numpy.in1d(ar1, ar2, assume_unique=False, invert=False)[source]\n \nTest whether each element of a 1-D array is also present in a second array. Returns a boolean array the same length as ar1 that is True where an element of ar1 is in ar2 and False otherwise. We recommend using isin instead of in1d for new code. Parameters ","title":"numpy.reference.generated.numpy.in1d"}]} {"task_id":15819980,"prompt":"def f_15819980(a):\n\treturn ","suffix":"","canonical_solution":"np.mean(a, axis=1)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_15819980","intent":"calculate mean across dimension in a 2d array `a`","library":["numpy"],"docs":[{"function":"numpy.mean","text":"numpy.mean numpy.mean(a, axis=None, dtype=None, out=None, keepdims=, *, where=)[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, otherwise over the specified axis. float64 intermediate and return values are used for integer inputs. Parameters ","title":"numpy.reference.generated.numpy.mean"}]} {"task_id":19894365,"prompt":"def f_19894365():\n\treturn ","suffix":"","canonical_solution":"subprocess.call(['\/usr\/bin\/Rscript', '--vanilla', '\/pathto\/MyrScript.r'])","test_start":"\nfrom unittest.mock import Mock\nimport subprocess\n\ndef check(candidate):","test":["\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n"],"entry_point":"f_19894365","intent":"running r script '\/pathto\/MyrScript.r' from python","library":["subprocess"],"docs":[{"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 stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.","title":"python.library.subprocess#subprocess.call"}]} {"task_id":19894365,"prompt":"def f_19894365():\n\treturn ","suffix":"","canonical_solution":"subprocess.call('\/usr\/bin\/Rscript --vanilla \/pathto\/MyrScript.r', shell=True)","test_start":"\nfrom unittest.mock import Mock\nimport subprocess\n\ndef check(candidate):","test":["\n subprocess.call = Mock(return_value = 0)\n assert candidate() == 0\n"],"entry_point":"f_19894365","intent":"run r script '\/usr\/bin\/Rscript --vanilla \/pathto\/MyrScript.r'","library":["subprocess"],"docs":[{"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 stderr should use run() instead: run(...).returncode\n To suppress stdout or stderr, supply a value of DEVNULL. The arguments shown above are merely some common ones. The full function signature is the same as that of the Popen constructor - this function passes all supplied arguments other than timeout directly through to that interface. Note Do not use stdout=PIPE or stderr=PIPE with this function. The child process will block if it generates enough output to a pipe to fill up the OS pipe buffer as the pipes are not being read from. Changed in version 3.3: timeout was added.","title":"python.library.subprocess#subprocess.call"}]} {"task_id":33058590,"prompt":"def f_33058590(df):\n\treturn ","suffix":"","canonical_solution":"df.fillna(df.mean(axis=0))","test_start":"\nimport pandas as pd\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_33058590","intent":"replacing nan in the dataframe `df` with row average","library":["numpy","pandas"],"docs":[{"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"},{"function":"pandas.dataframe.mean","text":"pandas.DataFrame.mean DataFrame.mean(axis=NoDefault.no_default, skipna=True, level=None, numeric_only=None, **kwargs)[source]\n \nReturn the mean of the values over the requested axis. Parameters ","title":"pandas.reference.api.pandas.dataframe.mean"}]} {"task_id":12400256,"prompt":"def f_12400256():\n\treturn ","suffix":"","canonical_solution":"time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))","test_start":"\nimport time\n\ndef check(candidate):","test":["\n assert candidate() == \"2012-09-13 06:22:50\"\n"],"entry_point":"f_12400256","intent":"Convert unix timestamp '1347517370' to formatted string '%Y-%m-%d %H:%M:%S'","library":["time"],"docs":[{"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. ValueError is raised if any field in t is outside of the allowed range. 0 is a legal argument for any position in the time tuple; if it is normally illegal the value is forced to a correct one. The following directives can be embedded in the format string. They are shown without the optional field width and precision specification, and are replaced by the indicated characters in the strftime() result: \nDirective Meaning Notes ","title":"python.library.time#time.strftime"}]} {"task_id":23359886,"prompt":"def f_23359886(a):\n\treturn ","suffix":"","canonical_solution":"a[np.where((a[:, (0)] == 0) * (a[:, (1)] == 1))]","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_23359886","intent":"selecting rows in Numpy ndarray 'a', where the value in the first column is 0 and value in the second column is 1","library":["numpy"],"docs":[{"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 behaves correctly for subclasses. The rest of this documentation covers only the case where all three arguments are provided. Parameters ","title":"numpy.reference.generated.numpy.where"}]} {"task_id":4383082,"prompt":"def f_4383082(words):\n\treturn ","suffix":"","canonical_solution":"re.split(' +', words)","test_start":"\nimport regex as re\n\ndef check(candidate):","test":["\n s = \"hello world sample text\"\n res = [\"hello\", \"world\", \"sample\", \"text\"]\n assert candidate(s) == res\n"],"entry_point":"f_4383082","intent":"separate words delimited by one or more spaces into a list","library":["regex"],"docs":[{"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 splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}]} {"task_id":14637696,"prompt":"def f_14637696(words):\n\treturn ","suffix":"","canonical_solution":"len(max(words, key=len))","test_start":"\ndef check(candidate):","test":["\n assert candidate([\"hello\", \"world\", \"sample\", \"text\", \"superballer\"]) == 11\n"],"entry_point":"f_14637696","intent":"length of longest element in list `words`","library":[],"docs":[]} {"task_id":3933478,"prompt":"def f_3933478(result):\n\treturn ","suffix":"","canonical_solution":"result[0]['from_user']","test_start":"\ndef check(candidate):","test":["\n Contents = [{\"hi\": 7, \"bye\": 4, \"from_user\": 0}, {1: 2, 3: 4, 5: 6}]\n assert candidate(Contents) == 0\n"],"entry_point":"f_3933478","intent":"get the value associated with unicode key 'from_user' of first dictionary in list `result`","library":[],"docs":[]} {"task_id":39112645,"prompt":"def f_39112645():\n\treturn ","suffix":"","canonical_solution":"[line.split() for line in open('File.txt')]","test_start":"\ndef check(candidate):","test":["\n with open('File.txt','w') as fw:\n fw.write(\"hi hello cat dog\")\n assert candidate() == [['hi', 'hello', 'cat', 'dog']]\n"],"entry_point":"f_39112645","intent":"Retrieve each line from a file 'File.txt' as a list","library":[],"docs":[]} {"task_id":1031851,"prompt":"def f_1031851(a):\n\treturn ","suffix":"","canonical_solution":"dict((v, k) for k, v in a.items())","test_start":"\ndef check(candidate):","test":["\n a = {\"one\": 1, \"two\": 2}\n assert candidate(a) == {1: \"one\", 2: \"two\"}\n"],"entry_point":"f_1031851","intent":"swap keys with values in a dictionary `a`","library":[],"docs":[]} {"task_id":8577137,"prompt":"def f_8577137():\n\treturn ","suffix":"","canonical_solution":"open('path\/to\/FILE_NAME.ext', 'w')","test_start":"\nimport os\n\ndef check(candidate):","test":["\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"],"entry_point":"f_8577137","intent":"Open a file `path\/to\/FILE_NAME.ext` in write mode","library":["os"],"docs":[{"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 new file descriptor is non-inheritable. For a description of the flag and mode values, see the C run-time documentation; flag constants (like O_RDONLY and O_WRONLY) are defined in the os module. In particular, on Windows adding O_BINARY is needed to open files in binary mode. This function can support paths relative to directory descriptors with the dir_fd parameter. Raises an auditing event open with arguments path, mode, flags. Changed in version 3.4: The new file descriptor is now non-inheritable. Note This function is intended for low-level I\/O. For normal usage, use the built-in function open(), which returns a file object with read() and write() methods (and many more). To wrap a file descriptor in a file object, use fdopen(). New in version 3.3: The dir_fd argument. Changed in version 3.5: If the system call is interrupted and the signal handler does not raise an exception, the function now retries the system call instead of raising an InterruptedError exception (see PEP 475 for the rationale). Changed in version 3.6: Accepts a path-like object.","title":"python.library.os#os.open"}]} {"task_id":17926273,"prompt":"def f_17926273(df):\n\treturn ","suffix":"","canonical_solution":"df.groupby(['col1', 'col2'])['col3'].nunique().reset_index()","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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.DataFrame(expected, columns = ['col1', 'col2', 'col3'])\n df1 = candidate(df)\n assert pd.DataFrame.equals(expected_df, df1)\n"],"entry_point":"f_17926273","intent":"count distinct values in a column 'col3' of a pandas dataframe `df` group by objects in 'col1' and 'col2'","library":["pandas"],"docs":[{"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 operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ","title":"pandas.reference.api.pandas.dataframe.groupby"},{"function":"nunique","text":"pandas.core.groupby.DataFrameGroupBy.nunique DataFrameGroupBy.nunique(dropna=True)[source]\n \nReturn DataFrame with counts of unique elements in each position. Parameters \n \ndropna:bool, default True\n\n\nDon\u2019t include NaN in the counts. Returns \n nunique: DataFrame\n Examples ","title":"pandas.reference.api.pandas.core.groupby.dataframegroupby.nunique"},{"function":"reset_index","text":"pandas.DataFrame.reset_index DataFrame.reset_index(level=None, drop=False, inplace=False, col_level=0, col_fill='')[source]\n \nReset the index, or a level of it. Reset the index of the DataFrame, and use the default one instead. If the DataFrame has a MultiIndex, this method can remove one or more levels. Parameters ","title":"pandas.reference.api.pandas.dataframe.reset_index"}]} {"task_id":3735814,"prompt":"def f_3735814(dict1):\n\treturn ","suffix":"","canonical_solution":"any(key.startswith('EMP$$') for key in dict1)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3735814","intent":"Check if any key in the dictionary `dict1` starts with the string `EMP$$`","library":[],"docs":[]} {"task_id":3735814,"prompt":"def f_3735814(dict1):\n\treturn ","suffix":"","canonical_solution":"[value for key, value in list(dict1.items()) if key.startswith('EMP$$')]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3735814","intent":"create list of values from dictionary `dict1` that have a key that starts with 'EMP$$'","library":[],"docs":[]} {"task_id":26097916,"prompt":"def f_26097916(sf):\n\t","suffix":"\n\treturn df","canonical_solution":"df = pd.DataFrame({'email': sf.index, 'list': sf.values})","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_26097916","intent":"convert a pandas series `sf` into a pandas dataframe `df` with columns `email` and `list`","library":["pandas"],"docs":[]} {"task_id":4048964,"prompt":"def f_4048964(list):\n\treturn ","suffix":"","canonical_solution":"'\\t'.join(map(str, list))","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_4048964","intent":"concatenate elements of list `list` by tabs `\t`","library":[],"docs":[]} {"task_id":3182716,"prompt":"def f_3182716():\n\treturn ","suffix":"","canonical_solution":"'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8'.encode('raw_unicode_escape')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == b'\\xd0\\xbf\\xd1\\x80\\xd0\\xb8'\n"],"entry_point":"f_3182716","intent":"print unicode string '\\xd0\\xbf\\xd1\\x80\\xd0\\xb8' with utf-8","library":[],"docs":[]} {"task_id":3182716,"prompt":"def f_3182716():\n\treturn ","suffix":"","canonical_solution":"'Sopet\\xc3\\xb3n'.encode('latin-1').decode('utf-8')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == \"Sopet\u00f3n\"\n"],"entry_point":"f_3182716","intent":"Encode a latin character in string `Sopet\\xc3\\xb3n` properly","library":[],"docs":[]} {"task_id":35622945,"prompt":"def f_35622945(s):\n\treturn ","suffix":"","canonical_solution":"re.findall('n(?<=[^n]n)n+(?=[^n])(?i)', s)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate(\"ncnnnne\") == ['nnnn']\n","\n assert candidate(\"nn\") == []\n","\n assert candidate(\"ask\") == []\n"],"entry_point":"f_35622945","intent":"regex, find \"n\"s only in the middle of string `s`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":5306756,"prompt":"def f_5306756():\n\treturn ","suffix":"","canonical_solution":"'{0:.0f}%'.format(1.0 \/ 3 * 100)","test_start":"\ndef check(candidate):","test":["\n assert(candidate() == \"33%\")\n"],"entry_point":"f_5306756","intent":"display the float `1\/3*100` as a percentage","library":[],"docs":[]} {"task_id":2878084,"prompt":"def f_2878084(mylist):\n\t","suffix":"\n\treturn mylist","canonical_solution":"mylist.sort(key=lambda x: x['title'])","test_start":"\ndef check(candidate):","test":["\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 {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n"],"entry_point":"f_2878084","intent":"sort a list of dictionary `mylist` by the key `title`","library":[],"docs":[]} {"task_id":2878084,"prompt":"def f_2878084(l):\n\t","suffix":"\n\treturn l","canonical_solution":"l.sort(key=lambda x: x['title'])","test_start":"\ndef check(candidate):","test":["\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 {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n"],"entry_point":"f_2878084","intent":"sort a list `l` of dicts by dict value 'title'","library":[],"docs":[]} {"task_id":2878084,"prompt":"def f_2878084(l):\n\t","suffix":"\n\treturn l","canonical_solution":"l.sort(key=lambda x: (x['title'], x['title_url'], x['id']))","test_start":"\ndef check(candidate):","test":["\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 {'title': 'New York Times', 'title_url': 'New_York_Times', 'id': 4},\n {'title': 'USA Today', 'title_url': 'USA_Today', 'id': 6}\n ]\n assert candidate(input) == res\n"],"entry_point":"f_2878084","intent":"sort a list of dictionaries by the value of keys 'title', 'title_url', 'id' in ascending order.","library":[],"docs":[]} {"task_id":9323159,"prompt":"def f_9323159(l1, l2):\n\treturn ","suffix":"","canonical_solution":"heapq.nlargest(10, range(len(l1)), key=lambda i: abs(l1[i] - l2[i]))","test_start":"\nimport heapq\n\ndef check(candidate):","test":["\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"],"entry_point":"f_9323159","intent":"find 10 largest differences between each respective elements of list `l1` and list `l2`","library":["heapq"],"docs":[{"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=str.lower). Equivalent to: sorted(iterable, key=key,\nreverse=True)[:n].","title":"python.library.heapq#heapq.nlargest"}]} {"task_id":29877663,"prompt":"def f_29877663(soup):\n\treturn ","suffix":"","canonical_solution":"soup.find_all('span', {'class': 'starGryB sp'})","test_start":"\nimport bs4\n\ndef check(candidate):","test":["\n html = '''4.1<\/span>\n 2.9<\/span>\n 2.9<\/span>\n 22<\/span>'''\n soup = bs4.BeautifulSoup(html, features=\"html5lib\")\n res = '''[2.9<\/span>]'''\n assert(str(candidate(soup)) == res)\n"],"entry_point":"f_29877663","intent":"BeautifulSoup find all 'span' elements in HTML string `soup` with class of 'starGryB sp'","library":["bs4"],"docs":[]} {"task_id":24189150,"prompt":"def f_24189150(df, engine):\n\t","suffix":"\n\treturn ","canonical_solution":"df.to_sql('test', engine)","test_start":"\nimport pandas as pd\nfrom sqlalchemy import create_engine\n\ndef check(candidate):","test":["\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"],"entry_point":"f_24189150","intent":"write records in dataframe `df` to table 'test' in schema 'a_schema' with `engine`","library":["pandas","sqlalchemy"],"docs":[{"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 supported. Tables can be newly created, appended to, or overwritten. Parameters ","title":"pandas.reference.api.pandas.dataframe.to_sql"}]} {"task_id":30766151,"prompt":"def f_30766151(s):\n\treturn ","suffix":"","canonical_solution":"re.sub('[^(){}[\\]]', '', s)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"(a(vdwvndw){}]\") == \"((){}]\"\n","\n assert candidate(\"12345\") == \"\"\n"],"entry_point":"f_30766151","intent":"Extract brackets from string `s`","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":1143379,"prompt":"def f_1143379(L):\n\treturn ","suffix":"","canonical_solution":"list(dict((x[0], x) for x in L).values())","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_1143379","intent":"remove duplicate elements from list 'L'","library":[],"docs":[]} {"task_id":12330522,"prompt":"def f_12330522(file):\n\treturn ","suffix":"","canonical_solution":"[line.rstrip('\\n') for line in file]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_12330522","intent":"read a file `file` without newlines","library":[],"docs":[]} {"task_id":364621,"prompt":"def f_364621(testlist):\n\treturn ","suffix":"","canonical_solution":"[i for (i, x) in enumerate(testlist) if (x == 1)]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_364621","intent":"get the position of item 1 in `testlist`","library":[],"docs":[]} {"task_id":364621,"prompt":"def f_364621(testlist):\n\treturn ","suffix":"","canonical_solution":"[i for (i, x) in enumerate(testlist) if (x == 1)]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_364621","intent":"get the position of item 1 in `testlist`","library":[],"docs":[]} {"task_id":364621,"prompt":"def f_364621(testlist, element):\n\treturn ","suffix":"","canonical_solution":"testlist.index(element)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_364621","intent":"get the position of item `element` in list `testlist`","library":[],"docs":[]} {"task_id":13145368,"prompt":"def f_13145368(lis):\n\treturn ","suffix":"","canonical_solution":"max(lis, key=lambda item: item[1])[0]","test_start":"\ndef check(candidate):","test":["\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n"],"entry_point":"f_13145368","intent":"find the first element of the tuple with the maximum second element in a list of tuples `lis`","library":[],"docs":[]} {"task_id":13145368,"prompt":"def f_13145368(lis):\n\treturn ","suffix":"","canonical_solution":"max(lis, key=itemgetter(1))[0]","test_start":"\nfrom operator import itemgetter \n\ndef check(candidate):","test":["\n lis = [(101, 153), (255, 827), (361, 961)]\n assert candidate(lis) == 361\n"],"entry_point":"f_13145368","intent":"get the item at index 0 from the tuple that has maximum value at index 1 in list `lis`","library":["operator"],"docs":[{"function":"operator.itemgetter","text":"operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand\u2019s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):","title":"python.library.operator#operator.itemgetter"}]} {"task_id":2689189,"prompt":"def f_2689189():\n\t","suffix":"\n\treturn ","canonical_solution":"time.sleep(1)","test_start":"\nimport time\n\ndef check(candidate):","test":["\n t1 = time.time()\n candidate()\n t2 = time.time()\n assert t2 - t1 > 1\n"],"entry_point":"f_2689189","intent":"Make a delay of 1 second","library":["time"],"docs":[{"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 terminate the sleep() following execution of that signal\u2019s catching routine. Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. Changed in version 3.5: The function now sleeps at least secs even if the sleep is interrupted by a signal, except if the signal handler raises an exception (see PEP 475 for the rationale).","title":"python.library.time#time.sleep"}]} {"task_id":12485244,"prompt":"def f_12485244(L):\n\treturn ","suffix":"","canonical_solution":"\"\"\", \"\"\".join('(' + ', '.join(i) + ')' for i in L)","test_start":"\ndef check(candidate):","test":["\n L = [(\"abc\", \"def\"), (\"hij\", \"klm\")]\n assert candidate(L) == '(abc, def), (hij, klm)'\n"],"entry_point":"f_12485244","intent":"convert list of tuples `L` to a string","library":[],"docs":[]} {"task_id":755857,"prompt":"def f_755857():\n\t","suffix":"\n\treturn b","canonical_solution":"b = models.CharField(max_length=7, default='0000000', editable=False)","test_start":"\nfrom django.db import models\n\ndef check(candidate):","test":["\n assert candidate().get_default() == '0000000'\n"],"entry_point":"f_755857","intent":"Django set default value of field `b` equal to '0000000'","library":["django"],"docs":[{"function":"models.CharField","text":"class CharField(max_length=None, **options)","title":"django.ref.models.fields#django.db.models.CharField"}]} {"task_id":16193578,"prompt":"def f_16193578(list5):\n\treturn ","suffix":"","canonical_solution":"sorted(list5, key = lambda x: (degrees(x), x))","test_start":"\nfrom math import degrees\n\ndef check(candidate):","test":["\n list5 = [4, 1, 2, 3, 9, 5]\n assert candidate(list5) == [1, 2, 3, 4, 5, 9]\n"],"entry_point":"f_16193578","intent":"Sort lis `list5` in ascending order based on the degrees value of its elements","library":["math"],"docs":[{"function":"math.degrees","text":"math.degrees(x) \nConvert angle x from radians to degrees.","title":"python.library.math#math.degrees"}]} {"task_id":16041405,"prompt":"def f_16041405(l):\n\treturn ","suffix":"","canonical_solution":"(n for n in l)","test_start":"\ndef check(candidate):","test":["\n generator = candidate([1,2,3,5])\n assert str(type(generator)) == \"\"\n assert [x for x in generator] == [1, 2, 3, 5]\n"],"entry_point":"f_16041405","intent":"convert a list `l` into a generator object","library":[],"docs":[]} {"task_id":18837607,"prompt":"def f_18837607(oldlist, removelist):\n\treturn ","suffix":"","canonical_solution":"[v for i, v in enumerate(oldlist) if i not in removelist]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_18837607","intent":"remove elements from list `oldlist` that have an index number mentioned in list `removelist`","library":[],"docs":[]} {"task_id":4710067,"prompt":"def f_4710067():\n\treturn ","suffix":"","canonical_solution":"open('yourfile.txt', 'w')","test_start":"\ndef check(candidate):","test":["\n fw = candidate()\n assert fw.name == \"yourfile.txt\"\n assert fw.mode == 'w'\n"],"entry_point":"f_4710067","intent":"Open a file `yourfile.txt` in write mode","library":[],"docs":[]} {"task_id":7373219,"prompt":"def f_7373219(obj, attr):\n\treturn ","suffix":"","canonical_solution":"getattr(obj, attr)","test_start":"\ndef check(candidate):","test":["\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') == \"Adam\")\n assert(candidate(student, 'student_id') == 101)\n","\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 try:\n value = candidate(student, 'student_none')\n except: \n assert True\n"],"entry_point":"f_7373219","intent":"get attribute 'attr' from object `obj`","library":[],"docs":[]} {"task_id":8171751,"prompt":"def f_8171751():\n\treturn ","suffix":"","canonical_solution":"reduce(lambda a, b: a + b, (('aa',), ('bb',), ('cc',)))","test_start":"\nfrom functools import reduce\n\ndef check(candidate):","test":["\n assert candidate() == ('aa', 'bb', 'cc')\n"],"entry_point":"f_8171751","intent":"convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to tuple","library":["functools"],"docs":[{"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)+5). The left argument, x, is the accumulated value and the right argument, y, is the update value from the iterable. If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty. If initializer is not given and iterable contains only one item, the first item is returned. Roughly equivalent to: def reduce(function, iterable, initializer=None):\n it = iter(iterable)","title":"python.library.functools#functools.reduce"}]} {"task_id":8171751,"prompt":"def f_8171751():\n\treturn ","suffix":"","canonical_solution":"list(map(lambda a: a[0], (('aa',), ('bb',), ('cc',))))","test_start":"\ndef check(candidate):","test":["\n assert candidate() == ['aa', 'bb', 'cc']\n"],"entry_point":"f_8171751","intent":"convert tuple of tuples `(('aa',), ('bb',), ('cc',))` to list in one line","library":[],"docs":[]} {"task_id":28986489,"prompt":"def f_28986489(df):\n\t","suffix":"\n\treturn df","canonical_solution":"df['range'].replace(',', '-', inplace=True)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame({'range' : [\",\", \"(50,290)\", \",,,\"]})\n res = pd.DataFrame({'range' : [\"-\", \"(50,290)\", \",,,\"]})\n assert candidate(df).equals(res)\n"],"entry_point":"f_28986489","intent":"replace a characters in a column of a dataframe `df`","library":["pandas"],"docs":[{"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 with other values dynamically. This differs from updating with .loc or .iloc, which require you to specify a location to update with some value. Parameters ","title":"pandas.reference.api.pandas.dataframe.replace"}]} {"task_id":19339,"prompt":"def f_19339():\n\treturn ","suffix":"","canonical_solution":"zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4)])","test_start":"\ndef check(candidate):","test":["\n assert [a for a in candidate()] == [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]\n"],"entry_point":"f_19339","intent":"unzip the list `[('a', 1), ('b', 2), ('c', 3), ('d', 4)]`","library":[],"docs":[]} {"task_id":19339,"prompt":"def f_19339(original):\n\treturn ","suffix":"","canonical_solution":"([a for (a, b) in original], [b for (a, b) in original])","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_19339","intent":"unzip list `original`","library":[],"docs":[]} {"task_id":19339,"prompt":"def f_19339(original):\n\treturn ","suffix":"","canonical_solution":"((a for (a, b) in original), (b for (a, b) in original))","test_start":"\ndef check(candidate):","test":["\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] == [[], [], 5, 6, 1, 2, 3, 4]\n"],"entry_point":"f_19339","intent":"unzip list `original` and return a generator","library":[],"docs":[]} {"task_id":19339,"prompt":"def f_19339():\n\treturn ","suffix":"","canonical_solution":"zip(*[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)])","test_start":"\ndef check(candidate):","test":["\n assert list(candidate()) == [('a', 'b', 'c', 'd', 'e')]\n"],"entry_point":"f_19339","intent":"unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]`","library":[],"docs":[]} {"task_id":19339,"prompt":"def f_19339():\n\treturn ","suffix":"","canonical_solution":"list(zip_longest(('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e',)))","test_start":"\nfrom itertools import zip_longest\n\ndef check(candidate):","test":["\n assert(candidate() == [('a', 'b', 'c', 'd', 'e'), (1, 2, 3, 4, None)])\n"],"entry_point":"f_19339","intent":"unzip list `[('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', )]` and fill empty results with None","library":["itertools"],"docs":[{"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 exhausted. Roughly equivalent to: def zip_longest(*args, fillvalue=None):\n # zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-","title":"python.library.itertools#itertools.zip_longest"}]} {"task_id":1960516,"prompt":"def f_1960516():\n\treturn ","suffix":"","canonical_solution":"json.dumps('3.9')","test_start":"\nimport json\n\ndef check(candidate):","test":["\n data = candidate()\n assert json.loads(data) == '3.9'\n"],"entry_point":"f_1960516","intent":"encode `Decimal('3.9')` to a JSON string","library":["json"],"docs":[{"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 meaning as in dump(). Note Keys in key\/value pairs of JSON are always of the type str. When a dictionary is converted into JSON, all the keys of the dictionary are coerced to strings. As a result of this, if a dictionary is converted into JSON and then back into a dictionary, the dictionary may not equal the original one. That is, loads(dumps(x)) != x if x has non-string keys.","title":"python.library.json#json.dumps"}]} {"task_id":1024847,"prompt":"def f_1024847(d):\n\t","suffix":"\n\treturn d","canonical_solution":"d['mynewkey'] = 'mynewvalue'","test_start":"\ndef check(candidate):","test":["\n assert candidate({'key': 'value'}) == {'key': 'value', 'mynewkey': 'mynewvalue'}\n"],"entry_point":"f_1024847","intent":"Add key \"mynewkey\" to dictionary `d` with value \"mynewvalue\"","library":[],"docs":[]} {"task_id":1024847,"prompt":"def f_1024847(data):\n\t","suffix":"\n\treturn data","canonical_solution":"data.update({'a': 1, })","test_start":"\ndef check(candidate):","test":["\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n","\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n"],"entry_point":"f_1024847","intent":"Add key 'a' to dictionary `data` with value 1","library":[],"docs":[]} {"task_id":1024847,"prompt":"def f_1024847(data):\n\t","suffix":"\n\treturn data","canonical_solution":"data.update(dict(a=1))","test_start":"\ndef check(candidate):","test":["\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n","\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n"],"entry_point":"f_1024847","intent":"Add key 'a' to dictionary `data` with value 1","library":[],"docs":[]} {"task_id":1024847,"prompt":"def f_1024847(data):\n\t","suffix":"\n\treturn data","canonical_solution":"data.update(a=1)","test_start":"\ndef check(candidate):","test":["\n assert candidate({'key': 'value'}) == {'key': 'value', 'a': 1}\n","\n assert candidate({'key': 'value', 'a' : 2}) == {'key': 'value', 'a': 1}\n"],"entry_point":"f_1024847","intent":"Add key 'a' to dictionary `data` with value 1","library":[],"docs":[]} {"task_id":35837346,"prompt":"def f_35837346(matrix):\n\treturn ","suffix":"","canonical_solution":"max([max(i) for i in matrix])","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_35837346","intent":"find maximal value in matrix `matrix`","library":[],"docs":[]} {"task_id":20457038,"prompt":"def f_20457038(answer):\n\t","suffix":"\n\treturn answer","canonical_solution":"answer = str(round(answer, 2))","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_20457038","intent":"Round number `answer` to 2 precision after the decimal point","library":[],"docs":[]} {"task_id":2890896,"prompt":"def f_2890896(s):\n\t","suffix":"\n\treturn ip","canonical_solution":"ip = re.findall('[0-9]+(?:\\\\.[0-9]+){3}', s)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(\"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.15<\/body><\/html>\") == [\"165.91.15.131\"]\n","\n assert candidate(\"<html><head><title>Current IP Check<\/title><\/head><body>Current IP Address: 192.168.1.1 & this is another IP address: 192.168.1.2<\/body><\/html>\") == [\"192.168.1.1\", \"192.168.1.2\"]\n"],"entry_point":"f_2890896","intent":"extract ip address `ip` from an html string `s`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":29836836,"prompt":"def f_29836836(df):\n\treturn ","suffix":"","canonical_solution":"df.groupby('A').filter(lambda x: len(x) > 1)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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\n"],"entry_point":"f_29836836","intent":"filter dataframe `df` by values in column `A` that appear more than once","library":["pandas"],"docs":[{"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 operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ","title":"pandas.reference.api.pandas.dataframe.groupby"},{"function":"dataframegroupby.filter","text":"pandas.core.groupby.DataFrameGroupBy.filter DataFrameGroupBy.filter(func, dropna=True, *args, **kwargs)[source]\n \nReturn a copy of a DataFrame excluding filtered elements. Elements from groups are filtered if they do not satisfy the boolean criterion specified by func. Parameters ","title":"pandas.reference.api.pandas.core.groupby.dataframegroupby.filter"}]} {"task_id":2545397,"prompt":"def f_2545397(myfile):\n\treturn ","suffix":"","canonical_solution":"[x for x in myfile if x != '']","test_start":"\ndef check(candidate):","test":["\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() == \"hello\"\n"],"entry_point":"f_2545397","intent":"append each line in file `myfile` into a list","library":[],"docs":[]} {"task_id":2545397,"prompt":"def f_2545397():\n\t","suffix":"\n\treturn lst","canonical_solution":"lst = list(map(int, open('filename.txt').readlines()))","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_2545397","intent":"Get a list of integers `lst` from a file `filename.txt`","library":["pandas"],"docs":[]} {"task_id":35420052,"prompt":"def f_35420052(plt, mappable, ax3):\n\t","suffix":"\n\treturn plt","canonical_solution":"plt.colorbar(mappable=mappable, cax=ax3)","test_start":"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom obspy.core.trace import Trace\nfrom obspy.imaging.spectrogram import spectrogram\n\ndef check(candidate):","test":["\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.stats.sampling_rate\n\n #plot waveform (top subfigure) \n ax1.plot(t, spl1.data, 'k')\n\n #plot spectrogram (bottom subfigure)\n spl2 = spl1\n fig = spl2.spectrogram(show=False, axes=ax2, wlen=10)\n mappable = ax2.images[0]\n candidate(plt, mappable, ax3)\n \n im=ax2.images\n assert im[-1].colorbar is not None\n"],"entry_point":"f_35420052","intent":"add color bar with image `mappable` to plot `plt`","library":["matplotlib","numpy","obspy"],"docs":[{"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"}]} {"task_id":29903025,"prompt":"def f_29903025(df):\n\treturn ","suffix":"","canonical_solution":"Counter(' '.join(df['text']).split()).most_common(100)","test_start":"\nimport pandas as pd\nfrom collections import Counter\n \ndef check(candidate):","test":["\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),('is', 2),('a', 1),('high-level,', 1),('general-purpose', 1),\n ('programming', 1),('language.', 1),('Its', 1),('design', 1),('philosophy', 1),('emphasizes', 1),\n ('code', 1),('readability', 1),('with', 1), ('the', 1),('use', 1),('of', 1),('significant', 1),\n ('indentation.', 1),('dynamically-typed', 1),('and', 1),('garbage-collected.', 1)]\n"],"entry_point":"f_29903025","intent":"count most frequent 100 words in column 'text' of dataframe `df`","library":["collections","pandas"],"docs":[{"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: >>> Counter('abracadabra').most_common(3)\n[('a', 5), ('b', 2), ('r', 2)]","title":"python.library.collections#collections.Counter.most_common"}]} {"task_id":7378180,"prompt":"def f_7378180():\n\treturn ","suffix":"","canonical_solution":"list(itertools.combinations((1, 2, 3), 2))","test_start":"\nimport itertools\n\ndef check(candidate):","test":["\n assert candidate() == [(1, 2), (1, 3), (2, 3)]\n"],"entry_point":"f_7378180","intent":"generate all 2-element subsets of tuple `(1, 2, 3)`","library":["itertools"],"docs":[{"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 combination tuples will be produced in sorted order. Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each combination. Roughly equivalent to: def combinations(iterable, r):\n # combinations('ABCD', 2) --> AB AC AD BC BD CD","title":"python.library.itertools#itertools.combinations"}]} {"task_id":4530069,"prompt":"def f_4530069():\n\treturn ","suffix":"","canonical_solution":"datetime.now(pytz.utc)","test_start":"\nimport pytz\nimport time\nfrom datetime import datetime, timezone\n\ndef check(candidate):","test":["\n assert (candidate() - datetime(1970, 1, 1).replace(tzinfo=timezone.utc)).total_seconds() - time.time() <= 1\n"],"entry_point":"f_4530069","intent":"get a value of datetime.today() in the UTC time zone","library":["datetime","pytz","time"],"docs":[{"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, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz\u2019s time zone. This function is preferred over today() and utcnow().","title":"python.library.datetime#datetime.datetime.now"}]} {"task_id":4842956,"prompt":"def f_4842956(list1):\n\t","suffix":"\n\treturn list2","canonical_solution":"list2 = [x for x in list1 if x != []]","test_start":"\ndef check(candidate):","test":["\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n","\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n"],"entry_point":"f_4842956","intent":"Get a new list `list2`by removing empty list from a list of lists `list1`","library":[],"docs":[]} {"task_id":4842956,"prompt":"def f_4842956(list1):\n\t","suffix":"\n\treturn list2","canonical_solution":"list2 = [x for x in list1 if x]","test_start":"\ndef check(candidate):","test":["\n assert candidate([[\"a\"], [], [\"b\"]]) == [[\"a\"], [\"b\"]]\n","\n assert candidate([[], [1,2,3], [], [\"b\"]]) == [[1,2,3], [\"b\"]]\n"],"entry_point":"f_4842956","intent":"Create `list2` to contain the lists from list `list1` excluding the empty lists from `list1`","library":[],"docs":[]} {"task_id":9262278,"prompt":"def f_9262278(data):\n\treturn ","suffix":"","canonical_solution":"HttpResponse(data, content_type='application\/json')","test_start":"\nimport os\nimport json\nfrom django.http import HttpResponse\nfrom django.conf import settings\nif not settings.configured:\n settings.configure(DEBUG=True)\n\ndef check(candidate):","test":["\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"],"entry_point":"f_9262278","intent":"Django response with JSON `data`","library":["django","json","os"],"docs":[{"function":"HttpResponse","text":"class HttpResponse","title":"django.ref.request-response#django.http.HttpResponse"}]} {"task_id":17284947,"prompt":"def f_17284947(example_str):\n\treturn ","suffix":"","canonical_solution":"re.findall('(.*?)\\\\[.*?\\\\]', example_str)","test_start":"\nimport re \n\ndef check(candidate): ","test":["\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"],"entry_point":"f_17284947","intent":"get all text that is not enclosed within square brackets in string `example_str`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":17284947,"prompt":"def f_17284947(example_str):\n\treturn ","suffix":"","canonical_solution":"re.findall('(.*?)(?:\\\\[.*?\\\\]|$)', example_str)","test_start":"\nimport re \n\ndef check(candidate): ","test":["\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"],"entry_point":"f_17284947","intent":"Use a regex to get all text in a string `example_str` that is not surrounded by square brackets","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":14182339,"prompt":"def f_14182339():\n\treturn ","suffix":"","canonical_solution":"re.findall('\\\\(.+?\\\\)|\\\\w', '(zyx)bc')","test_start":"\nimport re \n\ndef check(candidate): ","test":["\n assert candidate() == ['(zyx)', 'b', 'c']\n"],"entry_point":"f_14182339","intent":"get whatever is between parentheses as a single match, and any char outside as an individual match in string '(zyx)bc'","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":14182339,"prompt":"def f_14182339():\n\treturn ","suffix":"","canonical_solution":"re.findall('\\\\((.*?)\\\\)|(\\\\w)', '(zyx)bc')","test_start":"\nimport re \n\ndef check(candidate): ","test":["\n assert candidate() == [('zyx', ''), ('', 'b'), ('', 'c')]\n"],"entry_point":"f_14182339","intent":"match regex '\\\\((.*?)\\\\)|(\\\\w)' with string '(zyx)bc'","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":14182339,"prompt":"def f_14182339():\n\treturn ","suffix":"","canonical_solution":"re.findall('\\\\(.*?\\\\)|\\\\w', '(zyx)bc')","test_start":"\nimport re \n\ndef check(candidate): ","test":["\n assert candidate() == ['(zyx)', 'b', 'c']\n"],"entry_point":"f_14182339","intent":"match multiple regex patterns with the alternation operator `|` in a string `(zyx)bc`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":7126916,"prompt":"def f_7126916(elements):\n\t","suffix":"\n\treturn elements","canonical_solution":"elements = ['%{0}%'.format(element) for element in elements]","test_start":"\ndef check(candidate): ","test":["\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"],"entry_point":"f_7126916","intent":"formate each string cin list `elements` into pattern '%{0}%'","library":[],"docs":[]} {"task_id":3595685,"prompt":"def f_3595685():\n\treturn ","suffix":"","canonical_solution":"subprocess.Popen(['background-process', 'arguments'])","test_start":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n"],"entry_point":"f_3595685","intent":"Open a background process 'background-process' with arguments 'arguments'","library":["subprocess"],"docs":[{"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=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) \nExecute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen([\"\/usr\/bin\/git\", \"commit\", \"-m\", \"Fixes a bug.\"])\n On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess","title":"python.library.subprocess#subprocess.Popen"}]} {"task_id":18453566,"prompt":"def f_18453566(mydict, mykeys):\n\treturn ","suffix":"","canonical_solution":"[mydict[x] for x in mykeys]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_18453566","intent":"get list of values from dictionary 'mydict' w.r.t. list of keys 'mykeys'","library":[],"docs":[]} {"task_id":12692135,"prompt":"def f_12692135():\n\treturn ","suffix":"","canonical_solution":"dict([('Name', 'Joe'), ('Age', 22)])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == {'Name': 'Joe', 'Age': 22}\n"],"entry_point":"f_12692135","intent":"convert list `[('Name', 'Joe'), ('Age', 22)]` into a dictionary","library":[],"docs":[]} {"task_id":14401047,"prompt":"def f_14401047(data):\n\treturn ","suffix":"","canonical_solution":"data.mean(axis=1).reshape(data.shape[0], -1)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_14401047","intent":"average each two columns of array `data`","library":["numpy"],"docs":[{"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","title":"numpy.reference.generated.numpy.ndarray.mean"},{"function":"numpy.ndarray.reshape","text":"numpy.ndarray.reshape method ndarray.reshape(shape, order='C')\n \nReturns an array containing the same data with a new shape. Refer to numpy.reshape for full documentation. See also numpy.reshape\n\nequivalent function Notes Unlike the free function numpy.reshape, this method on ndarray allows the elements of the shape parameter to be passed in as separate arguments. For example, a.reshape(10, 11) is equivalent to a.reshape((10, 11)).","title":"numpy.reference.generated.numpy.ndarray.reshape"}]} {"task_id":18886596,"prompt":"def f_18886596(s):\n\treturn ","suffix":"","canonical_solution":"s.replace('\"', '\\\"')","test_start":"\ndef check(candidate):","test":["\n s = 'This sentence has some \"quotes\" in it'\n assert candidate(s) == 'This sentence has some \\\"quotes\\\" in it'\n"],"entry_point":"f_18886596","intent":"double backslash escape all double quotes in string `s`","library":[],"docs":[]} {"task_id":5932059,"prompt":"def f_5932059(s):\n\treturn ","suffix":"","canonical_solution":"re.split('(\\\\W+)', s)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n s = \"this is a\\nsentence\"\n assert candidate(s) == ['this', ' ', 'is', ' ', 'a', '\\n', 'sentence']\n"],"entry_point":"f_5932059","intent":"split a string `s` into a list of words and whitespace","library":["re"],"docs":[{"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 splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}]} {"task_id":9938130,"prompt":"def f_9938130(df):\n\treturn ","suffix":"","canonical_solution":"df.plot(kind='barh', stacked=True)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_9938130","intent":"plotting stacked barplots on a panda data frame `df`","library":["pandas"],"docs":[{"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"}]} {"task_id":35945473,"prompt":"def f_35945473(myDictionary):\n\treturn ","suffix":"","canonical_solution":"{i[1]: i[0] for i in list(myDictionary.items())}","test_start":"\ndef check(candidate):","test":["\n assert candidate({'a' : 'b', 'c' : 'd'}) == {'b': 'a', 'd': 'c'}\n"],"entry_point":"f_35945473","intent":"reverse the keys and values in a dictionary `myDictionary`","library":[],"docs":[]} {"task_id":30729735,"prompt":"def f_30729735(myList):\n\treturn ","suffix":"","canonical_solution":"[i for i, j in enumerate(myList) if 'how' in j.lower() or 'what' in j.lower()]","test_start":"\ndef check(candidate):","test":["\n assert candidate(['abc', 'how', 'what', 'def']) == [1, 2]\n"],"entry_point":"f_30729735","intent":"finding the index of elements containing substring 'how' and 'what' in a list of strings 'myList'.","library":[],"docs":[]} {"task_id":1303243,"prompt":"def f_1303243(obj):\n\treturn ","suffix":"","canonical_solution":"isinstance(obj, str)","test_start":"\ndef check(candidate):","test":["\n assert candidate('python3') == True\n","\n assert candidate(1.23) == False\n"],"entry_point":"f_1303243","intent":"check if object `obj` is a string","library":[],"docs":[]} {"task_id":1303243,"prompt":"def f_1303243(o):\n\treturn ","suffix":"","canonical_solution":"isinstance(o, str)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_1303243","intent":"check if object `o` is a string","library":[],"docs":[]} {"task_id":1303243,"prompt":"def f_1303243(o):\n\treturn ","suffix":"","canonical_solution":"(type(o) is str)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_1303243","intent":"check if object `o` is a string","library":[],"docs":[]} {"task_id":1303243,"prompt":"def f_1303243(obj_to_test):\n\treturn ","suffix":"","canonical_solution":"isinstance(obj_to_test, str)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_1303243","intent":"check if `obj_to_test` is a string","library":[],"docs":[]} {"task_id":8177079,"prompt":"def f_8177079(list1, list2):\n\t","suffix":"\n\treturn ","canonical_solution":"list2.extend(list1)","test_start":"\ndef check(candidate):","test":["\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, 5, 6, 1, 2, 3]\n"],"entry_point":"f_8177079","intent":"append list `list1` to `list2`","library":[],"docs":[]} {"task_id":8177079,"prompt":"def f_8177079(mylog, list1):\n\t","suffix":"\n\treturn ","canonical_solution":"list1.extend(mylog)","test_start":"\ndef check(candidate):","test":["\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, 5, 6, 1, 2, 3]\n"],"entry_point":"f_8177079","intent":"append list `mylog` to `list1`","library":[],"docs":[]} {"task_id":8177079,"prompt":"def f_8177079(a, c):\n\t","suffix":"\n\treturn ","canonical_solution":"c.extend(a)","test_start":"\ndef check(candidate):","test":["\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, 5, 6, 1, 2, 3]\n"],"entry_point":"f_8177079","intent":"append list `a` to `c`","library":[],"docs":[]} {"task_id":8177079,"prompt":"def f_8177079(mylog, list1):\n\t","suffix":"\n\treturn ","canonical_solution":"for line in mylog:\n\t list1.append(line)","test_start":"\ndef check(candidate):","test":["\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, 5, 6, 1, 2, 3]\n"],"entry_point":"f_8177079","intent":"append items in list `mylog` to `list1`","library":[],"docs":[]} {"task_id":4126227,"prompt":"def f_4126227(a, b):\n\t","suffix":"\n\treturn ","canonical_solution":"b.append((a[0][0], a[0][2]))","test_start":"\ndef check(candidate):","test":["\n a = [(1,2,3),(4,5,6)]\n b = [(0,0)]\n candidate(a, b)\n assert(b == [(0, 0), (1, 3)])\n"],"entry_point":"f_4126227","intent":"append a tuple of elements from list `a` with indexes '[0][0] [0][2]' to list `b`","library":[],"docs":[]} {"task_id":34902378,"prompt":"def f_34902378(app):\n\t","suffix":"\n\treturn ","canonical_solution":"app.config['SECRET_KEY'] = 'Your_secret_string'","test_start":"\nfrom flask import Flask\n\ndef check(candidate):","test":["\n app = Flask(\"test\")\n candidate(app)\n assert app.config['SECRET_KEY'] == 'Your_secret_string'\n"],"entry_point":"f_34902378","intent":"Initialize `SECRET_KEY` in flask config with `Your_secret_string `","library":["flask"],"docs":[{"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"}]} {"task_id":22799300,"prompt":"def f_22799300(out):\n\treturn ","suffix":"","canonical_solution":"pd.DataFrame(out.tolist(), columns=['out-1', 'out-2'], index=out.index)","test_start":"\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\n\ndef check(candidate):","test":["\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"],"entry_point":"f_22799300","intent":"unpack a series of tuples in pandas `out` into a DataFrame with column names 'out-1' and 'out-2'","library":["numpy","pandas","scipy"],"docs":[{"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 operations align on both row and column labels. Can be thought of as a dict-like container for Series objects. The primary pandas data structure. Parameters ","title":"pandas.reference.api.pandas.dataframe"}]} {"task_id":1762484,"prompt":"def f_1762484(stocks_list):\n\treturn ","suffix":"","canonical_solution":"[x for x in range(len(stocks_list)) if stocks_list[x] == 'MSFT']","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_1762484","intent":"find the index of an element 'MSFT' in a list `stocks_list`","library":[],"docs":[]} {"task_id":3464359,"prompt":"def f_3464359(ax, labels):\n\treturn ","suffix":"","canonical_solution":"ax.set_xticklabels(labels, rotation=45)","test_start":"\nimport matplotlib.pyplot as plt \n\ndef check(candidate):","test":["\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"],"entry_point":"f_3464359","intent":"rotate the xtick `labels` of matplotlib plot `ax` by `45` degrees to make long labels readable","library":["matplotlib"],"docs":[{"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_xticks. Otherwise, the labels may end up in unexpected positions. Parameters ","title":"matplotlib._as_gen.matplotlib.axes.axes.set_xticklabels"}]} {"task_id":875968,"prompt":"def f_875968(s):\n\treturn ","suffix":"","canonical_solution":"re.sub('[^\\\\w]', ' ', s)","test_start":"\nimport re\n\ndef check(candidate):","test":["\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"],"entry_point":"f_875968","intent":"remove symbols from a string `s`","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":34750084,"prompt":"def f_34750084(s):\n\treturn ","suffix":"","canonical_solution":"re.findall(\"'\\\\\\\\[0-7]{1,3}'\", s)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate(r\"char x = '\\077';\") == [\"'\\\\077'\"]\n"],"entry_point":"f_34750084","intent":"Find octal characters matches from a string `s` using regex","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":13209288,"prompt":"def f_13209288(input):\n\treturn ","suffix":"","canonical_solution":"re.split(r'[ ](?=[A-Z]+\\b)', input)","test_start":"\nimport re\n\ndef check(candidate):","test":["\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"],"entry_point":"f_13209288","intent":"split string `input` based on occurrences of regex pattern '[ ](?=[A-Z]+\\\\b)'","library":["re"],"docs":[{"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 splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}]} {"task_id":13209288,"prompt":"def f_13209288(input):\n\treturn ","suffix":"","canonical_solution":"re.split('[ ](?=[A-Z])', input)","test_start":"\nimport re\n\ndef check(candidate):","test":["\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"],"entry_point":"f_13209288","intent":"Split string `input` at every space followed by an upper-case letter","library":["re"],"docs":[{"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 splits occur, and the remainder of the string is returned as the final element of the list. >>> re.split(r'\\W+', 'Words, words, words.')\n['Words', 'words', 'words', '']","title":"python.library.re#re.split"}]} {"task_id":24642040,"prompt":"def f_24642040(url, files, headers, data):\n\treturn ","suffix":"","canonical_solution":"requests.post(url, files=files, headers=headers, data=data)","test_start":"\nimport requests\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\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"],"entry_point":"f_24642040","intent":"send multipart encoded file `files` to url `url` with headers `headers` and metadata `data`","library":["requests"],"docs":[]} {"task_id":4290716,"prompt":"def f_4290716(filename, bytes_):\n\treturn ","suffix":"","canonical_solution":"open(filename, 'wb').write(bytes_)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_4290716","intent":"write bytes `bytes_` to a file `filename` in python 3","library":[],"docs":[]} {"task_id":33078554,"prompt":"def f_33078554(lst, dct):\n\treturn ","suffix":"","canonical_solution":"[dct[k] for k in lst]","test_start":"\ndef check(candidate):","test":["\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': 3}) == [5, 3, 3, 3]\n"],"entry_point":"f_33078554","intent":"get a list from a list `lst` with values mapped into a dictionary `dct`","library":[],"docs":[]} {"task_id":15247628,"prompt":"def f_15247628(x):\n\treturn ","suffix":"","canonical_solution":"x['name'][x.duplicated('name')]","test_start":"\nimport pandas as pd \n\ndef check(candidate): ","test":["\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 assert candidate(pd.DataFrame([{'name': 'willy', 'age': 11}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == ['willy'] \n","\n assert candidate(pd.DataFrame([{'name': 'Willy', 'age': 11}, {'name': 'willy', 'age': 11}, {'name': 'zoe', 'age': 10}])).tolist() == []\n"],"entry_point":"f_15247628","intent":"find duplicate names in column 'name' of the dataframe `x`","library":["pandas"],"docs":[{"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"}]} {"task_id":783897,"prompt":"def f_783897():\n\treturn ","suffix":"","canonical_solution":"round(1.923328437452, 3)","test_start":"\ndef check(candidate): ","test":["\n assert candidate() == 1.923\n"],"entry_point":"f_783897","intent":"truncate float 1.923328437452 to 3 decimal places","library":[],"docs":[]} {"task_id":22859493,"prompt":"def f_22859493(li):\n\treturn ","suffix":"","canonical_solution":"sorted(li, key=lambda x: datetime.strptime(x[1], '%d\/%m\/%Y'), reverse=True)","test_start":"\nfrom datetime import datetime\n\ndef check(candidate): ","test":["\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', '03\/08\/2012', 'job']]) == [['name', '03\/08\/2012', 'job'], ['name', '02\/05\/2012', 'job'], ['name', '01\/03\/2012', 'job']] \n","\n assert candidate([['name', '01\/03\/2012', 'job'], ['name', '02\/03\/2012', 'job'], ['name', '03\/03\/2012', 'job']]) == [['name', '03\/03\/2012', 'job'], ['name', '02\/03\/2012', 'job'], ['name', '01\/03\/2012', 'job']] \n","\n assert candidate([['name', '03\/03\/2012', 'job'], ['name', '03\/03\/2012', 'job'], ['name', '03\/03\/2012', 'job']]) == [['name', '03\/03\/2012', 'job'], ['name', '03\/03\/2012', 'job'], ['name', '03\/03\/2012', 'job']] \n"],"entry_point":"f_22859493","intent":"sort list `li` in descending order based on the date value in second element of each list in list `li`","library":["datetime"],"docs":[{"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\u2019t be parsed by time.strptime() or if it returns a value which isn\u2019t a time tuple. For a complete list of formatting directives, see strftime() and strptime() Behavior.","title":"python.library.datetime#datetime.datetime.strptime"}]} {"task_id":29394552,"prompt":"def f_29394552(ax):\n\t","suffix":"\n\treturn ","canonical_solution":"ax.set_rlabel_position(135)","test_start":"\nimport matplotlib.pyplot as plt \n\ndef check(candidate): ","test":["\n ax = plt.subplot(111, polar=True)\n candidate(ax)\n assert ax.properties()['rlabel_position'] == 135.0\n"],"entry_point":"f_29394552","intent":"place the radial ticks in plot `ax` at 135 degrees","library":["matplotlib"],"docs":[{"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.set_rlabel_position"}]} {"task_id":3320406,"prompt":"def f_3320406(my_path):\n\treturn ","suffix":"","canonical_solution":"os.path.isabs(my_path)","test_start":"\nimport os\n\ndef check(candidate): ","test":["\n assert candidate('.') == False \n","\n assert candidate('\/') == True \n","\n assert candidate('\/usr') == True\n"],"entry_point":"f_3320406","intent":"check if path `my_path` is an absolute path","library":["os"],"docs":[{"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":"python.library.os.path#os.path.isabs"}]} {"task_id":2212433,"prompt":"def f_2212433(yourdict):\n\treturn ","suffix":"","canonical_solution":"len(list(yourdict.keys()))","test_start":"\ndef check(candidate): ","test":["\n assert candidate({'a': 1, 'b': 2, 'c': 3}) == 3 \n","\n assert candidate({'a': 2, 'c': 3}) == 2\n"],"entry_point":"f_2212433","intent":"get number of keys in dictionary `yourdict`","library":[],"docs":[]} {"task_id":2212433,"prompt":"def f_2212433(yourdictfile):\n\treturn ","suffix":"","canonical_solution":"len(set(open(yourdictfile).read().split()))","test_start":"\ndef check(candidate): ","test":["\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"],"entry_point":"f_2212433","intent":"count the number of keys in dictionary `yourdictfile`","library":[],"docs":[]} {"task_id":20067636,"prompt":"def f_20067636(df):\n\treturn ","suffix":"","canonical_solution":"df.groupby('id').first()","test_start":"\nimport pandas as pd \n\ndef check(candidate): ","test":["\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() == {'value': {1: 'first', 2: 'first', 3: 'first', 4: 'second', 5: 'first', 6: 'first', 7: 'fourth'}}\n"],"entry_point":"f_20067636","intent":"pandas dataframe `df` get first row of each group by 'id'","library":["pandas"],"docs":[{"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 operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ","title":"pandas.reference.api.pandas.dataframe.groupby"}]} {"task_id":40924332,"prompt":"def f_40924332(df):\n\treturn ","suffix":"","canonical_solution":"pd.concat([df[0].apply(pd.Series), df[1]], axis=1)","test_start":"\nimport numpy as np\nimport pandas as pd \n\ndef check(callerFunction):","test":["\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=[0,1,2,1]))\n","\n assert callerFunction(pd.DataFrame([[[8, 10, 12]], [[7, 9, 11], 'B']])).equals(pd.DataFrame([[8,10,12,None], [7,9,11,'B']], columns=[0,1,2,1]))\n"],"entry_point":"f_40924332","intent":"split a list in first column into multiple columns keeping other columns as well in pandas data frame `df`","library":["numpy","pandas"],"docs":[{"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. Can also add a layer of hierarchical indexing on the concatenation axis, which may be useful if the labels are the same (or overlapping) on the passed axis number. Parameters ","title":"pandas.reference.api.pandas.concat"},{"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\u2019s index (axis=0) or the DataFrame\u2019s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument. Parameters ","title":"pandas.reference.api.pandas.dataframe.apply"}]} {"task_id":30759776,"prompt":"def f_30759776(data):\n\treturn ","suffix":"","canonical_solution":"re.findall('src=\"js\/([^\"]*\\\\bjquery\\\\b[^\"]*)\"', data)","test_start":"\nimport re \n\ndef check(candidate):","test":["\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\/abc_core.js\"\/> <script type=\"text\/javascript\" src=\"js\/abc_explore.js\"\/><script type=\"text\/javascript\" src=\"js\/abc_qaa.js\"\/>'\n assert candidate(data) == ['jquery-1.9.1.min.js', 'jquery-migrate-1.2.1.min.js', 'jquery-ui.min.js']\n"],"entry_point":"f_30759776","intent":"extract attributes 'src=\"js\/([^\"]*\\\\bjquery\\\\b[^\"]*)\"' from string `data`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":25388796,"prompt":"def f_25388796():\n\treturn ","suffix":"","canonical_solution":"sum(int(float(item)) for item in [_f for _f in ['', '3.4', '', '', '1.0'] if _f])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 4\n"],"entry_point":"f_25388796","intent":"Sum integers contained in strings in list `['', '3.4', '', '', '1.0']`","library":[],"docs":[]} {"task_id":804995,"prompt":"def f_804995():\n\treturn ","suffix":"","canonical_solution":"subprocess.Popen(['c:\\\\Program Files\\\\VMware\\\\VMware Server\\\\vmware-cmd.bat'])","test_start":"\nimport subprocess\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n subprocess.Popen = Mock(return_value = 0)\n assert candidate() == 0\n"],"entry_point":"f_804995","intent":"Call a subprocess with arguments `c:\\\\Program Files\\\\VMware\\\\VMware Server\\\\vmware-cmd.bat` that may contain spaces","library":["subprocess"],"docs":[{"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=False, pass_fds=(), *, group=None, extra_groups=None, user=None, umask=-1, encoding=None, errors=None, text=None) \nExecute a child program in a new process. On POSIX, the class uses os.execvp()-like behavior to execute the child program. On Windows, the class uses the Windows CreateProcess() function. The arguments to Popen are as follows. args should be a sequence of program arguments or else a single string or path-like object. By default, the program to execute is the first item in args if args is a sequence. If args is a string, the interpretation is platform-dependent and described below. See the shell and executable arguments for additional differences from the default behavior. Unless otherwise stated, it is recommended to pass args as a sequence. An example of passing some arguments to an external program as a sequence is: Popen([\"\/usr\/bin\/git\", \"commit\", \"-m\", \"Fixes a bug.\"])\n On POSIX, if args is a string, the string is interpreted as the name or path of the program to execute. However, this can only be done if not passing arguments to the program. Note It may not be obvious how to break a shell command into a sequence of arguments, especially in complex cases. shlex.split() can illustrate how to determine the correct tokenization for args: >>> import shlex, subprocess","title":"python.library.subprocess#subprocess.Popen"}]} {"task_id":26441253,"prompt":"def f_26441253(q):\n\t","suffix":"\n\treturn q","canonical_solution":"for n in [1,3,4,2]: q.put((-n, n))","test_start":"\nfrom queue import PriorityQueue\n\ndef check(candidate):","test":["\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"],"entry_point":"f_26441253","intent":"reverse a priority queue `q` in python without using classes","library":["queue"],"docs":[{"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 exception if no free slot was available within that time. Otherwise (block is false), put an item on the queue if a free slot is immediately available, else raise the Full exception (timeout is ignored in that case).","title":"python.library.queue#queue.Queue.put"}]} {"task_id":18897261,"prompt":"def f_18897261(df):\n\treturn ","suffix":"","canonical_solution":"df['group'].plot(kind='bar', color=['r', 'g', 'b', 'r', 'g', 'b', 'r'])","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n df = pd.DataFrame([1, 3, 4, 5, 7, 9], columns = ['group'])\n a = candidate(df)\n assert 'AxesSubplot' in str(type(a))\n"],"entry_point":"f_18897261","intent":"make a barplot of data in column `group` of dataframe `df` colour-coded according to list `color`","library":["pandas"],"docs":[{"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"}]} {"task_id":373194,"prompt":"def f_373194(data):\n\treturn ","suffix":"","canonical_solution":"re.findall('([a-fA-F\\\\d]{32})', data)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate('6f96cfdfe5ccc627cadf24b41725caa4 gorilla') == ['6f96cfdfe5ccc627cadf24b41725caa4']\n"],"entry_point":"f_373194","intent":"find all matches of regex pattern '([a-fA-F\\\\d]{32})' in string `data`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":518021,"prompt":"def f_518021(my_list):\n\treturn ","suffix":"","canonical_solution":"len(my_list)","test_start":"\ndef check(candidate):","test":["\n assert candidate([]) == 0\n","\n assert candidate([1]) == 1\n","\n assert candidate([1, 2]) == 2\n"],"entry_point":"f_518021","intent":"Get the length of list `my_list`","library":[],"docs":[]} {"task_id":518021,"prompt":"def f_518021(l):\n\treturn ","suffix":"","canonical_solution":"len(l)","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n assert candidate([]) == 0\n","\n assert candidate(np.array([1])) == 1\n","\n assert candidate(np.array([1, 2])) == 2\n"],"entry_point":"f_518021","intent":"Getting the length of array `l`","library":["numpy"],"docs":[]} {"task_id":518021,"prompt":"def f_518021(s):\n\treturn ","suffix":"","canonical_solution":"len(s)","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n assert candidate([]) == 0\n","\n assert candidate(np.array([1])) == 1\n","\n assert candidate(np.array([1, 2])) == 2\n"],"entry_point":"f_518021","intent":"Getting the length of array `s`","library":["numpy"],"docs":[]} {"task_id":518021,"prompt":"def f_518021(my_tuple):\n\treturn ","suffix":"","canonical_solution":"len(my_tuple)","test_start":"\ndef check(candidate):","test":["\n assert candidate(()) == 0\n","\n assert candidate(('aa', 'wfseg', '')) == 3\n","\n assert candidate(('apple',)) == 1\n"],"entry_point":"f_518021","intent":"Getting the length of `my_tuple`","library":[],"docs":[]} {"task_id":518021,"prompt":"def f_518021(my_string):\n\treturn ","suffix":"","canonical_solution":"len(my_string)","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"sedfgbdjofgljnh\") == 15\n","\n assert candidate(\" \") == 13\n","\n assert candidate(\"vsdh4'cdf'\") == 10\n"],"entry_point":"f_518021","intent":"Getting the length of `my_string`","library":[],"docs":[]} {"task_id":40452956,"prompt":"def f_40452956():\n\treturn ","suffix":"","canonical_solution":"b'\\\\a'.decode('unicode-escape')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == '\\x07'\n"],"entry_point":"f_40452956","intent":"remove escape character from string \"\\\\a\"","library":[],"docs":[]} {"task_id":8687018,"prompt":"def f_8687018():\n\treturn ","suffix":"","canonical_solution":"\"\"\"obama\"\"\".replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 'oabmb'\n"],"entry_point":"f_8687018","intent":"replace each 'a' with 'b' and each 'b' with 'a' in the string 'obama' in a single pass.","library":[],"docs":[]} {"task_id":303200,"prompt":"def f_303200():\n\t","suffix":"\n\treturn ","canonical_solution":"shutil.rmtree('\/folder_name')","test_start":"\nimport os\nimport shutil\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n shutil.rmtree = Mock()\n os.walk = Mock(return_value = [])\n candidate()\n assert os.walk('\/') == []\n"],"entry_point":"f_303200","intent":"remove directory tree '\/folder_name'","library":["os","shutil"],"docs":[{"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, such errors are handled by calling a handler specified by onerror or, if that is omitted, they raise an exception. Note On platforms that support the necessary fd-based functions a symlink attack resistant version of rmtree() is used by default. On other platforms, the rmtree() implementation is susceptible to a symlink attack: given proper timing and circumstances, attackers can manipulate symlinks on the filesystem to delete files they wouldn\u2019t be able to access otherwise. Applications can use the rmtree.avoids_symlink_attacks function attribute to determine which case applies. If onerror is provided, it must be a callable that accepts three parameters: function, path, and excinfo. The first parameter, function, is the function which raised the exception; it depends on the platform and implementation. The second parameter, path, will be the path name passed to function. The third parameter, excinfo, will be the exception information returned by sys.exc_info(). Exceptions raised by onerror will not be caught. Raises an auditing event shutil.rmtree with argument path. Changed in version 3.3: Added a symlink attack resistant version that is used automatically if platform supports fd-based functions. Changed in version 3.8: On Windows, will no longer delete the contents of a directory junction before removing the junction. \nrmtree.avoids_symlink_attacks \nIndicates whether the current platform and implementation provides a symlink attack resistant version of rmtree(). Currently this is only true for platforms supporting fd-based directory access functions. New in version 3.3.","title":"python.library.shutil#shutil.rmtree"}]} {"task_id":13740672,"prompt":"def f_13740672(data):\n\t","suffix":"\n\treturn data","canonical_solution":"\n def weekday(i):\n if i >=1 and i <= 5: return True\n else: return False\n data['weekday'] = data['my_dt'].apply(lambda x: weekday(x))\n","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_13740672","intent":"create a new column `weekday` in pandas data frame `data` based on the values in column `my_dt`","library":["pandas"],"docs":[{"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\u2019s index (axis=0) or the DataFrame\u2019s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument. Parameters ","title":"pandas.reference.api.pandas.dataframe.apply"}]} {"task_id":20950650,"prompt":"def f_20950650(x):\n\treturn ","suffix":"","canonical_solution":"sorted(x, key=x.get, reverse=True)","test_start":"\nfrom collections import Counter\n\ndef check(candidate):","test":["\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 candidate(x) == ['red', 'green', 'blue']\n"],"entry_point":"f_20950650","intent":"reverse sort Counter `x` by values","library":["collections"],"docs":[]} {"task_id":20950650,"prompt":"def f_20950650(x):\n\treturn ","suffix":"","canonical_solution":"sorted(list(x.items()), key=lambda pair: pair[1], reverse=True)","test_start":"\nfrom collections import Counter\n\ndef check(candidate):","test":["\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\", 'red': \"r\", 'green': \"g\"})\n assert candidate(x) == [('red', \"r\"), ('green', \"g\"), ('blue', \"b\")]\n"],"entry_point":"f_20950650","intent":"reverse sort counter `x` by value","library":["collections"],"docs":[]} {"task_id":9775297,"prompt":"def f_9775297(a, b):\n\treturn ","suffix":"","canonical_solution":"np.vstack((a, b))","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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(candidate(a, b), np.array([[1, 2.45, 3], [4, 0.55, 612], [988, 8, 7], [6, 512, 4]]))\n"],"entry_point":"f_9775297","intent":"append a numpy array 'b' to a numpy array 'a'","library":["numpy"],"docs":[{"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 sense for arrays with up to 3 dimensions. For instance, for pixel-data with a height (first axis), width (second axis), and r\/g\/b channels (third axis). The functions concatenate, stack and block provide more general stacking and concatenation operations. Parameters ","title":"numpy.reference.generated.numpy.vstack"}]} {"task_id":21887754,"prompt":"def f_21887754(a, b):\n\treturn ","suffix":"","canonical_solution":"np.concatenate((a, b), axis=0)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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_equal(candidate(a, b), np.array([[1, 2.45, 3], [4, 0.55, 612], [988, 8, 7], [6, 512, 4]]))\n"],"entry_point":"f_21887754","intent":"numpy concatenate two arrays `a` and `b` along the first axis","library":["numpy"],"docs":[{"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"}]} {"task_id":21887754,"prompt":"def f_21887754(a, b):\n\treturn ","suffix":"","canonical_solution":"np.concatenate((a, b), axis=1)","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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_equal(candidate(a, b), np.array([[1, 2.45, 3, 988, 8, 7], [4, 0.55, 612, 6, 512, 4]]))\n"],"entry_point":"f_21887754","intent":"numpy concatenate two arrays `a` and `b` along the second axis","library":["numpy"],"docs":[{"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"}]} {"task_id":21887754,"prompt":"def f_21887754(a, b):\n\treturn ","suffix":"","canonical_solution":"np.r_[(a[None, :], b[None, :])]","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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_equal(candidate(a, b), np.array([[[1, 2.45, 3], [4, 0.55, 612]], [[988, 8 , 7], [6, 512, 4]]]))\n"],"entry_point":"f_21887754","intent":"numpy concatenate two arrays `a` and `b` along the first axis","library":["numpy"],"docs":[{"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 them along their first axis. If the index expression contains slice notation or scalars then create a 1-D array with a range indicated by the slice notation. If slice notation is used, the syntax start:stop:step is equivalent to np.arange(start, stop, step) inside of the brackets. However, if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive. In other words start:stop:stepj is interpreted as np.linspace(start, stop, step, endpoint=1) inside of the brackets. After expansion of slice notation, all comma separated sequences are concatenated together. Optional character strings placed as the first element of the index expression can be used to change the output. The strings \u2018r\u2019 or \u2018c\u2019 result in matrix output. If the result is 1-D and \u2018r\u2019 is specified a 1 x N (row) matrix is produced. If the result is 1-D and \u2018c\u2019 is specified, then a N x 1 (column) matrix is produced. If the result is 2-D then both provide the same matrix result. A string integer specifies which axis to stack multiple comma separated arrays along. A string of two comma-separated integers allows indication of the minimum number of dimensions to force each entry into as the second integer (the axis to concatenate along is still the first integer). A string with three comma-separated integers allows specification of the axis to concatenate along, the minimum number of dimensions to force the entries to, and which axis should contain the start of the arrays which are less than the specified number of dimensions. In other words the third integer allows you to specify where the 1\u2019s should be placed in the shape of the arrays that have their shapes upgraded. By default, they are placed in the front of the shape tuple. The third argument allows you to specify where the start of the array should be instead. Thus, a third argument of \u20180\u2019 would place the 1\u2019s at the end of the array shape. Negative integers specify where in the new shape tuple the last dimension of upgraded arrays should be placed, so the default is \u2018-1\u2019. Parameters ","title":"numpy.reference.generated.numpy.r_"}]} {"task_id":21887754,"prompt":"def f_21887754(a, b):\n\treturn ","suffix":"","canonical_solution":"np.array((a, b))","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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_equal(candidate(a, b), np.array([[[1, 2.45, 3], [4, 0.55, 612]], [[988, 8 , 7], [6, 512, 4]]]))\n"],"entry_point":"f_21887754","intent":"numpy concatenate two arrays `a` and `b` along the first axis","library":["numpy"],"docs":[{"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"}]} {"task_id":2805231,"prompt":"def f_2805231():\n\treturn ","suffix":"","canonical_solution":"socket.getaddrinfo('google.com', 80)","test_start":"\nimport socket\n\ndef check(candidate):","test":["\n res = candidate()\n assert all([(add[4][1] == 80) for add in res])\n"],"entry_point":"f_2805231","intent":"fetch address information for host 'google.com' ion port 80","library":["socket"],"docs":[{"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 representation of an IPv4\/v6 address or None. port is a string service name such as 'http', a numeric port number or None. By passing None as the value of host and port, you can pass NULL to the underlying C API. The family, type and proto arguments can be optionally specified in order to narrow the list of addresses returned. Passing zero as a value for each of these arguments selects the full range of results. The flags argument can be one or several of the AI_* constants, and will influence how results are computed and returned. For example, AI_NUMERICHOST will disable domain name resolution and will raise an error if host is a domain name. The function returns a list of 5-tuples with the following structure: (family, type, proto, canonname, sockaddr) In these tuples, family, type, proto are all integers and are meant to be passed to the socket() function. canonname will be a string representing the canonical name of the host if AI_CANONNAME is part of the flags argument; else canonname will be empty. sockaddr is a tuple describing a socket address, whose format depends on the returned family (a (address, port) 2-tuple for AF_INET, a (address, port, flowinfo, scope_id) 4-tuple for AF_INET6), and is meant to be passed to the socket.connect() method. Raises an auditing event socket.getaddrinfo with arguments host, port, family, type, protocol. The following example fetches address information for a hypothetical TCP connection to example.org on port 80 (results may differ on your system if IPv6 isn\u2019t enabled): >>> socket.getaddrinfo(\"example.org\", 80, proto=socket.IPPROTO_TCP)\n[(<AddressFamily.AF_INET6: 10>, <SocketType.SOCK_STREAM: 1>,\n 6, '', ('2606:2800:220:1:248:1893:25c8:1946', 80, 0, 0)),","title":"python.library.socket#socket.getaddrinfo"}]} {"task_id":17552997,"prompt":"def f_17552997(df):\n\treturn ","suffix":"","canonical_solution":"df.xs('sat', level='day', drop_level=False)","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\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 'sales':[10,12,22,23,11,13,23,24]})\n df = df.set_index(['year','flavour','day'])\n assert candidate(df).to_dict() == {'sales': {(2008, 'strawberry', 'sat'): 10, (2008, 'banana', 'sat'): 22, (2009, 'strawberry', 'sat'): 11, (2009, 'banana', 'sat'): 23}}\n"],"entry_point":"f_17552997","intent":"add a column 'day' with value 'sat' to dataframe `df`","library":["pandas"],"docs":[{"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.pandas.dataframe.xs"}]} {"task_id":4356842,"prompt":"def f_4356842():\n\treturn ","suffix":"","canonical_solution":"HttpResponse('Unauthorized', status=401)","test_start":"\nfrom django.http import HttpResponse\nfrom django.conf import settings\n\nif not settings.configured:\n settings.configure(DEBUG=True)\n\ndef check(candidate):","test":["\n assert candidate().status_code == 401\n"],"entry_point":"f_4356842","intent":"return a 401 unauthorized in django","library":["django"],"docs":[{"function":"HttpResponse","text":"class HttpResponse","title":"django.ref.request-response#django.http.HttpResponse"}]} {"task_id":13598363,"prompt":"def f_13598363():\n\treturn ","suffix":"","canonical_solution":"Flask('test', template_folder='wherever')","test_start":"\nfrom flask import Flask\n\ndef check(candidate):","test":["\n __name__ == \"test\"\n assert candidate().template_folder == \"wherever\"\n"],"entry_point":"f_13598363","intent":"Flask set folder 'wherever' as the default template folder","library":["flask"],"docs":[{"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 application and acts as the central object. It is passed the name of the module or package of the application. Once it is created it will act as a central registry for the view functions, the URL rules, template configuration and much more. The name of the package is used to resolve resources from inside the package or the folder the module is contained in depending on if the package parameter resolves to an actual python package (a folder with an __init__.py file inside) or a standard module (just a .py file). For more information about resource loading, see open_resource(). Usually you create a Flask instance in your main module or in the __init__.py file of your package like this: from flask import Flask\napp = Flask(__name__)","title":"flask.api.index#flask.Flask"}]} {"task_id":3398589,"prompt":"def f_3398589(c2):\n\t","suffix":"\n\treturn c2","canonical_solution":"c2.sort(key=lambda row: row[2])","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3398589","intent":"sort a list of lists 'c2' such that third row comes first","library":[],"docs":[]} {"task_id":3398589,"prompt":"def f_3398589(c2):\n\t","suffix":"\n\treturn c2","canonical_solution":"c2.sort(key=lambda row: (row[2], row[1], row[0]))","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3398589","intent":"sort a list of lists 'c2' in reversed row order","library":[],"docs":[]} {"task_id":3398589,"prompt":"def f_3398589(c2):\n\t","suffix":"\n\treturn c2","canonical_solution":"c2.sort(key=lambda row: (row[2], row[1]))","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3398589","intent":"Sorting a list of lists `c2`, each by the third and second row","library":[],"docs":[]} {"task_id":10960463,"prompt":"def f_10960463():\n\treturn ","suffix":"","canonical_solution":"matplotlib.rc('font', **{'sans-serif': 'Arial', 'family': 'sans-serif'})","test_start":"\nimport matplotlib\n\ndef check(candidate):","test":["\n try:\n candidate()\n except:\n assert False\n"],"entry_point":"f_10960463","intent":"set font `Arial` to display non-ascii characters in matplotlib","library":["matplotlib"],"docs":[{"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 group names, e.g., (xtick, ytick). kwargs is a dictionary attribute name\/value pairs, e.g.,: rc('lines', linewidth=2, color='r')\n sets the current rcParams and is equivalent to: rcParams['lines.linewidth'] = 2","title":"matplotlib._as_gen.matplotlib.pyplot.rc"}]} {"task_id":20576618,"prompt":"def f_20576618(df):\n\treturn ","suffix":"","canonical_solution":"df['date'].apply(lambda x: x.toordinal())","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\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).tolist()\n assert data_series[1] == 737437\n","\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).tolist()\n assert data_series[1] == 737437\n"],"entry_point":"f_20576618","intent":"Convert DateTime column 'date' of pandas dataframe 'df' to ordinal","library":["pandas"],"docs":[{"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\u2019s index (axis=0) or the DataFrame\u2019s columns (axis=1). By default (result_type=None), the final return type is inferred from the return type of the applied function. Otherwise, it depends on the result_type argument. Parameters ","title":"pandas.reference.api.pandas.dataframe.apply"}]} {"task_id":31793195,"prompt":"def f_31793195(df):\n\treturn ","suffix":"","canonical_solution":"df.index.get_loc('bob')","test_start":"\nimport pandas as pd\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_31793195","intent":"Get the integer location of a key `bob` in a pandas data frame `df`","library":["numpy","pandas"],"docs":[{"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"}]} {"task_id":10487278,"prompt":"def f_10487278(my_dict):\n\t","suffix":"\n\treturn my_dict","canonical_solution":"my_dict.update({'third_key': 1})","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_10487278","intent":"add an item with key 'third_key' and value 1 to an dictionary `my_dict`","library":[],"docs":[]} {"task_id":10487278,"prompt":"def f_10487278():\n\t","suffix":"\n\treturn my_list","canonical_solution":"my_list = []","test_start":"\ndef check(candidate):","test":["\n assert candidate() == []\n"],"entry_point":"f_10487278","intent":"declare an array `my_list`","library":[],"docs":[]} {"task_id":10487278,"prompt":"def f_10487278(my_list):\n\t","suffix":"\n\treturn my_list","canonical_solution":"my_list.append(12)","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2]) == [1, 2, 12] \n","\n assert candidate([5,6]) == [5, 6, 12]\n"],"entry_point":"f_10487278","intent":"Insert item `12` to a list `my_list`","library":[],"docs":[]} {"task_id":10155684,"prompt":"def f_10155684(myList):\n\t","suffix":"\n\treturn myList","canonical_solution":"myList.insert(0, 'wuggah')","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2]) == ['wuggah', 1, 2]\n","\n assert candidate([]) == ['wuggah'] \n"],"entry_point":"f_10155684","intent":"add an entry 'wuggah' at the beginning of list `myList`","library":[],"docs":[]} {"task_id":3519125,"prompt":"def f_3519125(hex_str):\n\treturn ","suffix":"","canonical_solution":"bytes.fromhex(hex_str.replace('\\\\x', ''))","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"\\\\xF3\\\\xBE\\\\x80\\\\x80\") == b'\\xf3\\xbe\\x80\\x80'\n"],"entry_point":"f_3519125","intent":"convert a hex-string representation `hex_str` to actual bytes","library":[],"docs":[]} {"task_id":40144769,"prompt":"def f_40144769(df):\n\treturn ","suffix":"","canonical_solution":"df[df.columns[-1]]","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\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"],"entry_point":"f_40144769","intent":"select the last column of dataframe `df`","library":["pandas"],"docs":[{"function":"dataframe.columns","text":"pandas.DataFrame.columns DataFrame.columns\n \nThe column labels of the DataFrame.","title":"pandas.reference.api.pandas.dataframe.columns"}]} {"task_id":30787901,"prompt":"def f_30787901(df):\n\treturn ","suffix":"","canonical_solution":"df.loc[df['Letters'] == 'C', 'Letters'].values[0]","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\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"],"entry_point":"f_30787901","intent":"get the first value from dataframe `df` where column 'Letters' is equal to 'C'","library":["pandas"],"docs":[{"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 interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. ","title":"pandas.reference.api.pandas.dataframe.loc"}]} {"task_id":18730044,"prompt":"def f_18730044():\n\treturn ","suffix":"","canonical_solution":"np.column_stack(([1, 2, 3], [4, 5, 6]))","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n assert np.all(candidate() == np.array([[1, 4], [2, 5], [3, 6]]))\n"],"entry_point":"f_18730044","intent":"converting two lists `[1, 2, 3]` and `[4, 5, 6]` into a matrix","library":["numpy"],"docs":[{"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 into 2-D columns first. Parameters ","title":"numpy.reference.generated.numpy.column_stack"}]} {"task_id":402504,"prompt":"def f_402504(i):\n\treturn ","suffix":"","canonical_solution":"type(i)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_402504","intent":"get the type of `i`","library":[],"docs":[]} {"task_id":402504,"prompt":"def f_402504(v):\n\treturn ","suffix":"","canonical_solution":"type(v)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_402504","intent":"determine the type of variable `v`","library":[],"docs":[]} {"task_id":402504,"prompt":"def f_402504(v):\n\treturn ","suffix":"","canonical_solution":"type(v)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_402504","intent":"determine the type of variable `v`","library":[],"docs":[]} {"task_id":402504,"prompt":"def f_402504(variable_name):\n\treturn ","suffix":"","canonical_solution":"type(variable_name)","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_402504","intent":"get the type of variable `variable_name`","library":[],"docs":[]} {"task_id":2300756,"prompt":"def f_2300756(g):\n\treturn ","suffix":"","canonical_solution":"next(itertools.islice(g, 5, 5 + 1))","test_start":"\nimport itertools\n\ndef check(candidate):","test":["\n test = [1, 2, 3, 4, 5, 6, 7]\n assert(candidate(test) == 6)\n"],"entry_point":"f_2300756","intent":"get the 5th item of a generator `g`","library":["itertools"],"docs":[{"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 are returned consecutively unless step is set higher than one which results in items being skipped. If stop is None, then iteration continues until the iterator is exhausted, if at all; otherwise, it stops at the specified position. Unlike regular slicing, islice() does not support negative values for start, stop, or step. Can be used to extract related fields from data where the internal structure has been flattened (for example, a multi-line report may list a name field on every third line). Roughly equivalent to: def islice(iterable, *args):","title":"python.library.itertools#itertools.islice"}]} {"task_id":20056548,"prompt":"def f_20056548(word):\n\treturn ","suffix":"","canonical_solution":"'\"{}\"'.format(word)","test_start":"\ndef check(candidate):","test":["\n assert candidate('Some Random Word') == '\"Some Random Word\"'\n"],"entry_point":"f_20056548","intent":"return a string `word` with string format","library":[],"docs":[]} {"task_id":8546245,"prompt":"def f_8546245(list):\n\treturn ","suffix":"","canonical_solution":"\"\"\" \"\"\".join(list)","test_start":"\ndef check(candidate):","test":["\n test = ['hello', 'good', 'morning']\n assert candidate(test) == \"hello good morning\"\n"],"entry_point":"f_8546245","intent":"join a list of strings `list` using a space ' '","library":[],"docs":[]} {"task_id":2276416,"prompt":"def f_2276416():\n\t","suffix":"\n\treturn y","canonical_solution":"y = [[] for n in range(2)]","test_start":"\ndef check(candidate):","test":["\n assert(candidate() == [[], []])\n"],"entry_point":"f_2276416","intent":"create list `y` containing two empty lists","library":[],"docs":[]} {"task_id":3925614,"prompt":"def f_3925614(filename):\n\t","suffix":"\n\treturn data","canonical_solution":"data = [line.strip() for line in open(filename, 'r')]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_3925614","intent":"read a file `filename` into a list `data`","library":[],"docs":[]} {"task_id":22187233,"prompt":"def f_22187233():\n\treturn ","suffix":"","canonical_solution":"\"\"\"\"\"\".join([char for char in 'it is icy' if char != 'i'])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 't s cy'\n"],"entry_point":"f_22187233","intent":"delete all occurrences of character 'i' in string 'it is icy'","library":[],"docs":[]} {"task_id":22187233,"prompt":"def f_22187233():\n\treturn ","suffix":"","canonical_solution":"re.sub('i', '', 'it is icy')","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate() == 't s cy'\n"],"entry_point":"f_22187233","intent":"delete all instances of a character 'i' in a string 'it is icy'","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":22187233,"prompt":"def f_22187233():\n\treturn ","suffix":"","canonical_solution":"\"\"\"it is icy\"\"\".replace('i', '')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 't s cy'\n"],"entry_point":"f_22187233","intent":"delete all characters \"i\" in string \"it is icy\"","library":[],"docs":[]} {"task_id":13413590,"prompt":"def f_13413590(df):\n\treturn ","suffix":"","canonical_solution":"df.dropna(subset=[1])","test_start":"\nimport numpy as np\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_13413590","intent":"Drop rows of pandas dataframe `df` having NaN in column at index \"1\"","library":["numpy","pandas"],"docs":[{"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":"pandas.reference.api.pandas.dataframe.dropna"}]} {"task_id":598398,"prompt":"def f_598398(myList):\n\treturn ","suffix":"","canonical_solution":"[x for x in myList if x.n == 30]","test_start":"\nimport numpy as np\nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_598398","intent":"get elements from list `myList`, that have a field `n` value 30","library":["numpy","pandas"],"docs":[]} {"task_id":10351772,"prompt":"def f_10351772(intstringlist):\n\t","suffix":"\n\treturn nums","canonical_solution":"nums = [int(x) for x in intstringlist]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_10351772","intent":"converting list of strings `intstringlist` to list of integer `nums`","library":[],"docs":[]} {"task_id":493386,"prompt":"def f_493386():\n\treturn ","suffix":"","canonical_solution":"sys.stdout.write('.')","test_start":"\nimport sys\n\ndef check(candidate):","test":["\n assert candidate() == 1\n"],"entry_point":"f_493386","intent":"print \".\" without newline","library":["sys"],"docs":[{"function":"sys.write","text":"sys \u2014 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 built with the standard configure script, this contains the ABI flags as specified by PEP 3149. Changed in version 3.8: Default flags became an empty string (m flag for pymalloc has been removed). New in version 3.2. \n ","title":"python.library.sys"},{"function":"sys.stdout","text":"sys.stdin \nsys.stdout \nsys.stderr \nFile objects used by the interpreter for standard input, output and errors: \nstdin is used for all interactive input (including calls to input()); \nstdout is used for the output of print() and expression statements and for the prompts of input(); The interpreter\u2019s own prompts and its error messages go to stderr. These streams are regular text files like those returned by the open() function. Their parameters are chosen as follows: \nThe character encoding is platform-dependent. Non-Windows platforms use the locale encoding (see locale.getpreferredencoding()). On Windows, UTF-8 is used for the console device. Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout\/stderr. This defaults to the system locale encoding if the process is not initially attached to a console. The special behaviour of the console can be overridden by setting the environment variable PYTHONLEGACYWINDOWSSTDIO before starting Python. In that case, the console codepages are used as for any other character device. Under all platforms, you can override the character encoding by setting the PYTHONIOENCODING environment variable before starting Python or by using the new -X utf8 command line option and PYTHONUTF8 environment variable. However, for the Windows console, this only applies when PYTHONLEGACYWINDOWSSTDIO is also set. When interactive, the stdout stream is line-buffered. Otherwise, it is block-buffered like regular text files. The stderr stream is line-buffered in both cases. You can make both streams unbuffered by passing the -u command-line option or setting the PYTHONUNBUFFERED environment variable. Changed in version 3.9: Non-interactive stderr is now line-buffered instead of fully buffered. Note To write or read binary data from\/to the standard streams, use the underlying binary buffer object. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc'). However, if you are writing a library (and do not control in which context its code will be executed), be aware that the standard streams may be replaced with file-like objects like io.StringIO which do not support the buffer attribute.","title":"python.library.sys#sys.stdout"}]} {"task_id":6569528,"prompt":"def f_6569528():\n\treturn ","suffix":"","canonical_solution":"int(round(2.52 * 100))","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 252\n"],"entry_point":"f_6569528","intent":"round off the float that is the product of `2.52 * 100` and convert it to an int","library":[],"docs":[]} {"task_id":3964681,"prompt":"def f_3964681():\n\t","suffix":"\n\treturn files","canonical_solution":"\n\tos.chdir('\/mydir')\n\tfiles = [] \n\tfor file in glob.glob('*.txt'):\n\t\tfiles.append(file)\n","test_start":"\nimport os\nimport glob\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n samples = ['abc.txt']\n os.chdir = Mock()\n glob.glob = Mock(return_value = samples)\n assert candidate() == samples\n"],"entry_point":"f_3964681","intent":"Find all files `files` in directory '\/mydir' with extension '.txt'","library":["glob","os"],"docs":[{"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, PermissionError, and NotADirectoryError. Raises an auditing event os.chdir with argument path. New in version 3.3: Added support for specifying path as a file descriptor on some platforms. Changed in version 3.6: Accepts a path-like object.","title":"python.library.os#os.chdir"},{"function":"glob.glob","text":"glob.glob(pathname, *, recursive=False) \nReturn a possibly-empty list of path names that match pathname, which must be a string containing a path specification. pathname can be either absolute (like \/usr\/src\/Python-1.5\/Makefile) or relative (like ..\/..\/Tools\/*\/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell). Whether or not the results are sorted depends on the file system. If a file that satisfies conditions is removed or added during the call of this function, whether a path name for that file be included is unspecified. If recursive is true, the pattern \u201c**\u201d will match any files and zero or more directories, subdirectories and symbolic links to directories. If the pattern is followed by an os.sep or os.altsep then files will not match. Raises an auditing event glob.glob with arguments pathname, recursive. Note Using the \u201c**\u201d pattern in large directory trees may consume an inordinate amount of time. Changed in version 3.5: Support for recursive globs using \u201c**\u201d.","title":"python.library.glob#glob.glob"}]} {"task_id":3964681,"prompt":"def f_3964681():\n\treturn ","suffix":"","canonical_solution":"[file for file in os.listdir('\/mydir') if file.endswith('.txt')]","test_start":"\nimport os\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n samples = ['abc.txt', 'f.csv']\n os.listdir = Mock(return_value = samples)\n assert candidate() == ['abc.txt']\n"],"entry_point":"f_3964681","intent":"Find all files in directory \"\/mydir\" with extension \".txt\"","library":["os"],"docs":[{"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 to the directory during the call of this function, whether a name for that file be included is unspecified. path may be a path-like object. If path is of type bytes (directly or indirectly through the PathLike interface), the filenames returned will also be of type bytes; in all other circumstances, they will be of type str. This function can also support specifying a file descriptor; the file descriptor must refer to a directory. Raises an auditing event os.listdir with argument path. Note To encode str filenames to bytes, use fsencode(). See also The scandir() function returns directory entries along with file attribute information, giving better performance for many common use cases. Changed in version 3.2: The path parameter became optional. New in version 3.3: Added support for specifying path as an open file descriptor. Changed in version 3.6: Accepts a path-like object.","title":"python.library.os#os.listdir"}]} {"task_id":3964681,"prompt":"def f_3964681():\n\treturn ","suffix":"","canonical_solution":"[file for (root, dirs, files) in os.walk('\/mydir') for file in files if file.endswith('.txt')]","test_start":"\nimport os\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n name = '\/mydir'\n samples = [(name, [], ['abc.txt', 'f.csv'])]\n os.walk = Mock(return_value = samples)\n assert candidate() == ['abc.txt']\n"],"entry_point":"f_3964681","intent":"Find all files in directory \"\/mydir\" with extension \".txt\"","library":["os"],"docs":[{"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,\nfilenames). dirpath is a string, the path to the directory. dirnames is a list of the names of the subdirectories in dirpath (excluding '.' and '..'). filenames is a list of the names of the non-directory files in dirpath. Note that the names in the lists contain no path components. To get a full path (which begins with top) to a file or directory in dirpath, do os.path.join(dirpath, name). Whether or not the lists are sorted depends on the file system. If a file is removed from or added to the dirpath directory during generating the lists, whether a name for that file be included is unspecified. If optional argument topdown is True or not specified, the triple for a directory is generated before the triples for any of its subdirectories (directories are generated top-down). If topdown is False, the triple for a directory is generated after the triples for all of its subdirectories (directories are generated bottom-up). No matter the value of topdown, the list of subdirectories is retrieved before the tuples for the directory and its subdirectories are generated. When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search, impose a specific order of visiting, or even to inform walk() about directories the caller creates or renames before it resumes walk() again. Modifying dirnames when topdown is False has no effect on the behavior of the walk, because in bottom-up mode the directories in dirnames are generated before dirpath itself is generated. By default, errors from the scandir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an OSError instance. It can report the error to continue with the walk, or raise the exception to abort the walk. Note that the filename is available as the filename attribute of the exception object. By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them. Note Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already. Note If you pass a relative pathname, don\u2019t change the current working directory between resumptions of walk(). walk() never changes the current directory, and assumes that its caller doesn\u2019t either. This example displays the number of bytes taken by non-directory files in each directory under the starting directory, except that it doesn\u2019t look under any CVS subdirectory: import os\nfrom os.path import join, getsize\nfor root, dirs, files in os.walk('python\/Lib\/email'):\n print(root, \"consumes\", end=\" \")\n print(sum(getsize(join(root, name)) for name in files), end=\" \")\n print(\"bytes in\", len(files), \"non-directory files\")\n if 'CVS' in dirs:","title":"python.library.os#os.walk"}]} {"task_id":20865487,"prompt":"def f_20865487(df):\n\treturn ","suffix":"","canonical_solution":"df.plot(legend=False)","test_start":"\nimport os \nimport pandas as pd\n\ndef check(candidate):","test":["\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"],"entry_point":"f_20865487","intent":"plot dataframe `df` without a legend","library":["os","pandas"],"docs":[{"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"}]} {"task_id":13368659,"prompt":"def f_13368659():\n\treturn ","suffix":"","canonical_solution":"['192.168.%d.%d'%(i, j) for i in range(256) for j in range(256)]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_13368659","intent":"loop through the IP address range \"192.168.x.x\"","library":[],"docs":[]} {"task_id":4065737,"prompt":"def f_4065737(x):\n\treturn ","suffix":"","canonical_solution":"sum(1 << i for i, b in enumerate(x) if b)","test_start":"\ndef check(candidate):","test":["\n assert candidate([1,2,3]) == 7\n","\n assert candidate([1,2,None,3,None]) == 11\n"],"entry_point":"f_4065737","intent":"Sum the corresponding decimal values for binary values of each boolean element in list `x`","library":[],"docs":[]} {"task_id":8691311,"prompt":"def f_8691311(line1, line2, line3, target):\n\t","suffix":"\n\treturn ","canonical_solution":"target.write('%r\\n%r\\n%r\\n' % (line1, line2, line3))","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_8691311","intent":"write multiple strings `line1`, `line2` and `line3` in one line in a file `target`","library":[],"docs":[]} {"task_id":10632111,"prompt":"def f_10632111(data):\n\treturn ","suffix":"","canonical_solution":"[y for x in data for y in (x if isinstance(x, list) else [x])]","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_10632111","intent":"Convert list of lists `data` into a flat list","library":[],"docs":[]} {"task_id":15392730,"prompt":"def f_15392730():\n\treturn ","suffix":"","canonical_solution":"'foo\\nbar'.encode('unicode_escape')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == b'foo\\\\nbar'\n"],"entry_point":"f_15392730","intent":"Print new line character as `\\n` in a string `foo\\nbar`","library":[],"docs":[]} {"task_id":1010961,"prompt":"def f_1010961(s):\n\treturn ","suffix":"","canonical_solution":"\"\"\"\"\"\".join(s.rsplit(',', 1))","test_start":"\ndef check(candidate):","test":["\n assert candidate('abc, def, klm') == 'abc, def klm'\n"],"entry_point":"f_1010961","intent":"remove last comma character ',' in string `s`","library":[],"docs":[]} {"task_id":23855976,"prompt":"def f_23855976(x):\n\treturn ","suffix":"","canonical_solution":"(x[1:] + x[:-1]) \/ 2","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_23855976","intent":"calculate the mean of each element in array `x` with the element previous to it","library":["numpy"],"docs":[]} {"task_id":23855976,"prompt":"def f_23855976(x):\n\treturn ","suffix":"","canonical_solution":"x[:-1] + (x[1:] - x[:-1]) \/ 2","test_start":"\nimport numpy as np\n\ndef check(candidate):","test":["\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"],"entry_point":"f_23855976","intent":"get an array of the mean of each two consecutive values in numpy array `x`","library":["numpy"],"docs":[]} {"task_id":6375343,"prompt":"def f_6375343():\n\t","suffix":"\n\treturn arr","canonical_solution":"arr = numpy.fromiter(codecs.open('new.txt', encoding='utf-8'), dtype='<U2')","test_start":"\nimport numpy\nimport codecs\nimport numpy as np\n\ndef check(candidate):","test":["\n with open ('new.txt', 'a', encoding='utf-8') as f:\n f.write('\u091f')\n f.write('\u091c')\n arr = candidate()\n assert arr[0] == '\u091f\u091c'\n"],"entry_point":"f_6375343","intent":"load data containing `utf-8` from file `new.txt` into numpy array `arr`","library":["codecs","numpy"],"docs":[{"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(filename, mode='r', encoding=None, errors='strict', buffering=-1) \nOpen an encoded file using the given mode and return an instance of StreamReaderWriter, providing transparent encoding\/decoding. The default file mode is 'r', meaning to open the file in read mode. Note Underlying encoded files are always opened in binary mode. No automatic conversion of '\\n' is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in open() function; the 'b' is automatically added. encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used. errors may be given to define the error handling. It defaults to 'strict' which causes a ValueError to be raised in case an encoding error occurs. buffering has the same meaning as for the built-in open() function. It defaults to -1 which means that the default buffer size will be used.","title":"python.library.codecs#codecs.open"}]} {"task_id":1547733,"prompt":"def f_1547733(l):\n\t","suffix":"\n\treturn l","canonical_solution":"l = sorted(l, key=itemgetter('time'), reverse=True)","test_start":"\nfrom operator import itemgetter\n\ndef check(candidate):","test":["\n l = [ {'time':33}, {'time':11}, {'time':66} ]\n assert candidate(l) == [{'time':66}, {'time':33}, {'time':11}]\n"],"entry_point":"f_1547733","intent":"reverse sort list of dicts `l` by value for key `time`","library":["operator"],"docs":[{"function":"operator.itemgetter","text":"operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand\u2019s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):","title":"python.library.operator#operator.itemgetter"}]} {"task_id":1547733,"prompt":"def f_1547733(l):\n\t","suffix":"\n\treturn l","canonical_solution":"l = sorted(l, key=lambda a: a['time'], reverse=True)","test_start":"\ndef check(candidate):","test":["\n l = [ {'time':33}, {'time':11}, {'time':66} ]\n assert candidate(l) == [{'time':66}, {'time':33}, {'time':11}]\n"],"entry_point":"f_1547733","intent":"Sort a list of dictionary `l` based on key `time` in descending order","library":[],"docs":[]} {"task_id":37080612,"prompt":"def f_37080612(df):\n\treturn ","suffix":"","canonical_solution":"df.loc[df[0].str.contains('(Hel|Just)')]","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\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"],"entry_point":"f_37080612","intent":"get rows of dataframe `df` that match regex '(Hel|Just)'","library":["pandas"],"docs":[{"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 interpreted as a label of the index, and never as an integer position along the index). A list or array of labels, e.g. ['a', 'b', 'c']. ","title":"pandas.reference.api.pandas.dataframe.loc"},{"function":"str.contains","text":"pandas.Series.str.contains Series.str.contains(pat, case=True, flags=0, na=None, regex=True)[source]\n \nTest if pattern or regex is contained within a string of a Series or Index. Return boolean Series or Index based on whether a given pattern or regex is contained within a string of a Series or Index. Parameters ","title":"pandas.reference.api.pandas.series.str.contains"}]} {"task_id":14716342,"prompt":"def f_14716342(your_string):\n\treturn ","suffix":"","canonical_solution":"re.search('\\\\[(.*)\\\\]', your_string).group(1)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n assert candidate('[uranus]') == 'uranus'\n","\n assert candidate('hello[world] !') == 'world'\n"],"entry_point":"f_14716342","intent":"find the string in `your_string` between two special characters \"[\" and \"]\"","library":["re"],"docs":[{"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 different from finding a zero-length match at some point in the string.","title":"python.library.re#re.search"},{"function":"re.Match.group","text":"Match.group([group1, ...]) \nReturns one or more subgroups of the match. If there is a single argument, the result is a single string; if there are multiple arguments, the result is a tuple with one item per argument. Without arguments, group1 defaults to zero (the whole match is returned). If a groupN argument is zero, the corresponding return value is the entire matching string; if it is in the inclusive range [1..99], it is the string matching the corresponding parenthesized group. If a group number is negative or larger than the number of groups defined in the pattern, an IndexError exception is raised. If a group is contained in a part of the pattern that did not match, the corresponding result is None. If a group is contained in a part of the pattern that matched multiple times, the last match is returned. >>> m = re.match(r\"(\\w+) (\\w+)\", \"Isaac Newton, physicist\")","title":"python.library.re#re.Match.group"}]} {"task_id":18684076,"prompt":"def f_18684076():\n\treturn ","suffix":"","canonical_solution":"[d.strftime('%Y%m%d') for d in pandas.date_range('20130226', '20130302')]","test_start":"\nimport pandas \n\ndef check(candidate):","test":["\n assert candidate() == ['20130226', '20130227', '20130228', '20130301', '20130302']\n"],"entry_point":"f_18684076","intent":"create a list of date string in 'yyyymmdd' format with Python Pandas from '20130226' to '20130302'","library":["pandas"],"docs":[{"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 information on the format string: https:\/\/docs.python.org\/3\/library\/datetime.html#strftime-and-strptime-behavior. Examples ","title":"pandas.reference.api.pandas.timestamp.strftime"},{"function":"pandas.date_range","text":"pandas.date_range pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=NoDefault.no_default, inclusive=None, **kwargs)[source]\n \nReturn a fixed frequency DatetimeIndex. Returns the range of equally spaced time points (where the difference between any two adjacent points is specified by the given frequency) such that they all satisfy start <[=] x <[=] end, where the first one and the last one are, resp., the first and last time points in that range that fall on the boundary of freq (if given as a frequency string) or that are valid for freq (if given as a pandas.tseries.offsets.DateOffset). (If exactly one of start, end, or freq is not specified, this missing parameter can be computed given periods, the number of timesteps in the range. See the note below.) Parameters ","title":"pandas.reference.api.pandas.date_range"}]} {"task_id":1666700,"prompt":"def f_1666700():\n\treturn ","suffix":"","canonical_solution":"\"\"\"The big brown fox is brown\"\"\".count('brown')","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 2\n"],"entry_point":"f_1666700","intent":"count number of times string 'brown' occurred in string 'The big brown fox is brown'","library":[],"docs":[]} {"task_id":18979111,"prompt":"def f_18979111(request_body):\n\treturn ","suffix":"","canonical_solution":"json.loads(request_body)","test_start":"\nimport json \n\ndef check(candidate):","test":["\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', 'Email': 'jen123@gmail.com', 'Contact Number': 7867567898}\n"],"entry_point":"f_18979111","intent":"decode json string `request_body` to python dict","library":["json"],"docs":[{"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 arguments have the same meaning as in load(). If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.9: The keyword argument encoding has been removed.","title":"python.library.json#json.loads"}]} {"task_id":7243750,"prompt":"def f_7243750(url, file_name):\n\treturn ","suffix":"","canonical_solution":"urllib.request.urlretrieve(url, file_name)","test_start":"\nimport urllib \n\ndef check(candidate):","test":["\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\n"],"entry_point":"f_7243750","intent":"download the file from url `url` and save it under file `file_name`","library":["urllib"],"docs":[{"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) where filename is the local file name under which the object can be found, and headers is whatever the info() method of the object returned by urlopen() returned (for a remote object). Exceptions are the same as for urlopen(). The second argument, if present, specifies the file location to copy to (if absent, the location will be a tempfile with a generated name). The third argument, if present, is a callable that will be called once on establishment of the network connection and once after each block read thereafter. The callable will be passed three arguments; a count of blocks transferred so far, a block size in bytes, and the total size of the file. The third argument may be -1 on older FTP servers which do not return a file size in response to a retrieval request. The following example illustrates the most common usage scenario: >>> import urllib.request","title":"python.library.urllib.request#urllib.request.urlretrieve"}]} {"task_id":743806,"prompt":"def f_743806(text):\n\treturn ","suffix":"","canonical_solution":"text.split()","test_start":"\ndef check(candidate):","test":["\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"],"entry_point":"f_743806","intent":"split string `text` by space","library":[],"docs":[]} {"task_id":743806,"prompt":"def f_743806(text):\n\treturn ","suffix":"","canonical_solution":"text.split(',')","test_start":"\ndef check(candidate):","test":["\n assert candidate('The quick brown fox') == ['The quick brown fox']\n","\n assert candidate('The,quick,brown,fox') == ['The', 'quick', 'brown', 'fox']\n"],"entry_point":"f_743806","intent":"split string `text` by \",\"","library":[],"docs":[]} {"task_id":743806,"prompt":"def f_743806(line):\n\treturn ","suffix":"","canonical_solution":"line.split()","test_start":"\ndef check(candidate):","test":["\n assert candidate('The quick brown fox') == ['The', 'quick', 'brown', 'fox']\n"],"entry_point":"f_743806","intent":"Split string `line` into a list by whitespace","library":[],"docs":[]} {"task_id":35044115,"prompt":"def f_35044115(s):\n\treturn ","suffix":"","canonical_solution":"[re.sub('(?<!\\\\d)\\\\.(?!\\\\d)', ' ', i) for i in s]","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate('h.j.k') == ['h', ' ', 'j', ' ', 'k']\n"],"entry_point":"f_35044115","intent":"replace dot characters '.' associated with ascii letters in list `s` with space ' '","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":38388799,"prompt":"def f_38388799(list_of_strings):\n\treturn ","suffix":"","canonical_solution":"sorted(list_of_strings, key=lambda s: s.split(',')[1])","test_start":"\ndef check(candidate):","test":["\n assert candidate(['parrot, medicine', 'abott, kangaroo', 'sriracha, coriander', 'phone, bottle']) == ['phone, bottle', 'sriracha, coriander', 'abott, kangaroo', 'parrot, medicine']\n","\n assert candidate(['abott, kangaroo', 'parrot, medicine', 'sriracha, coriander', 'phone, bottle']) == ['phone, bottle', 'sriracha, coriander', 'abott, kangaroo', 'parrot, medicine']\n"],"entry_point":"f_38388799","intent":"sort list `list_of_strings` based on second index of each string `s`","library":[],"docs":[]} {"task_id":37004138,"prompt":"def f_37004138(lst):\n\treturn ","suffix":"","canonical_solution":"[element for element in lst if isinstance(element, int)]","test_start":"\ndef check(candidate):","test":["\n lst = [1, \"hello\", \"string\", 2, 4.46]\n assert candidate(lst) == [1, 2]\n","\n lst = [\"hello\", \"string\"]\n assert candidate(lst) == []\n"],"entry_point":"f_37004138","intent":"eliminate non-integer items from list `lst`","library":[],"docs":[]} {"task_id":37004138,"prompt":"def f_37004138(lst):\n\treturn ","suffix":"","canonical_solution":"[element for element in lst if not isinstance(element, str)]","test_start":"\ndef check(candidate):","test":["\n lst = [1, \"hello\", \"string\", 2, 4.46]\n assert candidate(lst) == [1, 2, 4.46]\n","\n lst = [\"hello\", \"string\"]\n assert candidate(lst) == []\n"],"entry_point":"f_37004138","intent":"get all the elements except strings from the list 'lst'.","library":[],"docs":[]} {"task_id":72899,"prompt":"def f_72899(list_to_be_sorted):\n\treturn ","suffix":"","canonical_solution":"sorted(list_to_be_sorted, key=lambda k: k['name'])","test_start":"\ndef check(candidate):","test":["\n list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n","\n list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]\n assert candidate(list_to_be_sorted) == [{'name': 'AABCD'}, {'name': 'ABCD'}]\n"],"entry_point":"f_72899","intent":"Sort a list of dictionaries `list_to_be_sorted` by the value of the dictionary key `name`","library":[],"docs":[]} {"task_id":72899,"prompt":"def f_72899(l):\n\treturn ","suffix":"","canonical_solution":"sorted(l, key=itemgetter('name'), reverse=True)","test_start":"\nfrom operator import itemgetter\n\ndef check(candidate):","test":["\n list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n assert candidate(list_to_be_sorted) == [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n","\n list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]\n assert candidate(list_to_be_sorted) == [{'name': 'ABCD'}, {'name': 'AABCD'}]\n"],"entry_point":"f_72899","intent":"sort a list of dictionaries `l` by values in key `name` in descending order","library":["operator"],"docs":[{"function":"operator.itemgetter","text":"operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand\u2019s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):","title":"python.library.operator#operator.itemgetter"}]} {"task_id":72899,"prompt":"def f_72899(list_of_dicts):\n\t","suffix":"\n\treturn list_of_dicts","canonical_solution":"list_of_dicts.sort(key=operator.itemgetter('name'))","test_start":"\nimport operator\n\ndef check(candidate):","test":["\n list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n","\n list_to_be_sorted = [{'name': 'ABCD'}, {'name': 'AABCD'}]\n assert candidate(list_to_be_sorted) == [{'name': 'AABCD'}, {'name': 'ABCD'}]\n"],"entry_point":"f_72899","intent":"sort a list of dictionaries `list_of_dicts` by `name` values of the dictionary","library":["operator"],"docs":[{"function":"operator.itemgetter","text":"operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand\u2019s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):","title":"python.library.operator#operator.itemgetter"}]} {"task_id":72899,"prompt":"def f_72899(list_of_dicts):\n\t","suffix":"\n\treturn list_of_dicts","canonical_solution":"list_of_dicts.sort(key=operator.itemgetter('age'))","test_start":"\nimport operator\n\ndef check(candidate):","test":["\n list_to_be_sorted = [{'name': 'Homer', 'age': 39}, {'name': 'Bart', 'age': 10}]\n assert candidate(list_to_be_sorted) == [{'name': 'Bart', 'age': 10}, {'name': 'Homer', 'age': 39}]\n","\n list_to_be_sorted = [{'name': 'ABCD', 'age': 10}, {'name': 'AABCD', 'age': 9}]\n assert candidate(list_to_be_sorted) == [{'name': 'AABCD', 'age': 9}, {'name': 'ABCD', 'age': 10}]\n"],"entry_point":"f_72899","intent":"sort a list of dictionaries `list_of_dicts` by `age` values of the dictionary","library":["operator"],"docs":[{"function":"operator.itemgetter","text":"operator.itemgetter(item) \noperator.itemgetter(*items) \nReturn a callable object that fetches item from its operand using the operand\u2019s __getitem__() method. If multiple items are specified, returns a tuple of lookup values. For example: After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]). Equivalent to: def itemgetter(*items):","title":"python.library.operator#operator.itemgetter"}]} {"task_id":36402748,"prompt":"def f_36402748(df):\n\treturn ","suffix":"","canonical_solution":"df.groupby('prots').sum().sort_values('scores', ascending=False)","test_start":"\nimport pandas as pd \n\ndef check(candidate):","test":["\n COLUMN_NAMES = [\"chemicals\", \"prots\", \"scores\"]\n data = [[\"chemical1\", \"prot1\", 100],[\"chemical2\", \"prot2\", 50],[\"chemical3\", \"prot1\", 120]]\n df = pd.DataFrame(data, columns = COLUMN_NAMES)\n assert candidate(df).to_dict() == {'scores': {'prot1': 220, 'prot2': 50}}\n"],"entry_point":"f_36402748","intent":"sort a Dataframe `df` by the total ocurrences in a column 'scores' group by 'prots'","library":["pandas"],"docs":[{"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 operation involves some combination of splitting the object, applying a function, and combining the results. This can be used to group large amounts of data and compute operations on these groups. Parameters ","title":"pandas.reference.api.pandas.dataframe.groupby"},{"function":"dataframe.sort_values","text":"pandas.DataFrame.sort_values DataFrame.sort_values(by, axis=0, ascending=True, inplace=False, kind='quicksort', na_position='last', ignore_index=False, key=None)[source]\n \nSort by the values along either axis. Parameters ","title":"pandas.reference.api.pandas.dataframe.sort_values"}]} {"task_id":29881993,"prompt":"def f_29881993(trans):\n\treturn ","suffix":"","canonical_solution":"\"\"\",\"\"\".join(trans['category'])","test_start":"\ndef check(candidate):","test":["\n trans = {'category':[\"hello\", \"world\",\"test\"], 'dummy_key':[\"dummy_val\"]}\n assert candidate(trans) == \"hello,world,test\"\n"],"entry_point":"f_29881993","intent":"join together with \",\" elements inside a list indexed with 'category' within a dictionary `trans`","library":[],"docs":[]} {"task_id":34158494,"prompt":"def f_34158494():\n\treturn ","suffix":"","canonical_solution":"\"\"\"\"\"\".join(['A', 'B', 'C', 'D'])","test_start":"\ndef check(candidate):","test":["\n assert candidate() == 'ABCD'\n"],"entry_point":"f_34158494","intent":"concatenate array of strings `['A', 'B', 'C', 'D']` into a string","library":[],"docs":[]} {"task_id":12666897,"prompt":"def f_12666897(sents):\n\treturn ","suffix":"","canonical_solution":"[x for x in sents if not x.startswith('@$\\t') and not x.startswith('#')]","test_start":"\ndef check(candidate):","test":["\n sents = [\"@$\tabcd\", \"#453923\", \"abcd\", \"hello\", \"1\"]\n assert candidate(sents) == [\"abcd\", \"hello\", \"1\"]\n","\n sents = [\"@$\tabcd\", \"@$t453923\", \"abcd\", \"hello\", \"1\"]\n assert candidate(sents) == [\"@$t453923\", \"abcd\", \"hello\", \"1\"]\n","\n sents = [\"#tabcd\", \"##453923\", \"abcd\", \"hello\", \"1\"]\n assert candidate(sents) == [\"abcd\", \"hello\", \"1\"] \n"],"entry_point":"f_12666897","intent":"Remove all strings from a list a strings `sents` where the values starts with `@$\\t` or `#`","library":[],"docs":[]} {"task_id":5944630,"prompt":"def f_5944630(list):\n\t","suffix":"\n\treturn list","canonical_solution":"list.sort(key=lambda item: (item['points'], item['time']))","test_start":"\ndef check(candidate):","test":["\n list = [\n {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},\n {'name':'KARL','points':50,'time': '0:03:00'},\n {'name':'TEST','points':20,'time': '0:03:00'}\n ]\n assert candidate(list) == [\n {'name':'TEST','points':20,'time': '0:03:00'}, \n {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},\n {'name':'KARL','points':50,'time': '0:03:00'}\n ]\n","\n list = [\n {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},\n {'name':'KARL','points':30,'time': '0:03:00'},\n {'name':'TEST','points':30,'time': '0:01:01'}\n ]\n assert candidate(list) == [\n {'name':'TEST','points':30,'time': '0:01:01'},\n {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},\n {'name':'KARL','points':30,'time': '0:03:00'}\n ]\n"],"entry_point":"f_5944630","intent":"sort a list of dictionary `list` first by key `points` and then by `time`","library":[],"docs":[]} {"task_id":7852855,"prompt":"def f_7852855():\n\treturn ","suffix":"","canonical_solution":"datetime.datetime(1970, 1, 1).second","test_start":"\nimport time\nimport datetime\n\ndef check(candidate):","test":["\n assert candidate() == 0\n"],"entry_point":"f_7852855","intent":"convert datetime object `(1970, 1, 1)` to seconds","library":["datetime","time"],"docs":[{"function":"datetime.datetime","text":"class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0) \nThe year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges: \nMINYEAR <= year <= MAXYEAR, \n1 <= month <= 12, \n1 <= day <= number of days in the given month and year, \n0 <= hour < 24, \n0 <= minute < 60, \n0 <= second < 60, \n0 <= microsecond < 1000000, \nfold in [0, 1]. If an argument outside those ranges is given, ValueError is raised. New in version 3.6: Added the fold argument.","title":"python.library.datetime#datetime.datetime"}]} {"task_id":2763750,"prompt":"def f_2763750():\n\treturn ","suffix":"","canonical_solution":"re.sub('(\\\\_a)?\\\\.([^\\\\.]*)$', '_suff.\\\\2', 'long.file.name.jpg')","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate() == 'long.file.name_suff.jpg'\n"],"entry_point":"f_2763750","intent":"insert `_suff` before the file extension in `long.file.name.jpg` or replace `_a` with `suff` if it precedes the extension.","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":6420361,"prompt":"def f_6420361(module):\n\t","suffix":"\n\treturn ","canonical_solution":"imp.reload(module)","test_start":"\nimport imp\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n imp.reload = Mock()\n try:\n candidate('ads')\n assert True\n except:\n assert False\n"],"entry_point":"f_6420361","intent":"reload a module `module`","library":["imp"],"docs":[{"function":"imp.reload","text":"importlib.reload(module) \nReload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter. The return value is the module object (which can be different if re-importing causes a different object to be placed in sys.modules). When reload() is executed: Python module\u2019s code is recompiled and the module-level code re-executed, defining a new set of objects which are bound to names in the module\u2019s dictionary by reusing the loader which originally loaded the module. The init function of extension modules is not called a second time. As with all other objects in Python the old objects are only reclaimed after their reference counts drop to zero. The names in the module namespace are updated to point to any new or changed objects. Other references to the old objects (such as names external to the module) are not rebound to refer to the new objects and must be updated in each namespace where they occur if that is desired. There are a number of other caveats: When a module is reloaded, its dictionary (containing the module\u2019s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem. If the new version of a module does not define a name that was defined by the old version, the old definition remains. This feature can be used to the module\u2019s advantage if it maintains a global table or cache of objects \u2014 with a try statement it can test for the table\u2019s presence and skip its initialization if desired: try:\n cache\nexcept NameError:\n cache = {}\n It is generally not very useful to reload built-in or dynamically loaded modules. Reloading sys, __main__, builtins and other key modules is not recommended. In many cases extension modules are not designed to be initialized more than once, and may fail in arbitrary ways when reloaded. If a module imports objects from another module using from \u2026 import \u2026, calling reload() for the other module does not redefine the objects imported from it \u2014 one way around this is to re-execute the from statement, another is to use import and qualified names (module.name) instead. If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances \u2014 they continue to use the old class definition. The same is true for derived classes. New in version 3.4. Changed in version 3.7: ModuleNotFoundError is raised when the module being reloaded lacks a ModuleSpec.","title":"python.library.importlib#importlib.reload"}]} {"task_id":19546911,"prompt":"def f_19546911(number):\n\treturn ","suffix":"","canonical_solution":"struct.unpack('H', struct.pack('h', number))","test_start":"\nimport struct \n\ndef check(candidate):","test":["\n assert candidate(3) == (3,)\n"],"entry_point":"f_19546911","intent":"Convert integer `number` into an unassigned integer","library":["struct"],"docs":[{"function":"struct.unpack","text":"struct.unpack(format, buffer) \nUnpack from the buffer buffer (presumably packed by pack(format, ...)) according to the format string format. The result is a tuple even if it contains exactly one item. The buffer\u2019s size in bytes must match the size required by the format, as reflected by calcsize().","title":"python.library.struct#struct.unpack"}]} {"task_id":9746522,"prompt":"def f_9746522(numlist):\n\t","suffix":"\n\treturn numlist","canonical_solution":"numlist = [float(x) for x in numlist]","test_start":"\ndef check(candidate):","test":["\n assert candidate([3, 4]) == [3.0, 4.0]\n"],"entry_point":"f_9746522","intent":"convert int values in list `numlist` to float","library":[],"docs":[]} {"task_id":20107570,"prompt":"def f_20107570(df, filename):\n\t","suffix":"\n\treturn ","canonical_solution":"df.to_csv(filename, index=False)","test_start":"\nimport pandas as pd\n\ndef check(candidate):","test":["\n file_name = 'a.csv'\n df = pd.DataFrame([1, 2, 3], columns = ['Vals'])\n candidate(df, file_name)\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert len(lines) == 4\n"],"entry_point":"f_20107570","intent":"write dataframe `df`, excluding index, to a csv file `filename`","library":["pandas"],"docs":[{"function":"df.to_csv","text":"pandas.DataFrame.to_csv DataFrame.to_csv(path_or_buf=None, sep=',', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, quotechar='\"', line_terminator=None, chunksize=None, date_format=None, doublequote=True, escapechar=None, decimal='.', errors='strict', storage_options=None)[source]\n \nWrite object to a comma-separated values (csv) file. Parameters ","title":"pandas.reference.api.pandas.dataframe.to_csv"}]} {"task_id":8740353,"prompt":"def f_8740353(unescaped):\n\t","suffix":"\n\treturn json_data","canonical_solution":"json_data = json.loads(unescaped)","test_start":"\nimport json \n\ndef check(candidate):","test":["\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', 'Email': 'jen123@gmail.com', 'Contact Number': 7867567898}\n"],"entry_point":"f_8740353","intent":"convert a urllib unquoted string `unescaped` to a json data `json_data`","library":["json"],"docs":[{"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 arguments have the same meaning as in load(). If the data being deserialized is not a valid JSON document, a JSONDecodeError will be raised. Changed in version 3.6: s can now be of type bytes or bytearray. The input encoding should be UTF-8, UTF-16 or UTF-32. Changed in version 3.9: The keyword argument encoding has been removed.","title":"python.library.json#json.loads"}]} {"task_id":5891453,"prompt":"def f_5891453():\n\treturn ","suffix":"","canonical_solution":"[chr(i) for i in range(127)]","test_start":"\ndef check(candidate):","test":["\n chars = candidate()\n assert len(chars) == 127\n assert chars == [chr(i) for i in range(127)]\n"],"entry_point":"f_5891453","intent":"Create a list containing all ascii characters as its elements","library":[],"docs":[]} {"task_id":18367007,"prompt":"def f_18367007(newFileBytes, newFile):\n\t","suffix":"\n\treturn ","canonical_solution":"newFile.write(struct.pack('5B', *newFileBytes))","test_start":"\nimport struct \n\ndef check(candidate):","test":["\n newFileBytes = [123, 3, 123, 100, 99]\n file_name = 'f.txt'\n newFile = open(file_name, 'wb')\n candidate(newFileBytes, newFile)\n newFile.close()\n with open (file_name, 'rb') as f:\n lines = f.readlines()\n assert lines == [b'{\u0003{dc']\n"],"entry_point":"f_18367007","intent":"write `newFileBytes` to a binary file `newFile`","library":["struct"],"docs":[{"function":"struct.pack","text":"struct.pack(format, v1, v2, ...) \nReturn a bytes object containing the values v1, v2, \u2026 packed according to the format string format. The arguments must match the values required by the format exactly.","title":"python.library.struct#struct.pack"}]} {"task_id":21805490,"prompt":"def f_21805490(string):\n\treturn ","suffix":"","canonical_solution":"re.sub('^[A-Z0-9]*(?![a-z])', '', string)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate(\"AASKH317298DIUANFProgramming is fun\") == \"Programming is fun\"\n"],"entry_point":"f_21805490","intent":"python regex - check for a capital letter with a following lowercase in string `string`","library":["re"],"docs":[{"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\u2019t found, string is returned unchanged. repl can be a string or a function; if it is a string, any backslash escapes in it are processed. That is, \\n is converted to a single newline character, \\r is converted to a carriage return, and so forth. Unknown escapes of ASCII letters are reserved for future use and treated as errors. Other unknown escapes such as \\& are left alone. Backreferences, such as \\6, are replaced with the substring matched by group 6 in the pattern. For example: >>> re.sub(r'def\\s+([a-zA-Z_][a-zA-Z_0-9]*)\\s*\\(\\s*\\):',\n... r'static PyObject*\\npy_\\1(void)\\n{',\n... 'def myfunc():')\n'static PyObject*\\npy_myfunc(void)\\n{'\n If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string. For example: >>> def dashrepl(matchobj):\n... if matchobj.group(0) == '-': return ' '\n... else: return '-'","title":"python.library.re#re.sub"}]} {"task_id":16125229,"prompt":"def f_16125229(dict):\n\treturn ","suffix":"","canonical_solution":"list(dict.keys())[-1]","test_start":"\ndef check(candidate):","test":["\n assert candidate({'t': 1, 'r': 2}) == 'r'\n","\n assert candidate({'c': 1, 'b': 2, 'a': 1}) == 'a'\n"],"entry_point":"f_16125229","intent":"get the last key of dictionary `dict`","library":[],"docs":[]} {"task_id":6159900,"prompt":"def f_6159900(f):\n\treturn ","suffix":"","canonical_solution":"print('hi there', file=f)","test_start":"\ndef check(candidate):","test":["\n file_name = 'a.txt'\n f = open(file_name, 'w')\n candidate(f)\n f.close()\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert lines[0] == 'hi there\\n'\n"],"entry_point":"f_6159900","intent":"write line \"hi there\" to file `f`","library":[],"docs":[]} {"task_id":6159900,"prompt":"def f_6159900(myfile):\n\t","suffix":"\n\treturn ","canonical_solution":"\n\tf = open(myfile, 'w')\n\tf.write(\"hi there\\n\")\n\tf.close()\n","test_start":"\ndef check(candidate):","test":["\n file_name = 'myfile'\n candidate(file_name)\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert lines[0] == 'hi there\\n'\n"],"entry_point":"f_6159900","intent":"write line \"hi there\" to file `myfile`","library":[],"docs":[]} {"task_id":6159900,"prompt":"def f_6159900():\n\t","suffix":"\n\treturn ","canonical_solution":"\n\twith open('somefile.txt', 'a') as the_file: \n\t\tthe_file.write('Hello\\n')\n","test_start":"\ndef check(candidate):","test":["\n file_name = 'somefile.txt'\n candidate()\n with open (file_name, 'r') as f:\n lines = f.readlines()\n assert lines[0] == 'Hello\\n'\n"],"entry_point":"f_6159900","intent":"write line \"Hello\" to file `somefile.txt`","library":[],"docs":[]} {"task_id":19527279,"prompt":"def f_19527279(s):\n\treturn ","suffix":"","canonical_solution":"s.encode('iso-8859-15')","test_start":"\ndef check(candidate):","test":["\n assert candidate('table') == b'table'\n","\n assert candidate('hello world!') == b'hello world!'\n"],"entry_point":"f_19527279","intent":"convert unicode string `s` to ascii","library":[],"docs":[]} {"task_id":356483,"prompt":"def f_356483(text):\n\treturn ","suffix":"","canonical_solution":"re.findall('Test([0-9.]*[0-9]+)', text)","test_start":"\nimport re \n\ndef check(candidate):","test":["\n assert candidate('Test0.9ssd') == ['0.9']\n","\n assert candidate('Test0.0 ..2ssd') == ['0.0']\n"],"entry_point":"f_356483","intent":"Find all numbers and dots from a string `text` using regex","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":38081866,"prompt":"def f_38081866():\n\treturn ","suffix":"","canonical_solution":"os.system('powershell.exe', 'script.ps1')","test_start":"\nimport os\nfrom unittest.mock import Mock\n\ndef check(candidate):","test":["\n os.system = Mock()\n try:\n candidate()\n assert True\n except:\n assert False\n"],"entry_point":"f_38081866","intent":"execute script 'script.ps1' using 'powershell.exe' shell","library":["os"],"docs":[{"function":"os.system","text":"os.system(command) \nExecute the command (a string) in a subshell. This is implemented by calling the Standard C function system(), and has the same limitations. Changes to sys.stdin, etc. are not reflected in the environment of the executed command. If command generates any output, it will be sent to the interpreter standard output stream. On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent. On Windows, the return value is that returned by the system shell after running command. The shell is given by the Windows environment variable COMSPEC: it is usually cmd.exe, which returns the exit status of the command run; on systems using a non-native shell, consult your shell documentation. The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes. On Unix, waitstatus_to_exitcode() can be used to convert the result (exit status) into an exit code. On Windows, the result is directly the exit code. Raises an auditing event os.system with argument command. Availability: Unix, Windows.","title":"python.library.os#os.system"}]} {"task_id":7349646,"prompt":"def f_7349646(b):\n\t","suffix":"\n\treturn b","canonical_solution":"b.sort(key=lambda x: x[2])","test_start":"\ndef check(candidate):","test":["\n b = [(1,2,3), (4,5,6), (7,8,0)]\n assert candidate(b) == [(7,8,0), (1,2,3), (4,5,6)]\n","\n b = [(1,2,'a'), (4,5,'c'), (7,8,'A')]\n assert candidate(b) == [(7,8,'A'), (1,2,'a'), (4,5,'c')]\n"],"entry_point":"f_7349646","intent":"Sort a list of tuples `b` by third item in the tuple","library":[],"docs":[]} {"task_id":10607688,"prompt":"def f_10607688():\n\treturn ","suffix":"","canonical_solution":"datetime.datetime.now()","test_start":"\nimport datetime\n\ndef check(candidate):","test":["\n y = candidate()\n assert y.year >= 2022\n"],"entry_point":"f_10607688","intent":"create a datetime with the current date & time","library":["datetime"],"docs":[{"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, this may be possible on platforms supplying the C gettimeofday() function). If tz is not None, it must be an instance of a tzinfo subclass, and the current date and time are converted to tz\u2019s time zone. This function is preferred over today() and utcnow().","title":"python.library.datetime#datetime.datetime.now"}]} {"task_id":30843103,"prompt":"def f_30843103(lst):\n\treturn ","suffix":"","canonical_solution":"next(i for i, x in enumerate(lst) if not isinstance(x, bool) and x == 1)","test_start":"\ndef check(candidate):","test":["\n lst = [True, False, 1, 3]\n assert candidate(lst) == 2\n"],"entry_point":"f_30843103","intent":"get the index of an integer `1` from a list `lst` if the list also contains boolean items","library":[],"docs":[]} {"task_id":4918425,"prompt":"def f_4918425(a):\n\t","suffix":"\n\treturn a","canonical_solution":"a[:] = [(x - 13) for x in a]","test_start":"\ndef check(candidate):","test":["\n a = [14, 15]\n candidate(a)\n assert a == [1, 2]\n","\n a = [float(x) for x in range(13, 20)]\n candidate(a)\n assert a == [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\n"],"entry_point":"f_4918425","intent":"subtract 13 from every number in a list `a`","library":[],"docs":[]} {"task_id":17794266,"prompt":"def f_17794266(x):\n\treturn ","suffix":"","canonical_solution":"max(x.min(), x.max(), key=abs)","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n x = np.matrix([[1, 1], [2, -3]])\n assert candidate(x) == -3\n"],"entry_point":"f_17794266","intent":"get the highest element in absolute value in a numpy matrix `x`","library":["numpy"],"docs":[{"function":"max","text":"numpy.ndarray.max method ndarray.max(axis=None, out=None, keepdims=False, initial=<no value>, where=True)\n \nReturn the maximum along a given axis. Refer to numpy.amax for full documentation. See also numpy.amax\n\nequivalent function","title":"numpy.reference.generated.numpy.ndarray.max"}]} {"task_id":30551576,"prompt":"def f_30551576(s):\n\treturn ","suffix":"","canonical_solution":"re.findall(r'\"(http.*?)\"', s, re.MULTILINE | re.DOTALL)","test_start":"\nimport re\n\ndef check(candidate):","test":["\n s = (\n ' [irrelevant javascript code here]'\n ' sources:[{file:\"http:\/\/url.com\/folder1\/v.html\",label:\"label1\"},'\n ' {file:\"http:\/\/url.com\/folder2\/v.html\",label:\"label2\"},'\n ' {file:\"http:\/\/url.com\/folder3\/v.html\",label:\"label3\"}],'\n ' [irrelevant javascript code here]'\n )\n assert candidate(s) == ['http:\/\/url.com\/folder1\/v.html', 'http:\/\/url.com\/folder2\/v.html', 'http:\/\/url.com\/folder3\/v.html']\n","\n s = (\n ' [irrelevant javascript code here]'\n ' [irrelevant python code here]'\n )\n assert candidate(s) == []\n"],"entry_point":"f_30551576","intent":"Get all urls within text `s`","library":["re"],"docs":[{"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 groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result. Changed in version 3.7: Non-empty matches can now start just after a previous empty match.","title":"python.library.re#re.findall"}]} {"task_id":113534,"prompt":"def f_113534(mystring):\n\treturn ","suffix":"","canonical_solution":"mystring.replace(' ', '! !').split('!')","test_start":"\ndef check(candidate):","test":["\n assert candidate(\"This is the string I want to split\") == ['This',' ','is',' ','the',' ','string',' ','I',' ','want',' ','to',' ','split']\n"],"entry_point":"f_113534","intent":"split a string `mystring` considering the spaces ' '","library":[],"docs":[]} {"task_id":5838735,"prompt":"def f_5838735(path):\n\treturn ","suffix":"","canonical_solution":"open(path, 'r')","test_start":"\ndef check(candidate):","test":["\n with open('tmp.txt', 'w') as fw: fw.write('hello world!')\n f = candidate('tmp.txt')\n assert f.name == 'tmp.txt'\n assert f.mode == 'r'\n"],"entry_point":"f_5838735","intent":"open file `path` with mode 'r'","library":[],"docs":[]} {"task_id":36003967,"prompt":"def f_36003967(data):\n\treturn ","suffix":"","canonical_solution":"[[sum(item) for item in zip(*items)] for items in zip(*data)]","test_start":"\ndef check(candidate):","test":["\n data = [[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]],\n [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]],\n [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]]\n assert candidate(data) == [[54, 40, 50, 50, 200], [20, 30, 75, 90, 180]]\n"],"entry_point":"f_36003967","intent":"sum elements at the same index in list `data`","library":[],"docs":[]} {"task_id":7635237,"prompt":"def f_7635237(a):\n\treturn ","suffix":"","canonical_solution":"a[:, (np.newaxis)]","test_start":"\nimport numpy as np \n\ndef check(candidate):","test":["\n data = np.array([[[5, 10, 30, 24, 100], [1, 9, 25, 49, 81]],\n [[15, 10, 10, 16, 70], [10, 1, 25, 11, 19]],\n [[34, 20, 10, 10, 30], [9, 20, 25, 30, 80]]])\n assert candidate(data).tolist() == [[[[ 5, 10, 30, 24, 100],\n [ 1, 9, 25, 49, 81]]],\n [[[ 15, 10, 10, 16, 70],\n [ 10, 1, 25, 11, 19]]],\n [[[ 34, 20, 10, 10, 30],\n [ 9, 20, 25, 30, 80]]]]\n"],"entry_point":"f_7635237","intent":"add a new axis to array `a`","library":["numpy"],"docs":[{"function":"numpy.newaxis","text":"numpy.newaxis\n \nA convenient alias for None, useful for indexing arrays. Examples >>> newaxis is None\nTrue","title":"numpy.reference.constants#numpy.newaxis"}]}