Instruction
stringlengths
362
7.83k
output_code
stringlengths
1
945
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def test_times(): <|code_end|> . Use current file imports: import pytest import asyncio from paco import times from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/times.py # @decorate # def times(coro, limit=1, raise_exception=False, return_value=None): # """ # Wraps a given coroutine function to be executed only a certain amount # of times. # # If the execution limit is exceeded, the last execution return value will # be returned as result. # # You can optionally define a custom return value on exceeded via # `return_value` param. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # limit (int): max limit of coroutine executions. # raise_exception (bool): raise exception if execution times exceeded. # return_value (mixed): value to return when execution times exceeded. # # Raises: # TypeError: if coro argument is not a coroutine function. # RuntimeError: if max execution excedeed (optional). # # Returns: # coroutinefunction # # Usage:: # # async def mul_2(num): # return num * 2 # # timed = paco.times(mul_2, 3) # await timed(2) # # => 4 # await timed(3) # # => 6 # await timed(4) # # => 8 # await timed(5) # ignored! # # => 8 # """ # assert_corofunction(coro=coro) # # # Store call times # limit = max(limit, 1) # times = limit # # # Store result from last execution # result = None # # @asyncio.coroutine # def wrapper(*args, **kw): # nonlocal limit # nonlocal result # # # Check execution limit # if limit == 0: # if raise_exception: # raise RuntimeError(ExceptionMessage.format(times)) # if return_value: # return return_value # return result # # # Decreases counter # limit -= 1 # # # If return_value is present, do not memoize result # if return_value: # return (yield from coro(*args, **kw)) # # # Schedule coroutine and memoize result # result = yield from coro(*args, **kw) # return result # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = times(coro, 2)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def test_times(): task = times(coro, 2) <|code_end|> . Use current file imports: import pytest import asyncio from paco import times from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/times.py # @decorate # def times(coro, limit=1, raise_exception=False, return_value=None): # """ # Wraps a given coroutine function to be executed only a certain amount # of times. # # If the execution limit is exceeded, the last execution return value will # be returned as result. # # You can optionally define a custom return value on exceeded via # `return_value` param. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # limit (int): max limit of coroutine executions. # raise_exception (bool): raise exception if execution times exceeded. # return_value (mixed): value to return when execution times exceeded. # # Raises: # TypeError: if coro argument is not a coroutine function. # RuntimeError: if max execution excedeed (optional). # # Returns: # coroutinefunction # # Usage:: # # async def mul_2(num): # return num * 2 # # timed = paco.times(mul_2, 3) # await timed(2) # # => 4 # await timed(3) # # => 6 # await timed(4) # # => 8 # await timed(5) # ignored! # # => 8 # """ # assert_corofunction(coro=coro) # # # Store call times # limit = max(limit, 1) # times = limit # # # Store result from last execution # result = None # # @asyncio.coroutine # def wrapper(*args, **kw): # nonlocal limit # nonlocal result # # # Check execution limit # if limit == 0: # if raise_exception: # raise RuntimeError(ExceptionMessage.format(times)) # if return_value: # return return_value # return result # # # Decreases counter # limit -= 1 # # # If return_value is present, do not memoize result # if return_value: # return (yield from coro(*args, **kw)) # # # Schedule coroutine and memoize result # result = yield from coro(*args, **kw) # return result # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
args, kw = run_in_loop(task, 1, 2, foo='bar')
Continue the code snippet: <|code_start|> def __init__(self, values=None): self.pos = 0 self.values = values or [1, 2, 3] @asyncio.coroutine def __aiter__(self): self.pos = 0 return self @asyncio.coroutine def __anext__(self): if self.pos == len(self.values): raise StopAsyncIteration # noqa value = self.values[self.pos] self.pos += 1 return value @asyncio.coroutine def task(numbers): return (yield from (AsyncGenerator(numbers) | paco.map(mapper) | paco.reduce(reducer, initializer=0))) result = paco.run(task([1, 2, 3, 4, 5])) assert result == 30 def test_overload_error(): with pytest.raises(TypeError, message='fn must be a callable object'): <|code_end|> . Use current file imports: import sys import pytest import asyncio import paco from paco.pipe import overload and context (classes, functions, or code) from other files: # Path: paco/pipe.py # def overload(fn): # """ # Overload a given callable object to be used with ``|`` operator # overloading. # # This is especially used for composing a pipeline of # transformation over a single data set. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # spec = getargspec(fn) # args = spec.args # if not spec.varargs and (len(args) < 2 or args[1] != 'iterable'): # raise ValueError('paco: invalid function signature or arity') # # @functools.wraps(fn) # def decorator(*args, **kw): # # Check function arity # if len(args) < 2: # return PipeOverloader(fn, args, kw) # # Otherwise, behave like a normal wrapper # return fn(*args, **kw) # # return decorator . Output only the next line.
overload(None)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): return num < 4 @asyncio.coroutine def coro_truly(num): return num < 10 def test_every_truly(): <|code_end|> . Write the next line using the current file imports: import pytest import asyncio from paco import every from .helpers import run_in_loop and context from other files: # Path: paco/every.py # @overload # @asyncio.coroutine # def every(coro, iterable, limit=1, loop=None): # """ # Returns `True` if every element in a given iterable satisfies the coroutine # asynchronous test. # # If any iteratee coroutine call returns `False`, the process is inmediately # stopped, and `False` will be returned. # # You can increase the concurrency limit for a fast race condition scenario. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine function to call with values # to reduce. # iterable (iterable): an iterable collection yielding # coroutines functions. # limit (int): max concurrency execution limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if input arguments are not valid. # # Returns: # bool: `True` if all the values passes the test, otherwise `False`. # # Usage:: # # async def gt_10(num): # return num > 10 # # await paco.every(gt_10, [1, 2, 3, 11]) # # => False # # await paco.every(gt_10, [11, 12, 13]) # # => True # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # Reduced accumulator value # passes = True # # # Handle empty iterables # if len(iterable) == 0: # return passes # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Tester function to guarantee the file is canceled. # @asyncio.coroutine # def tester(element): # nonlocal passes # if not passes: # return None # # if not (yield from coro(element)): # # Flag as not test passed # passes = False # # Force ignoring pending coroutines # pool.cancel() # # # Iterate and attach coroutine for defer scheduling # for element in iterable: # pool.add(partial(tester, element)) # # # Wait until all coroutines finish # yield from pool.run() # # return passes # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
task = every(coro_truly, [1, 2, 3, 4, 3, 1])
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): return num < 4 @asyncio.coroutine def coro_truly(num): return num < 10 def test_every_truly(): task = every(coro_truly, [1, 2, 3, 4, 3, 1]) <|code_end|> , predict the next line using imports from the current file: import pytest import asyncio from paco import every from .helpers import run_in_loop and context including class names, function names, and sometimes code from other files: # Path: paco/every.py # @overload # @asyncio.coroutine # def every(coro, iterable, limit=1, loop=None): # """ # Returns `True` if every element in a given iterable satisfies the coroutine # asynchronous test. # # If any iteratee coroutine call returns `False`, the process is inmediately # stopped, and `False` will be returned. # # You can increase the concurrency limit for a fast race condition scenario. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine function to call with values # to reduce. # iterable (iterable): an iterable collection yielding # coroutines functions. # limit (int): max concurrency execution limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if input arguments are not valid. # # Returns: # bool: `True` if all the values passes the test, otherwise `False`. # # Usage:: # # async def gt_10(num): # return num > 10 # # await paco.every(gt_10, [1, 2, 3, 11]) # # => False # # await paco.every(gt_10, [11, 12, 13]) # # => True # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # Reduced accumulator value # passes = True # # # Handle empty iterables # if len(iterable) == 0: # return passes # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Tester function to guarantee the file is canceled. # @asyncio.coroutine # def tester(element): # nonlocal passes # if not passes: # return None # # if not (yield from coro(element)): # # Flag as not test passed # passes = False # # Force ignoring pending coroutines # pool.cancel() # # # Iterate and attach coroutine for defer scheduling # for element in iterable: # pool.add(partial(tester, element)) # # # Wait until all coroutines finish # yield from pool.run() # # return passes # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
assert run_in_loop(task) is True
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): yield from asyncio.sleep(0.1) return num * 2 def test_gather(): <|code_end|> , generate the next line using the imports in this file: import time import pytest import asyncio from paco import gather, partial from .helpers import run_in_loop and context (functions, classes, or occasionally code) from other files: # Path: paco/gather.py # @asyncio.coroutine # def gather(*coros_or_futures, limit=0, loop=None, timeout=None, # preserve_order=False, return_exceptions=False): # """ # Return a future aggregating results from the given coroutine objects # with a concurrency execution limit. # # If all the tasks are done successfully, the returned future’s result is # the list of results (in the order of the original sequence, # not necessarily the order of results arrival). # # If return_exceptions is `True`, exceptions in the tasks are treated the # same as successful results, and gathered in the result list; otherwise, # the first raised exception will be immediately propagated to the # returned future. # # All futures must share the same event loop. # # This functions is mostly compatible with Python standard # ``asyncio.gather``, but providing ordered results and concurrency control # flow. # # This function is a coroutine. # # Arguments: # *coros_or_futures (coroutines|list): an iterable collection yielding # coroutines functions or futures. # limit (int): max concurrency limit. Use ``0`` for no limit. # timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # preserve_order (bool): preserves results order. # return_exceptions (bool): returns exceptions as valid results. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Returns: # list: coroutines returned results. # # Usage:: # # async def sum(x, y): # return x + y # # await paco.gather( # sum(1, 2), # sum(None, 'str'), # return_exceptions=True) # # => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa # # """ # # If no coroutines to schedule, return empty list (as Python stdlib) # if len(coros_or_futures) == 0: # return [] # # # Support iterable as first argument for better interoperability # if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): # coros_or_futures = coros_or_futures[0] # # # Pre-initialize results # results = [None] * len(coros_or_futures) if preserve_order else [] # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Iterate and attach coroutine for defer scheduling # for index, coro in enumerate(coros_or_futures): # # Validate coroutine object # if asyncio.iscoroutinefunction(coro): # coro = coro() # if not asyncio.iscoroutine(coro): # raise TypeError( # 'paco: only coroutines or coroutine functions allowed') # # # Add coroutine to the executor pool # pool.add(collect(coro, index, results, # preserve_order=preserve_order, # return_exceptions=return_exceptions)) # # # Wait until all the tasks finishes # yield from pool.run(timeout=timeout, return_exceptions=return_exceptions) # # # Returns aggregated results # return results # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
results = run_in_loop(gather(coro(1), coro(2), coro(3),
Given the code snippet: <|code_start|>@asyncio.coroutine def coro(num): yield from asyncio.sleep(0.1) return num * 2 def test_gather(): results = run_in_loop(gather(coro(1), coro(2), coro(3), preserve_order=True)) assert results == [2, 4, 6] # Test array first argument results = run_in_loop(gather([coro(1), coro(2), coro(3)], preserve_order=True)) assert results == [2, 4, 6] def test_gather_sequential(): start = time.time() results = run_in_loop(gather(coro(1), coro(2), coro(3), limit=1)) assert results == [2, 4, 6] assert time.time() - start >= 0.3 def test_gather_empty(): results = run_in_loop(gather(limit=1)) assert results == [] def test_gather_coroutinefunction(): <|code_end|> , generate the next line using the imports in this file: import time import pytest import asyncio from paco import gather, partial from .helpers import run_in_loop and context (functions, classes, or occasionally code) from other files: # Path: paco/gather.py # @asyncio.coroutine # def gather(*coros_or_futures, limit=0, loop=None, timeout=None, # preserve_order=False, return_exceptions=False): # """ # Return a future aggregating results from the given coroutine objects # with a concurrency execution limit. # # If all the tasks are done successfully, the returned future’s result is # the list of results (in the order of the original sequence, # not necessarily the order of results arrival). # # If return_exceptions is `True`, exceptions in the tasks are treated the # same as successful results, and gathered in the result list; otherwise, # the first raised exception will be immediately propagated to the # returned future. # # All futures must share the same event loop. # # This functions is mostly compatible with Python standard # ``asyncio.gather``, but providing ordered results and concurrency control # flow. # # This function is a coroutine. # # Arguments: # *coros_or_futures (coroutines|list): an iterable collection yielding # coroutines functions or futures. # limit (int): max concurrency limit. Use ``0`` for no limit. # timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # preserve_order (bool): preserves results order. # return_exceptions (bool): returns exceptions as valid results. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Returns: # list: coroutines returned results. # # Usage:: # # async def sum(x, y): # return x + y # # await paco.gather( # sum(1, 2), # sum(None, 'str'), # return_exceptions=True) # # => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa # # """ # # If no coroutines to schedule, return empty list (as Python stdlib) # if len(coros_or_futures) == 0: # return [] # # # Support iterable as first argument for better interoperability # if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): # coros_or_futures = coros_or_futures[0] # # # Pre-initialize results # results = [None] * len(coros_or_futures) if preserve_order else [] # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Iterate and attach coroutine for defer scheduling # for index, coro in enumerate(coros_or_futures): # # Validate coroutine object # if asyncio.iscoroutinefunction(coro): # coro = coro() # if not asyncio.iscoroutine(coro): # raise TypeError( # 'paco: only coroutines or coroutine functions allowed') # # # Add coroutine to the executor pool # pool.add(collect(coro, index, results, # preserve_order=preserve_order, # return_exceptions=return_exceptions)) # # # Wait until all the tasks finishes # yield from pool.run(timeout=timeout, return_exceptions=return_exceptions) # # # Returns aggregated results # return results # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
results = run_in_loop(gather(partial(coro, 1), partial(coro, 2), limit=1))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): yield from asyncio.sleep(0.1) return num * 2 def test_gather(): <|code_end|> . Write the next line using the current file imports: import time import pytest import asyncio from paco import gather, partial from .helpers import run_in_loop and context from other files: # Path: paco/gather.py # @asyncio.coroutine # def gather(*coros_or_futures, limit=0, loop=None, timeout=None, # preserve_order=False, return_exceptions=False): # """ # Return a future aggregating results from the given coroutine objects # with a concurrency execution limit. # # If all the tasks are done successfully, the returned future’s result is # the list of results (in the order of the original sequence, # not necessarily the order of results arrival). # # If return_exceptions is `True`, exceptions in the tasks are treated the # same as successful results, and gathered in the result list; otherwise, # the first raised exception will be immediately propagated to the # returned future. # # All futures must share the same event loop. # # This functions is mostly compatible with Python standard # ``asyncio.gather``, but providing ordered results and concurrency control # flow. # # This function is a coroutine. # # Arguments: # *coros_or_futures (coroutines|list): an iterable collection yielding # coroutines functions or futures. # limit (int): max concurrency limit. Use ``0`` for no limit. # timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # preserve_order (bool): preserves results order. # return_exceptions (bool): returns exceptions as valid results. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Returns: # list: coroutines returned results. # # Usage:: # # async def sum(x, y): # return x + y # # await paco.gather( # sum(1, 2), # sum(None, 'str'), # return_exceptions=True) # # => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa # # """ # # If no coroutines to schedule, return empty list (as Python stdlib) # if len(coros_or_futures) == 0: # return [] # # # Support iterable as first argument for better interoperability # if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): # coros_or_futures = coros_or_futures[0] # # # Pre-initialize results # results = [None] * len(coros_or_futures) if preserve_order else [] # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Iterate and attach coroutine for defer scheduling # for index, coro in enumerate(coros_or_futures): # # Validate coroutine object # if asyncio.iscoroutinefunction(coro): # coro = coro() # if not asyncio.iscoroutine(coro): # raise TypeError( # 'paco: only coroutines or coroutine functions allowed') # # # Add coroutine to the executor pool # pool.add(collect(coro, index, results, # preserve_order=preserve_order, # return_exceptions=return_exceptions)) # # # Wait until all the tasks finishes # yield from pool.run(timeout=timeout, return_exceptions=return_exceptions) # # # Returns aggregated results # return results # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
results = run_in_loop(gather(coro(1), coro(2), coro(3),
Given snippet: <|code_start|># -*- coding: utf-8 -*- def test_whilst(): calls = 0 @asyncio.coroutine def coro_test(): return calls < 5 @asyncio.coroutine def coro(): nonlocal calls calls += 1 return calls <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import asyncio from paco import whilst from .helpers import run_in_loop and context: # Path: paco/whilst.py # @asyncio.coroutine # def whilst(coro, coro_test, assert_coro=None, *args, **kw): # """ # Repeatedly call `coro` coroutine function while `coro_test` returns `True`. # # This function is the inverse of `paco.until()`. # # This function is a coroutine. # # Arguments: # coro (coroutinefunction): coroutine function to execute. # coro_test (coroutinefunction): coroutine function to test. # assert_coro (coroutinefunction): optional assertion coroutine used # to determine if the test passed or not. # *args (mixed): optional variadic arguments to pass to `coro` function. # # Raises: # TypeError: if input arguments are invalid. # # Returns: # list: result values returned by `coro`. # # Usage:: # # calls = 0 # # async def task(): # nonlocal calls # calls += 1 # return calls # # async def calls_lt_4(): # return calls > 4 # # await paco.until(task, calls_lt_4) # # => [1, 2, 3, 4, 5] # # """ # assert_corofunction(coro=coro, coro_test=coro_test) # # # Store yielded values by coroutine # results = [] # # # Set assertion coroutine # assert_coro = assert_coro or assert_true # # # Execute coroutine until a certain # while (yield from assert_coro((yield from coro_test()))): # results.append((yield from coro(*args, **kw))) # # return results # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) which might include code, classes, or functions. Output only the next line.
task = whilst(coro, coro_test)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- def test_whilst(): calls = 0 @asyncio.coroutine def coro_test(): return calls < 5 @asyncio.coroutine def coro(): nonlocal calls calls += 1 return calls task = whilst(coro, coro_test) <|code_end|> . Write the next line using the current file imports: import pytest import asyncio from paco import whilst from .helpers import run_in_loop and context from other files: # Path: paco/whilst.py # @asyncio.coroutine # def whilst(coro, coro_test, assert_coro=None, *args, **kw): # """ # Repeatedly call `coro` coroutine function while `coro_test` returns `True`. # # This function is the inverse of `paco.until()`. # # This function is a coroutine. # # Arguments: # coro (coroutinefunction): coroutine function to execute. # coro_test (coroutinefunction): coroutine function to test. # assert_coro (coroutinefunction): optional assertion coroutine used # to determine if the test passed or not. # *args (mixed): optional variadic arguments to pass to `coro` function. # # Raises: # TypeError: if input arguments are invalid. # # Returns: # list: result values returned by `coro`. # # Usage:: # # calls = 0 # # async def task(): # nonlocal calls # calls += 1 # return calls # # async def calls_lt_4(): # return calls > 4 # # await paco.until(task, calls_lt_4) # # => [1, 2, 3, 4, 5] # # """ # assert_corofunction(coro=coro, coro_test=coro_test) # # # Store yielded values by coroutine # results = [] # # # Set assertion coroutine # assert_coro = assert_coro or assert_true # # # Execute coroutine until a certain # while (yield from assert_coro((yield from coro_test()))): # results.append((yield from coro(*args, **kw))) # # return results # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
assert run_in_loop(task) == [1, 2, 3, 4, 5]
Given the code snippet: <|code_start|> This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. limit (int): max limit of coroutine executions. raise_exception (bool): raise exception if execution times exceeded. return_value (mixed): value to return when execution times exceeded. Raises: TypeError: if coro argument is not a coroutine function. RuntimeError: if max execution excedeed (optional). Returns: coroutinefunction Usage:: async def mul_2(num): return num * 2 timed = paco.times(mul_2, 3) await timed(2) # => 4 await timed(3) # => 6 await timed(4) # => 8 await timed(5) # ignored! # => 8 """ <|code_end|> , generate the next line using the imports in this file: import asyncio from .decorator import decorate from .assertions import assert_corofunction and context (functions, classes, or occasionally code) from other files: # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator # # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) . Output only the next line.
assert_corofunction(coro=coro)
Continue the code snippet: <|code_start|> assert_coro (coroutinefunction): optional assertion coroutine used to determine if the test passed or not. *args (mixed): optional variadic arguments to pass to `coro` function. Raises: TypeError: if input arguments are invalid. Returns: list: result values returned by `coro`. Usage:: calls = 0 async def task(): nonlocal calls calls += 1 return calls async def calls_gt_4(): return calls > 4 await paco.until(task, calls_gt_4) # => [1, 2, 3, 4, 5] """ @asyncio.coroutine def assert_coro(value): return not value <|code_end|> . Use current file imports: import asyncio from .whilst import whilst and context (classes, functions, or code) from other files: # Path: paco/whilst.py # @asyncio.coroutine # def whilst(coro, coro_test, assert_coro=None, *args, **kw): # """ # Repeatedly call `coro` coroutine function while `coro_test` returns `True`. # # This function is the inverse of `paco.until()`. # # This function is a coroutine. # # Arguments: # coro (coroutinefunction): coroutine function to execute. # coro_test (coroutinefunction): coroutine function to test. # assert_coro (coroutinefunction): optional assertion coroutine used # to determine if the test passed or not. # *args (mixed): optional variadic arguments to pass to `coro` function. # # Raises: # TypeError: if input arguments are invalid. # # Returns: # list: result values returned by `coro`. # # Usage:: # # calls = 0 # # async def task(): # nonlocal calls # calls += 1 # return calls # # async def calls_lt_4(): # return calls > 4 # # await paco.until(task, calls_lt_4) # # => [1, 2, 3, 4, 5] # # """ # assert_corofunction(coro=coro, coro_test=coro_test) # # # Store yielded values by coroutine # results = [] # # # Set assertion coroutine # assert_coro = assert_coro or assert_true # # # Execute coroutine until a certain # while (yield from assert_coro((yield from coro_test()))): # results.append((yield from coro(*args, **kw))) # # return results . Output only the next line.
return (yield from whilst(coro, coro_test,
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): return num < 4 def test_dropwhile(): <|code_end|> . Use current file imports: import pytest import asyncio from paco import dropwhile from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/dropwhile.py # @overload # @asyncio.coroutine # def dropwhile(coro, iterable, loop=None): # """ # Make an iterator that drops elements from the iterable as long as the # predicate is true; afterwards, returns every element. # # Note, the iterator does not produce any output until the predicate first # becomes false, so it may have a lengthy start-up time. # # This function is pretty much equivalent to Python standard # `itertools.dropwhile()`, but designed to be used with async coroutines. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine function to call with values # to reduce. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # filtered values (list): ordered list of resultant values. # # Usage:: # # async def filter(num): # return num < 4 # # await paco.dropwhile(filter, [1, 2, 3, 4, 5, 1]) # # => [4, 5, 1] # # """ # drop = False # # @asyncio.coroutine # def assert_fn(element): # nonlocal drop # # if element and not drop: # return False # # if not element and not drop: # drop = True # # return True if drop else element # # @asyncio.coroutine # def filter_fn(element): # return (yield from coro(element)) # # return (yield from filter(filter_fn, iterable, # assert_fn=assert_fn, limit=1, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = dropwhile(coro, [1, 2, 3, 4, 3, 1])
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): return num < 4 def test_dropwhile(): task = dropwhile(coro, [1, 2, 3, 4, 3, 1]) <|code_end|> with the help of current file imports: import pytest import asyncio from paco import dropwhile from .helpers import run_in_loop and context from other files: # Path: paco/dropwhile.py # @overload # @asyncio.coroutine # def dropwhile(coro, iterable, loop=None): # """ # Make an iterator that drops elements from the iterable as long as the # predicate is true; afterwards, returns every element. # # Note, the iterator does not produce any output until the predicate first # becomes false, so it may have a lengthy start-up time. # # This function is pretty much equivalent to Python standard # `itertools.dropwhile()`, but designed to be used with async coroutines. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine function to call with values # to reduce. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # filtered values (list): ordered list of resultant values. # # Usage:: # # async def filter(num): # return num < 4 # # await paco.dropwhile(filter, [1, 2, 3, 4, 5, 1]) # # => [4, 5, 1] # # """ # drop = False # # @asyncio.coroutine # def assert_fn(element): # nonlocal drop # # if element and not drop: # return False # # if not element and not drop: # drop = True # # return True if drop else element # # @asyncio.coroutine # def filter_fn(element): # return (yield from coro(element)) # # return (yield from filter(filter_fn, iterable, # assert_fn=assert_fn, limit=1, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may contain function names, class names, or code. Output only the next line.
assert run_in_loop(task) == [4, 3, 1]
Using the snippet: <|code_start|># -*- coding: utf-8 -*- # Yielded iterable error IterableError = TypeError('pipeline yielded a non iterable object') class PipeOverloader(object): """ Pipe operator overloader object wrapping a given fn. """ def __init__(self, fn, args, kw): self.__fn = fn self.__args = args self.__kw = kw @asyncio.coroutine def __await_coro(self, coro): return (yield from self.__trigger((yield from coro))) @asyncio.coroutine def __consume_generator(self, iterable): <|code_end|> , determine the next line of code. You have imports: import asyncio import functools from inspect import isfunction, getargspec from .generator import consume from .assertions import isiter and context (class names, function names, or code) available: # Path: paco/generator.py # @asyncio.coroutine # def consume(generator): # pragma: no cover # """ # Helper function to consume a synchronous or asynchronous generator. # # Arguments: # generator (generator|asyncgenerator): generator to consume. # # Returns: # list # """ # # If synchronous generator, just consume and return as list # if hasattr(generator, '__next__'): # return list(generator) # # if not PY_35: # raise RuntimeError( # 'paco: asynchronous iterator protocol not supported') # # # If asynchronous generator, consume it generator protocol manually # buf = [] # while True: # try: # buf.append((yield from generator.__anext__())) # except StopAsyncIteration: # noqa # break # # return buf # # Path: paco/assertions.py # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) . Output only the next line.
return (yield from self.__trigger((yield from consume(iterable))))
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- # Yielded iterable error IterableError = TypeError('pipeline yielded a non iterable object') class PipeOverloader(object): """ Pipe operator overloader object wrapping a given fn. """ def __init__(self, fn, args, kw): self.__fn = fn self.__args = args self.__kw = kw @asyncio.coroutine def __await_coro(self, coro): return (yield from self.__trigger((yield from coro))) @asyncio.coroutine def __consume_generator(self, iterable): return (yield from self.__trigger((yield from consume(iterable)))) def __trigger(self, iterable): <|code_end|> . Use current file imports: import asyncio import functools from inspect import isfunction, getargspec from .generator import consume from .assertions import isiter and context (classes, functions, or code) from other files: # Path: paco/generator.py # @asyncio.coroutine # def consume(generator): # pragma: no cover # """ # Helper function to consume a synchronous or asynchronous generator. # # Arguments: # generator (generator|asyncgenerator): generator to consume. # # Returns: # list # """ # # If synchronous generator, just consume and return as list # if hasattr(generator, '__next__'): # return list(generator) # # if not PY_35: # raise RuntimeError( # 'paco: asynchronous iterator protocol not supported') # # # If asynchronous generator, consume it generator protocol manually # buf = [] # while True: # try: # buf.append((yield from generator.__anext__())) # except StopAsyncIteration: # noqa # break # # return buf # # Path: paco/assertions.py # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) . Output only the next line.
if not isiter(iterable):
Predict the next line after this snippet: <|code_start|> This is similar to `paco.partial()`. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. *args (mixed): mixed variadic arguments for partial application. *kwargs (mixed): mixed variadic keyword arguments for partial application. Raises: TypeError: if coro argument is not a coroutine function. Returns: coroutinefunction: wrapped coroutine function. Usage:: async def hello(name, mark='!'): print('Hello, {name}{mark}'.format(name=name, mark=mark)) hello_mike = paco.apply(hello, 'Mike') await hello_mike() # => Hello, Mike! hello_mike = paco.apply(hello, 'Mike', mark='?') await hello_mike() # => Hello, Mike? """ <|code_end|> using the current file's imports: import asyncio from .decorator import decorate from .assertions import assert_corofunction and any relevant context from other files: # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator # # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) . Output only the next line.
assert_corofunction(coro=coro)
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def even(num): return num % 2 == 0 def test_filterfalse(): <|code_end|> using the current file's imports: import time import pytest import asyncio from paco import filterfalse from .helpers import run_in_loop and any relevant context from other files: # Path: paco/filterfalse.py # @overload # @asyncio.coroutine # def filterfalse(coro, iterable, limit=0, loop=None): # """ # Returns a list of all the values in coll which pass an asynchronous truth # test coroutine. # # Operations are executed concurrently by default, but results # will be in order. # # You can configure the concurrency via `limit` param. # # This function is the asynchronous equivalent port Python built-in # `filterfalse()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine filter function to call accepting # iterable values. # iterable (iterable): an iterable collection yielding # coroutines functions. # assert_fn (coroutinefunction): optional assertion function. # limit (int): max filtering concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # filtered values (list): ordered list containing values that do not # passed the filter. # # Usage:: # # async def iseven(num): # return num % 2 == 0 # # await paco.filterfalse(coro, [1, 2, 3, 4, 5]) # # => [1, 3, 5] # # """ # return (yield from filter(coro, iterable, # assert_fn=assert_false, # limit=limit, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = filterfalse(even, [1, 2, 3, 4, 5, 6])
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def even(num): return num % 2 == 0 def test_filterfalse(): task = filterfalse(even, [1, 2, 3, 4, 5, 6]) <|code_end|> . Write the next line using the current file imports: import time import pytest import asyncio from paco import filterfalse from .helpers import run_in_loop and context from other files: # Path: paco/filterfalse.py # @overload # @asyncio.coroutine # def filterfalse(coro, iterable, limit=0, loop=None): # """ # Returns a list of all the values in coll which pass an asynchronous truth # test coroutine. # # Operations are executed concurrently by default, but results # will be in order. # # You can configure the concurrency via `limit` param. # # This function is the asynchronous equivalent port Python built-in # `filterfalse()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine filter function to call accepting # iterable values. # iterable (iterable): an iterable collection yielding # coroutines functions. # assert_fn (coroutinefunction): optional assertion function. # limit (int): max filtering concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # filtered values (list): ordered list containing values that do not # passed the filter. # # Usage:: # # async def iseven(num): # return num % 2 == 0 # # await paco.filterfalse(coro, [1, 2, 3, 4, 5]) # # => [1, 3, 5] # # """ # return (yield from filter(coro, iterable, # assert_fn=assert_false, # limit=limit, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
assert run_in_loop(task) == [1, 3, 5]
Using the snippet: <|code_start|> timeout (int/float): maximum number of seconds to wait before returning. return_exceptions (bool): exceptions in the tasks are treated the same as successful results, instead of raising them. loop (asyncio.BaseEventLoop): optional event loop to use. *args (mixed): optional variadic argument to pass to the coroutines function. Returns: list: coroutines returned results. Raises: TypeError: in case of invalid coroutine object. ValueError: in case of empty set of coroutines or futures. TimeoutError: if execution takes more than expected. Usage:: async def sum(x, y): return x + y await paco.series( sum(1, 2), sum(2, 3), sum(3, 4)) # => [3, 5, 7] """ <|code_end|> , determine the next line of code. You have imports: import asyncio from .gather import gather and context (class names, function names, or code) available: # Path: paco/gather.py # @asyncio.coroutine # def gather(*coros_or_futures, limit=0, loop=None, timeout=None, # preserve_order=False, return_exceptions=False): # """ # Return a future aggregating results from the given coroutine objects # with a concurrency execution limit. # # If all the tasks are done successfully, the returned future’s result is # the list of results (in the order of the original sequence, # not necessarily the order of results arrival). # # If return_exceptions is `True`, exceptions in the tasks are treated the # same as successful results, and gathered in the result list; otherwise, # the first raised exception will be immediately propagated to the # returned future. # # All futures must share the same event loop. # # This functions is mostly compatible with Python standard # ``asyncio.gather``, but providing ordered results and concurrency control # flow. # # This function is a coroutine. # # Arguments: # *coros_or_futures (coroutines|list): an iterable collection yielding # coroutines functions or futures. # limit (int): max concurrency limit. Use ``0`` for no limit. # timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # preserve_order (bool): preserves results order. # return_exceptions (bool): returns exceptions as valid results. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Returns: # list: coroutines returned results. # # Usage:: # # async def sum(x, y): # return x + y # # await paco.gather( # sum(1, 2), # sum(None, 'str'), # return_exceptions=True) # # => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa # # """ # # If no coroutines to schedule, return empty list (as Python stdlib) # if len(coros_or_futures) == 0: # return [] # # # Support iterable as first argument for better interoperability # if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): # coros_or_futures = coros_or_futures[0] # # # Pre-initialize results # results = [None] * len(coros_or_futures) if preserve_order else [] # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Iterate and attach coroutine for defer scheduling # for index, coro in enumerate(coros_or_futures): # # Validate coroutine object # if asyncio.iscoroutinefunction(coro): # coro = coro() # if not asyncio.iscoroutine(coro): # raise TypeError( # 'paco: only coroutines or coroutine functions allowed') # # # Add coroutine to the executor pool # pool.add(collect(coro, index, results, # preserve_order=preserve_order, # return_exceptions=return_exceptions)) # # # Wait until all the tasks finishes # yield from pool.run(timeout=timeout, return_exceptions=return_exceptions) # # # Returns aggregated results # return results . Output only the next line.
return (yield from gather(*coros_or_futures,
Given the code snippet: <|code_start|> @decorate def partial(coro, *args, **kw): """ Partial function implementation designed for coroutines, allowing variadic input arguments. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. *args (mixed): mixed variadic arguments for partial application. Raises: TypeError: if ``coro`` is not a coroutine function. Returns: coroutinefunction Usage:: async def pow(x, y): return x ** y pow_2 = paco.partial(pow, 2) await pow_2(4) # => 16 """ <|code_end|> , generate the next line using the imports in this file: import asyncio from .decorator import decorate from .assertions import assert_corofunction and context (functions, classes, or occasionally code) from other files: # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator # # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) . Output only the next line.
assert_corofunction(coro=coro)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- def test_repeat(): calls = 0 @asyncio.coroutine def coro(num): nonlocal calls calls += 1 return num * 2 <|code_end|> . Use current file imports: import pytest import asyncio from paco import repeat from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/repeat.py # @asyncio.coroutine # def repeat(coro, times=1, step=1, limit=1, loop=None): # """ # Executes the coroutine function ``x`` number of times, # and accumulates results in order as you would use with ``map``. # # Execution concurrency is configurable using ``limit`` param. # # This function is a coroutine. # # Arguments: # coro (coroutinefunction): coroutine function to schedule. # times (int): number of times to execute the coroutine. # step (int): increment iteration step, as with ``range()``. # limit (int): concurrency execution limit. Defaults to 10. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro is not a coroutine function. # # Returns: # list: accumulated yielded values returned by coroutine. # # Usage:: # # async def mul_2(num): # return num * 2 # # await paco.repeat(mul_2, times=5) # # => [2, 4, 6, 8, 10] # # """ # assert_corofunction(coro=coro) # # # Iterate and attach coroutine for defer scheduling # times = max(int(times), 1) # iterable = range(1, times + 1, step) # # # Run iterable times # return (yield from map(coro, iterable, limit=limit, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
assert run_in_loop(repeat(coro, 5)) == [2, 4, 6, 8, 10]
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- def test_repeat(): calls = 0 @asyncio.coroutine def coro(num): nonlocal calls calls += 1 return num * 2 <|code_end|> , predict the next line using imports from the current file: import pytest import asyncio from paco import repeat from .helpers import run_in_loop and context including class names, function names, and sometimes code from other files: # Path: paco/repeat.py # @asyncio.coroutine # def repeat(coro, times=1, step=1, limit=1, loop=None): # """ # Executes the coroutine function ``x`` number of times, # and accumulates results in order as you would use with ``map``. # # Execution concurrency is configurable using ``limit`` param. # # This function is a coroutine. # # Arguments: # coro (coroutinefunction): coroutine function to schedule. # times (int): number of times to execute the coroutine. # step (int): increment iteration step, as with ``range()``. # limit (int): concurrency execution limit. Defaults to 10. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro is not a coroutine function. # # Returns: # list: accumulated yielded values returned by coroutine. # # Usage:: # # async def mul_2(num): # return num * 2 # # await paco.repeat(mul_2, times=5) # # => [2, 4, 6, 8, 10] # # """ # assert_corofunction(coro=coro) # # # Iterate and attach coroutine for defer scheduling # times = max(int(times), 1) # iterable = range(1, times + 1, step) # # # Run iterable times # return (yield from map(coro, iterable, limit=limit, loop=loop)) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
assert run_in_loop(repeat(coro, 5)) == [2, 4, 6, 8, 10]
Given the following code snippet before the placeholder: <|code_start|>def test_isfunc(): @asyncio.coroutine def coro(): pass assert isfunc(test_isfunc) assert isfunc(lambda: True) assert not isfunc(coro) assert not isfunc(tuple()) assert not isfunc([]) assert not isfunc('foo') assert not isfunc(bytes()) assert not isfunc(True) @asyncio.coroutine def coro(*args, **kw): return args, kw def test_iscoro_or_(): assert iscoro_or_corofunc(coro) assert iscoro_or_corofunc(coro()) assert not iscoro_or_corofunc(lambda: True) assert not iscoro_or_corofunc(None) assert not iscoro_or_corofunc(1) assert not iscoro_or_corofunc(True) def test_assert_corofunction(): <|code_end|> , predict the next line using imports from the current file: import pytest import asyncio from paco.assertions import (assert_corofunction, assert_iter, isiter, iscoro_or_corofunc, iscallable, isfunc) and context including class names, function names, and sometimes code from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # def assert_iter(**kw): # """ # Asserts if a given values implements a valid iterable interface. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not isiter(value): # raise TypeError( # 'paco: {} must be an iterable object'.format(name)) # # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) # # def iscoro_or_corofunc(x): # """ # Returns ``True`` if the given value is a coroutine or a coroutine function. # # Arguments: # x (mixed): object value to assert. # # Returns: # bool: returns ``True`` if ``x` is a coroutine or coroutine function. # """ # return asyncio.iscoroutinefunction(x) or asyncio.iscoroutine(x) # # def iscallable(x): # """ # Returns `True` if the given value is a callable primitive object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # isfunc(x), # asyncio.iscoroutinefunction(x) # ]) # # def isfunc(x): # """ # Returns `True` if the given value is a function or method object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), # inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) # ]) . Output only the next line.
assert_corofunction(coro=coro)
Given the following code snippet before the placeholder: <|code_start|> assert not isfunc(coro) assert not isfunc(tuple()) assert not isfunc([]) assert not isfunc('foo') assert not isfunc(bytes()) assert not isfunc(True) @asyncio.coroutine def coro(*args, **kw): return args, kw def test_iscoro_or_(): assert iscoro_or_corofunc(coro) assert iscoro_or_corofunc(coro()) assert not iscoro_or_corofunc(lambda: True) assert not iscoro_or_corofunc(None) assert not iscoro_or_corofunc(1) assert not iscoro_or_corofunc(True) def test_assert_corofunction(): assert_corofunction(coro=coro) with pytest.raises(TypeError, message='coro must be a coroutine function'): assert_corofunction(coro=None) def test_assert_iter(): <|code_end|> , predict the next line using imports from the current file: import pytest import asyncio from paco.assertions import (assert_corofunction, assert_iter, isiter, iscoro_or_corofunc, iscallable, isfunc) and context including class names, function names, and sometimes code from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # def assert_iter(**kw): # """ # Asserts if a given values implements a valid iterable interface. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not isiter(value): # raise TypeError( # 'paco: {} must be an iterable object'.format(name)) # # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) # # def iscoro_or_corofunc(x): # """ # Returns ``True`` if the given value is a coroutine or a coroutine function. # # Arguments: # x (mixed): object value to assert. # # Returns: # bool: returns ``True`` if ``x` is a coroutine or coroutine function. # """ # return asyncio.iscoroutinefunction(x) or asyncio.iscoroutine(x) # # def iscallable(x): # """ # Returns `True` if the given value is a callable primitive object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # isfunc(x), # asyncio.iscoroutinefunction(x) # ]) # # def isfunc(x): # """ # Returns `True` if the given value is a function or method object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), # inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) # ]) . Output only the next line.
assert_iter(iterable=())
Here is a snippet: <|code_start|> assert iscallable(lambda: True) assert iscallable(coro) assert not iscallable(tuple()) assert not iscallable([]) assert not iscallable('foo') assert not iscallable(bytes()) assert not iscallable(True) def test_isfunc(): @asyncio.coroutine def coro(): pass assert isfunc(test_isfunc) assert isfunc(lambda: True) assert not isfunc(coro) assert not isfunc(tuple()) assert not isfunc([]) assert not isfunc('foo') assert not isfunc(bytes()) assert not isfunc(True) @asyncio.coroutine def coro(*args, **kw): return args, kw def test_iscoro_or_(): <|code_end|> . Write the next line using the current file imports: import pytest import asyncio from paco.assertions import (assert_corofunction, assert_iter, isiter, iscoro_or_corofunc, iscallable, isfunc) and context from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # def assert_iter(**kw): # """ # Asserts if a given values implements a valid iterable interface. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not isiter(value): # raise TypeError( # 'paco: {} must be an iterable object'.format(name)) # # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) # # def iscoro_or_corofunc(x): # """ # Returns ``True`` if the given value is a coroutine or a coroutine function. # # Arguments: # x (mixed): object value to assert. # # Returns: # bool: returns ``True`` if ``x` is a coroutine or coroutine function. # """ # return asyncio.iscoroutinefunction(x) or asyncio.iscoroutine(x) # # def iscallable(x): # """ # Returns `True` if the given value is a callable primitive object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # isfunc(x), # asyncio.iscoroutinefunction(x) # ]) # # def isfunc(x): # """ # Returns `True` if the given value is a function or method object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), # inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) # ]) , which may include functions, classes, or code. Output only the next line.
assert iscoro_or_corofunc(coro)
Next line prediction: <|code_start|># -*- coding: utf-8 -*- def test_isiter(): assert isiter(()) assert isiter([]) assert not isiter('foo') assert not isiter(bytes()) assert not isiter(True) def test_iscallable(): @asyncio.coroutine def coro(): pass <|code_end|> . Use current file imports: (import pytest import asyncio from paco.assertions import (assert_corofunction, assert_iter, isiter, iscoro_or_corofunc, iscallable, isfunc)) and context including class names, function names, or small code snippets from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # def assert_iter(**kw): # """ # Asserts if a given values implements a valid iterable interface. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not isiter(value): # raise TypeError( # 'paco: {} must be an iterable object'.format(name)) # # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) # # def iscoro_or_corofunc(x): # """ # Returns ``True`` if the given value is a coroutine or a coroutine function. # # Arguments: # x (mixed): object value to assert. # # Returns: # bool: returns ``True`` if ``x` is a coroutine or coroutine function. # """ # return asyncio.iscoroutinefunction(x) or asyncio.iscoroutine(x) # # def iscallable(x): # """ # Returns `True` if the given value is a callable primitive object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # isfunc(x), # asyncio.iscoroutinefunction(x) # ]) # # def isfunc(x): # """ # Returns `True` if the given value is a function or method object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), # inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) # ]) . Output only the next line.
assert iscallable(test_iscallable)
Here is a snippet: <|code_start|> def test_isiter(): assert isiter(()) assert isiter([]) assert not isiter('foo') assert not isiter(bytes()) assert not isiter(True) def test_iscallable(): @asyncio.coroutine def coro(): pass assert iscallable(test_iscallable) assert iscallable(lambda: True) assert iscallable(coro) assert not iscallable(tuple()) assert not iscallable([]) assert not iscallable('foo') assert not iscallable(bytes()) assert not iscallable(True) def test_isfunc(): @asyncio.coroutine def coro(): pass <|code_end|> . Write the next line using the current file imports: import pytest import asyncio from paco.assertions import (assert_corofunction, assert_iter, isiter, iscoro_or_corofunc, iscallable, isfunc) and context from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # def assert_iter(**kw): # """ # Asserts if a given values implements a valid iterable interface. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not isiter(value): # raise TypeError( # 'paco: {} must be an iterable object'.format(name)) # # def isiter(x): # """ # Returns `True` if the given value implements an valid iterable # interface. # # Arguments: # x (mixed): value to check if it is an iterable. # # Returns: # bool # """ # return hasattr(x, '__iter__') and not isinstance(x, (str, bytes)) # # def iscoro_or_corofunc(x): # """ # Returns ``True`` if the given value is a coroutine or a coroutine function. # # Arguments: # x (mixed): object value to assert. # # Returns: # bool: returns ``True`` if ``x` is a coroutine or coroutine function. # """ # return asyncio.iscoroutinefunction(x) or asyncio.iscoroutine(x) # # def iscallable(x): # """ # Returns `True` if the given value is a callable primitive object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # isfunc(x), # asyncio.iscoroutinefunction(x) # ]) # # def isfunc(x): # """ # Returns `True` if the given value is a function or method object. # # Arguments: # x (mixed): value to check. # # Returns: # bool # """ # return any([ # inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), # inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) # ]) , which may include functions, classes, or code. Output only the next line.
assert isfunc(test_isfunc)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def test_once(): <|code_end|> . Use current file imports: import pytest import asyncio from paco import once from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/once.py # @decorate # def once(coro, raise_exception=False, return_value=None): # """ # Wrap a given coroutine function that is restricted to one execution. # # Repeated calls to the coroutine function will return the value of the first # invocation. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # raise_exception (bool): raise exception if execution times exceeded. # return_value (mixed): value to return when execution times exceeded, # instead of the memoized one from last invocation. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def mul_2(num): # return num * 2 # # once = paco.once(mul_2) # await once(2) # # => 4 # await once(3) # # => 4 # # once = paco.once(mul_2, return_value='exceeded') # await once(2) # # => 4 # await once(3) # # => 'exceeded' # # """ # return times(coro, # limit=1, # return_value=return_value, # raise_exception=raise_exception) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = once(coro)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def test_once(): task = once(coro) <|code_end|> . Use current file imports: import pytest import asyncio from paco import once from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/once.py # @decorate # def once(coro, raise_exception=False, return_value=None): # """ # Wrap a given coroutine function that is restricted to one execution. # # Repeated calls to the coroutine function will return the value of the first # invocation. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # raise_exception (bool): raise exception if execution times exceeded. # return_value (mixed): value to return when execution times exceeded, # instead of the memoized one from last invocation. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def mul_2(num): # return num * 2 # # once = paco.once(mul_2) # await once(2) # # => 4 # await once(3) # # => 4 # # once = paco.once(mul_2, return_value='exceeded') # await once(2) # # => 4 # await once(3) # # => 'exceeded' # # """ # return times(coro, # limit=1, # return_value=return_value, # raise_exception=raise_exception) # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
args, kw = run_in_loop(task, 1, 2, foo='bar')
Using the snippet: <|code_start|> arguments: coro (coroutinefunction): coroutine function to wrap. raise_exception (bool): raise exception if execution times exceeded. return_value (mixed): value to return when execution times exceeded, instead of the memoized one from last invocation. Raises: TypeError: if coro argument is not a coroutine function. Returns: coroutinefunction Usage:: async def mul_2(num): return num * 2 once = paco.once(mul_2) await once(2) # => 4 await once(3) # => 4 once = paco.once(mul_2, return_value='exceeded') await once(2) # => 4 await once(3) # => 'exceeded' """ <|code_end|> , determine the next line of code. You have imports: from .times import times from .decorator import decorate and context (class names, function names, or code) available: # Path: paco/times.py # @decorate # def times(coro, limit=1, raise_exception=False, return_value=None): # """ # Wraps a given coroutine function to be executed only a certain amount # of times. # # If the execution limit is exceeded, the last execution return value will # be returned as result. # # You can optionally define a custom return value on exceeded via # `return_value` param. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # limit (int): max limit of coroutine executions. # raise_exception (bool): raise exception if execution times exceeded. # return_value (mixed): value to return when execution times exceeded. # # Raises: # TypeError: if coro argument is not a coroutine function. # RuntimeError: if max execution excedeed (optional). # # Returns: # coroutinefunction # # Usage:: # # async def mul_2(num): # return num * 2 # # timed = paco.times(mul_2, 3) # await timed(2) # # => 4 # await timed(3) # # => 6 # await timed(4) # # => 8 # await timed(5) # ignored! # # => 8 # """ # assert_corofunction(coro=coro) # # # Store call times # limit = max(limit, 1) # times = limit # # # Store result from last execution # result = None # # @asyncio.coroutine # def wrapper(*args, **kw): # nonlocal limit # nonlocal result # # # Check execution limit # if limit == 0: # if raise_exception: # raise RuntimeError(ExceptionMessage.format(times)) # if return_value: # return return_value # return result # # # Decreases counter # limit -= 1 # # # If return_value is present, do not memoize result # if return_value: # return (yield from coro(*args, **kw)) # # # Schedule coroutine and memoize result # result = yield from coro(*args, **kw) # return result # # return wrapper # # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator . Output only the next line.
return times(coro,
Predict the next line for this snippet: <|code_start|> """ Executes the coroutine function ``x`` number of times, and accumulates results in order as you would use with ``map``. Execution concurrency is configurable using ``limit`` param. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to schedule. times (int): number of times to execute the coroutine. step (int): increment iteration step, as with ``range()``. limit (int): concurrency execution limit. Defaults to 10. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if coro is not a coroutine function. Returns: list: accumulated yielded values returned by coroutine. Usage:: async def mul_2(num): return num * 2 await paco.repeat(mul_2, times=5) # => [2, 4, 6, 8, 10] """ <|code_end|> with the help of current file imports: import asyncio from .assertions import assert_corofunction from .map import map and context from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # Path: paco/map.py # @overload # @asyncio.coroutine # def map(coro, iterable, limit=0, loop=None, timeout=None, # return_exceptions=False, *args, **kw): # """ # Concurrently maps values yielded from an iterable, passing then # into an asynchronous coroutine function. # # Mapped values will be returned as list. # Items order will be preserved based on origin iterable order. # # Concurrency level can be configurable via ``limit`` param. # # This function is the asynchronous equivalent port Python built-in # `map()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutinefunction): map coroutine function to use. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # limit (int): max concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # timeout (int|float): timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # return_exceptions (bool): returns exceptions as valid results. # *args (mixed): optional variadic arguments to be passed to the # coroutine map function. # # Returns: # list: ordered list of values yielded by coroutines # # Usage:: # # async def mul_2(num): # return num * 2 # # await paco.map(mul_2, [1, 2, 3, 4, 5]) # # => [2, 4, 6, 8, 10] # # """ # # Call each iterable but collecting yielded values # return (yield from each(coro, iterable, # limit=limit, loop=loop, # timeout=timeout, collect=True, # return_exceptions=return_exceptions, # *args, **kw)) , which may contain function names, class names, or code. Output only the next line.
assert_corofunction(coro=coro)
Continue the code snippet: <|code_start|> Arguments: coro (coroutinefunction): coroutine function to schedule. times (int): number of times to execute the coroutine. step (int): increment iteration step, as with ``range()``. limit (int): concurrency execution limit. Defaults to 10. loop (asyncio.BaseEventLoop): optional event loop to use. Raises: TypeError: if coro is not a coroutine function. Returns: list: accumulated yielded values returned by coroutine. Usage:: async def mul_2(num): return num * 2 await paco.repeat(mul_2, times=5) # => [2, 4, 6, 8, 10] """ assert_corofunction(coro=coro) # Iterate and attach coroutine for defer scheduling times = max(int(times), 1) iterable = range(1, times + 1, step) # Run iterable times <|code_end|> . Use current file imports: import asyncio from .assertions import assert_corofunction from .map import map and context (classes, functions, or code) from other files: # Path: paco/assertions.py # def assert_corofunction(**kw): # """ # Asserts if a given values are a coroutine function. # # Arguments: # **kw (mixed): value to check if it is an iterable. # # Raises: # TypeError: if assertion fails. # """ # for name, value in kw.items(): # if not asyncio.iscoroutinefunction(value): # raise TypeError( # 'paco: {} must be a coroutine function'.format(name)) # # Path: paco/map.py # @overload # @asyncio.coroutine # def map(coro, iterable, limit=0, loop=None, timeout=None, # return_exceptions=False, *args, **kw): # """ # Concurrently maps values yielded from an iterable, passing then # into an asynchronous coroutine function. # # Mapped values will be returned as list. # Items order will be preserved based on origin iterable order. # # Concurrency level can be configurable via ``limit`` param. # # This function is the asynchronous equivalent port Python built-in # `map()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutinefunction): map coroutine function to use. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # limit (int): max concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # timeout (int|float): timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # return_exceptions (bool): returns exceptions as valid results. # *args (mixed): optional variadic arguments to be passed to the # coroutine map function. # # Returns: # list: ordered list of values yielded by coroutines # # Usage:: # # async def mul_2(num): # return num * 2 # # await paco.map(mul_2, [1, 2, 3, 4, 5]) # # => [2, 4, 6, 8, 10] # # """ # # Call each iterable but collecting yielded values # return (yield from each(coro, iterable, # limit=limit, loop=loop, # timeout=timeout, collect=True, # return_exceptions=return_exceptions, # *args, **kw)) . Output only the next line.
return (yield from map(coro, iterable, limit=limit, loop=loop))
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num): return num * 2 def test_run(): <|code_end|> , predict the next line using imports from the current file: import asyncio from paco import run and context including class names, function names, and sometimes code from other files: # Path: paco/run.py # def run(coro, loop=None): # """ # Convenient shortcut alias to ``loop.run_until_complete``. # # Arguments: # coro (coroutine): coroutine object to schedule. # loop (asyncio.BaseEventLoop): optional event loop to use. # Defaults to: ``asyncio.get_event_loop()``. # # Returns: # mixed: returned value by coroutine. # # Usage:: # # async def mul_2(num): # return num * 2 # # paco.run(mul_2(4)) # # => 8 # # """ # loop = loop or asyncio.get_event_loop() # return loop.run_until_complete(coro) . Output only the next line.
assert run(coro(2)) == 4
Given snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def task(): return 'foo' def test_thunk(): <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import asyncio from paco import thunk from .helpers import run_in_loop and context: # Path: paco/thunk.py # def thunk(coro): # """ # A thunk is a subroutine that is created, often automatically, to assist # a call to another subroutine. # # Creates a thunk coroutine which returns coroutine function that accepts no # arguments and when invoked it schedules the wrapper coroutine and # returns the final result. # # See Wikipedia page for more information about Thunk subroutines: # https://en.wikipedia.org/wiki/Thunk # # Arguments: # value (coroutinefunction): wrapped coroutine function to invoke. # # Returns: # coroutinefunction # # Usage:: # # async def task(): # return 'foo' # # coro = paco.thunk(task) # # await coro() # # => 'foo' # await coro() # # => 'foo' # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(): # return (yield from coro()) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) which might include code, classes, or functions. Output only the next line.
coro = thunk(task)
Given snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def task(): return 'foo' def test_thunk(): coro = thunk(task) <|code_end|> , continue by predicting the next line. Consider current file imports: import pytest import asyncio from paco import thunk from .helpers import run_in_loop and context: # Path: paco/thunk.py # def thunk(coro): # """ # A thunk is a subroutine that is created, often automatically, to assist # a call to another subroutine. # # Creates a thunk coroutine which returns coroutine function that accepts no # arguments and when invoked it schedules the wrapper coroutine and # returns the final result. # # See Wikipedia page for more information about Thunk subroutines: # https://en.wikipedia.org/wiki/Thunk # # Arguments: # value (coroutinefunction): wrapped coroutine function to invoke. # # Returns: # coroutinefunction # # Usage:: # # async def task(): # return 'foo' # # coro = paco.thunk(task) # # await coro() # # => 'foo' # await coro() # # => 'foo' # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(): # return (yield from coro()) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) which might include code, classes, or functions. Output only the next line.
assert run_in_loop(coro()) == 'foo'
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def sample(coro, *args, **kw): return coro(*args, **kw) def test_decorate_with_arguments(): <|code_end|> , determine the next line of code. You have imports: import pytest import asyncio from paco.decorator import decorate from .helpers import run_in_loop and context (class names, function names, or code) available: # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
wrapper = decorate(sample)
Given the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(*args, **kw): return args, kw def sample(coro, *args, **kw): return coro(*args, **kw) def test_decorate_with_arguments(): wrapper = decorate(sample) task = wrapper(1, foo='bar') <|code_end|> , generate the next line using the imports in this file: import pytest import asyncio from paco.decorator import decorate from .helpers import run_in_loop and context (functions, classes, or occasionally code) from other files: # Path: paco/decorator.py # def decorate(fn): # """ # Generic decorator for coroutines helper functions allowing # multiple variadic initialization arguments. # # This function is intended to be used internally. # # Arguments: # fn (function): target function to decorate. # # Raises: # TypeError: if function or coroutine function is not provided. # # Returns: # function: decorated function. # """ # if not isfunction(fn): # raise TypeError('paco: fn must be a callable object') # # @functools.wraps(fn) # def decorator(*args, **kw): # # If coroutine object is passed # for arg in args: # if iscoro_or_corofunc(arg): # return fn(*args, **kw) # # # Explicit argument must be at least a coroutine # if len(args) and args[0] is None: # raise TypeError('paco: first argument cannot be empty') # # def wrapper(coro, *_args, **_kw): # # coro must be a valid type # if not iscoro_or_corofunc(coro): # raise TypeError('paco: first argument must be a ' # 'coroutine or coroutine function') # # # Merge call arguments # _args = ((coro,) + (args + _args)) # kw.update(_kw) # # # Trigger original decorated function # return fn(*_args, **kw) # return wrapper # return decorator # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
args, kw = run_in_loop(task, coro, 2, bar='baz')
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num, acc): yield from asyncio.sleep(0.1) return acc + (num,) def test_compose(): <|code_end|> , determine the next line of code. You have imports: import time import pytest import asyncio from paco import compose, partial from .helpers import run_in_loop and context (class names, function names, or code) available: # Path: paco/compose.py # def compose(*coros): # """ # Creates a coroutine function based on the composition of the passed # coroutine functions. # # Each function consumes the yielded result of the coroutine that follows. # # Composing coroutine functions f(), g(), and h() would produce # the result of f(g(h())). # # Arguments: # *coros (coroutinefunction): variadic coroutine functions to compose. # # Raises: # RuntimeError: if cannot execute a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def sum_1(num): # return num + 1 # # async def mul_2(num): # return num * 2 # # coro = paco.compose(sum_1, mul_2, sum_1) # await coro(2) # # => 7 # # """ # # Make list to inherit built-in type methods # coros = list(coros) # # @asyncio.coroutine # def reducer(acc, coro): # return (yield from coro(acc)) # # @asyncio.coroutine # def wrapper(acc): # return (yield from reduce(reducer, coros, # initializer=acc, right=True)) # # return wrapper # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = compose(partial(coro, 1), partial(coro, 2), partial(coro, 3))
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num, acc): yield from asyncio.sleep(0.1) return acc + (num,) def test_compose(): <|code_end|> , predict the next line using imports from the current file: import time import pytest import asyncio from paco import compose, partial from .helpers import run_in_loop and context including class names, function names, and sometimes code from other files: # Path: paco/compose.py # def compose(*coros): # """ # Creates a coroutine function based on the composition of the passed # coroutine functions. # # Each function consumes the yielded result of the coroutine that follows. # # Composing coroutine functions f(), g(), and h() would produce # the result of f(g(h())). # # Arguments: # *coros (coroutinefunction): variadic coroutine functions to compose. # # Raises: # RuntimeError: if cannot execute a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def sum_1(num): # return num + 1 # # async def mul_2(num): # return num * 2 # # coro = paco.compose(sum_1, mul_2, sum_1) # await coro(2) # # => 7 # # """ # # Make list to inherit built-in type methods # coros = list(coros) # # @asyncio.coroutine # def reducer(acc, coro): # return (yield from coro(acc)) # # @asyncio.coroutine # def wrapper(acc): # return (yield from reduce(reducer, coros, # initializer=acc, right=True)) # # return wrapper # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = compose(partial(coro, 1), partial(coro, 2), partial(coro, 3))
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(num, acc): yield from asyncio.sleep(0.1) return acc + (num,) def test_compose(): task = compose(partial(coro, 1), partial(coro, 2), partial(coro, 3)) now = time.time() <|code_end|> . Write the next line using the current file imports: import time import pytest import asyncio from paco import compose, partial from .helpers import run_in_loop and context from other files: # Path: paco/compose.py # def compose(*coros): # """ # Creates a coroutine function based on the composition of the passed # coroutine functions. # # Each function consumes the yielded result of the coroutine that follows. # # Composing coroutine functions f(), g(), and h() would produce # the result of f(g(h())). # # Arguments: # *coros (coroutinefunction): variadic coroutine functions to compose. # # Raises: # RuntimeError: if cannot execute a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def sum_1(num): # return num + 1 # # async def mul_2(num): # return num * 2 # # coro = paco.compose(sum_1, mul_2, sum_1) # await coro(2) # # => 7 # # """ # # Make list to inherit built-in type methods # coros = list(coros) # # @asyncio.coroutine # def reducer(acc, coro): # return (yield from coro(acc)) # # @asyncio.coroutine # def wrapper(acc): # return (yield from reduce(reducer, coros, # initializer=acc, right=True)) # # return wrapper # # Path: paco/partial.py # @decorate # def partial(coro, *args, **kw): # """ # Partial function implementation designed # for coroutines, allowing variadic input arguments. # # This function can be used as decorator. # # arguments: # coro (coroutinefunction): coroutine function to wrap. # *args (mixed): mixed variadic arguments for partial application. # # Raises: # TypeError: if ``coro`` is not a coroutine function. # # Returns: # coroutinefunction # # Usage:: # # async def pow(x, y): # return x ** y # # pow_2 = paco.partial(pow, 2) # await pow_2(4) # # => 16 # # """ # assert_corofunction(coro=coro) # # @asyncio.coroutine # def wrapper(*_args, **_kw): # call_args = args + _args # kw.update(_kw) # return (yield from coro(*call_args, **kw)) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
assert run_in_loop(task, (0,)) == (0, 3, 2, 1)
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(track): track['calls'] += 1 def test_interval(): track = {'calls': 0} start = time.time() <|code_end|> . Write the next line using the current file imports: import time import pytest import asyncio from paco import interval from .helpers import run_in_loop and context from other files: # Path: paco/interval.py # @decorate # def interval(coro, interval=1, times=None, loop=None): # """ # Schedules the execution of a coroutine function every `x` amount of # seconds. # # The function returns an `asyncio.Task`, which implements also an # `asyncio.Future` interface, allowing the user to cancel the execution # cycle. # # This function can be used as decorator. # # Arguments: # coro (coroutinefunction): coroutine function to defer. # interval (int/float): number of seconds to repeat the coroutine # execution. # times (int): optional maximum time of executions. Infinite by default. # loop (asyncio.BaseEventLoop, optional): loop to run. # Defaults to asyncio.get_event_loop(). # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # future (asyncio.Task): coroutine wrapped as task future. # Useful for cancellation and state checking. # # Usage:: # # # Usage as function # future = paco.interval(coro, 1) # # # Cancel it after a while... # await asyncio.sleep(5) # future.cancel() # # # Usage as decorator # @paco.interval(10) # async def metrics(): # await send_metrics() # # future = await metrics() # # """ # assert_corofunction(coro=coro) # # # Store maximum allowed number of calls # times = int(times or 0) or float('inf') # # @asyncio.coroutine # def schedule(times, *args, **kw): # while times > 0: # # Decrement times counter # times -= 1 # # # Schedule coroutine # yield from coro(*args, **kw) # yield from asyncio.sleep(interval) # # def wrapper(*args, **kw): # return ensure_future(schedule(times, *args, **kw), loop=loop) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) , which may include functions, classes, or code. Output only the next line.
task = interval(coro, .1, 5)
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def coro(track): track['calls'] += 1 def test_interval(): track = {'calls': 0} start = time.time() task = interval(coro, .1, 5) future = task(track) <|code_end|> . Use current file imports: import time import pytest import asyncio from paco import interval from .helpers import run_in_loop and context (classes, functions, or code) from other files: # Path: paco/interval.py # @decorate # def interval(coro, interval=1, times=None, loop=None): # """ # Schedules the execution of a coroutine function every `x` amount of # seconds. # # The function returns an `asyncio.Task`, which implements also an # `asyncio.Future` interface, allowing the user to cancel the execution # cycle. # # This function can be used as decorator. # # Arguments: # coro (coroutinefunction): coroutine function to defer. # interval (int/float): number of seconds to repeat the coroutine # execution. # times (int): optional maximum time of executions. Infinite by default. # loop (asyncio.BaseEventLoop, optional): loop to run. # Defaults to asyncio.get_event_loop(). # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # future (asyncio.Task): coroutine wrapped as task future. # Useful for cancellation and state checking. # # Usage:: # # # Usage as function # future = paco.interval(coro, 1) # # # Cancel it after a while... # await asyncio.sleep(5) # future.cancel() # # # Usage as decorator # @paco.interval(10) # async def metrics(): # await send_metrics() # # future = await metrics() # # """ # assert_corofunction(coro=coro) # # # Store maximum allowed number of calls # times = int(times or 0) or float('inf') # # @asyncio.coroutine # def schedule(times, *args, **kw): # while times > 0: # # Decrement times counter # times -= 1 # # # Schedule coroutine # yield from coro(*args, **kw) # yield from asyncio.sleep(interval) # # def wrapper(*args, **kw): # return ensure_future(schedule(times, *args, **kw), loop=loop) # # return wrapper # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
run_in_loop(future)
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def even(num): return num % 2 == 0 def test_filter(): <|code_end|> , predict the next line using imports from the current file: import time import pytest import asyncio from paco import filter from .helpers import run_in_loop and context including class names, function names, and sometimes code from other files: # Path: paco/filter.py # @overload # @asyncio.coroutine # def filter(coro, iterable, assert_fn=None, limit=0, loop=None): # """ # Returns a list of all the values in coll which pass an asynchronous truth # test coroutine. # # Operations are executed concurrently by default, but results # will be in order. # # You can configure the concurrency via `limit` param. # # This function is the asynchronous equivalent port Python built-in # `filter()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine filter function to call accepting # iterable values. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # assert_fn (coroutinefunction): optional assertion function. # limit (int): max filtering concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # list: ordered list containing values that passed # the filter. # # Usage:: # # async def iseven(num): # return num % 2 == 0 # # async def assert_false(el): # return not el # # await paco.filter(iseven, [1, 2, 3, 4, 5]) # # => [2, 4] # # await paco.filter(iseven, [1, 2, 3, 4, 5], assert_fn=assert_false) # # => [1, 3, 5] # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # Check valid or empty iterable # if len(iterable) == 0: # return iterable # # # Reduced accumulator value # results = [None] * len(iterable) # # # Use a custom or default filter assertion function # assert_fn = assert_fn or assert_true # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Reducer partial function for deferred coroutine execution # def filterer(index, element): # @asyncio.coroutine # def wrapper(): # result = yield from coro(element) # if (yield from assert_fn(result)): # results[index] = element # return wrapper # # # Iterate and attach coroutine for defer scheduling # for index, element in enumerate(iterable): # pool.add(filterer(index, element)) # # # Wait until all coroutines finish # yield from pool.run(ignore_empty=True) # # # Returns filtered elements # return [x for x in results if x is not None] # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
task = filter(even, [1, 2, 3, 4, 5, 6])
Using the snippet: <|code_start|># -*- coding: utf-8 -*- @asyncio.coroutine def even(num): return num % 2 == 0 def test_filter(): task = filter(even, [1, 2, 3, 4, 5, 6]) <|code_end|> , determine the next line of code. You have imports: import time import pytest import asyncio from paco import filter from .helpers import run_in_loop and context (class names, function names, or code) available: # Path: paco/filter.py # @overload # @asyncio.coroutine # def filter(coro, iterable, assert_fn=None, limit=0, loop=None): # """ # Returns a list of all the values in coll which pass an asynchronous truth # test coroutine. # # Operations are executed concurrently by default, but results # will be in order. # # You can configure the concurrency via `limit` param. # # This function is the asynchronous equivalent port Python built-in # `filter()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine filter function to call accepting # iterable values. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # assert_fn (coroutinefunction): optional assertion function. # limit (int): max filtering concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # list: ordered list containing values that passed # the filter. # # Usage:: # # async def iseven(num): # return num % 2 == 0 # # async def assert_false(el): # return not el # # await paco.filter(iseven, [1, 2, 3, 4, 5]) # # => [2, 4] # # await paco.filter(iseven, [1, 2, 3, 4, 5], assert_fn=assert_false) # # => [1, 3, 5] # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # Check valid or empty iterable # if len(iterable) == 0: # return iterable # # # Reduced accumulator value # results = [None] * len(iterable) # # # Use a custom or default filter assertion function # assert_fn = assert_fn or assert_true # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Reducer partial function for deferred coroutine execution # def filterer(index, element): # @asyncio.coroutine # def wrapper(): # result = yield from coro(element) # if (yield from assert_fn(result)): # results[index] = element # return wrapper # # # Iterate and attach coroutine for defer scheduling # for index, element in enumerate(iterable): # pool.add(filterer(index, element)) # # # Wait until all coroutines finish # yield from pool.run(ignore_empty=True) # # # Returns filtered elements # return [x for x in results if x is not None] # # Path: tests/helpers.py # def run_in_loop(coro, *args, **kw): # loop = asyncio.get_event_loop() # if asyncio.iscoroutinefunction(coro) or isfunction(coro): # coro = coro(*args, **kw) # return loop.run_until_complete(coro) . Output only the next line.
assert run_in_loop(task) == [2, 4, 6]
Predict the next line after this snippet: <|code_start|> This function can be composed in a pipeline chain with ``|`` operator. Arguments: coro (coroutinefunction): map coroutine function to use. iterable (iterable|asynchronousiterable): an iterable collection yielding coroutines functions. limit (int): max concurrency limit. Use ``0`` for no limit. loop (asyncio.BaseEventLoop): optional event loop to use. timeout (int|float): timeout can be used to control the maximum number of seconds to wait before returning. timeout can be an int or float. If timeout is not specified or None, there is no limit to the wait time. return_exceptions (bool): returns exceptions as valid results. *args (mixed): optional variadic arguments to be passed to the coroutine map function. Returns: list: ordered list of values yielded by coroutines Usage:: async def mul_2(num): return num * 2 await paco.map(mul_2, [1, 2, 3, 4, 5]) # => [2, 4, 6, 8, 10] """ # Call each iterable but collecting yielded values <|code_end|> using the current file's imports: import asyncio from .each import each from .decorator import overload and any relevant context from other files: # Path: paco/each.py # @overload # @asyncio.coroutine # def each(coro, iterable, limit=0, loop=None, # collect=False, timeout=None, return_exceptions=False, *args, **kw): # """ # Concurrently iterates values yielded from an iterable, passing them to # an asynchronous coroutine. # # You can optionally collect yielded values passing collect=True param, # which would be equivalent to `paco.map()``. # # Mapped values will be returned as an ordered list. # Items order is preserved based on origin iterable order. # # Concurrency level can be configurable via `limit` param. # # All coroutines will be executed in the same loop. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutinefunction): coroutine iterator function that accepts # iterable values. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # limit (int): max iteration concurrency limit. Use ``0`` for no limit. # collect (bool): return yielded values from coroutines. Default False. # loop (asyncio.BaseEventLoop): optional event loop to use. # return_exceptions (bool): enable/disable returning exceptions in case # of error. `collect` param must be True. # timeout (int|float): timeout can be used to control the maximum number # of seconds to wait before returning. timeout can be an int or # float. If timeout is not specified or None, there is no limit to # the wait time. # *args (mixed): optional variadic arguments to pass to the # coroutine iterable function. # # Returns: # results (list): ordered list of values yielded by coroutines # # Raises: # TypeError: in case of invalid input arguments. # # Usage:: # # async def mul_2(num): # return num * 2 # # await paco.each(mul_2, [1, 2, 3, 4, 5]) # # => None # # await paco.each(mul_2, [1, 2, 3, 4, 5], collect=True) # # => [2, 4, 6, 8, 10] # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # By default do not collect yielded values from coroutines # results = None # # if collect: # # Store ordered results # results = [None] * len(iterable) # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # @asyncio.coroutine # def collector(index, item): # result = yield from safe_run(coro(item, *args, **kw), # return_exceptions=return_exceptions) # if collect: # results[index] = result # # return result # # # Iterate and pass elements to coroutine # for index, value in enumerate(iterable): # pool.add(collector(index, value)) # # # Wait until all the coroutines finishes # yield from pool.run(return_exceptions=return_exceptions, # ignore_empty=True, # timeout=timeout) # # # Returns list of mapped results in order # return results # # Path: paco/decorator.py # def generator_consumer(coro): # pragma: no cover # def wrapper(*args, **kw): # def decorate(fn): # def decorator(*args, **kw): # def wrapper(coro, *_args, **_kw): . Output only the next line.
return (yield from each(coro, iterable,
Given the following code snippet before the placeholder: <|code_start|> Returns: filtered values (list): ordered list of resultant values. Usage:: async def filter(num): return num < 4 await paco.dropwhile(filter, [1, 2, 3, 4, 5, 1]) # => [4, 5, 1] """ drop = False @asyncio.coroutine def assert_fn(element): nonlocal drop if element and not drop: return False if not element and not drop: drop = True return True if drop else element @asyncio.coroutine def filter_fn(element): return (yield from coro(element)) <|code_end|> , predict the next line using imports from the current file: import asyncio from .filter import filter from .decorator import overload and context including class names, function names, and sometimes code from other files: # Path: paco/filter.py # @overload # @asyncio.coroutine # def filter(coro, iterable, assert_fn=None, limit=0, loop=None): # """ # Returns a list of all the values in coll which pass an asynchronous truth # test coroutine. # # Operations are executed concurrently by default, but results # will be in order. # # You can configure the concurrency via `limit` param. # # This function is the asynchronous equivalent port Python built-in # `filter()` function. # # This function is a coroutine. # # This function can be composed in a pipeline chain with ``|`` operator. # # Arguments: # coro (coroutine function): coroutine filter function to call accepting # iterable values. # iterable (iterable|asynchronousiterable): an iterable collection # yielding coroutines functions. # assert_fn (coroutinefunction): optional assertion function. # limit (int): max filtering concurrency limit. Use ``0`` for no limit. # loop (asyncio.BaseEventLoop): optional event loop to use. # # Raises: # TypeError: if coro argument is not a coroutine function. # # Returns: # list: ordered list containing values that passed # the filter. # # Usage:: # # async def iseven(num): # return num % 2 == 0 # # async def assert_false(el): # return not el # # await paco.filter(iseven, [1, 2, 3, 4, 5]) # # => [2, 4] # # await paco.filter(iseven, [1, 2, 3, 4, 5], assert_fn=assert_false) # # => [1, 3, 5] # # """ # assert_corofunction(coro=coro) # assert_iter(iterable=iterable) # # # Check valid or empty iterable # if len(iterable) == 0: # return iterable # # # Reduced accumulator value # results = [None] * len(iterable) # # # Use a custom or default filter assertion function # assert_fn = assert_fn or assert_true # # # Create concurrent executor # pool = ConcurrentExecutor(limit=limit, loop=loop) # # # Reducer partial function for deferred coroutine execution # def filterer(index, element): # @asyncio.coroutine # def wrapper(): # result = yield from coro(element) # if (yield from assert_fn(result)): # results[index] = element # return wrapper # # # Iterate and attach coroutine for defer scheduling # for index, element in enumerate(iterable): # pool.add(filterer(index, element)) # # # Wait until all coroutines finish # yield from pool.run(ignore_empty=True) # # # Returns filtered elements # return [x for x in results if x is not None] # # Path: paco/decorator.py # def generator_consumer(coro): # pragma: no cover # def wrapper(*args, **kw): # def decorate(fn): # def decorator(*args, **kw): # def wrapper(coro, *_args, **_kw): . Output only the next line.
return (yield from filter(filter_fn, iterable,
Using the snippet: <|code_start|> def circle(cx, cy, r, n): result = [] for i in range(n + 1): p = i / float(n) a = 2 * pi * p x = cx + cos(a) * r y = cy + sin(a) * r result.append((x, y)) return result def main(): mm = 25.4 w = 11 * mm h = 8.5 * mm p = 0.5 * mm s = 0.25 * mm <|code_end|> , determine the next line of code. You have imports: from math import sin, cos, pi, hypot from poisson_disc import poisson_disc import random import time import xy and context (class names, function names, or code) available: # Path: poisson_disc.py # def poisson_disc(x1, y1, x2, y2, r, n): # grid = Grid(r) # active = [] # for i in range(1): # x = x1 + random.random() * (x2 - x1) # y = y1 + random.random() * (y2 - y1) # x = (x1 + x2) / 2.0 # y = (y1 + y2) / 2.0 # a = random.random() * 2 * pi # if grid.insert(x, y): # active.append((x, y, a, 0, 0, i)) # pairs = [] # while active: # ax, ay, aa, ai, ad, ag = record = choice(active) # for i in range(n): # # a = random.random() * 2 * pi # a = aa + (random.random() - 0.5) * max_angle(ai, ad) # # a = random.gauss(aa, pi / 8) # d = random.random() * r + r # x = ax + cos(a) * d # y = ay + sin(a) * d # if x < x1 or y < y1 or x > x2 or y > y2: # continue # if ad + d > 150: # continue # pair = ((ax, ay), (x, y)) # line = LineString(pair) # if not grid.insert(x, y, line): # continue # pairs.append(pair) # active.append((x, y, a, ai + 1, ad + d, ag)) # active.sort(key=lambda x: -x[4]) # # if random.random() < 0.5: # # active.remove(record) # break # else: # active.remove(record) # return grid.points.values(), pairs . Output only the next line.
points = poisson_disc(p, p, w - p * 2, h - p * 2, s, 32)
Given the following code snippet before the placeholder: <|code_start|> class Scene(object): def __init__(self, shapes): self.shapes = shapes self.tree = tree.Tree(shapes) def paths(self): result = [] for shape in self.shapes: result.extend(shape.paths()) return result def intersect(self, o, d, tmin, tmax): return self.tree.intersect(o, d, tmin, tmax) def clip_paths(self, eye, step): print 'Clipping paths...' <|code_end|> , predict the next line using imports from the current file: from matrix import Matrix from xy import progress import itertools import tree import util and context including class names, function names, and sometimes code from other files: # Path: xy/progress.py # def pretty_time(seconds): # def __init__(self, max_value=100, min_value=0): # def percent_complete(self): # def elapsed_time(self): # def eta(self): # def __call__(self, sequence): # def __enter__(self): # def __exit__(self, exc_type, exc_val, exc_tb): # def update(self, value): # def done(self): # def stop(self): # def render(self): # def render_percent_complete(self): # def render_value(self): # def render_bar(self, size=30): # def render_elapsed_time(self): # def render_eta(self): # class Bar(object): . Output only the next line.
bar = progress.Bar()
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import __author__ = 'Last G' class AnswerForm(forms.ModelForm): class Meta: <|code_end|> , predict the next line using imports from the current file: from django import forms from .models import QuestAnswer from django.utils.translation import ugettext as _ and context including class names, function names, and sometimes code from other files: # Path: apps/quests/models.py # class QuestAnswer(qtils.CreateAndUpdateDateMixin, qtils.ModelDiffMixin, models.Model): # """Model that describes someones try to score quest""" # quest_variant = models.ForeignKey(QuestVariant, blank=False, null=False) # # is_checked = models.BooleanField(default=False, null=False, blank=False, db_index=True) # is_success = models.BooleanField(default=False, null=False, blank=False, db_index=True) # # result = models.TextField(editable=True, blank=True, null=False) # score = models.IntegerField(default=0, null=False, blank=False, db_index=True) # # answer = models.TextField() # answer_file = models.FileField(upload_to="media", editable=False) # # class Meta(object): # index_together = [ # ['is_success', 'is_checked'], # ['quest_variant', 'is_success', 'is_checked'], # ] # # @classmethod # def count_by_time(cls, team, period=timedelta(minutes=1)): # return cls.objects.filter(quest_variant__team__id=team.id, created_at__gte=timezone.now() - period).aggregate( # count=Count('id'))['count'] # # def check_answer(self): # status, message = self.quest_variant.check_answer(self.answer) # self.is_checked = True # self.is_success = status # self.result = message # self.score = self.quest_variant.quest.score # self.save() # # def get_absolute_url(self): # from django.core.urlresolvers import reverse # # return reverse('quests.views.check_answer', args=[self.id]) . Output only the next line.
model = QuestAnswer
Here is a snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import __author__ = 'Last G' class TokenAuthBackend(object): def authenticate(self, token=None): if token: <|code_end|> . Write the next line using the current file imports: from .models import Team and context from other files: # Path: apps/teams/models.py # class Team(AbstractBaseUser, PermissionsMixin): # name = models.CharField(max_length=60, help_text=_("team name"), blank=False, null=False, unique=True, db_index=True) # is_staff = models.BooleanField(help_text=_('staff status'), blank=False, null=False, default=False, db_index=True) # is_active = models.BooleanField(help_text=_('User can log in'), blank=False, null=False, default=True, db_index=True) # token = models.CharField(max_length=64, unique=True, blank=False, null=True, db_index=True) # # USERNAME_FIELD = 'name' # # objects = TeamManager() # # @property # def get_full_name(self): # return self.name # # @property # def get_short_name(self): # return self.name # # def get_absolute_url(self): # from django.core.urlresolvers import reverse # return reverse('teams.views.show', args=[self.name]) , which may include functions, classes, or code. Output only the next line.
return Team.objects.filter(token=token).first()
Based on the snippet: <|code_start|># -*- coding: utf-8 -*- from __future__ import print_function, unicode_literals, absolute_import # Create your views here. def show(req, name): team = get_object_or_404(Team, name=name) solved_tasks = Quest.objects.filter(questvariant__team_id=team.id, questvariant__questanswer__is_checked=True, questvariant__questanswer__is_success=True).select_related('category') return render(req, 'teams/show.html', {"team": team, "solved_tasks": solved_tasks}) def do_login(request): if request.method == "POST": <|code_end|> , predict the immediate next line with the help of imports: from django.conf import settings from django.shortcuts import render, get_object_or_404, redirect from django.contrib.auth import authenticate, login, logout from .forms import TokenAuthForm from .models import Team from quests.models import Quest from django.utils import translation and context (classes, functions, sometimes code) from other files: # Path: apps/teams/forms.py # class TokenAuthForm(forms.Form): # token = forms.CharField() # # Path: apps/teams/models.py # class Team(AbstractBaseUser, PermissionsMixin): # name = models.CharField(max_length=60, help_text=_("team name"), blank=False, null=False, unique=True, db_index=True) # is_staff = models.BooleanField(help_text=_('staff status'), blank=False, null=False, default=False, db_index=True) # is_active = models.BooleanField(help_text=_('User can log in'), blank=False, null=False, default=True, db_index=True) # token = models.CharField(max_length=64, unique=True, blank=False, null=True, db_index=True) # # USERNAME_FIELD = 'name' # # objects = TeamManager() # # @property # def get_full_name(self): # return self.name # # @property # def get_short_name(self): # return self.name # # def get_absolute_url(self): # from django.core.urlresolvers import reverse # return reverse('teams.views.show', args=[self.name]) . Output only the next line.
form = TokenAuthForm(data=request.POST)
Continue the code snippet: <|code_start|> "null": None, "boolean": True, "string": "foo", "bytes": b"\xe2\x99\xa5", "int": 1, "long": 1 << 33, "float": 2.2, "double": 3.3, "fixed": b"\x61\x61\x61\x61\x61", "union": None, "enum": "BAR", "enum2": "BAZBAZ", "array": ["a", "b"], "map": {"c": 1, "d": 2}, "record": {"sub_int": 123}, "record2": {"sub_int": 321}, }, ] named_schemas = {} parsed_writer_schema = fastavro.parse_schema(writer_schema, named_schemas) roundtrip_records = roundtrip( parsed_writer_schema, records, reader_schema=reader_schema ) new_file = BytesIO() fastavro.writer(new_file, parsed_writer_schema, records) new_file.seek(0) skip_record = {} <|code_end|> . Use current file imports: from io import BytesIO from fastavro.io.binary_decoder import BinaryDecoder from fastavro.read import _read as _reader, HEADER_SCHEMA, SchemaResolutionError from fastavro.write import _write as _writer, Writer from collections import OrderedDict from os.path import join, abspath, dirname, basename from glob import iglob import fastavro import pytest import copy import datetime import sys import traceback import zipfile import snappy # NOQA and context (classes, functions, or code) from other files: # Path: fastavro/io/binary_decoder.py # class BinaryDecoder: # """Decoder for the avro binary format. # # NOTE: All attributes and methods on this class should be considered # private. # # Parameters # ---------- # fo: file-like # Input stream # # """ # # def __init__(self, fo): # self.fo = fo # # def read_null(self): # """null is written as zero bytes.""" # return None # # def read_boolean(self): # """A boolean is written as a single byte whose value is either 0 # (false) or 1 (true). # """ # # # technically 0x01 == true and 0x00 == false, but many languages will # # cast anything other than 0 to True and only 0 to False # return unpack("B", self.fo.read(1))[0] != 0 # # def read_long(self): # """int and long values are written using variable-length, zig-zag # coding.""" # c = self.fo.read(1) # # # We do EOF checking only here, since most reader start here # if not c: # raise StopIteration # # b = ord(c) # n = b & 0x7F # shift = 7 # # while (b & 0x80) != 0: # b = ord(self.fo.read(1)) # n |= (b & 0x7F) << shift # shift += 7 # # return (n >> 1) ^ -(n & 1) # # read_int = read_long # # def read_float(self): # """A float is written as 4 bytes. # # The float is converted into a 32-bit integer using a method equivalent # to Java's floatToIntBits and then encoded in little-endian format. # """ # return unpack("<f", self.fo.read(4))[0] # # def read_double(self): # """A double is written as 8 bytes. # # The double is converted into a 64-bit integer using a method equivalent # to Java's doubleToLongBits and then encoded in little-endian format. # """ # return unpack("<d", self.fo.read(8))[0] # # def read_bytes(self): # """Bytes are encoded as a long followed by that many bytes of data.""" # size = self.read_long() # return self.fo.read(size) # # def read_utf8(self): # """A string is encoded as a long followed by that many bytes of UTF-8 # encoded character data. # """ # return self.read_bytes().decode() # # def read_fixed(self, size): # """Fixed instances are encoded using the number of bytes declared in the # schema.""" # return self.fo.read(size) # # def read_enum(self): # """An enum is encoded by a int, representing the zero-based position of the # symbol in the schema. # """ # return self.read_long() # # def read_array_start(self): # """Arrays are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_array_end(self): # pass # # def _iter_array_or_map(self): # """Each block consists of a long count value, followed by that many # array items. A block with count zero indicates the end of the array. # Each item is encoded per the array's item schema. # # If a block's count is negative, then the count is followed immediately # by a long block size, indicating the number of bytes in the block. # The actual count in this case is the absolute value of the count # written. # """ # while self._block_count != 0: # if self._block_count < 0: # self._block_count = -self._block_count # # Read block size, unused # self.read_long() # # for i in range(self._block_count): # yield # self._block_count = self.read_long() # # iter_array = _iter_array_or_map # iter_map = _iter_array_or_map # # def read_map_start(self): # """Maps are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_map_end(self): # pass # # def read_index(self): # """A union is encoded by first writing a long value indicating the # zero-based position within the union of the schema of its value. # # The value is then encoded per the indicated schema within the union. # """ # return self.read_long() # # Path: fastavro/read.py # HEADER_SCHEMA = _read_common.HEADER_SCHEMA # SYNC_SIZE = _read_common.SYNC_SIZE # MAGIC = _read_common.MAGIC # BLOCK_READERS = _read.BLOCK_READERS # LOGICAL_READERS = _read.LOGICAL_READERS # # Path: fastavro/write.py # LOGICAL_WRITERS = logical_writers.LOGICAL_WRITERS . Output only the next line.
decoder = BinaryDecoder(new_file)
Given the code snippet: <|code_start|> assert fastavro.is_avro(fp) with open(__file__, "rb") as fp: assert not fastavro.is_avro(fp) def test_write_long_union_type(): schema = { "name": "test_name", "namespace": "test", "type": "record", "fields": [ {"name": "time", "type": ["null", "long"]}, ], } records = [ {"time": 809066167221092352}, ] assert records == roundtrip(schema, records) def test_cython_python(): # Since Cython and Python implement the same behavior, it is possible for # build errors or coding errors to accidentally result in using the wrong # one. This is bad, because the pure Python version is faster in Pypy, # while the Cython version is faster in CPython. This test verifies the # correct reader and writer implementations are used. if hasattr(sys, "pypy_version_info"): # Pypy should not use Cython. <|code_end|> , generate the next line using the imports in this file: from io import BytesIO from fastavro.io.binary_decoder import BinaryDecoder from fastavro.read import _read as _reader, HEADER_SCHEMA, SchemaResolutionError from fastavro.write import _write as _writer, Writer from collections import OrderedDict from os.path import join, abspath, dirname, basename from glob import iglob import fastavro import pytest import copy import datetime import sys import traceback import zipfile import snappy # NOQA and context (functions, classes, or occasionally code) from other files: # Path: fastavro/io/binary_decoder.py # class BinaryDecoder: # """Decoder for the avro binary format. # # NOTE: All attributes and methods on this class should be considered # private. # # Parameters # ---------- # fo: file-like # Input stream # # """ # # def __init__(self, fo): # self.fo = fo # # def read_null(self): # """null is written as zero bytes.""" # return None # # def read_boolean(self): # """A boolean is written as a single byte whose value is either 0 # (false) or 1 (true). # """ # # # technically 0x01 == true and 0x00 == false, but many languages will # # cast anything other than 0 to True and only 0 to False # return unpack("B", self.fo.read(1))[0] != 0 # # def read_long(self): # """int and long values are written using variable-length, zig-zag # coding.""" # c = self.fo.read(1) # # # We do EOF checking only here, since most reader start here # if not c: # raise StopIteration # # b = ord(c) # n = b & 0x7F # shift = 7 # # while (b & 0x80) != 0: # b = ord(self.fo.read(1)) # n |= (b & 0x7F) << shift # shift += 7 # # return (n >> 1) ^ -(n & 1) # # read_int = read_long # # def read_float(self): # """A float is written as 4 bytes. # # The float is converted into a 32-bit integer using a method equivalent # to Java's floatToIntBits and then encoded in little-endian format. # """ # return unpack("<f", self.fo.read(4))[0] # # def read_double(self): # """A double is written as 8 bytes. # # The double is converted into a 64-bit integer using a method equivalent # to Java's doubleToLongBits and then encoded in little-endian format. # """ # return unpack("<d", self.fo.read(8))[0] # # def read_bytes(self): # """Bytes are encoded as a long followed by that many bytes of data.""" # size = self.read_long() # return self.fo.read(size) # # def read_utf8(self): # """A string is encoded as a long followed by that many bytes of UTF-8 # encoded character data. # """ # return self.read_bytes().decode() # # def read_fixed(self, size): # """Fixed instances are encoded using the number of bytes declared in the # schema.""" # return self.fo.read(size) # # def read_enum(self): # """An enum is encoded by a int, representing the zero-based position of the # symbol in the schema. # """ # return self.read_long() # # def read_array_start(self): # """Arrays are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_array_end(self): # pass # # def _iter_array_or_map(self): # """Each block consists of a long count value, followed by that many # array items. A block with count zero indicates the end of the array. # Each item is encoded per the array's item schema. # # If a block's count is negative, then the count is followed immediately # by a long block size, indicating the number of bytes in the block. # The actual count in this case is the absolute value of the count # written. # """ # while self._block_count != 0: # if self._block_count < 0: # self._block_count = -self._block_count # # Read block size, unused # self.read_long() # # for i in range(self._block_count): # yield # self._block_count = self.read_long() # # iter_array = _iter_array_or_map # iter_map = _iter_array_or_map # # def read_map_start(self): # """Maps are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_map_end(self): # pass # # def read_index(self): # """A union is encoded by first writing a long value indicating the # zero-based position within the union of the schema of its value. # # The value is then encoded per the indicated schema within the union. # """ # return self.read_long() # # Path: fastavro/read.py # HEADER_SCHEMA = _read_common.HEADER_SCHEMA # SYNC_SIZE = _read_common.SYNC_SIZE # MAGIC = _read_common.MAGIC # BLOCK_READERS = _read.BLOCK_READERS # LOGICAL_READERS = _read.LOGICAL_READERS # # Path: fastavro/write.py # LOGICAL_WRITERS = logical_writers.LOGICAL_WRITERS . Output only the next line.
assert not hasattr(_reader, "CYTHON_MODULE")
Based on the snippet: <|code_start|> with open(__file__, "rb") as fp: assert not fastavro.is_avro(fp) def test_write_long_union_type(): schema = { "name": "test_name", "namespace": "test", "type": "record", "fields": [ {"name": "time", "type": ["null", "long"]}, ], } records = [ {"time": 809066167221092352}, ] assert records == roundtrip(schema, records) def test_cython_python(): # Since Cython and Python implement the same behavior, it is possible for # build errors or coding errors to accidentally result in using the wrong # one. This is bad, because the pure Python version is faster in Pypy, # while the Cython version is faster in CPython. This test verifies the # correct reader and writer implementations are used. if hasattr(sys, "pypy_version_info"): # Pypy should not use Cython. assert not hasattr(_reader, "CYTHON_MODULE") <|code_end|> , predict the immediate next line with the help of imports: from io import BytesIO from fastavro.io.binary_decoder import BinaryDecoder from fastavro.read import _read as _reader, HEADER_SCHEMA, SchemaResolutionError from fastavro.write import _write as _writer, Writer from collections import OrderedDict from os.path import join, abspath, dirname, basename from glob import iglob import fastavro import pytest import copy import datetime import sys import traceback import zipfile import snappy # NOQA and context (classes, functions, sometimes code) from other files: # Path: fastavro/io/binary_decoder.py # class BinaryDecoder: # """Decoder for the avro binary format. # # NOTE: All attributes and methods on this class should be considered # private. # # Parameters # ---------- # fo: file-like # Input stream # # """ # # def __init__(self, fo): # self.fo = fo # # def read_null(self): # """null is written as zero bytes.""" # return None # # def read_boolean(self): # """A boolean is written as a single byte whose value is either 0 # (false) or 1 (true). # """ # # # technically 0x01 == true and 0x00 == false, but many languages will # # cast anything other than 0 to True and only 0 to False # return unpack("B", self.fo.read(1))[0] != 0 # # def read_long(self): # """int and long values are written using variable-length, zig-zag # coding.""" # c = self.fo.read(1) # # # We do EOF checking only here, since most reader start here # if not c: # raise StopIteration # # b = ord(c) # n = b & 0x7F # shift = 7 # # while (b & 0x80) != 0: # b = ord(self.fo.read(1)) # n |= (b & 0x7F) << shift # shift += 7 # # return (n >> 1) ^ -(n & 1) # # read_int = read_long # # def read_float(self): # """A float is written as 4 bytes. # # The float is converted into a 32-bit integer using a method equivalent # to Java's floatToIntBits and then encoded in little-endian format. # """ # return unpack("<f", self.fo.read(4))[0] # # def read_double(self): # """A double is written as 8 bytes. # # The double is converted into a 64-bit integer using a method equivalent # to Java's doubleToLongBits and then encoded in little-endian format. # """ # return unpack("<d", self.fo.read(8))[0] # # def read_bytes(self): # """Bytes are encoded as a long followed by that many bytes of data.""" # size = self.read_long() # return self.fo.read(size) # # def read_utf8(self): # """A string is encoded as a long followed by that many bytes of UTF-8 # encoded character data. # """ # return self.read_bytes().decode() # # def read_fixed(self, size): # """Fixed instances are encoded using the number of bytes declared in the # schema.""" # return self.fo.read(size) # # def read_enum(self): # """An enum is encoded by a int, representing the zero-based position of the # symbol in the schema. # """ # return self.read_long() # # def read_array_start(self): # """Arrays are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_array_end(self): # pass # # def _iter_array_or_map(self): # """Each block consists of a long count value, followed by that many # array items. A block with count zero indicates the end of the array. # Each item is encoded per the array's item schema. # # If a block's count is negative, then the count is followed immediately # by a long block size, indicating the number of bytes in the block. # The actual count in this case is the absolute value of the count # written. # """ # while self._block_count != 0: # if self._block_count < 0: # self._block_count = -self._block_count # # Read block size, unused # self.read_long() # # for i in range(self._block_count): # yield # self._block_count = self.read_long() # # iter_array = _iter_array_or_map # iter_map = _iter_array_or_map # # def read_map_start(self): # """Maps are encoded as a series of blocks.""" # self._block_count = self.read_long() # # def read_map_end(self): # pass # # def read_index(self): # """A union is encoded by first writing a long value indicating the # zero-based position within the union of the schema of its value. # # The value is then encoded per the indicated schema within the union. # """ # return self.read_long() # # Path: fastavro/read.py # HEADER_SCHEMA = _read_common.HEADER_SCHEMA # SYNC_SIZE = _read_common.SYNC_SIZE # MAGIC = _read_common.MAGIC # BLOCK_READERS = _read.BLOCK_READERS # LOGICAL_READERS = _read.LOGICAL_READERS # # Path: fastavro/write.py # LOGICAL_WRITERS = logical_writers.LOGICAL_WRITERS . Output only the next line.
assert not hasattr(_writer, "CYTHON_MODULE")
Given the following code snippet before the placeholder: <|code_start|> Check that the data value is python bytes type Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return isinstance(datum, (bytes, bytearray)) def validate_int(datum, **kwargs): """ Check that the data value is a non floating point number with size less that Int32. Int32 = -2147483648<=datum<=2147483647 conditional python types: int, numbers.Integral Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) <|code_end|> , predict the next line using imports from the current file: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context including class names, function names, and sometimes code from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
and INT_MIN_VALUE <= datum <= INT_MAX_VALUE
Predict the next line after this snippet: <|code_start|> Check that the data value is python bytes type Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return isinstance(datum, (bytes, bytearray)) def validate_int(datum, **kwargs): """ Check that the data value is a non floating point number with size less that Int32. Int32 = -2147483648<=datum<=2147483647 conditional python types: int, numbers.Integral Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) <|code_end|> using the current file's imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and any relevant context from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
and INT_MIN_VALUE <= datum <= INT_MAX_VALUE
Predict the next line for this snippet: <|code_start|> datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) and INT_MIN_VALUE <= datum <= INT_MAX_VALUE and not isinstance(datum, bool) ) def validate_long(datum, **kwargs): """ Check that the data value is a non floating point number with size less that long64. Int64 = -9223372036854775808 <= datum <= 9223372036854775807 conditional python types: int, numbers.Integral :Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) <|code_end|> with the help of current file imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name , which may contain function names, class names, or code. Output only the next line.
and LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE
Next line prediction: <|code_start|> datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) and INT_MIN_VALUE <= datum <= INT_MAX_VALUE and not isinstance(datum, bool) ) def validate_long(datum, **kwargs): """ Check that the data value is a non floating point number with size less that long64. Int64 = -9223372036854775808 <= datum <= 9223372036854775807 conditional python types: int, numbers.Integral :Parameters ---------- datum: Any Data being validated kwargs: Any Unused kwargs """ return ( isinstance(datum, (int, numbers.Integral)) <|code_end|> . Use current file imports: (import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType) and context including class names, function names, or small code snippets from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
and LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE
Predict the next line for this snippet: <|code_start|> (name, datum) = datum for candidate in schema: if extract_record_type(candidate) == "record": schema_name = candidate["name"] else: schema_name = candidate if schema_name == name: return _validate( datum, schema=candidate, named_schemas=named_schemas, field=parent_ns, raise_errors=raise_errors, ) else: return False errors = [] for s in schema: try: ret = _validate( datum, schema=s, named_schemas=named_schemas, field=parent_ns, raise_errors=raise_errors, ) if ret: # We exit on the first passing type in Unions return True <|code_end|> with the help of current file imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name , which may contain function names, class names, or code. Output only the next line.
except ValidationError as e:
Using the snippet: <|code_start|> record_type = extract_record_type(schema) result = None logical_type = extract_logical_type(schema) if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(datum, schema) validator = VALIDATORS.get(record_type) if validator: result = validator( datum, schema=schema, named_schemas=named_schemas, parent_ns=field, raise_errors=raise_errors, ) elif record_type in named_schemas: result = _validate( datum, schema=named_schemas[record_type], named_schemas=named_schemas, field=field, raise_errors=raise_errors, ) else: raise UnknownType(record_type) if raise_errors and result is False: <|code_end|> , determine the next line of code. You have imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
raise ValidationError(ValidationErrorData(datum, schema, field))
Given the code snippet: <|code_start|> datum=datum.get(f["name"], f.get("default")), schema=f["type"], named_schemas=named_schemas, field=f"{fullname}.{f['name']}", raise_errors=raise_errors, ) for f in schema["fields"] ) ) def validate_union(datum, schema, named_schemas, parent_ns=None, raise_errors=True): """ Check that the data is a list type with possible options to validate as True. Parameters ---------- datum: Any Data being validated schema: dict Schema parent_ns: str parent namespace raise_errors: bool If true, raises ValidationError on invalid data """ if isinstance(datum, tuple): (name, datum) = datum for candidate in schema: <|code_end|> , generate the next line using the imports in this file: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (functions, classes, or occasionally code) from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
if extract_record_type(candidate) == "record":
Based on the snippet: <|code_start|> raise ValidationError(*errors) return False VALIDATORS = { "null": validate_null, "boolean": validate_boolean, "string": validate_string, "int": validate_int, "long": validate_long, "float": validate_float, "double": validate_float, "bytes": validate_bytes, "fixed": validate_fixed, "enum": validate_enum, "array": validate_array, "map": validate_map, "union": validate_union, "error_union": validate_union, "record": validate_record, "error": validate_record, "request": validate_record, } def _validate(datum, schema, named_schemas, field=None, raise_errors=True): # This function expects the schema to already be parsed record_type = extract_record_type(schema) result = None <|code_end|> , predict the immediate next line with the help of imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (classes, functions, sometimes code) from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
logical_type = extract_logical_type(schema)
Continue the code snippet: <|code_start|> and all(isinstance(k, str) for k in datum) and all( _validate( datum=v, schema=schema["values"], named_schemas=named_schemas, field=parent_ns, raise_errors=raise_errors, ) for v in datum.values() ) ) def validate_record(datum, schema, named_schemas, parent_ns=None, raise_errors=True): """ Check that the data is a Mapping type with all schema defined fields validated as True. Parameters ---------- datum: Any Data being validated schema: dict Schema parent_ns: str parent namespace raise_errors: bool If true, raises ValidationError on invalid data """ <|code_end|> . Use current file imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (classes, functions, or code) from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
_, fullname = schema_name(schema, parent_ns)
Using the snippet: <|code_start|> raise ValidationError(ValidationErrorData(datum, schema, field)) return result def validate(datum, schema, field=None, raise_errors=True): """ Determine if a python datum is an instance of a schema. Parameters ---------- datum: Any Data being validated schema: dict Schema field: str, optional Record field being validated raise_errors: bool, optional If true, errors are raised for invalid data. If false, a simple True (valid) or False (invalid) result is returned Example:: from fastavro.validation import validate schema = {...} record = {...} validate(record, schema) """ named_schemas = {} <|code_end|> , determine the next line of code. You have imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
parsed_schema = parse_schema(schema, named_schemas)
Based on the snippet: <|code_start|> VALIDATORS = { "null": validate_null, "boolean": validate_boolean, "string": validate_string, "int": validate_int, "long": validate_long, "float": validate_float, "double": validate_float, "bytes": validate_bytes, "fixed": validate_fixed, "enum": validate_enum, "array": validate_array, "map": validate_map, "union": validate_union, "error_union": validate_union, "record": validate_record, "error": validate_record, "request": validate_record, } def _validate(datum, schema, named_schemas, field=None, raise_errors=True): # This function expects the schema to already be parsed record_type = extract_record_type(schema) result = None logical_type = extract_logical_type(schema) if logical_type: <|code_end|> , predict the immediate next line with the help of imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (classes, functions, sometimes code) from other files: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
prepare = LOGICAL_WRITERS.get(logical_type)
Using the snippet: <|code_start|> def _validate(datum, schema, named_schemas, field=None, raise_errors=True): # This function expects the schema to already be parsed record_type = extract_record_type(schema) result = None logical_type = extract_logical_type(schema) if logical_type: prepare = LOGICAL_WRITERS.get(logical_type) if prepare: datum = prepare(datum, schema) validator = VALIDATORS.get(record_type) if validator: result = validator( datum, schema=schema, named_schemas=named_schemas, parent_ns=field, raise_errors=raise_errors, ) elif record_type in named_schemas: result = _validate( datum, schema=named_schemas[record_type], named_schemas=named_schemas, field=field, raise_errors=raise_errors, ) else: <|code_end|> , determine the next line of code. You have imports: import array import numbers from collections.abc import Mapping, Sequence from fastavro.const import INT_MAX_VALUE, INT_MIN_VALUE, LONG_MAX_VALUE, LONG_MIN_VALUE from ._validate_common import ValidationError, ValidationErrorData from .schema import extract_record_type, extract_logical_type, schema_name, parse_schema from .logical_writers import LOGICAL_WRITERS from ._schema_common import UnknownType and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MAX_VALUE = (1 << 31) - 1 # # INT_MIN_VALUE = -(1 << 31) # # LONG_MAX_VALUE = (1 << 63) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # Path: fastavro/_validate_common.py # class ValidationError(Exception): # def __init__(self, *errors): # message = json.dumps([str(e) for e in errors], indent=2, ensure_ascii=False) # super(ValidationError, self).__init__(message) # self.errors = errors # # class ValidationErrorData( # namedtuple("ValidationErrorData", ["datum", "schema", "field"]) # ): # def __str__(self): # # update field for prettier printing # field = self.field # if field is None: # field = "" # # if self.datum is None: # return f"Field({field}) is None expected {self.schema}" # # return ( # f"{field} is <{self.datum}> of type " # + f"{type(self.datum)} expected {self.schema}" # ) # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/logical_writers.py # LOGICAL_WRITERS = _logical_writers.LOGICAL_WRITERS # # Path: fastavro/_schema_common.py # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name . Output only the next line.
raise UnknownType(record_type)
Given the following code snippet before the placeholder: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any: record_type = extract_record_type(schema) if record_type == "null": return None elif record_type == "string": return _gen_utf8() elif record_type == "int": <|code_end|> , predict the next line using imports from the current file: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context including class names, function names, and sometimes code from other files: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
return random.randint(INT_MIN_VALUE, INT_MAX_VALUE)
Predict the next line after this snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any: record_type = extract_record_type(schema) if record_type == "null": return None elif record_type == "string": return _gen_utf8() elif record_type == "int": <|code_end|> using the current file's imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and any relevant context from other files: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
return random.randint(INT_MIN_VALUE, INT_MAX_VALUE)
Using the snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any: record_type = extract_record_type(schema) if record_type == "null": return None elif record_type == "string": return _gen_utf8() elif record_type == "int": return random.randint(INT_MIN_VALUE, INT_MAX_VALUE) elif record_type == "long": <|code_end|> , determine the next line of code. You have imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
return random.randint(LONG_MIN_VALUE, LONG_MAX_VALUE)
Using the snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any: record_type = extract_record_type(schema) if record_type == "null": return None elif record_type == "string": return _gen_utf8() elif record_type == "int": return random.randint(INT_MIN_VALUE, INT_MAX_VALUE) elif record_type == "long": <|code_end|> , determine the next line of code. You have imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
return random.randint(LONG_MIN_VALUE, LONG_MAX_VALUE)
Using the snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any: <|code_end|> , determine the next line of code. You have imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
record_type = extract_record_type(schema)
Using the snippet: <|code_start|> Parameters ---------- schema: dict, list, string Schema count: int Number of objects to generate Example:: from fastavro import writer from fastavro.utils import generate_data schema = { 'doc': 'A weather reading.', 'name': 'Weather', 'namespace': 'test', 'type': 'record', 'fields': [ {'name': 'station', 'type': 'string'}, {'name': 'time', 'type': 'long'}, {'name': 'temp', 'type': 'int'}, ], } with open('weather.avro', 'wb') as out: writer(out, schema, generate_data(schema, 5)) """ named_schemas: NamedSchemas = {} <|code_end|> , determine the next line of code. You have imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context (class names, function names, or code) available: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
parsed_schema = parse_schema(schema, named_schemas)
Here is a snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) <|code_end|> . Write the next line using the current file imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context from other files: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } , which may include functions, classes, or code. Output only the next line.
def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any:
Continue the code snippet: <|code_start|> def _randbytes(num: int) -> bytes: # TODO: Use random.randbytes when this library is Python 3.9+ only return random.getrandbits(num * 8).to_bytes(num, "little") def _md5(string: str) -> str: return md5(string.encode()).hexdigest() def _gen_utf8() -> str: return "".join(random.choices(ascii_letters, k=10)) <|code_end|> . Use current file imports: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context (classes, functions, or code) from other files: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
def gen_data(schema: Schema, named_schemas: NamedSchemas, index: int) -> Any:
Given the following code snippet before the placeholder: <|code_start|> yield gen_data(parsed_schema, named_schemas, index) def anonymize_schema(schema: Schema) -> Schema: """Returns an anonymized schema Parameters ---------- schema: dict, list, string Schema Example:: from fastavro.utils import anonymize_schema anonymized_schema = anonymize_schema(original_schema) """ named_schemas: NamedSchemas = {} parsed_schema = parse_schema(schema, named_schemas) return _anonymize_schema(parsed_schema, named_schemas) def _anonymize_schema(schema: Schema, named_schemas: NamedSchemas) -> Schema: # union schemas if isinstance(schema, list): return [_anonymize_schema(s, named_schemas) for s in schema] # string schemas; this could be either a named schema or a primitive type elif not isinstance(schema, dict): <|code_end|> , predict the next line using imports from the current file: from hashlib import md5 from string import ascii_letters from typing import Any, Iterator, Dict, List, cast from .const import INT_MIN_VALUE, INT_MAX_VALUE, LONG_MIN_VALUE, LONG_MAX_VALUE from .schema import extract_record_type, parse_schema from .types import Schema, NamedSchemas from ._schema_common import PRIMITIVES import random and context including class names, function names, and sometimes code from other files: # Path: fastavro/const.py # INT_MIN_VALUE = -(1 << 31) # # INT_MAX_VALUE = (1 << 31) - 1 # # LONG_MIN_VALUE = -(1 << 63) # # LONG_MAX_VALUE = (1 << 63) - 1 # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/types.py # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
if schema in PRIMITIVES:
Given snippet: <|code_start|> parsed_schema = load_schema("namespace.Parent.avsc") """ schema_name = schema_path if repo is None: file_dir, file_name = path.split(schema_path) schema_name, _file_ext = path.splitext(file_name) repo = FlatDictRepository(file_dir) if named_schemas is None: named_schemas = {} if _injected_schemas is None: _injected_schemas = set() return _load_schema( schema_name, repo, named_schemas, _write_hint, _injected_schemas ) def _load_schema(schema_name, repo, named_schemas, write_hint, injected_schemas): try: schema = repo.load(schema_name) return _parse_schema_with_repo( schema, repo, named_schemas, write_hint, injected_schemas, ) <|code_end|> , continue by predicting the next line. Consider current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() which might include code, classes, or functions. Output only the next line.
except SchemaRepositoryError as error:
Here is a snippet: <|code_start|> "namespace": "namespace", "fields": [ { "name": "child", "type": "Child" } ] } namespace.Child.avsc:: { "type": "record", "namespace": "namespace", "name": "Child", "fields": [] } Code:: from fastavro.schema import load_schema parsed_schema = load_schema("namespace.Parent.avsc") """ schema_name = schema_path if repo is None: file_dir, file_name = path.split(schema_path) schema_name, _file_ext = path.splitext(file_name) <|code_end|> . Write the next line using the current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() , which may include functions, classes, or code. Output only the next line.
repo = FlatDictRepository(file_dir)
Given the code snippet: <|code_start|> # to re-parse the schema to handle named types return _parse_schema(schema, "", expand, _write_hint, set(), named_schemas) if _force or expand: return _parse_schema(schema, "", expand, _write_hint, set(), named_schemas) elif isinstance(schema, dict) and "__fastavro_parsed" in schema: return schema elif isinstance(schema, list): # If we are given a list we should make sure that the immediate sub # schemas have the hint in them return [ parse_schema( s, named_schemas, expand=expand, _write_hint=_write_hint, _force=_force ) for s in schema ] else: return _parse_schema(schema, "", expand, _write_hint, set(), named_schemas) def _parse_schema(schema, namespace, expand, _write_hint, names, named_schemas): # union schemas if isinstance(schema, list): return [ _parse_schema(s, namespace, expand, False, names, named_schemas) for s in schema ] # string schemas; this could be either a named schema or a primitive type elif not isinstance(schema, dict): <|code_end|> , generate the next line using the imports in this file: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (functions, classes, or occasionally code) from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
if schema in PRIMITIVES:
Continue the code snippet: <|code_start|> elif isinstance(schema, list): # If we are given a list we should make sure that the immediate sub # schemas have the hint in them return [ parse_schema( s, named_schemas, expand=expand, _write_hint=_write_hint, _force=_force ) for s in schema ] else: return _parse_schema(schema, "", expand, _write_hint, set(), named_schemas) def _parse_schema(schema, namespace, expand, _write_hint, names, named_schemas): # union schemas if isinstance(schema, list): return [ _parse_schema(s, namespace, expand, False, names, named_schemas) for s in schema ] # string schemas; this could be either a named schema or a primitive type elif not isinstance(schema, dict): if schema in PRIMITIVES: return schema if "." not in schema and namespace: schema = namespace + "." + schema if schema not in named_schemas: <|code_end|> . Use current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (classes, functions, or code) from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
raise UnknownType(schema)
Continue the code snippet: <|code_start|> schema: dict Input schema Example:: from fastavro.schema import fullname schema = { 'doc': 'A weather reading.', 'name': 'Weather', 'namespace': 'test', 'type': 'record', 'fields': [ {'name': 'station', 'type': 'string'}, {'name': 'time', 'type': 'long'}, {'name': 'temp', 'type': 'int'}, ], } fname = fullname(schema) assert fname == "test.Weather" """ return schema_name(schema, "")[1] def schema_name(schema, parent_ns): try: name = schema["name"] except KeyError: <|code_end|> . Use current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (classes, functions, or code) from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
raise SchemaParseException(
Here is a snippet: <|code_start|> # string schemas; this could be either a named schema or a primitive type elif not isinstance(schema, dict): if schema in PRIMITIVES: return schema if "." not in schema and namespace: schema = namespace + "." + schema if schema not in named_schemas: raise UnknownType(schema) elif expand: # If `name` is in the schema, it has been fully resolved and so we # can include the full schema. If `name` is not in the schema yet, # then we are still recursing that schema and must use the named # schema or else we will have infinite recursion when printing the # final schema if "name" in named_schemas[schema]: return named_schemas[schema] else: return schema else: return schema else: # Remaining valid schemas must be dict types schema_type = schema["type"] parsed_schema = { key: value for key, value in schema.items() <|code_end|> . Write the next line using the current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() , which may include functions, classes, or code. Output only the next line.
if key not in RESERVED_PROPERTIES
Based on the snippet: <|code_start|> parsed_schema["name"] = fullname parsed_schema["fields"] = fields # Hint that we have parsed the record if _write_hint: # Make a copy of parsed_schema so that we don't have a cyclical # reference. Using deepcopy is pretty slow, and we don't need a # true deepcopy so this works good enough named_schemas[fullname] = {k: v for k, v in parsed_schema.items()} parsed_schema["__fastavro_parsed"] = True parsed_schema["__named_schemas"] = named_schemas elif schema_type in PRIMITIVES: parsed_schema["type"] = schema_type else: raise UnknownType(schema) return parsed_schema def parse_field(field, namespace, expand, names, named_schemas): parsed_field = { key: value for key, value in field.items() if key not in RESERVED_FIELD_PROPERTIES } <|code_end|> , predict the immediate next line with the help of imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (classes, functions, sometimes code) from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
for prop in OPTIONAL_FIELD_PROPERTIES:
Based on the snippet: <|code_start|> fields.append( parse_field(field, namespace, expand, names, named_schemas) ) parsed_schema["name"] = fullname parsed_schema["fields"] = fields # Hint that we have parsed the record if _write_hint: # Make a copy of parsed_schema so that we don't have a cyclical # reference. Using deepcopy is pretty slow, and we don't need a # true deepcopy so this works good enough named_schemas[fullname] = {k: v for k, v in parsed_schema.items()} parsed_schema["__fastavro_parsed"] = True parsed_schema["__named_schemas"] = named_schemas elif schema_type in PRIMITIVES: parsed_schema["type"] = schema_type else: raise UnknownType(schema) return parsed_schema def parse_field(field, namespace, expand, names, named_schemas): parsed_field = { key: value for key, value in field.items() <|code_end|> , predict the immediate next line with the help of imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (classes, functions, sometimes code) from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
if key not in RESERVED_FIELD_PROPERTIES
Using the snippet: <|code_start|> name = schema["name"] fo.write(f'{{"name":"{name}","type":"record","fields":[') for idx, field in enumerate(schema["fields"]): if idx != 0: fo.write(",") name = field["name"] fo.write(f'{{"name":"{name}","type":') _to_parsing_canonical_form(field["type"], fo) fo.write("}") fo.write("]}") elif schema_type in PRIMITIVES: fo.write(f'"{schema_type}"') def fingerprint(parsing_canonical_form, algorithm): """Returns a string represening a fingerprint/hash of the parsing canonical form of a schema. For more details on the fingerprint, see here: https://avro.apache.org/docs/current/spec.html#schema_fingerprints """ if algorithm not in FINGERPRINT_ALGORITHMS: raise ValueError( f"Unknown schema fingerprint algorithm {algorithm}. " + f"Valid values include: {FINGERPRINT_ALGORITHMS}" ) # Fix Java names <|code_end|> , determine the next line of code. You have imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context (class names, function names, or code) available: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
algorithm = JAVA_FINGERPRINT_MAPPING.get(algorithm, algorithm)
Next line prediction: <|code_start|> elif schema_type == "fixed": name = schema["name"] size = schema["size"] fo.write(f'{{"name":"{name}","type":"{schema_type}","size":{size}}}') elif schema_type == "record" or schema_type == "error": name = schema["name"] fo.write(f'{{"name":"{name}","type":"record","fields":[') for idx, field in enumerate(schema["fields"]): if idx != 0: fo.write(",") name = field["name"] fo.write(f'{{"name":"{name}","type":') _to_parsing_canonical_form(field["type"], fo) fo.write("}") fo.write("]}") elif schema_type in PRIMITIVES: fo.write(f'"{schema_type}"') def fingerprint(parsing_canonical_form, algorithm): """Returns a string represening a fingerprint/hash of the parsing canonical form of a schema. For more details on the fingerprint, see here: https://avro.apache.org/docs/current/spec.html#schema_fingerprints """ <|code_end|> . Use current file imports: (import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, )) and context including class names, function names, or small code snippets from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
if algorithm not in FINGERPRINT_ALGORITHMS:
Predict the next line for this snippet: <|code_start|> for idx, field in enumerate(schema["fields"]): if idx != 0: fo.write(",") name = field["name"] fo.write(f'{{"name":"{name}","type":') _to_parsing_canonical_form(field["type"], fo) fo.write("}") fo.write("]}") elif schema_type in PRIMITIVES: fo.write(f'"{schema_type}"') def fingerprint(parsing_canonical_form, algorithm): """Returns a string represening a fingerprint/hash of the parsing canonical form of a schema. For more details on the fingerprint, see here: https://avro.apache.org/docs/current/spec.html#schema_fingerprints """ if algorithm not in FINGERPRINT_ALGORITHMS: raise ValueError( f"Unknown schema fingerprint algorithm {algorithm}. " + f"Valid values include: {FINGERPRINT_ALGORITHMS}" ) # Fix Java names algorithm = JAVA_FINGERPRINT_MAPPING.get(algorithm, algorithm) <|code_end|> with the help of current file imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and context from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() , which may contain function names, class names, or code. Output only the next line.
if algorithm == RABIN_64:
Predict the next line after this snippet: <|code_start|> for idx, field in enumerate(schema["fields"]): if idx != 0: fo.write(",") name = field["name"] fo.write(f'{{"name":"{name}","type":') _to_parsing_canonical_form(field["type"], fo) fo.write("}") fo.write("]}") elif schema_type in PRIMITIVES: fo.write(f'"{schema_type}"') def fingerprint(parsing_canonical_form, algorithm): """Returns a string represening a fingerprint/hash of the parsing canonical form of a schema. For more details on the fingerprint, see here: https://avro.apache.org/docs/current/spec.html#schema_fingerprints """ if algorithm not in FINGERPRINT_ALGORITHMS: raise ValueError( f"Unknown schema fingerprint algorithm {algorithm}. " + f"Valid values include: {FINGERPRINT_ALGORITHMS}" ) # Fix Java names algorithm = JAVA_FINGERPRINT_MAPPING.get(algorithm, algorithm) if algorithm == RABIN_64: <|code_end|> using the current file's imports: import hashlib import math import re from io import StringIO from os import path from copy import deepcopy from .repository import FlatDictRepository, SchemaRepositoryError from ._schema_common import ( PRIMITIVES, UnknownType, SchemaParseException, RESERVED_PROPERTIES, OPTIONAL_FIELD_PROPERTIES, RESERVED_FIELD_PROPERTIES, JAVA_FINGERPRINT_MAPPING, FINGERPRINT_ALGORITHMS, RABIN_64, rabin_fingerprint, ) and any relevant context from other files: # Path: fastavro/repository/base.py # class SchemaRepositoryError(Exception): # pass # # Path: fastavro/repository/flat_dict.py # class FlatDictRepository(AbstractSchemaRepository): # def __init__(self, path): # self.path = path # self.file_ext = "avsc" # # def load(self, name): # file_path = path.join(self.path, f"{name}.{self.file_ext}") # try: # with open(file_path) as schema_file: # return json.load(schema_file) # except IOError as error: # raise SchemaRepositoryError( # f"Failed to load '{name}' schema", # ) from error # except json.decoder.JSONDecodeError as error: # raise SchemaRepositoryError( # f"Failed to parse '{name}' schema", # ) from error # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } # # class UnknownType(ValueError): # def __init__(self, name): # super().__init__(name) # self.name = name # # class SchemaParseException(Exception): # pass # # RESERVED_PROPERTIES = { # "type", # "name", # "namespace", # "fields", # Record # "items", # Array # "size", # Fixed # "symbols", # Enum # "values", # Map # "doc", # } # # OPTIONAL_FIELD_PROPERTIES = { # "doc", # "aliases", # "default", # } # # RESERVED_FIELD_PROPERTIES = {"type", "name"} | OPTIONAL_FIELD_PROPERTIES # # JAVA_FINGERPRINT_MAPPING = {"SHA-256": "sha256", "MD5": "md5"} # # FINGERPRINT_ALGORITHMS = ( # hashlib.algorithms_guaranteed | JAVA_FINGERPRINT_MAPPING.keys() | {RABIN_64} # ) # # RABIN_64 = "CRC-64-AVRO" # # def rabin_fingerprint(data): # empty_64 = 0xC15D213AA4D7A795 # # fp_table = [] # for i in range(256): # fp = i # for j in range(8): # mask = -(fp & 1) # fp = (fp >> 1) ^ (empty_64 & mask) # fp_table.append(fp) # # result = empty_64 # for byte in data: # result = (result >> 8) ^ fp_table[(result ^ byte) & 0xFF] # # # Although not mentioned in the Avro specification, the Java # # implementation gives fingerprint bytes in little-endian order # return result.to_bytes(length=8, byteorder="little", signed=False).hex() . Output only the next line.
return rabin_fingerprint(parsing_canonical_form.encode())
Using the snippet: <|code_start|> @pytest.mark.parametrize( "fingerprint", ["CRC-64-AVRO", "SHA-256", "MD5", "sha256", "md5"] ) def test_required_fingerprints(fingerprint): <|code_end|> , determine the next line of code. You have imports: import pytest from fastavro.schema import ( FINGERPRINT_ALGORITHMS, fingerprint, to_parsing_canonical_form, ) and context (class names, function names, or code) available: # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
assert fingerprint in FINGERPRINT_ALGORITHMS
Next line prediction: <|code_start|> @pytest.mark.parametrize( "fingerprint", ["CRC-64-AVRO", "SHA-256", "MD5", "sha256", "md5"] ) <|code_end|> . Use current file imports: (import pytest from fastavro.schema import ( FINGERPRINT_ALGORITHMS, fingerprint, to_parsing_canonical_form, )) and context including class names, function names, or small code snippets from other files: # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
def test_required_fingerprints(fingerprint):
Given the following code snippet before the placeholder: <|code_start|> "doc": "Doc String", }, "md5", "d883f2a9b16ed085fcc5e4ca6c8f6ed1", ), ( { "type": "enum", "name": "Test", "symbols": ["A", "B"], "doc": "Doc String", }, "sha256", "9b51286144f87ce5aebdc61ca834379effa5a41ce6ac0938630ff246297caca8", ), ( {"type": "int"}, "MD5", # JAVA Name "ef524ea1b91e73173d938ade36c1db32", ), ( {"type": "int"}, "SHA-256", # JAVA Name "3f2b87a9fe7cc9b13835598c3981cd45e3e355309e5090aa0933d7becb6fba45", ), ], ) def test_random_cases(original_schema, algorithm, expected_fingerprint): # All of these random test cases came from the test cases here: # https://github.com/apache/avro/blob/0552c674637dd15b8751ed5181387cdbd81480d5/lang/py3/avro/tests/test_normalization.py <|code_end|> , predict the next line using imports from the current file: import pytest from fastavro.schema import ( FINGERPRINT_ALGORITHMS, fingerprint, to_parsing_canonical_form, ) and context including class names, function names, and sometimes code from other files: # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
canonical_form = to_parsing_canonical_form(original_schema)
Using the snippet: <|code_start|> @pytest.mark.parametrize( "original_schema,canonical_form", ( [(primitive, f'"{primitive}"') for primitive in PRIMITIVES] + [({"type": primitive}, f'"{primitive}"') for primitive in PRIMITIVES] ), ) def test_primitive_conversion(original_schema, canonical_form): <|code_end|> , determine the next line of code. You have imports: import pytest from fastavro.schema import to_parsing_canonical_form from fastavro._schema_common import PRIMITIVES and context (class names, function names, or code) available: # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } . Output only the next line.
assert to_parsing_canonical_form(original_schema) == canonical_form
Here is a snippet: <|code_start|> @pytest.mark.parametrize( "original_schema,canonical_form", ( <|code_end|> . Write the next line using the current file imports: import pytest from fastavro.schema import to_parsing_canonical_form from fastavro._schema_common import PRIMITIVES and context from other files: # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS # # Path: fastavro/_schema_common.py # PRIMITIVES = { # "boolean", # "bytes", # "double", # "float", # "int", # "long", # "null", # "string", # } , which may include functions, classes, or code. Output only the next line.
[(primitive, f'"{primitive}"') for primitive in PRIMITIVES]
Predict the next line for this snippet: <|code_start|> class Parser: def __init__(self, schema, named_schemas, action_function): self.schema = schema self.named_schemas = named_schemas self.action_function = action_function self.stack = self.parse() def parse(self): symbol = self._parse(self.schema) <|code_end|> with the help of current file imports: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and context from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS , which may contain function names, class names, or code. Output only the next line.
root = Root([symbol])
Predict the next line for this snippet: <|code_start|> return Null() elif record_type == "boolean": return Boolean(default=default) elif record_type == "string": return String(default=default) elif record_type == "bytes": return Bytes(default=default) elif record_type == "int": return Int(default=default) elif record_type == "long": return Long(default=default) elif record_type == "float": return Float(default=default) elif record_type == "double": return Double(default=default) elif record_type == "fixed": return Fixed(default=default) elif record_type in self.named_schemas: return self._parse(self.named_schemas[record_type]) else: raise Exception(f"Unhandled type: {record_type}") def advance(self, symbol): while True: top = self.stack.pop() if top == symbol: return top elif isinstance(top, Action): self.action_function(top) <|code_end|> with the help of current file imports: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and context from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS , which may contain function names, class names, or code. Output only the next line.
elif isinstance(top, Terminal):
Given the code snippet: <|code_start|> ) else: labels.append(candidate_schema) return Sequence(Alternative(symbols, labels, default=default), Union()) elif record_type == "map": repeat = Repeater( MapEnd(), # ItemEnd(), # TODO: Maybe need this? self._parse(schema["values"]), MapKeyMarker(), String(), ) return Sequence(repeat, MapStart(default=default)) elif record_type == "array": repeat = Repeater( ArrayEnd(), ItemEnd(), self._parse(schema["items"]), ) return Sequence(repeat, ArrayStart(default=default)) elif record_type == "enum": return Sequence(EnumLabels(schema["symbols"]), Enum(default=default)) elif record_type == "null": return Null() elif record_type == "boolean": <|code_end|> , generate the next line using the imports in this file: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and context (functions, classes, or occasionally code) from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
return Boolean(default=default)
Predict the next line after this snippet: <|code_start|> class Parser: def __init__(self, schema, named_schemas, action_function): self.schema = schema self.named_schemas = named_schemas self.action_function = action_function self.stack = self.parse() def parse(self): symbol = self._parse(self.schema) root = Root([symbol]) root.production.insert(0, root) return [root, symbol] def _parse(self, schema, default=NO_DEFAULT): record_type = extract_record_type(schema) if record_type == "record": production = [] production.append(RecordStart(default=default)) for field in schema["fields"]: production.insert(0, FieldStart(field["name"])) production.insert( 0, self._parse(field["type"], field.get("default", NO_DEFAULT)) ) production.insert(0, FieldEnd()) production.insert(0, RecordEnd()) <|code_end|> using the current file's imports: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and any relevant context from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
seq = Sequence(*production)
Given snippet: <|code_start|> if record_type == "record": production = [] production.append(RecordStart(default=default)) for field in schema["fields"]: production.insert(0, FieldStart(field["name"])) production.insert( 0, self._parse(field["type"], field.get("default", NO_DEFAULT)) ) production.insert(0, FieldEnd()) production.insert(0, RecordEnd()) seq = Sequence(*production) return seq elif record_type == "union": symbols = [] labels = [] for candidate_schema in schema: symbols.append(self._parse(candidate_schema)) if isinstance(candidate_schema, dict): labels.append( candidate_schema.get("name", candidate_schema.get("type")) ) else: labels.append(candidate_schema) return Sequence(Alternative(symbols, labels, default=default), Union()) elif record_type == "map": <|code_end|> , continue by predicting the next line. Consider current file imports: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and context: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS which might include code, classes, or functions. Output only the next line.
repeat = Repeater(
Given the following code snippet before the placeholder: <|code_start|> elif record_type == "null": return Null() elif record_type == "boolean": return Boolean(default=default) elif record_type == "string": return String(default=default) elif record_type == "bytes": return Bytes(default=default) elif record_type == "int": return Int(default=default) elif record_type == "long": return Long(default=default) elif record_type == "float": return Float(default=default) elif record_type == "double": return Double(default=default) elif record_type == "fixed": return Fixed(default=default) elif record_type in self.named_schemas: return self._parse(self.named_schemas[record_type]) else: raise Exception(f"Unhandled type: {record_type}") def advance(self, symbol): while True: top = self.stack.pop() if top == symbol: return top <|code_end|> , predict the next line using imports from the current file: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and context including class names, function names, and sometimes code from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
elif isinstance(top, Action):
Predict the next line after this snippet: <|code_start|> class Parser: def __init__(self, schema, named_schemas, action_function): self.schema = schema self.named_schemas = named_schemas self.action_function = action_function self.stack = self.parse() def parse(self): symbol = self._parse(self.schema) root = Root([symbol]) root.production.insert(0, root) return [root, symbol] def _parse(self, schema, default=NO_DEFAULT): record_type = extract_record_type(schema) if record_type == "record": production = [] <|code_end|> using the current file's imports: from .symbols import ( Root, Terminal, Boolean, Sequence, Repeater, Action, RecordStart, RecordEnd, FieldStart, FieldEnd, Int, Null, String, Alternative, Union, Long, Float, Double, Bytes, MapEnd, MapStart, MapKeyMarker, Enum, EnumLabels, Fixed, ArrayStart, ArrayEnd, ItemEnd, NO_DEFAULT, ) from ..schema import extract_record_type and any relevant context from other files: # Path: fastavro/io/symbols.py # class _NoDefault: # class Symbol: # class Root(Symbol): # class Terminal(Symbol): # class Sequence(Symbol): # class Repeater(Symbol): # class Alternative(Symbol): # class Action(Symbol): # class EnumLabels(Action): # class UnionEnd(Action): # class RecordStart(Action): # class RecordEnd(Action): # class FieldStart(Action): # class FieldEnd(Action): # NO_DEFAULT = _NoDefault() # def __init__(self, production=None, default=NO_DEFAULT): # def get_default(self): # def __eq__(self, other): # def __ne__(self, other): # def __init__(self, *symbols, default=NO_DEFAULT): # def __init__(self, end, *symbols, default=NO_DEFAULT): # def __init__(self, symbols, labels, default=NO_DEFAULT): # def get_symbol(self, index): # def get_label(self, index): # def __init__(self, labels): # def __init__(self, field_name): # # Path: fastavro/schema.py # FINGERPRINT_ALGORITHMS = _schema.FINGERPRINT_ALGORITHMS . Output only the next line.
production.append(RecordStart(default=default))