Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Here is a snippet: <|code_start|># This conftest.py file should be found in the top directory of the tests
# module. The fixture data should be in a subdirectory named fixtures
TESTSPATH = Path(__file__).parents[0]
FIXTUREPATH = TESTSPATH / "fixtures"
# Convenience structs to emulate returned objects
class MockGenome(NamedTuple):
"""Mock genome object."""
path: str
class MockProcess(NamedTuple):
"""Mock process object."""
stdout: str
stderr: str
class MockMatch(NamedTuple):
"""Mock match object."""
def group(self):
return ""
@pytest.fixture
def blastall_available():
"""Returns True if blastall can be run, False otherwise."""
<|code_end|>
. Write the next line using the current file imports:
import subprocess
import shutil
import os
import re
import platform
import pytest
from pathlib import Path
from typing import NamedTuple
from pyani import download
from pyani.download import ASMIDs, DLStatus
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
NUCMER_DEFAULT,
FRAGSIZE,
)
from pyani.scripts import genbank_get_genomes_by_taxon
and context from other files:
# Path: pyani/download.py
# TAXONREGEX = re.compile(r"([0-9]\,?){1,}")
# class NCBIDownloadException(Exception):
# class FileExistsException(Exception):
# class PyaniIndexException(Exception):
# class ASMIDs(NamedTuple):
# class Classification(NamedTuple):
# class DLFileData(NamedTuple):
# class Hashstatus(NamedTuple):
# class DLStatus:
# def __init__(self, msg: str = "Error downloading file from NCBI"):
# def __init__(self, msg: str = "Specified file exists"):
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# def last_exception() -> str:
# def make_asm_dict(taxon_ids: List[str], retries: int) -> Dict:
# def set_ncbi_email(email: str) -> None:
# def download_genome_and_hash(
# outdir: Path,
# timeout: int,
# dlfiledata: DLFileData,
# dltype: str = "RefSeq",
# disable_tqdm: bool = False,
# ) -> namedlist:
# def entrez_retry(func):
# def wrapper(*args, retries=1, **kwargs):
# def entrez_batch(func):
# def wrapper(*args, expected=None, batchsize=None, **kwargs):
# def entrez_batched_webhistory(*args, **kwargs):
# def entrez_esearch(*args, **kwargs):
# def entrez_esummary(*args, **kwargs):
# def split_taxa(taxa: str) -> List[str]:
# def get_asm_uids(taxon_uid: str, retries: int) -> ASMIDs:
# def extract_filestem(esummary) -> str:
# def get_ncbi_esummary(asm_uid, retries, api_key=None) -> Tuple:
# def get_ncbi_classification(esummary) -> Classification:
# def compile_url(filestem: str, suffix: str, ftpstem: str) -> Tuple[str, str]:
# def download_url(
# url: str, outfname: Path, timeout: int, disable_tqdm: bool = False
# ) -> None:
# def construct_output_paths(
# filestem: str, suffix: str, outdir: Path
# ) -> Tuple[Path, Path]:
# def retrieve_genome_and_hash(
# filestem: str,
# suffix: str,
# ftpstem: str,
# outdir: Path,
# timeout: int,
# disable_tqdm: bool = False,
# ) -> DLStatus:
# def check_hash(fname: Path, hashfile: Path) -> Hashstatus:
# def extract_contigs(fname: Path, ename: Path) -> CompletedProcess:
# def create_labels(
# classification: Classification, filestem: str, genomehash: str
# ) -> Tuple[str, str]:
# def create_hash(fname: Path) -> str:
# def extract_hash(hashfile: Path, name: str) -> str:
#
# Path: pyani/download.py
# class ASMIDs(NamedTuple):
#
# """Matching Assembly ID information for a query taxID."""
#
# query: str
# result_count: int
# asm_ids: List[str]
#
# class DLStatus:
#
# """Download status data."""
#
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# self.url = url
# self.hashurl = hashurl
# self.outfname = outfname
# self.outfhash = outfhash
# self.skipped = skipped
# self.error = error
#
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# FRAGSIZE = 1020 # Default ANIb fragment size
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
, which may include functions, classes, or code. Output only the next line. | cmd = str(BLASTALL_DEFAULT) |
Next line prediction: <|code_start|>
class MockMatch(NamedTuple):
"""Mock match object."""
def group(self):
return ""
@pytest.fixture
def blastall_available():
"""Returns True if blastall can be run, False otherwise."""
cmd = str(BLASTALL_DEFAULT)
# Can't use check=True, as blastall without arguments returns 1!
try:
result = subprocess.run(
cmd,
shell=False,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
except OSError:
return False
return result.stdout[1:9] == b"blastall"
@pytest.fixture
def blastn_available():
"""Returns True if blastn can be run, False otherwise."""
<|code_end|>
. Use current file imports:
(import subprocess
import shutil
import os
import re
import platform
import pytest
from pathlib import Path
from typing import NamedTuple
from pyani import download
from pyani.download import ASMIDs, DLStatus
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
NUCMER_DEFAULT,
FRAGSIZE,
)
from pyani.scripts import genbank_get_genomes_by_taxon)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/download.py
# TAXONREGEX = re.compile(r"([0-9]\,?){1,}")
# class NCBIDownloadException(Exception):
# class FileExistsException(Exception):
# class PyaniIndexException(Exception):
# class ASMIDs(NamedTuple):
# class Classification(NamedTuple):
# class DLFileData(NamedTuple):
# class Hashstatus(NamedTuple):
# class DLStatus:
# def __init__(self, msg: str = "Error downloading file from NCBI"):
# def __init__(self, msg: str = "Specified file exists"):
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# def last_exception() -> str:
# def make_asm_dict(taxon_ids: List[str], retries: int) -> Dict:
# def set_ncbi_email(email: str) -> None:
# def download_genome_and_hash(
# outdir: Path,
# timeout: int,
# dlfiledata: DLFileData,
# dltype: str = "RefSeq",
# disable_tqdm: bool = False,
# ) -> namedlist:
# def entrez_retry(func):
# def wrapper(*args, retries=1, **kwargs):
# def entrez_batch(func):
# def wrapper(*args, expected=None, batchsize=None, **kwargs):
# def entrez_batched_webhistory(*args, **kwargs):
# def entrez_esearch(*args, **kwargs):
# def entrez_esummary(*args, **kwargs):
# def split_taxa(taxa: str) -> List[str]:
# def get_asm_uids(taxon_uid: str, retries: int) -> ASMIDs:
# def extract_filestem(esummary) -> str:
# def get_ncbi_esummary(asm_uid, retries, api_key=None) -> Tuple:
# def get_ncbi_classification(esummary) -> Classification:
# def compile_url(filestem: str, suffix: str, ftpstem: str) -> Tuple[str, str]:
# def download_url(
# url: str, outfname: Path, timeout: int, disable_tqdm: bool = False
# ) -> None:
# def construct_output_paths(
# filestem: str, suffix: str, outdir: Path
# ) -> Tuple[Path, Path]:
# def retrieve_genome_and_hash(
# filestem: str,
# suffix: str,
# ftpstem: str,
# outdir: Path,
# timeout: int,
# disable_tqdm: bool = False,
# ) -> DLStatus:
# def check_hash(fname: Path, hashfile: Path) -> Hashstatus:
# def extract_contigs(fname: Path, ename: Path) -> CompletedProcess:
# def create_labels(
# classification: Classification, filestem: str, genomehash: str
# ) -> Tuple[str, str]:
# def create_hash(fname: Path) -> str:
# def extract_hash(hashfile: Path, name: str) -> str:
#
# Path: pyani/download.py
# class ASMIDs(NamedTuple):
#
# """Matching Assembly ID information for a query taxID."""
#
# query: str
# result_count: int
# asm_ids: List[str]
#
# class DLStatus:
#
# """Download status data."""
#
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# self.url = url
# self.hashurl = hashurl
# self.outfname = outfname
# self.outfhash = outfhash
# self.skipped = skipped
# self.error = error
#
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# FRAGSIZE = 1020 # Default ANIb fragment size
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | cmd = [str(BLASTN_DEFAULT), "-version"] |
Next line prediction: <|code_start|>
:param name: String describing the job (uniquely)
:param command: String, the valid shell command to run the job
:param queue: String, the SGE queue under which the job shall run
"""
self.name = name # Unique name for the job
self.queue = queue # The SGE queue to run the job under
self.command = command # Command line to run for this job
self.script = command
self.scriptPath = None # type: Optional[Any]
self.dependencies = [] # type: List[Any]
self.submitted = False # type: bool
self.finished = False # type: int
def add_dependency(self, job) -> None:
"""Add passed job to the dependency list for this Job.
:param job: Job to be added to the Job's dependency list
This Job should not execute until all dependent jobs are completed.
"""
self.dependencies.append(job)
def remove_dependency(self, job) -> None:
"""Remove passed job from this Job's dependency list.
:param job: Job to be removed from the Job's dependency list
"""
self.dependencies.remove(job)
<|code_end|>
. Use current file imports:
(import os
import time
from typing import Any, Dict, List, Optional
from .pyani_config import SGE_WAIT)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_config.py
# SGE_WAIT = 0.01 # Base unit of time (s) to wait between polling SGE
. Output only the next line. | def wait(self, interval: float = SGE_WAIT) -> None: |
Next line prediction: <|code_start|> dlfiledata: DLFileData,
dltype: str = "RefSeq",
disable_tqdm: bool = False,
) -> namedlist:
"""Download genome and accompanying MD5 hash from NCBI.
:param args: Namespace for command-line arguments
:param outdir: Path to output directory for downloads
:param timeout: int: timeout for download attempt
:param dlfiledata: namedtuple of info for file to download
:param dltype: reference database to use: RefSeq or GenBank
:param disable_tqdm: disable progress bar
This function tries the (assumed to be passed) RefSeq FTP URL first and,
if that fails, then attempts to download the corresponding GenBank data.
We attempt to gracefully skip genomes with download errors.
"""
# Create logger
logger = logging.getLogger(__name__)
if dltype == "GenBank":
filestem = re.sub("^GCF_", "GCA_", dlfiledata.filestem)
else:
filestem = dlfiledata.filestem
dlstatus = retrieve_genome_and_hash(
filestem, dlfiledata.suffix, dlfiledata.ftpstem, outdir, timeout, disable_tqdm
)
# Pylint is confused by the content of dlstatus (a namedlist)
if dlstatus.error is not None: # pylint: disable=no-member
<|code_end|>
. Use current file imports:
(import hashlib
import logging
import re
import shlex
import subprocess
import os
import sys
import traceback
import urllib.request
from namedlist import namedlist
from pathlib import Path
from subprocess import CompletedProcess
from typing import Any, Dict, List, NamedTuple, Optional, Tuple
from urllib.error import HTTPError, URLError
from Bio import Entrez # type: ignore
from tqdm import tqdm # type: ignore
from pyani.pyani_tools import termcolor)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_tools.py
# def termcolor(
# logstr: str, color: Optional[str] = None, bold: Optional[bool] = False
# ) -> str:
# """Return the passed logstr, wrapped in terminal colouring."""
# # For terminal colouring
# termcolors = {
# "BLACK": 0,
# "RED": 1,
# "GREEN": 2,
# "YELLOW": 3,
# "BLUE": 4,
# "MAGENTA": 5,
# "CYAN": 6,
# "WHITE": 7,
# }
# reset = "\033[0m"
#
# # Colour the string
# if isinstance(color, str) and color.upper() in termcolors:
# logstr = f"\033[1;{30 + termcolors[color.upper()]}m{logstr}{reset}"
#
# # Make the string bold
# if bold is True:
# logstr = f"\033[1m{logstr}"
# if not logstr.endswith(reset):
# logstr += reset
#
# return logstr
. Output only the next line. | logger.warning(termcolor("%s download failed: skipping!", "magenta"), dltype) |
Given the following code snippet before the placeholder: <|code_start|>
# Holds summary information about a graph's cliques
class Cliquesinfo(NamedTuple):
"""Summary of clique structure."""
n_nodes: int
n_subgraphs: int
all_k_complete: bool
# Build an undirected graph from an ANIResults object
def build_graph_from_results(
results, label_dict: Dict[int, str], cov_min: float = 0, id_min: float = 0
) -> nx.Graph:
"""Return undirected graph representing the passed ANIResults object.
The passed ANIResults object is converted to an undirected graph where
nodes on the graph represent genomes, and edges represent pairwise
comparisons having the minimum coverage and identity indicated.
:param results: - Run object from pyani_orm
:param label_dict: dictionary of genome labels for result matrices
the dict is keyed by the index/column values for the results
matrices
:param cov_min: - minimum coverage for an edge
:param id_min: - minimum identity for an edge
"""
# Parse identity and coverage matrices
<|code_end|>
, predict the next line using imports from the current file:
from typing import Dict, List, NamedTuple, Tuple
from pyani.pyani_tools import label_results_matrix
import networkx as nx # type: ignore
import pandas as pd # type: ignore
and context including class names, function names, and sometimes code from other files:
# Path: pyani/pyani_tools.py
# def label_results_matrix(matrix: pd.DataFrame, labels: Dict) -> pd.DataFrame:
# """Return results matrix dataframe with labels.
#
# :param matrix: results dataframe deriving from Run object
# :param labels: dictionary of genome labels
# labels must be keyed by index/col values from matrix
#
# Applies the labels from the dictionary to the dataframe in
# matrix, and returns the result.
# """
# # The dictionary uses string keys!
# # Create a label function that produces <label>:<genome_id>
# # when a label is available; and just Genome_id:<genome_id> when no
# # label exists
# label = lambda gen_id: f"{labels.get(str(gen_id), 'Genome_id')}:{gen_id}"
# matrix.columns = [label(_) for _ in matrix.columns]
# matrix.index = [label(_) for _ in matrix.index]
# return matrix
. Output only the next line. | mat_identity = label_results_matrix(pd.read_json(results.df_identity), label_dict) |
Next line prediction: <|code_start|># (c) The University of Strathclude 2019-2020
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Tests for pyani package intermediate file parsing.
These tests are intended to be run from the repository root using:
pytest -v
"""
def test_anim_delta(dir_anim_in):
"""Test parsing of NUCmer delta file."""
<|code_end|>
. Use current file imports:
(from pyani.anim import parse_delta)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/anim.py
# def parse_delta(filename: Path) -> Tuple[int, int]:
# """Return (alignment length, similarity errors) tuple from passed .delta.
#
# :param filename: Path, path to the input .delta file
#
# Extracts the aligned length and number of similarity errors for each
# aligned uniquely-matched region, and returns the cumulative total for
# each as a tuple.
#
# Similarity errors are defined in the .delta file spec (see below) as
# non-positive match scores. For NUCmer output, this is identical to the
# number of errors (non-identities and indels).
#
# Delta file format has seven numbers in the lines of interest:
# see http://mummer.sourceforge.net/manual/ for specification
#
# - start on query
# - end on query
# - start on target
# - end on target
# - error count (non-identical, plus indels)
# - similarity errors (non-positive match scores)
# [NOTE: with PROmer this is equal to error count]
# - stop codons (always zero for nucmer)
#
# To calculate alignment length, we take the length of the aligned region of
# the reference (no gaps), and process the delta information. This takes the
# form of one value per line, following the header sequence. Positive values
# indicate an insertion in the reference; negative values a deletion in the
# reference (i.e. an insertion in the query). The total length of the alignment
# is then:
#
# reference_length + insertions - deletions
#
# For example:
#
# A = ABCDACBDCAC$
# B = BCCDACDCAC$
# Delta = (1, -3, 4, 0)
# A = ABC.DACBDCAC$
# B = .BCCDAC.DCAC$
#
# A is the reference and has length 11. There are two insertions (positive delta),
# and one deletion (negative delta). Alignment length is then 11 + 1 = 12.
# """
# in_aln, aln_length, sim_errors = False, 0, 0
# for line in [_.strip().split() for _ in filename.open("r").readlines()]:
# if line[0] == "NUCMER" or line[0].startswith(">"): # Skip headers
# continue
# # Lines with seven columns are alignment region headers:
# if len(line) == 7:
# aln_length += abs(int(line[1]) - int(line[0])) + 1 # reference length
# sim_errors += int(line[4]) # count of non-identities and indels
# in_aln = True
# # Lines with a single column (following a header) report numbers of symbols
# # until next insertion (+ve) or deletion (-ve) in the reference; one line per
# # insertion/deletion; the alignment always ends with 0
# if in_aln and line[0].startswith("0"):
# in_aln = False
# elif in_aln:
# # Add one to the alignment length for each reference insertion; subtract
# # one for each deletion
# val = int(line[0])
# if val < 1: # deletion in reference
# aln_length += 1
# elif val == 0: # ends the alignment entry
# in_aln = False
# return aln_length, sim_errors
. Output only the next line. | aln, sim = parse_delta(dir_anim_in / "NC_002696_vs_NC_011916.delta") |
Next line prediction: <|code_start|> "-f_ARRAY=( file1 file2 file3 )\n\n",
'let "-f_INDEX=$TASK_ID % 3"\n',
"-f=${-f_ARRAY[$-f_INDEX]}\n",
'let "TASK_ID=$TASK_ID / 3"\n\n',
"cat\n",
]
),
),
JobScript(
{"-f": ["file1", "file2"], "--format": ["fmtA", "fmtB"]},
"".join(
[
'let "TASK_ID=$SGE_TASK_ID - 1"\n',
"--format_ARRAY=( fmtA fmtB )\n",
"-f_ARRAY=( file1 file2 )\n\n",
'let "--format_INDEX=$TASK_ID % 2"\n',
"--format=${--format_ARRAY[$--format_INDEX]}\n",
'let "TASK_ID=$TASK_ID / 2"\n',
'let "-f_INDEX=$TASK_ID % 2"\n',
"-f=${-f_ARRAY[$-f_INDEX]}\n",
'let "TASK_ID=$TASK_ID / 2"\n\n',
"myprog\n",
]
),
),
)
def test_create_job():
"""Create a dummy job."""
<|code_end|>
. Use current file imports:
(from typing import Dict, NamedTuple
from pyani import pyani_jobs
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_jobs.py
# class Job(object):
# class JobGroup(object):
# def __init__(self, name: str, command: str, queue: Optional[str] = None) -> None:
# def add_dependency(self, job) -> None:
# def remove_dependency(self, job) -> None:
# def wait(self, interval: float = SGE_WAIT) -> None:
# def __init__(
# self,
# name: str,
# command: str,
# queue: Optional[str] = None,
# arguments: Optional[Dict[str, List[Any]]] = None,
# ) -> None:
# def generate_script(self) -> None:
# def add_dependency(self, job) -> None:
# def remove_dependency(self, job) -> None:
# def wait(self, interval: float = SGE_WAIT) -> None:
. Output only the next line. | job = pyani_jobs.Job("empty", "") |
Given snippet: <|code_start|> fragfiles - list of fragmented FASTA query files
blastdir - path to BLAST+ output data
legacyblastdir - path to blastall output data
blastresult - pd.DataFrame result for BLAST+
legacyblastresult - pd.DataFrame result for blastall
"""
return ANIbOutputDir(
[
_
for _ in (dir_anib_in / "sequences").iterdir()
if _.is_file() and _.suffix == ".fna"
],
[
_
for _ in (dir_anib_in / "fragfiles").iterdir()
if _.is_file() and _.suffix == ".fna"
],
dir_anib_in / "blastn",
dir_anib_in / "blastall",
pd.read_csv(dir_anib_in / "dataframes" / "blastn_result.csv", index_col=0),
pd.read_csv(dir_anib_in / "dataframes" / "blastall_result.csv", index_col=0),
)
# Test get_version()
# Test case 0: no executable location is specified
def test_get_version_nonetype():
"""Test behaviour when no location for the executable is given."""
test_file_0 = None
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from pathlib import Path
from typing import List, NamedTuple
from pandas.testing import assert_frame_equal
from pyani import anib, pyani_files
import pandas as pd
import pytest # noqa: F401 # pylint: disable=unused-import
import unittest
and context:
# Path: pyani/anib.py
# class PyaniANIbException(PyaniException):
# def get_version(blast_exe: Path = pyani_config.BLASTN_DEFAULT) -> str:
# def fragment_fasta_files(
# infiles: List[Path], outdirname: Path, fragsize: int
# ) -> Tuple[List, Dict]:
# def get_fraglength_dict(fastafiles: List[Path]) -> Dict:
# def get_fragment_lengths(fastafile: Path) -> Dict:
# def build_db_jobs(infiles: List[Path], blastcmds: BLASTcmds) -> Dict:
# def make_blastcmd_builder(
# mode: str,
# outdir: Path,
# format_exe: Optional[Path] = None,
# blast_exe: Optional[Path] = None,
# prefix: str = "ANIBLAST",
# ) -> BLASTcmds:
# def make_job_graph(
# infiles: List[Path], fragfiles: List[Path], blastcmds: BLASTcmds
# ) -> List[pyani_jobs.Job]:
# def generate_blastdb_commands(
# filenames: List[Path],
# outdir: Path,
# blastdb_exe: Optional[Path] = None,
# mode: str = "ANIb",
# ) -> List[Tuple[str, Path]]:
# def construct_makeblastdb_cmd(
# filename: Path, outdir: Path, blastdb_exe: Path = pyani_config.MAKEBLASTDB_DEFAULT
# ) -> Tuple[str, Path]:
# def construct_formatdb_cmd(
# filename: Path, outdir: Path, blastdb_exe: Path = pyani_config.FORMATDB_DEFAULT
# ) -> Tuple[str, Path]:
# def generate_blastn_commands(
# filenames: List[Path],
# outdir: Path,
# blast_exe: Optional[Path] = None,
# mode: str = "ANIb",
# ) -> List[str]:
# def construct_blastn_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path,
# blastn_exe: Path = pyani_config.BLASTN_DEFAULT,
# ) -> str:
# def construct_blastall_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path,
# blastall_exe: Path = pyani_config.BLASTALL_DEFAULT,
# ) -> str:
# def process_blast(
# blast_dir: Path,
# org_lengths: Dict,
# fraglengths: Dict,
# mode: str = "ANIb",
# logger: Optional[Logger] = None,
# ) -> ANIResults:
# def parse_blast_tab(
# filename: Path, fraglengths: Dict, mode: str = "ANIb"
# ) -> Tuple[int, int, int]:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
which might include code, classes, or functions. Output only the next line. | assert anib.get_version(test_file_0) == f"{test_file_0} is not found in $PATH" |
Using the snippet: <|code_start|> (
f"makeblastdb -dbtype nucl -in {path_fna_two[0]} "
f"-title {path_fna_two[0].stem} -out {tmp_path / path_fna_two[0].name}"
),
tmp_path / path_fna_two[0].name,
),
(
(
f"makeblastdb -dbtype nucl -in {path_fna_two[1]} "
f"-title {path_fna_two[1].stem} -out {tmp_path / path_fna_two[1].name}"
),
tmp_path / path_fna_two[1].name,
),
]
assert cmds == expected
def test_makeblastdb_single(path_fna, tmp_path):
"""Generate single BLAST+ makeblastdb command-line."""
cmd = anib.construct_makeblastdb_cmd(path_fna, tmp_path)
expected = (
f"makeblastdb -dbtype nucl -in {path_fna} "
f"-title {path_fna.stem} -out {tmp_path / path_fna.name}"
)
assert cmd[0] == expected
# Test output file parsing for ANIb methods
def test_parse_legacy_blastdir(anib_output_dir):
"""Parses directory of legacy BLAST output."""
<|code_end|>
, determine the next line of code. You have imports:
from pathlib import Path
from typing import List, NamedTuple
from pandas.testing import assert_frame_equal
from pyani import anib, pyani_files
import pandas as pd
import pytest # noqa: F401 # pylint: disable=unused-import
import unittest
and context (class names, function names, or code) available:
# Path: pyani/anib.py
# class PyaniANIbException(PyaniException):
# def get_version(blast_exe: Path = pyani_config.BLASTN_DEFAULT) -> str:
# def fragment_fasta_files(
# infiles: List[Path], outdirname: Path, fragsize: int
# ) -> Tuple[List, Dict]:
# def get_fraglength_dict(fastafiles: List[Path]) -> Dict:
# def get_fragment_lengths(fastafile: Path) -> Dict:
# def build_db_jobs(infiles: List[Path], blastcmds: BLASTcmds) -> Dict:
# def make_blastcmd_builder(
# mode: str,
# outdir: Path,
# format_exe: Optional[Path] = None,
# blast_exe: Optional[Path] = None,
# prefix: str = "ANIBLAST",
# ) -> BLASTcmds:
# def make_job_graph(
# infiles: List[Path], fragfiles: List[Path], blastcmds: BLASTcmds
# ) -> List[pyani_jobs.Job]:
# def generate_blastdb_commands(
# filenames: List[Path],
# outdir: Path,
# blastdb_exe: Optional[Path] = None,
# mode: str = "ANIb",
# ) -> List[Tuple[str, Path]]:
# def construct_makeblastdb_cmd(
# filename: Path, outdir: Path, blastdb_exe: Path = pyani_config.MAKEBLASTDB_DEFAULT
# ) -> Tuple[str, Path]:
# def construct_formatdb_cmd(
# filename: Path, outdir: Path, blastdb_exe: Path = pyani_config.FORMATDB_DEFAULT
# ) -> Tuple[str, Path]:
# def generate_blastn_commands(
# filenames: List[Path],
# outdir: Path,
# blast_exe: Optional[Path] = None,
# mode: str = "ANIb",
# ) -> List[str]:
# def construct_blastn_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path,
# blastn_exe: Path = pyani_config.BLASTN_DEFAULT,
# ) -> str:
# def construct_blastall_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path,
# blastall_exe: Path = pyani_config.BLASTALL_DEFAULT,
# ) -> str:
# def process_blast(
# blast_dir: Path,
# org_lengths: Dict,
# fraglengths: Dict,
# mode: str = "ANIb",
# logger: Optional[Logger] = None,
# ) -> ANIResults:
# def parse_blast_tab(
# filename: Path, fraglengths: Dict, mode: str = "ANIb"
# ) -> Tuple[int, int, int]:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
. Output only the next line. | orglengths = pyani_files.get_sequence_lengths(anib_output_dir.infiles) |
Here is a snippet: <|code_start|> :param value:
:param sym:
"""
self.percentage_identity.loc[qname, sname] = value
if sym:
self.percentage_identity.loc[sname, qname] = value
def add_coverage(
self, qname: str, sname: str, qcover: float, scover: Optional[float] = None
) -> None:
"""Add percentage coverage values to self.alignment_coverage.
:param qname:
:param sname:
:param value:
:param sym:
"""
self.alignment_coverage.loc[qname, sname] = qcover
if scover:
self.alignment_coverage.loc[sname, qname] = scover
@property
def hadamard(self) -> float:
"""Return Hadamard matrix (identity * coverage)."""
return self.percentage_identity * self.alignment_coverage
@property
def data(self) -> Iterator[Tuple[Any, str]]:
"""Return list of (dataframe, filestem) tuples."""
stemdict = {
<|code_end|>
. Write the next line using the current file imports:
import shutil
import pandas as pd # type: ignore
from logging import Logger
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Tuple,
)
from Bio import SeqIO # type: ignore
from pyani import pyani_config
and context from other files:
# Path: pyani/pyani_config.py
# NUCMER_DEFAULT = Path("nucmer")
# FILTER_DEFAULT = Path("delta-filter")
# BLASTN_DEFAULT = Path("blastn")
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
# BLASTALL_DEFAULT = Path("blastall")
# FORMATDB_DEFAULT = Path("formatdb")
# QSUB_DEFAULT = Path("qsub")
# FASTANI_DEFAULT = Path("fastANI")
# ANIM_FILESTEMS = (
# "ANIm_alignment_lengths",
# "ANIm_percentage_identity",
# "ANIm_alignment_coverage",
# "ANIm_similarity_errors",
# "ANIm_hadamard",
# )
# ANIB_FILESTEMS = (
# "ANIb_alignment_lengths",
# "ANIb_percentage_identity",
# "ANIb_alignment_coverage",
# "ANIb_similarity_errors",
# "ANIb_hadamard",
# )
# TETRA_FILESTEMS = ("TETRA_correlations",)
# ANIBLASTALL_FILESTEMS = (
# "ANIblastall_alignment_lengths",
# "ANIblastall_percentage_identity",
# "ANIblastall_alignment_coverage",
# "ANIblastall_similarity_errors",
# "ANIblastall_hadamard",
# )
# ALIGNDIR = {
# "ANIm": "nucmer_output",
# "ANIb": "blastn_output",
# "ANIblastall": "blastall_output",
# "fastANI": "fastani_output",
# }
# MPL_CBAR = "Spectral"
# FRAGSIZE = 1020 # Default ANIb fragment size
# SGE_WAIT = 0.01 # Base unit of time (s) to wait between polling SGE
# CMAP_SPBND_BURD = LinearSegmentedColormap("spbnd_BuRd", cdict_spbnd_BuRd)
# CMAP_HADAMARD_BURD = LinearSegmentedColormap("hadamard_BuRd", cdict_hadamard_BuRd)
# CMAP_BURD = LinearSegmentedColormap("BuRd", cdict_BuRd)
# def params_mpl(dfm: pd.DataFrame) -> Dict[str, Tuple[str, Any, Any]]:
# def get_colormap(dataframe: pd.DataFrame, matname: str) -> Tuple[str, Any, Any]:
, which may include functions, classes, or code. Output only the next line. | "ANIm": pyani_config.ANIM_FILESTEMS, |
Given the code snippet: <|code_start|> )
def assertNucmerEqual(self, fname1, fname2): # pylint: disable=C0103
"""Assert that two passed nucmer output files are equal.
:param fname1: path to reference .delta/.filter file
:param fname2: path to comparator .delta/.filter file
This is a standard file comparison, skipping the first line.
"""
with open(fname1, "r") as fh1:
with open(fname2, "r") as fh2:
fdata1 = nucmer.DeltaData("fh1", fh1)
fdata2 = nucmer.DeltaData("fh2", fh2)
self.assertEqual(
fdata1,
fdata2,
msg="Nucmer files {} and {} are not equivalent".format(
fname1, fname2
),
)
def assertBlasttabEqual(self, fname1, fname2): # pylint: disable=C0103
"""Assert that two passed BLAST+ .tab output files contain the same data.
This is not a simple comparison, as we can't rely on the same ordering,
so we parse the files and compare objects.
"""
with open(fname1, "r") as fh1:
with open(fname2, "r") as fh2:
<|code_end|>
, generate the next line using the imports in this file:
import copy
import json
import unittest
import pandas as pd
from pyani import blast, nucmer
and context (functions, classes, or occasionally code) from other files:
# Path: pyani/blast.py
# def parse_blasttab(fhandle: TextIO) -> List[List[str]]:
#
# Path: pyani/nucmer.py
# class DeltaData:
# class DeltaHeader:
# class DeltaAlignment:
# class DeltaMetadata:
# class DeltaComparison:
# class DeltaIterator:
# def __init__(self, name: str, handle: TextIO = None) -> None:
# def from_delta(self, handle: TextIO) -> None:
# def comparisons(self):
# def metadata(self):
# def reference(self):
# def program(self):
# def query(self):
# def __eq__(self, other):
# def __len__(self):
# def __str__(self):
# def __init__(
# self, reference: Path, query: Path, reflen: int, querylen: int
# ) -> None:
# def __eq__(self, other):
# def __str__(self):
# def __init__(
# self,
# refstart: int,
# refend: int,
# qrystart: int,
# qryend: int,
# errs: int,
# simerrs: int,
# stops: int,
# ) -> None:
# def __lt__(self, other):
# def __eq__(self, other):
# def __str__(self):
# def __init__(self) -> None:
# def __eq__(self, other):
# def __str__(self):
# def __init__(self, header: DeltaHeader, alignments: List[DeltaAlignment]) -> None:
# def add_alignment(self, aln: DeltaAlignment) -> None:
# def __eq__(self, other):
# def __len__(self):
# def __str__(self):
# def __init__(self, handle: TextIO) -> None:
# def __iter__(self):
# def __next__(self):
. Output only the next line. | data1 = blast.parse_blasttab(fh1) |
Next line prediction: <|code_start|>
def assertJsonEqual(self, json1, json2): # pylint: disable=C0103
"""Assert that two passed JSON files are equal.
:param json1: path to reference JSON file
:param json2: path to comparator JSON file
As we can't always be sure that JSON elements are in the same order in otherwise
equal files, we compare ordered components.
"""
with open(json1, "r") as fh1:
with open(json2, "r") as fh2:
self.assertEqual(
ordered(json.load(fh1)),
ordered(json.load(fh2)),
msg="JSON files {} and {} do not contain equal contents".format(
json1, json2
),
)
def assertNucmerEqual(self, fname1, fname2): # pylint: disable=C0103
"""Assert that two passed nucmer output files are equal.
:param fname1: path to reference .delta/.filter file
:param fname2: path to comparator .delta/.filter file
This is a standard file comparison, skipping the first line.
"""
with open(fname1, "r") as fh1:
with open(fname2, "r") as fh2:
<|code_end|>
. Use current file imports:
(import copy
import json
import unittest
import pandas as pd
from pyani import blast, nucmer)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/blast.py
# def parse_blasttab(fhandle: TextIO) -> List[List[str]]:
#
# Path: pyani/nucmer.py
# class DeltaData:
# class DeltaHeader:
# class DeltaAlignment:
# class DeltaMetadata:
# class DeltaComparison:
# class DeltaIterator:
# def __init__(self, name: str, handle: TextIO = None) -> None:
# def from_delta(self, handle: TextIO) -> None:
# def comparisons(self):
# def metadata(self):
# def reference(self):
# def program(self):
# def query(self):
# def __eq__(self, other):
# def __len__(self):
# def __str__(self):
# def __init__(
# self, reference: Path, query: Path, reflen: int, querylen: int
# ) -> None:
# def __eq__(self, other):
# def __str__(self):
# def __init__(
# self,
# refstart: int,
# refend: int,
# qrystart: int,
# qryend: int,
# errs: int,
# simerrs: int,
# stops: int,
# ) -> None:
# def __lt__(self, other):
# def __eq__(self, other):
# def __str__(self):
# def __init__(self) -> None:
# def __eq__(self, other):
# def __str__(self):
# def __init__(self, header: DeltaHeader, alignments: List[DeltaAlignment]) -> None:
# def add_alignment(self, aln: DeltaAlignment) -> None:
# def __eq__(self, other):
# def __len__(self):
# def __str__(self):
# def __init__(self, handle: TextIO) -> None:
# def __iter__(self):
# def __next__(self):
. Output only the next line. | fdata1 = nucmer.DeltaData("fh1", fh1) |
Given the following code snippet before the placeholder: <|code_start|> ),
(
"delta_filter_wrapper.py delta-filter -1 "
"nucmer_output/file2/file2_vs_file3.delta "
"nucmer_output/file2/file2_vs_file3.filter"
),
(
"delta_filter_wrapper.py delta-filter -1 "
"nucmer_output/file2/file2_vs_file4.delta "
"nucmer_output/file2/file2_vs_file4.filter"
),
(
"delta_filter_wrapper.py delta-filter -1 "
"nucmer_output/file3/file3_vs_file4.delta "
"nucmer_output/file3/file3_vs_file4.filter"
),
],
)
# Create object for accessing unittest assertions
assertions = unittest.TestCase("__init__")
# Test get_version()
# Test case 0: no executable location is specified
def test_get_version_nonetype():
"""Test behaviour when no location for the executable is given."""
test_file_0 = None
<|code_end|>
, predict the next line using imports from the current file:
from pathlib import Path
from typing import List, NamedTuple, Tuple
from pandas.testing import assert_frame_equal
from pyani import anim, pyani_files
import pandas as pd
import pytest
import unittest
and context including class names, function names, and sometimes code from other files:
# Path: pyani/anim.py
# class PyaniANImException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> Iterable:
# def get_version(nucmer_exe: Path = pyani_config.NUCMER_DEFAULT) -> str:
# def generate_nucmer_jobs(
# filenames: List[Path],
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# jobprefix: str = "ANINUCmer",
# ):
# def generate_nucmer_commands(
# filenames: List[Path],
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# ) -> Tuple[List, List]:
# def construct_nucmer_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# ) -> Tuple[str, str]:
# def parse_delta(filename: Path) -> Tuple[int, int]:
# def process_deltadir(
# delta_dir: Path, org_lengths: Dict, logger: Optional[Logger] = None
# ) -> ANIResults:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
. Output only the next line. | assert anim.get_version(test_file_0) == f"{test_file_0} is not found in $PATH" |
Predict the next line after this snippet: <|code_start|>
# Test case 3: there is an executable file, but the version can't be retrieved
def test_get_version_exe_no_version(executable_without_version):
"""Test behaviour when the version for the executable can not be retrieved."""
test_file_3 = Path("/missing/version/nucmer")
assert (
anim.get_version(test_file_3)
== f"nucmer exists at {test_file_3} but could not retrieve version"
)
# Test regex for different NUCmer versions
def test_get_version_nucmer_3(mock_get_nucmer_3_version):
"""Tests the regex that gets the version number for NUCmer <= 3."""
fake_nucmer_3 = Path("/fake/nucmer3/executable")
assert anim.get_version(fake_nucmer_3) == f"Darwin_3.1 ({fake_nucmer_3})"
def test_get_version_nucmer_4(mock_get_nucmer_4_version):
"""Tests the regex that gets the version number for NUCmer 4."""
fake_nucmer_4 = Path("/fake/nucmer4/executable")
assert anim.get_version(fake_nucmer_4) == f"Darwin_4.0.0rc1 ({fake_nucmer_4})"
# Test .delta output file processing
def test_deltadir_parsing(delta_output_dir):
"""Process test directory of .delta files into ANIResults."""
<|code_end|>
using the current file's imports:
from pathlib import Path
from typing import List, NamedTuple, Tuple
from pandas.testing import assert_frame_equal
from pyani import anim, pyani_files
import pandas as pd
import pytest
import unittest
and any relevant context from other files:
# Path: pyani/anim.py
# class PyaniANImException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> Iterable:
# def get_version(nucmer_exe: Path = pyani_config.NUCMER_DEFAULT) -> str:
# def generate_nucmer_jobs(
# filenames: List[Path],
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# jobprefix: str = "ANINUCmer",
# ):
# def generate_nucmer_commands(
# filenames: List[Path],
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# ) -> Tuple[List, List]:
# def construct_nucmer_cmdline(
# fname1: Path,
# fname2: Path,
# outdir: Path = Path("."),
# nucmer_exe: Path = pyani_config.NUCMER_DEFAULT,
# filter_exe: Path = pyani_config.FILTER_DEFAULT,
# maxmatch: bool = False,
# ) -> Tuple[str, str]:
# def parse_delta(filename: Path) -> Tuple[int, int]:
# def process_deltadir(
# delta_dir: Path, org_lengths: Dict, logger: Optional[Logger] = None
# ) -> ANIResults:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
. Output only the next line. | seqfiles = pyani_files.get_fasta_files(delta_output_dir.seqdir) |
Based on the snippet: <|code_start|>
@pytest.fixture
def args_createdb(tmp_path):
"""Command-line arguments for database creation."""
return ["createdb", "--dbpath", tmp_path / "pyanidb", "--force"]
@pytest.fixture
def args_single_genome_download(email_address, tmp_path):
"""Command-line arguments for single genome download."""
return [
"download",
"-t",
"218491",
"--email",
email_address,
"-o",
tmp_path,
"--force",
]
def test_createdb(args_createdb, monkeypatch):
"""Create empty test database."""
def mock_return_none(*args, **kwargs):
return None
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import pytest
from pathlib import Path
from pyani import pyani_orm
from pyani.scripts import pyani_script
and context (classes, functions, sometimes code) from other files:
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
#
# Path: pyani/scripts/pyani_script.py
# VERSION_INFO = f"pyani version: {__version__}"
# CITATION_INFO = [
# termcolor(
# "If you use pyani in your work, please cite the following publication:", "green"
# ),
# termcolor(
# "\tPritchard, L., Glover, R. H., Humphris, S., Elphinstone, J. G.,", "yellow"
# ),
# termcolor(
# "\t& Toth, I.K. (2016) 'Genomics and taxonomy in diagnostics for", "yellow"
# ),
# termcolor(
# "\tfood security: soft-rotting enterobacterial plant pathogens.'", "yellow"
# ),
# termcolor(
# "\tAnalytical Methods, 8(1), 12–24. http://doi.org/10.1039/C5AY02550H", "yellow"
# ),
# ]
# def run_main(argv: Optional[List[str]] = None) -> int:
# def add_log_headers():
. Output only the next line. | monkeypatch.setattr(pyani_orm, "create_db", mock_return_none) |
Based on the snippet: <|code_start|>
@pytest.fixture
def args_createdb(tmp_path):
"""Command-line arguments for database creation."""
return ["createdb", "--dbpath", tmp_path / "pyanidb", "--force"]
@pytest.fixture
def args_single_genome_download(email_address, tmp_path):
"""Command-line arguments for single genome download."""
return [
"download",
"-t",
"218491",
"--email",
email_address,
"-o",
tmp_path,
"--force",
]
def test_createdb(args_createdb, monkeypatch):
"""Create empty test database."""
def mock_return_none(*args, **kwargs):
return None
monkeypatch.setattr(pyani_orm, "create_db", mock_return_none)
<|code_end|>
, predict the immediate next line with the help of imports:
import logging
import pytest
from pathlib import Path
from pyani import pyani_orm
from pyani.scripts import pyani_script
and context (classes, functions, sometimes code) from other files:
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
#
# Path: pyani/scripts/pyani_script.py
# VERSION_INFO = f"pyani version: {__version__}"
# CITATION_INFO = [
# termcolor(
# "If you use pyani in your work, please cite the following publication:", "green"
# ),
# termcolor(
# "\tPritchard, L., Glover, R. H., Humphris, S., Elphinstone, J. G.,", "yellow"
# ),
# termcolor(
# "\t& Toth, I.K. (2016) 'Genomics and taxonomy in diagnostics for", "yellow"
# ),
# termcolor(
# "\tfood security: soft-rotting enterobacterial plant pathogens.'", "yellow"
# ),
# termcolor(
# "\tAnalytical Methods, 8(1), 12–24. http://doi.org/10.1039/C5AY02550H", "yellow"
# ),
# ]
# def run_main(argv: Optional[List[str]] = None) -> int:
# def add_log_headers():
. Output only the next line. | pyani_script.run_main(args_createdb) |
Given the code snippet: <|code_start|># THE SOFTWARE.
"""Provides the listdeps subcommand for pyani."""
def subcmd_listdeps(args: Namespace) -> int:
"""Reports dependency versions to logger.
:param args: Namespace, received command-line arguments
"""
# If the -v argument is provided, we don't want to have two
# streams writing to STDOUT
logger = logging.getLogger(__name__)
# Adding this handler means we bypass the default logging
# formatter, and write straight to the terminal as stdout
if not args.verbose:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
# System information
logger.info("System information")
logger.info("\tPlatorm==%s", platform.platform())
logger.info("\tPython==%s", sys.version)
# Pyani dependencies
logger.info("Installed pyani Python dependendencies...")
<|code_end|>
, generate the next line using the imports in this file:
import logging
import platform
import sys
from argparse import Namespace
from pyani.dependencies import (
get_requirements,
get_dev_requirements,
get_pip_requirements,
get_tool_versions,
)
and context (functions, classes, or occasionally code) from other files:
# Path: pyani/dependencies.py
# def get_requirements() -> Generator:
# """Yield package name and version for Python requirements."""
# return get_versions("REQUIREMENTS")
#
# def get_dev_requirements() -> Generator:
# """Yield package name and version for Python developer requirements."""
# return get_versions("DEVELOPMENT")
#
# def get_pip_requirements() -> Generator:
# """Yield package name and version for Python pip installed requirements."""
# return get_versions("PIP")
#
# def get_tool_versions() -> Generator:
# """Yield tool name and version for third-party installed tools."""
# for name, func in [
# ("blast+", get_blast_version),
# ("nucmer", get_nucmer_version),
# ("blastall", get_blastall_version),
# ("fastani", get_fastani_version),
# ]:
# yield (name, func())
. Output only the next line. | for package, version, loc in get_requirements(): |
Given the code snippet: <|code_start|>
def subcmd_listdeps(args: Namespace) -> int:
"""Reports dependency versions to logger.
:param args: Namespace, received command-line arguments
"""
# If the -v argument is provided, we don't want to have two
# streams writing to STDOUT
logger = logging.getLogger(__name__)
# Adding this handler means we bypass the default logging
# formatter, and write straight to the terminal as stdout
if not args.verbose:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
# System information
logger.info("System information")
logger.info("\tPlatorm==%s", platform.platform())
logger.info("\tPython==%s", sys.version)
# Pyani dependencies
logger.info("Installed pyani Python dependendencies...")
for package, version, loc in get_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed pyani development dependendencies...")
<|code_end|>
, generate the next line using the imports in this file:
import logging
import platform
import sys
from argparse import Namespace
from pyani.dependencies import (
get_requirements,
get_dev_requirements,
get_pip_requirements,
get_tool_versions,
)
and context (functions, classes, or occasionally code) from other files:
# Path: pyani/dependencies.py
# def get_requirements() -> Generator:
# """Yield package name and version for Python requirements."""
# return get_versions("REQUIREMENTS")
#
# def get_dev_requirements() -> Generator:
# """Yield package name and version for Python developer requirements."""
# return get_versions("DEVELOPMENT")
#
# def get_pip_requirements() -> Generator:
# """Yield package name and version for Python pip installed requirements."""
# return get_versions("PIP")
#
# def get_tool_versions() -> Generator:
# """Yield tool name and version for third-party installed tools."""
# for name, func in [
# ("blast+", get_blast_version),
# ("nucmer", get_nucmer_version),
# ("blastall", get_blastall_version),
# ("fastani", get_fastani_version),
# ]:
# yield (name, func())
. Output only the next line. | for package, version, loc in get_dev_requirements(): |
Here is a snippet: <|code_start|>
def subcmd_listdeps(args: Namespace) -> int:
"""Reports dependency versions to logger.
:param args: Namespace, received command-line arguments
"""
# If the -v argument is provided, we don't want to have two
# streams writing to STDOUT
logger = logging.getLogger(__name__)
# Adding this handler means we bypass the default logging
# formatter, and write straight to the terminal as stdout
if not args.verbose:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
# System information
logger.info("System information")
logger.info("\tPlatorm==%s", platform.platform())
logger.info("\tPython==%s", sys.version)
# Pyani dependencies
logger.info("Installed pyani Python dependendencies...")
for package, version, loc in get_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed pyani development dependendencies...")
for package, version, loc in get_dev_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed pyani pip-install dependendencies...")
<|code_end|>
. Write the next line using the current file imports:
import logging
import platform
import sys
from argparse import Namespace
from pyani.dependencies import (
get_requirements,
get_dev_requirements,
get_pip_requirements,
get_tool_versions,
)
and context from other files:
# Path: pyani/dependencies.py
# def get_requirements() -> Generator:
# """Yield package name and version for Python requirements."""
# return get_versions("REQUIREMENTS")
#
# def get_dev_requirements() -> Generator:
# """Yield package name and version for Python developer requirements."""
# return get_versions("DEVELOPMENT")
#
# def get_pip_requirements() -> Generator:
# """Yield package name and version for Python pip installed requirements."""
# return get_versions("PIP")
#
# def get_tool_versions() -> Generator:
# """Yield tool name and version for third-party installed tools."""
# for name, func in [
# ("blast+", get_blast_version),
# ("nucmer", get_nucmer_version),
# ("blastall", get_blastall_version),
# ("fastani", get_fastani_version),
# ]:
# yield (name, func())
, which may include functions, classes, or code. Output only the next line. | for package, version, loc in get_pip_requirements(): |
Here is a snippet: <|code_start|>
:param args: Namespace, received command-line arguments
"""
# If the -v argument is provided, we don't want to have two
# streams writing to STDOUT
logger = logging.getLogger(__name__)
# Adding this handler means we bypass the default logging
# formatter, and write straight to the terminal as stdout
if not args.verbose:
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
logger.addHandler(handler)
# System information
logger.info("System information")
logger.info("\tPlatorm==%s", platform.platform())
logger.info("\tPython==%s", sys.version)
# Pyani dependencies
logger.info("Installed pyani Python dependendencies...")
for package, version, loc in get_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed pyani development dependendencies...")
for package, version, loc in get_dev_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed pyani pip-install dependendencies...")
for package, version, loc in get_pip_requirements():
logger.info("\t%s==%s (%s)", package, version, loc)
logger.info("Installed third-party tool versions...")
<|code_end|>
. Write the next line using the current file imports:
import logging
import platform
import sys
from argparse import Namespace
from pyani.dependencies import (
get_requirements,
get_dev_requirements,
get_pip_requirements,
get_tool_versions,
)
and context from other files:
# Path: pyani/dependencies.py
# def get_requirements() -> Generator:
# """Yield package name and version for Python requirements."""
# return get_versions("REQUIREMENTS")
#
# def get_dev_requirements() -> Generator:
# """Yield package name and version for Python developer requirements."""
# return get_versions("DEVELOPMENT")
#
# def get_pip_requirements() -> Generator:
# """Yield package name and version for Python pip installed requirements."""
# return get_versions("PIP")
#
# def get_tool_versions() -> Generator:
# """Yield tool name and version for third-party installed tools."""
# for name, func in [
# ("blast+", get_blast_version),
# ("nucmer", get_nucmer_version),
# ("blastall", get_blastall_version),
# ("fastani", get_fastani_version),
# ]:
# yield (name, func())
, which may include functions, classes, or code. Output only the next line. | for tool, version in get_tool_versions(): |
Here is a snippet: <|code_start|> """Generate a file with the MD5 hash for each genome in an input directory.
:param args: Namespace, received command-line arguments
:param logger: logging object
Identify the genome files in the input directory, and generate a single
MD5 for each so that <genome>.fna produces <genome>.md5
Genome files (FASTA) are identified from the file extension.
"""
logger = logging.getLogger(__name__)
# Get list of FASTA files in the input directory
logger.info("Scanning directory %s for FASTA files", args.indir)
fpaths = pyani_files.get_fasta_paths(args.indir)
logger.info("Found FASTA files:\n" + "\n".join([f"\t{fpath}" for fpath in fpaths]))
# Lists of class/label information
classes = []
labels = []
# Create MD5 hash for each file, if needed
for fpath in fpaths:
hashfname = fpath.with_name(f"{fpath.name}.md5")
if hashfname.is_file():
logger.info("%s already indexed (using existing hash)", fpath)
with open(hashfname, "r") as ifh:
datahash = ifh.readline().split()[0]
else:
# Write an .md5 hash file
<|code_end|>
. Write the next line using the current file imports:
import logging
import os
from argparse import Namespace
from pathlib import Path
from Bio import SeqIO
from pyani import download, pyani_files
and context from other files:
# Path: pyani/download.py
# TAXONREGEX = re.compile(r"([0-9]\,?){1,}")
# class NCBIDownloadException(Exception):
# class FileExistsException(Exception):
# class PyaniIndexException(Exception):
# class ASMIDs(NamedTuple):
# class Classification(NamedTuple):
# class DLFileData(NamedTuple):
# class Hashstatus(NamedTuple):
# class DLStatus:
# def __init__(self, msg: str = "Error downloading file from NCBI"):
# def __init__(self, msg: str = "Specified file exists"):
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# def last_exception() -> str:
# def make_asm_dict(taxon_ids: List[str], retries: int) -> Dict:
# def set_ncbi_email(email: str) -> None:
# def download_genome_and_hash(
# outdir: Path,
# timeout: int,
# dlfiledata: DLFileData,
# dltype: str = "RefSeq",
# disable_tqdm: bool = False,
# ) -> namedlist:
# def entrez_retry(func):
# def wrapper(*args, retries=1, **kwargs):
# def entrez_batch(func):
# def wrapper(*args, expected=None, batchsize=None, **kwargs):
# def entrez_batched_webhistory(*args, **kwargs):
# def entrez_esearch(*args, **kwargs):
# def entrez_esummary(*args, **kwargs):
# def split_taxa(taxa: str) -> List[str]:
# def get_asm_uids(taxon_uid: str, retries: int) -> ASMIDs:
# def extract_filestem(esummary) -> str:
# def get_ncbi_esummary(asm_uid, retries, api_key=None) -> Tuple:
# def get_ncbi_classification(esummary) -> Classification:
# def compile_url(filestem: str, suffix: str, ftpstem: str) -> Tuple[str, str]:
# def download_url(
# url: str, outfname: Path, timeout: int, disable_tqdm: bool = False
# ) -> None:
# def construct_output_paths(
# filestem: str, suffix: str, outdir: Path
# ) -> Tuple[Path, Path]:
# def retrieve_genome_and_hash(
# filestem: str,
# suffix: str,
# ftpstem: str,
# outdir: Path,
# timeout: int,
# disable_tqdm: bool = False,
# ) -> DLStatus:
# def check_hash(fname: Path, hashfile: Path) -> Hashstatus:
# def extract_contigs(fname: Path, ename: Path) -> CompletedProcess:
# def create_labels(
# classification: Classification, filestem: str, genomehash: str
# ) -> Tuple[str, str]:
# def create_hash(fname: Path) -> str:
# def extract_hash(hashfile: Path, name: str) -> str:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
, which may include functions, classes, or code. Output only the next line. | datahash = download.create_hash(fpath) |
Given the code snippet: <|code_start|>#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Provides the index subcommand for pyani."""
def subcmd_index(args: Namespace) -> int:
"""Generate a file with the MD5 hash for each genome in an input directory.
:param args: Namespace, received command-line arguments
:param logger: logging object
Identify the genome files in the input directory, and generate a single
MD5 for each so that <genome>.fna produces <genome>.md5
Genome files (FASTA) are identified from the file extension.
"""
logger = logging.getLogger(__name__)
# Get list of FASTA files in the input directory
logger.info("Scanning directory %s for FASTA files", args.indir)
<|code_end|>
, generate the next line using the imports in this file:
import logging
import os
from argparse import Namespace
from pathlib import Path
from Bio import SeqIO
from pyani import download, pyani_files
and context (functions, classes, or occasionally code) from other files:
# Path: pyani/download.py
# TAXONREGEX = re.compile(r"([0-9]\,?){1,}")
# class NCBIDownloadException(Exception):
# class FileExistsException(Exception):
# class PyaniIndexException(Exception):
# class ASMIDs(NamedTuple):
# class Classification(NamedTuple):
# class DLFileData(NamedTuple):
# class Hashstatus(NamedTuple):
# class DLStatus:
# def __init__(self, msg: str = "Error downloading file from NCBI"):
# def __init__(self, msg: str = "Specified file exists"):
# def __init__(
# self,
# url: str,
# hashurl: str,
# outfname: Path,
# outfhash: Path,
# skipped: bool,
# error: Optional[str] = None,
# ):
# def last_exception() -> str:
# def make_asm_dict(taxon_ids: List[str], retries: int) -> Dict:
# def set_ncbi_email(email: str) -> None:
# def download_genome_and_hash(
# outdir: Path,
# timeout: int,
# dlfiledata: DLFileData,
# dltype: str = "RefSeq",
# disable_tqdm: bool = False,
# ) -> namedlist:
# def entrez_retry(func):
# def wrapper(*args, retries=1, **kwargs):
# def entrez_batch(func):
# def wrapper(*args, expected=None, batchsize=None, **kwargs):
# def entrez_batched_webhistory(*args, **kwargs):
# def entrez_esearch(*args, **kwargs):
# def entrez_esummary(*args, **kwargs):
# def split_taxa(taxa: str) -> List[str]:
# def get_asm_uids(taxon_uid: str, retries: int) -> ASMIDs:
# def extract_filestem(esummary) -> str:
# def get_ncbi_esummary(asm_uid, retries, api_key=None) -> Tuple:
# def get_ncbi_classification(esummary) -> Classification:
# def compile_url(filestem: str, suffix: str, ftpstem: str) -> Tuple[str, str]:
# def download_url(
# url: str, outfname: Path, timeout: int, disable_tqdm: bool = False
# ) -> None:
# def construct_output_paths(
# filestem: str, suffix: str, outdir: Path
# ) -> Tuple[Path, Path]:
# def retrieve_genome_and_hash(
# filestem: str,
# suffix: str,
# ftpstem: str,
# outdir: Path,
# timeout: int,
# disable_tqdm: bool = False,
# ) -> DLStatus:
# def check_hash(fname: Path, hashfile: Path) -> Hashstatus:
# def extract_contigs(fname: Path, ename: Path) -> CompletedProcess:
# def create_labels(
# classification: Classification, filestem: str, genomehash: str
# ) -> Tuple[str, str]:
# def create_hash(fname: Path) -> str:
# def extract_hash(hashfile: Path, name: str) -> str:
#
# Path: pyani/pyani_files.py
# class PyaniFilesException(PyaniException):
# def get_fasta_files(dirname: Path = Path(".")) -> List[Path]:
# def get_fasta_paths(
# dirname: Path = Path("."), extlist: Optional[List] = None
# ) -> List[Path]:
# def get_fasta_and_hash_paths(dirname: Path = Path(".")) -> List[Tuple[Path, Path]]:
# def get_input_files(dirname: Path, *ext) -> List[Path]:
# def get_sequence_lengths(fastafilenames: Iterable[Path]) -> Dict[str, int]:
# def read_hash_string(filename: Path) -> Tuple[str, str]:
# def read_fasta_description(filename: Path) -> str:
# def load_classes_labels(path: Path) -> Dict[str, str]:
# def collect_existing_output(dirpath: Path, program: str, args: Namespace) -> List[Path]:
. Output only the next line. | fpaths = pyani_files.get_fasta_paths(args.indir) |
Using the snippet: <|code_start|>#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Test aniblastall.py module.
These tests are intended to be run from the repository root using:
pytest -v
"""
# Create object for accessing unittest assertions
assertions = unittest.TestCase("__init__")
# Test get_version()
# Test case 0: no executable location is specified
def test_get_version_nonetype():
"""Test behaviour when no location for the executable is given."""
test_file_0 = None
assert (
<|code_end|>
, determine the next line of code. You have imports:
from pathlib import Path
from pyani import aniblastall
import unittest
and context (class names, function names, or code) available:
# Path: pyani/aniblastall.py
# class PyaniblastallException(PyaniException):
# def get_version(blast_exe: Path = pyani_config.BLASTALL_DEFAULT) -> str:
. Output only the next line. | aniblastall.get_version(test_file_0) == f"{test_file_0} is not found in $PATH" |
Next line prediction: <|code_start|>"""Provides the createdb subcommand for pyani."""
def subcmd_createdb(args: Namespace) -> int:
"""Create an empty pyani database.
:param args: Namespace, command-line arguments
:param logger: logging object
"""
# Create logger
logger = logging.getLogger(__name__)
# If the database exists, raise an error rather than overwrite
if args.dbpath.is_file():
if not args.force:
logger.error("Database %s already exists (exiting)", args.dbpath)
raise SystemError(1)
logger.warning("Database %s already exists - overwriting", args.dbpath)
args.dbpath.unlink()
# If the path to the database doesn't exist, create it
if not args.dbpath.parent.is_dir():
logger.info("Creating database directory %s", args.dbpath.parent)
args.dbpath.parent.mkdir(parents=True, exist_ok=True)
# Create the empty database
logger.info("Creating pyani database at %s", args.dbpath)
<|code_end|>
. Use current file imports:
(import logging
from argparse import Namespace
from pyani import pyani_orm)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
. Output only the next line. | pyani_orm.create_db(args.dbpath) |
Continue the code snippet: <|code_start|># of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Provides the classify subcommand for pyani."""
class SubgraphData(NamedTuple):
"""Subgraph clique/classification output."""
interval: float # the trimming threshold for this subgraph
graph: nx.Graph # the trimmed subgraph
<|code_end|>
. Use current file imports:
import logging
import networkx as nx # pylint: disable=E0401
import numpy as np
from argparse import Namespace
from typing import Generator, NamedTuple
from tqdm import tqdm
from pyani import pyani_classify, pyani_orm
from pyani.pyani_tools import termcolor
and context (classes, functions, or code) from other files:
# Path: pyani/pyani_classify.py
# class Cliquesinfo(NamedTuple):
# def build_graph_from_results(
# results, label_dict: Dict[int, str], cov_min: float = 0, id_min: float = 0
# ) -> nx.Graph:
# def analyse_cliques(graph: nx.Graph) -> Cliquesinfo:
# def all_components_k_complete(graph: nx.Graph) -> bool:
# def k_complete_component_status(graph: nx.Graph) -> List[bool]:
# def remove_low_weight_edges(
# graph: nx.Graph, threshold: float, attribute: str = "identity"
# ) -> Tuple[nx.Graph, List]:
#
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
#
# Path: pyani/pyani_tools.py
# def termcolor(
# logstr: str, color: Optional[str] = None, bold: Optional[bool] = False
# ) -> str:
# """Return the passed logstr, wrapped in terminal colouring."""
# # For terminal colouring
# termcolors = {
# "BLACK": 0,
# "RED": 1,
# "GREEN": 2,
# "YELLOW": 3,
# "BLUE": 4,
# "MAGENTA": 5,
# "CYAN": 6,
# "WHITE": 7,
# }
# reset = "\033[0m"
#
# # Colour the string
# if isinstance(color, str) and color.upper() in termcolors:
# logstr = f"\033[1;{30 + termcolors[color.upper()]}m{logstr}{reset}"
#
# # Make the string bold
# if bold is True:
# logstr = f"\033[1m{logstr}"
# if not logstr.endswith(reset):
# logstr += reset
#
# return logstr
. Output only the next line. | cliqueinfo: pyani_classify.Cliquesinfo |
Next line prediction: <|code_start|>
class SubgraphData(NamedTuple):
"""Subgraph clique/classification output."""
interval: float # the trimming threshold for this subgraph
graph: nx.Graph # the trimmed subgraph
cliqueinfo: pyani_classify.Cliquesinfo
def subcmd_classify(args: Namespace) -> int:
"""Generate classifications for an analysis.
:param args: Namespace, command-line arguments
"""
logger = logging.getLogger(__name__)
# Tell the user what's going on
logger.info(
termcolor("Generating classification for ANI run: %s", "red"), args.run_id
)
logger.info("\tWriting output to: %s", args.outdir)
logger.info(termcolor("\tCoverage threshold: %s", "cyan"), args.cov_min)
logger.info(
termcolor("\tInitial minimum identity threshold: %s", "cyan"), args.id_min
)
# Get results data for the specified run
logger.info("Acquiring results for run: %s", args.run_id)
logger.debug("Connecting to database: %s", args.dbpath)
<|code_end|>
. Use current file imports:
(import logging
import networkx as nx # pylint: disable=E0401
import numpy as np
from argparse import Namespace
from typing import Generator, NamedTuple
from tqdm import tqdm
from pyani import pyani_classify, pyani_orm
from pyani.pyani_tools import termcolor)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_classify.py
# class Cliquesinfo(NamedTuple):
# def build_graph_from_results(
# results, label_dict: Dict[int, str], cov_min: float = 0, id_min: float = 0
# ) -> nx.Graph:
# def analyse_cliques(graph: nx.Graph) -> Cliquesinfo:
# def all_components_k_complete(graph: nx.Graph) -> bool:
# def k_complete_component_status(graph: nx.Graph) -> List[bool]:
# def remove_low_weight_edges(
# graph: nx.Graph, threshold: float, attribute: str = "identity"
# ) -> Tuple[nx.Graph, List]:
#
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
#
# Path: pyani/pyani_tools.py
# def termcolor(
# logstr: str, color: Optional[str] = None, bold: Optional[bool] = False
# ) -> str:
# """Return the passed logstr, wrapped in terminal colouring."""
# # For terminal colouring
# termcolors = {
# "BLACK": 0,
# "RED": 1,
# "GREEN": 2,
# "YELLOW": 3,
# "BLUE": 4,
# "MAGENTA": 5,
# "CYAN": 6,
# "WHITE": 7,
# }
# reset = "\033[0m"
#
# # Colour the string
# if isinstance(color, str) and color.upper() in termcolors:
# logstr = f"\033[1;{30 + termcolors[color.upper()]}m{logstr}{reset}"
#
# # Make the string bold
# if bold is True:
# logstr = f"\033[1m{logstr}"
# if not logstr.endswith(reset):
# logstr += reset
#
# return logstr
. Output only the next line. | session = pyani_orm.get_session(args.dbpath) |
Continue the code snippet: <|code_start|># AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""Provides the classify subcommand for pyani."""
class SubgraphData(NamedTuple):
"""Subgraph clique/classification output."""
interval: float # the trimming threshold for this subgraph
graph: nx.Graph # the trimmed subgraph
cliqueinfo: pyani_classify.Cliquesinfo
def subcmd_classify(args: Namespace) -> int:
"""Generate classifications for an analysis.
:param args: Namespace, command-line arguments
"""
logger = logging.getLogger(__name__)
# Tell the user what's going on
logger.info(
<|code_end|>
. Use current file imports:
import logging
import networkx as nx # pylint: disable=E0401
import numpy as np
from argparse import Namespace
from typing import Generator, NamedTuple
from tqdm import tqdm
from pyani import pyani_classify, pyani_orm
from pyani.pyani_tools import termcolor
and context (classes, functions, or code) from other files:
# Path: pyani/pyani_classify.py
# class Cliquesinfo(NamedTuple):
# def build_graph_from_results(
# results, label_dict: Dict[int, str], cov_min: float = 0, id_min: float = 0
# ) -> nx.Graph:
# def analyse_cliques(graph: nx.Graph) -> Cliquesinfo:
# def all_components_k_complete(graph: nx.Graph) -> bool:
# def k_complete_component_status(graph: nx.Graph) -> List[bool]:
# def remove_low_weight_edges(
# graph: nx.Graph, threshold: float, attribute: str = "identity"
# ) -> Tuple[nx.Graph, List]:
#
# Path: pyani/pyani_orm.py
# class PyaniORMException(PyaniException):
# class LabelTuple(NamedTuple):
# class Label(Base):
# class BlastDB(Base):
# class Genome(Base):
# class Run(Base):
# class Comparison(Base):
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def __str__(self) -> str:
# def __repr__(self) -> str:
# def create_db(dbpath: Path) -> None:
# def get_session(dbpath: Path) -> Any:
# def get_comparison_dict(session: Any) -> Dict[Tuple, Any]:
# def get_matrix_labels_for_run(session: Any, run_id: int) -> Dict:
# def get_matrix_classes_for_run(session: Any, run_id: int) -> Dict[str, List]:
# def filter_existing_comparisons(
# session,
# run,
# comparisons,
# program,
# version,
# fragsize: Optional[int] = None,
# maxmatch: Optional[bool] = False,
# kmersize: Optional[int] = None,
# minmatch: Optional[float] = None,
# ) -> List:
# def add_run(session, method, cmdline, date, status, name):
# def add_run_genomes(
# session, run, indir: Path, classpath: Path, labelpath: Path, **kwargs
# ) -> List:
# def update_comparison_matrices(session, run) -> None:
#
# Path: pyani/pyani_tools.py
# def termcolor(
# logstr: str, color: Optional[str] = None, bold: Optional[bool] = False
# ) -> str:
# """Return the passed logstr, wrapped in terminal colouring."""
# # For terminal colouring
# termcolors = {
# "BLACK": 0,
# "RED": 1,
# "GREEN": 2,
# "YELLOW": 3,
# "BLUE": 4,
# "MAGENTA": 5,
# "CYAN": 6,
# "WHITE": 7,
# }
# reset = "\033[0m"
#
# # Colour the string
# if isinstance(color, str) and color.upper() in termcolors:
# logstr = f"\033[1;{30 + termcolors[color.upper()]}m{logstr}{reset}"
#
# # Make the string bold
# if bold is True:
# logstr = f"\033[1m{logstr}"
# if not logstr.endswith(reset):
# logstr += reset
#
# return logstr
. Output only the next line. | termcolor("Generating classification for ANI run: %s", "red"), args.run_id |
Predict the next line after this snippet: <|code_start|> jobgraph, workers: Optional[int] = None, logger: Optional[Logger] = None
) -> int:
"""Create and run pools of jobs based on the passed jobgraph.
:param jobgraph: list of jobs, which may have dependencies.
:param workers: int, number of workers to use with multiprocessing
:param logger: a logger module logger (optional)
The strategy here is to loop over each job in the list of jobs (jobgraph),
and create/populate a series of Sets of commands, to be run in
reverse order with multiprocessing_run as asynchronous pools.
"""
cmdsets = [] # type: List
for job in jobgraph:
cmdsets = populate_cmdsets(job, cmdsets, depth=1)
# Put command sets in reverse order, and submit to multiprocessing_run
cmdsets.reverse()
cumretval = 0
for cmdset in cmdsets:
if logger: # Try to be informative, if the logger module is being used
logger.info("Command pool now running:")
for cmd in cmdset:
logger.info(cmd)
cumretval += multiprocessing_run(cmdset, workers)
if logger: # Try to be informative, if the logger module is being used
logger.info("Command pool done.")
return cumretval
<|code_end|>
using the current file's imports:
import multiprocessing
import subprocess
import sys
from logging import Logger
from typing import List, Optional
from .pyani_jobs import Job
and any relevant context from other files:
# Path: pyani/pyani_jobs.py
# class Job(object):
#
# """Individual job to be run, with list of dependencies."""
#
# def __init__(self, name: str, command: str, queue: Optional[str] = None) -> None:
# """Instantiate a Job object.
#
# :param name: String describing the job (uniquely)
# :param command: String, the valid shell command to run the job
# :param queue: String, the SGE queue under which the job shall run
# """
# self.name = name # Unique name for the job
# self.queue = queue # The SGE queue to run the job under
# self.command = command # Command line to run for this job
# self.script = command
# self.scriptPath = None # type: Optional[Any]
# self.dependencies = [] # type: List[Any]
# self.submitted = False # type: bool
# self.finished = False # type: int
#
# def add_dependency(self, job) -> None:
# """Add passed job to the dependency list for this Job.
#
# :param job: Job to be added to the Job's dependency list
#
# This Job should not execute until all dependent jobs are completed.
# """
# self.dependencies.append(job)
#
# def remove_dependency(self, job) -> None:
# """Remove passed job from this Job's dependency list.
#
# :param job: Job to be removed from the Job's dependency list
# """
# self.dependencies.remove(job)
#
# def wait(self, interval: float = SGE_WAIT) -> None:
# """Wait until the job finishes, and poll SGE on its status.
#
# :param interval: float, number of seconds to wait before polling SGE
# """
# while not self.finished:
# time.sleep(interval)
# interval = min(2.0 * interval, 60)
# self.finished = os.system(f"qstat -j {self.name} > /dev/null")
. Output only the next line. | def populate_cmdsets(job: Job, cmdsets: List, depth: int) -> List: |
Here is a snippet: <|code_start|>
@pytest.fixture
def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
nucmer_exe=NUCMER_DEFAULT,
filter_exe=FILTER_DEFAULT,
blastn_exe=BLASTN_DEFAULT,
<|code_end|>
. Write the next line using the current file imports:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
, which may include functions, classes, or code. Output only the next line. | blastall_exe=BLASTALL_DEFAULT, |
Given snippet: <|code_start|>
@pytest.fixture
def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
nucmer_exe=NUCMER_DEFAULT,
filter_exe=FILTER_DEFAULT,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
which might include code, classes, or functions. Output only the next line. | blastn_exe=BLASTN_DEFAULT, |
Predict the next line after this snippet: <|code_start|>
@pytest.fixture
def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
nucmer_exe=NUCMER_DEFAULT,
<|code_end|>
using the current file's imports:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and any relevant context from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | filter_exe=FILTER_DEFAULT, |
Given snippet: <|code_start|>def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
nucmer_exe=NUCMER_DEFAULT,
filter_exe=FILTER_DEFAULT,
blastn_exe=BLASTN_DEFAULT,
blastall_exe=BLASTALL_DEFAULT,
makeblastdb_exe=MAKEBLASTDB_DEFAULT,
<|code_end|>
, continue by predicting the next line. Consider current file imports:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
which might include code, classes, or functions. Output only the next line. | formatdb_exe=FORMATDB_DEFAULT, |
Given the following code snippet before the placeholder: <|code_start|>@pytest.fixture
def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
nucmer_exe=NUCMER_DEFAULT,
filter_exe=FILTER_DEFAULT,
blastn_exe=BLASTN_DEFAULT,
blastall_exe=BLASTALL_DEFAULT,
<|code_end|>
, predict the next line using imports from the current file:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | makeblastdb_exe=MAKEBLASTDB_DEFAULT, |
Given the following code snippet before the placeholder: <|code_start|>
@pytest.fixture
def legacy_ani_namespace(path_fixtures_base, tmp_path):
"""Base namespace for legacy average_nucleotide_identity.py tests."""
return Namespace(
outdirname=tmp_path,
indirname=path_fixtures_base / "legacy" / "ANI_input",
verbose=False,
debug=False,
force=True,
fragsize=1020,
logfile=Path("test_ANIm.log"),
skip_nucmer=False,
skip_blastn=False,
noclobber=False,
nocompress=False,
graphics=True,
gformat="pdf,png",
gmethod="seaborn",
labels=path_fixtures_base / "legacy" / "ANI_input" / "labels.txt",
classes=path_fixtures_base / "legacy" / "ANI_input" / "classes.txt",
method="ANIm",
scheduler="multiprocessing",
workers=None,
sgeargs=None,
sgegroupsize=10000,
maxmatch=False,
<|code_end|>
, predict the next line using imports from the current file:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context including class names, function names, and sometimes code from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | nucmer_exe=NUCMER_DEFAULT, |
Next line prediction: <|code_start|>
@pytest.fixture
def legacy_tetra_sns_namespace(tmp_path, legacy_ani_namespace):
"""Namespace for legacy ANIm script tests.
Uses the base namespace to run ANIm with seaborn output
"""
return modify_namespace(legacy_ani_namespace, method="TETRA")
@pytest.fixture
def legacy_tetra_mpl_namespace(tmp_path, legacy_ani_namespace):
"""Namespace for legacy ANIm script tests.
Uses the base namespace to run ANIm with mpl output
"""
return modify_namespace(legacy_ani_namespace, method="TETRA", gmethod="mpl")
@pytest.mark.skip_if_exe_missing("nucmer")
def test_legacy_anim_sns(legacy_anim_sns_namespace):
r"""Use legacy script to run ANIm (seaborn output).
average_nucleotide_identity.py \
-l test_ANIm.log \
-i tests/fixtures/legacy/ANI_input \
-o tests/test_output/legacy_scripts/ANIm_seaborn \
-g --gmethod seaborn --gformat pdf,png \
-f --jobprefix ANI
"""
<|code_end|>
. Use current file imports:
(from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest)
and context including class names, function names, or small code snippets from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | average_nucleotide_identity.run_main(legacy_anim_sns_namespace) |
Continue the code snippet: <|code_start|> -i tests/test_output/legacy_scripts/C_blochmannia \
-o tests/test_output/legacy_scripts/ANIb_mpl \
-g --gmethod mpl --gformat pdf,png \
-f --jobprefix ANI
"""
average_nucleotide_identity.run_main(legacy_anib_mpl_namespace)
def test_legacy_tetra_sns(legacy_tetra_sns_namespace):
r"""Use legacy script to run TETRA (seaborn output)."""
average_nucleotide_identity.run_main(legacy_tetra_sns_namespace)
def test_legacy_tetra_mpl(legacy_tetra_mpl_namespace):
r"""Use legacy script to run TETRA (mpl output)."""
average_nucleotide_identity.run_main(legacy_tetra_mpl_namespace)
def test_legacy_genome_downloads(
legacy_download_namespace, mock_legacy_single_genome_dl
):
r"""Use legacy script to download genomes; mocks file downloading.
Otherwise emulates a command such as:
genbank_get_genomes_by_taxon.py \
-o tests/fixtures/legacy/ANI_input \
--email emailme@my.email.domain \
-t 203804 -f
"""
<|code_end|>
. Use current file imports:
from argparse import Namespace
from pathlib import Path
from pyani.pyani_config import (
BLASTALL_DEFAULT,
BLASTN_DEFAULT,
FILTER_DEFAULT,
FORMATDB_DEFAULT,
MAKEBLASTDB_DEFAULT,
NUCMER_DEFAULT,
)
from pyani.scripts import average_nucleotide_identity, genbank_get_genomes_by_taxon
from tools import modify_namespace
import pytest
and context (classes, functions, or code) from other files:
# Path: pyani/pyani_config.py
# BLASTALL_DEFAULT = Path("blastall")
#
# BLASTN_DEFAULT = Path("blastn")
#
# FILTER_DEFAULT = Path("delta-filter")
#
# FORMATDB_DEFAULT = Path("formatdb")
#
# MAKEBLASTDB_DEFAULT = Path("makeblastdb")
#
# NUCMER_DEFAULT = Path("nucmer")
#
# Path: pyani/scripts/average_nucleotide_identity.py
# def parse_cmdline(argv: Optional[List] = None) -> Namespace:
# def last_exception() -> str:
# def make_outdirs(args: Namespace):
# def compress_delete_outdir(outdir: Path, logger: Logger) -> None:
# def calculate_anim(
# args: Namespace, infiles: List[Path], org_lengths: Dict
# ) -> pyani_tools.ANIResults:
# def calculate_tetra(infiles: List[Path]) -> pd.DataFrame:
# def make_sequence_fragments(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple[List, Dict]:
# def run_blast(
# args: Namespace, logger: Logger, infiles: List[Path], blastdir: Path
# ) -> Tuple:
# def unified_anib(
# args: Namespace, infiles: List[Path], org_lengths: Dict[str, int]
# ) -> pyani_tools.ANIResults:
# def write(args: Namespace, results: pd.DataFrame) -> None:
# def draw(args: Namespace, filestems: List[str], gformat: str) -> None:
# def subsample_input(args: Namespace, logger: Logger, infiles: List[Path]) -> List[Path]:
# def process_arguments(args: Optional[Namespace]) -> Namespace:
# def test_class_label_paths(args: Namespace, logger: Logger) -> None:
# def get_method(args: Namespace) -> Tuple:
# def test_scheduler(args: Namespace, logger: Logger) -> None:
# def run_main(argsin: Optional[Namespace] = None) -> int:
#
# Path: pyani/scripts/genbank_get_genomes_by_taxon.py
# class NCBIDownloadException(Exception):
# def __init__(self):
# def parse_cmdline(argv=None):
# def last_exception():
# def set_ncbi_email(args: Namespace) -> None:
# def make_outdir(args: Namespace) -> None:
# def entrez_retry(args, func, *fnargs, **fnkwargs):
# def entrez_batch_webhistory(args, record, expected, batchsize, *fnargs, **fnkwargs):
# def get_asm_uids(args, taxon_uid):
# def extract_filestem(data):
# def get_ncbi_asm(args, asm_uid, fmt="fasta"):
# def retrieve_asm_contigs(
# args,
# filestem,
# ftpstem="ftp://ftp.ncbi.nlm.nih.gov/genomes/all",
# fmt="fasta",
# ):
# def extract_archive(archivepath):
# def write_contigs(args, asm_uid, contig_uids, batchsize=10000):
# def logreport_downloaded(accn, skiplist, accndict, uidaccndict):
# def run_main(args=None):
. Output only the next line. | genbank_get_genomes_by_taxon.run_main(legacy_download_namespace) |
Given the code snippet: <|code_start|>
def test_text_word2vec2npy():
# check whether files are present in folder
vectors_name = 'wiki.fiu_vro.vec'
path = os.path.dirname(inspect.getfile(inspect.currentframe()))
if not os.path.exists(path + '/' + vectors_name):
call(["wget https://dl.fbaipublicfiles.com/fasttext/vectors-wiki/" + vectors_name + " -O " + path + "/" + vectors_name],
shell=True)
<|code_end|>
, generate the next line using the imports in this file:
import inspect
import os
import pytest
import numpy as np
from subprocess import call
from utils.preprocess_text_word_vectors import txtvec2npy
and context (functions, classes, or occasionally code) from other files:
# Path: utils/preprocess_text_word_vectors.py
# def txtvec2npy(v_path, base_path_save, dest_filename):
# """
# Preprocess pretrained text vectors and stores them in a suitable format
# :param v_path: Path to the text vectors file.
# :param base_path_save: Path where the formatted vectors will be stored.
# :param dest_filename: Filename of the formatted vectors.
# """
# word_vecs = dict()
# print ("Loading vectors from %s" % v_path)
# vectors = [x[:-1] for x in open(v_path).readlines()]
# if len(vectors[0].split()) == 2:
# signature = vectors.pop(0).split()
# dimension = int(signature[1])
# n_vecs = len(vectors)
# assert int(signature[0]) == n_vecs, 'The number of read vectors does not match with the expected one (read %d, expected %d)' % (n_vecs, int(signature[0]))
# else:
# n_vecs = len(vectors)
# dimension = len(vectors[0].split()) - 1
#
# print ("Found %d vectors of dimension %d in %s" % (n_vecs, dimension, v_path))
# i = 0
# for vector in vectors:
# v = vector.split()
# vec = np.asarray(v[-dimension:], dtype='float32')
# word = ' '.join(v[0: len(v) - dimension])
# word_vecs[word] = vec
# i += 1
# if i % 1000 == 0:
# print ("Processed %d vectors (%.2f %%)\r" % (i, 100 * float(i) / n_vecs),)
#
# print ("")
# # Store dict
# print ("Saving word vectors in %s" % (base_path_save + dest_filename + '.npy'))
# np.save(base_path_save + dest_filename + '.npy', word_vecs)
# print ("")
. Output only the next line. | txtvec2npy(path + '/' + vectors_name, './', vectors_name[:-4]) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
def test_observer():
def foo_listener(data, key=None):
assert data == 'foo'
assert key == 'foo'
@asyncio.coroutine
def bar_listener(data, key=None):
assert data == 'bar'
assert key == 'bar'
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
from paco.observer import Observer
from .helpers import run_in_loop
and context (functions, classes, or occasionally code) from other files:
# Path: paco/observer.py
# class Observer(object):
# """
# Observer implements a simple observer pub/sub pattern with a minimal
# interface and built-in coroutines support for asynchronous-first approach,
# desiged as abstract class to be inherited or embed by observable classes.
# """
#
# def __init__(self):
# self._pool = {}
#
# def observe(self, event, fn):
# """
# Arguments:
# event (str): event to subscribe.
# fn (function|coroutinefunction): function to trigger.
#
# Raises:
# TypeError: if fn argument is not valid
# """
# iscoroutine = asyncio.iscoroutinefunction(fn)
# if not iscoroutine and not isfunction(fn):
# raise TypeError('paco: fn param must be a callable '
# 'object or coroutine function')
#
# observers = self._pool.get(event)
# if not observers:
# observers = self._pool[event] = []
#
# # Register the observer
# observers.append(fn if iscoroutine else coroutine_wrapper(fn))
#
# def remove(self, event=None):
# """
# Remove all the registered observers for the given event name.
#
# Arguments:
# event (str): event name to remove.
# """
# observers = self._pool.get(event)
# if observers:
# self._pool[event] = []
#
# def clear(self):
# """
# Clear all the registered observers.
# """
# self._pool = {}
#
# # Shortcut methods
# on = observe
# off = remove
#
# @asyncio.coroutine
# def trigger(self, event, *args, **kw):
# """
# Triggers event observers for the given event name,
# passing custom variadic arguments.
# """
# observers = self._pool.get(event)
#
# # If no observers registered for the event, do no-op
# if not observers or len(observers) == 0:
# return None
#
# # Trigger observers coroutines in FIFO sequentially
# for fn in observers:
# # Review: perhaps this should not wait
# yield from fn(*args, **kw)
#
# 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. | observer = Observer() |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def test_observer():
def foo_listener(data, key=None):
assert data == 'foo'
assert key == 'foo'
@asyncio.coroutine
def bar_listener(data, key=None):
assert data == 'bar'
assert key == 'bar'
observer = Observer()
observer.observe('foo', foo_listener)
observer.observe('bar', bar_listener)
assert len(observer._pool) == 2
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
from paco.observer import Observer
from .helpers import run_in_loop
and context:
# Path: paco/observer.py
# class Observer(object):
# """
# Observer implements a simple observer pub/sub pattern with a minimal
# interface and built-in coroutines support for asynchronous-first approach,
# desiged as abstract class to be inherited or embed by observable classes.
# """
#
# def __init__(self):
# self._pool = {}
#
# def observe(self, event, fn):
# """
# Arguments:
# event (str): event to subscribe.
# fn (function|coroutinefunction): function to trigger.
#
# Raises:
# TypeError: if fn argument is not valid
# """
# iscoroutine = asyncio.iscoroutinefunction(fn)
# if not iscoroutine and not isfunction(fn):
# raise TypeError('paco: fn param must be a callable '
# 'object or coroutine function')
#
# observers = self._pool.get(event)
# if not observers:
# observers = self._pool[event] = []
#
# # Register the observer
# observers.append(fn if iscoroutine else coroutine_wrapper(fn))
#
# def remove(self, event=None):
# """
# Remove all the registered observers for the given event name.
#
# Arguments:
# event (str): event name to remove.
# """
# observers = self._pool.get(event)
# if observers:
# self._pool[event] = []
#
# def clear(self):
# """
# Clear all the registered observers.
# """
# self._pool = {}
#
# # Shortcut methods
# on = observe
# off = remove
#
# @asyncio.coroutine
# def trigger(self, event, *args, **kw):
# """
# Triggers event observers for the given event name,
# passing custom variadic arguments.
# """
# observers = self._pool.get(event)
#
# # If no observers registered for the event, do no-op
# if not observers or len(observers) == 0:
# return None
#
# # Trigger observers coroutines in FIFO sequentially
# for fn in observers:
# # Review: perhaps this should not wait
# yield from fn(*args, **kw)
#
# 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. | run_in_loop(observer.trigger, 'foo', 'foo', key='foo') |
Given the code snippet: <|code_start|> *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):
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
from .reduce import reduce
and context (functions, classes, or occasionally code) from other files:
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
. Output only the next line. | return (yield from reduce(reducer, coros, |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(*args, **kw):
return args, kw
def test_apply():
<|code_end|>
. Use current file imports:
(import asyncio
from paco import apply
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets from other files:
# Path: paco/apply.py
# @decorate
# def apply(coro, *args, **kw):
# """
# Creates a continuation coroutine function with some arguments
# already applied.
#
# Useful as a shorthand when combined with other control flow functions.
# Any arguments passed to the returned function are added to the arguments
# originally passed to apply.
#
# 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?
#
# """
# assert_corofunction(coro=coro)
#
# @asyncio.coroutine
# def wrapper(*_args, **_kw):
# # Explicitely ignore wrapper arguments
# return (yield from coro(*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 = apply(coro, 1, 2, foo='bar') |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(*args, **kw):
return args, kw
def test_apply():
task = apply(coro, 1, 2, foo='bar')
<|code_end|>
. Use current file imports:
import asyncio
from paco import apply
from .helpers import run_in_loop
and context (classes, functions, or code) from other files:
# Path: paco/apply.py
# @decorate
# def apply(coro, *args, **kw):
# """
# Creates a continuation coroutine function with some arguments
# already applied.
#
# Useful as a shorthand when combined with other control flow functions.
# Any arguments passed to the returned function are added to the arguments
# originally passed to apply.
#
# 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?
#
# """
# assert_corofunction(coro=coro)
#
# @asyncio.coroutine
# def wrapper(*_args, **_kw):
# # Explicitely ignore wrapper arguments
# return (yield from coro(*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. | args, kw = run_in_loop(task) |
Predict the next line after this snippet: <|code_start|> *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
<|code_end|>
using the current file's imports:
import asyncio
from .filter import assert_true
from .assertions import assert_corofunction
and any relevant context from other files:
# Path: paco/filter.py
# @asyncio.coroutine
# def assert_true(element):
# """
# Asserts that a given coroutine yields a true-like value.
#
# Arguments:
# element (mixed): element to evaluate.
#
# Returns:
# bool
# """
# return element
#
# 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_coro = assert_coro or assert_true |
Given the following code snippet before the placeholder: <|code_start|>
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]
"""
<|code_end|>
, predict the next line using imports from the current file:
import asyncio
from .filter import assert_true
from .assertions import assert_corofunction
and context including class names, function names, and sometimes code from other files:
# Path: paco/filter.py
# @asyncio.coroutine
# def assert_true(element):
# """
# Asserts that a given coroutine yields a true-like value.
#
# Arguments:
# element (mixed): element to evaluate.
#
# Returns:
# bool
# """
# return element
#
# 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, coro_test=coro_test) |
Predict the next line after this snippet: <|code_start|> # Get current function call accumulated arity
current_arity = len(args)
# Count keyword params as arity to satisfy, if required
if not ignore_kwargs:
current_arity += len(kw)
# Decrease function arity to satisfy
arity -= current_arity
# Use user-defined custom arity evaluator strategy, if present
currify = evaluator and evaluator(acc, fn)
# If arity is not satisfied, return recursive partial function
if currify is not False and arity > 0:
return functools.partial(currier, arity, (_args, _kw), fn)
# If arity is satisfied, instanciate coroutine and return it
return fn(*_args, **_kw)
def wrapper(fn, *args, **kw):
if not iscallable(fn):
raise TypeError('paco: first argument must a coroutine function, '
'a function or a method.')
# Infer function arity, if required
arity = (arity_or_fn if isinstance(arity_or_fn, int)
else infer_arity(fn))
# Wraps function as coroutine function, if needed.
<|code_end|>
using the current file's imports:
import inspect
import functools
from .wraps import wraps
from .assertions import isfunc, iscallable
and any relevant context from other files:
# Path: paco/wraps.py
# def wraps(fn):
# """
# Wraps a given function as coroutine function.
#
# This function can be used as decorator.
#
# Arguments:
# fn (function): function object to wrap.
#
# Returns:
# coroutinefunction: wrapped function as coroutine.
#
# Usage::
#
# def mul_2(num):
# return num * 2
#
# # Use as function wrapper
# coro = paco.wraps(mul_2)
# await coro(2)
# # => 4
#
# # Use as decorator
# @paco.wraps
# def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# return asyncio.coroutine(fn)
#
# Path: paco/assertions.py
# 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)
# ])
#
# 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)
# ])
. Output only the next line. | fn = wraps(fn) if isfunc(fn) else fn |
Using the snippet: <|code_start|> # Get current function call accumulated arity
current_arity = len(args)
# Count keyword params as arity to satisfy, if required
if not ignore_kwargs:
current_arity += len(kw)
# Decrease function arity to satisfy
arity -= current_arity
# Use user-defined custom arity evaluator strategy, if present
currify = evaluator and evaluator(acc, fn)
# If arity is not satisfied, return recursive partial function
if currify is not False and arity > 0:
return functools.partial(currier, arity, (_args, _kw), fn)
# If arity is satisfied, instanciate coroutine and return it
return fn(*_args, **_kw)
def wrapper(fn, *args, **kw):
if not iscallable(fn):
raise TypeError('paco: first argument must a coroutine function, '
'a function or a method.')
# Infer function arity, if required
arity = (arity_or_fn if isinstance(arity_or_fn, int)
else infer_arity(fn))
# Wraps function as coroutine function, if needed.
<|code_end|>
, determine the next line of code. You have imports:
import inspect
import functools
from .wraps import wraps
from .assertions import isfunc, iscallable
and context (class names, function names, or code) available:
# Path: paco/wraps.py
# def wraps(fn):
# """
# Wraps a given function as coroutine function.
#
# This function can be used as decorator.
#
# Arguments:
# fn (function): function object to wrap.
#
# Returns:
# coroutinefunction: wrapped function as coroutine.
#
# Usage::
#
# def mul_2(num):
# return num * 2
#
# # Use as function wrapper
# coro = paco.wraps(mul_2)
# await coro(2)
# # => 4
#
# # Use as decorator
# @paco.wraps
# def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# return asyncio.coroutine(fn)
#
# Path: paco/assertions.py
# 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)
# ])
#
# 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)
# ])
. Output only the next line. | fn = wraps(fn) if isfunc(fn) else fn |
Continue the code snippet: <|code_start|> """
Function either continues curring of the arguments
or executes function if desired arguments have being collected.
If function curried is variadic then execution without arguments
will finish curring and trigger the function
"""
# Merge call arguments with accumulated ones
_args, _kw = merge_args(acc, args, kw)
# Get current function call accumulated arity
current_arity = len(args)
# Count keyword params as arity to satisfy, if required
if not ignore_kwargs:
current_arity += len(kw)
# Decrease function arity to satisfy
arity -= current_arity
# Use user-defined custom arity evaluator strategy, if present
currify = evaluator and evaluator(acc, fn)
# If arity is not satisfied, return recursive partial function
if currify is not False and arity > 0:
return functools.partial(currier, arity, (_args, _kw), fn)
# If arity is satisfied, instanciate coroutine and return it
return fn(*_args, **_kw)
def wrapper(fn, *args, **kw):
<|code_end|>
. Use current file imports:
import inspect
import functools
from .wraps import wraps
from .assertions import isfunc, iscallable
and context (classes, functions, or code) from other files:
# Path: paco/wraps.py
# def wraps(fn):
# """
# Wraps a given function as coroutine function.
#
# This function can be used as decorator.
#
# Arguments:
# fn (function): function object to wrap.
#
# Returns:
# coroutinefunction: wrapped function as coroutine.
#
# Usage::
#
# def mul_2(num):
# return num * 2
#
# # Use as function wrapper
# coro = paco.wraps(mul_2)
# await coro(2)
# # => 4
#
# # Use as decorator
# @paco.wraps
# def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# return asyncio.coroutine(fn)
#
# Path: paco/assertions.py
# 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)
# ])
#
# 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)
# ])
. Output only the next line. | if not iscallable(fn): |
Continue the code snippet: <|code_start|> 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.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# => [2, 4, 6, 8, 10]
# Pipeline style
await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# => [2, 4, 6, 8, 10]
"""
assert_corofunction(coro=coro)
assert_iter(iterable=iterable)
# By default do not collect yielded values from coroutines
<|code_end|>
. Use current file imports:
import asyncio
from .assertions import isiter
from .reduce import reduce
from .decorator import overload
from .assertions import assert_corofunction, assert_iter
and context (classes, functions, or code) from other files:
# 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))
#
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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):
#
# 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))
. Output only the next line. | results = initializer if isiter(initializer) else [] |
Predict the next line after this snippet: <|code_start|> TypeError: in case of invalid input arguments.
Usage::
async def mul_2(num):
return num * 2
await paco.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# => [2, 4, 6, 8, 10]
# Pipeline style
await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# => [2, 4, 6, 8, 10]
"""
assert_corofunction(coro=coro)
assert_iter(iterable=iterable)
# By default do not collect yielded values from coroutines
results = initializer if isiter(initializer) else []
@asyncio.coroutine
def reducer(buf, value):
if isiter(value):
yield from _reduce(value)
else:
buf.append((yield from coro(value)))
return buf
def _reduce(iterable):
<|code_end|>
using the current file's imports:
import asyncio
from .assertions import isiter
from .reduce import reduce
from .decorator import overload
from .assertions import assert_corofunction, assert_iter
and any relevant context from other files:
# 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))
#
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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):
#
# 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))
. Output only the next line. | return reduce(reducer, iterable, |
Next line prediction: <|code_start|> 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.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# => [2, 4, 6, 8, 10]
# Pipeline style
await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# => [2, 4, 6, 8, 10]
"""
<|code_end|>
. Use current file imports:
(import asyncio
from .assertions import isiter
from .reduce import reduce
from .decorator import overload
from .assertions import assert_corofunction, assert_iter)
and context including class names, function names, or small code snippets from other files:
# 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))
#
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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):
#
# 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))
. Output only the next line. | assert_corofunction(coro=coro) |
Here is a snippet: <|code_start|> 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.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# => [2, 4, 6, 8, 10]
# Pipeline style
await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# => [2, 4, 6, 8, 10]
"""
assert_corofunction(coro=coro)
<|code_end|>
. Write the next line using the current file imports:
import asyncio
from .assertions import isiter
from .reduce import reduce
from .decorator import overload
from .assertions import assert_corofunction, assert_iter
and context from other files:
# 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))
#
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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):
#
# 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))
, which may include functions, classes, or code. Output only the next line. | assert_iter(iterable=iterable) |
Predict the next line after this snippet: <|code_start|> 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 argument to pass to coroutine
function, if provided.
Raises:
TypeError: if ``iterable`` argument is not iterable.
asyncio.TimoutError: if wait timeout is exceeded.
Returns:
filtered values (list): ordered list of resultant values.
Usage::
async def coro1():
await asyncio.sleep(2)
return 1
async def coro2():
return 2
async def coro3():
await asyncio.sleep(1)
return 3
await paco.race([coro1, coro2, coro3])
# => 2
"""
<|code_end|>
using the current file's imports:
import asyncio
from .assertions import assert_iter
from asyncio import ensure_future
and any relevant context from other files:
# Path: paco/assertions.py
# 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))
. Output only the next line. | assert_iter(iterable=iterable) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
def test_constant():
task = constant(1)
assert run_in_loop(task) == 1
task = constant('foo')
assert run_in_loop(task) == 'foo'
task = constant({'foo': 'bar'})
assert run_in_loop(task) == {'foo': 'bar'}
task = constant((1, 2, 3))
assert run_in_loop(task) == (1, 2, 3)
task = constant(None)
assert run_in_loop(task) is None
def test_identify():
<|code_end|>
. Write the next line using the current file imports:
import time
from paco import constant, identity
from .helpers import run_in_loop
and context from other files:
# Path: paco/constant.py
# def constant(value, delay=None):
# """
# Returns a coroutine function that when called, always returns
# the provided value.
#
# This function has an alias: `paco.identity`.
#
# Arguments:
# value (mixed): value to constantly return when coroutine is called.
# delay (int/float): optional return value delay in seconds.
#
# Returns:
# coroutinefunction
#
# Usage::
#
# coro = paco.constant('foo')
#
# await coro()
# # => 'foo'
# await coro()
# # => 'foo'
#
# """
# @asyncio.coroutine
# def coro():
# if delay:
# yield from asyncio.sleep(delay)
# return value
#
# return coro
#
# def identity(value, delay=None):
# """
# Returns a coroutine function that when called, always returns
# the provided value.
#
# This function is an alias to `paco.constant`.
#
# Arguments:
# value (mixed): value to constantly return when coroutine is called.
# delay (int/float): optional return value delay in seconds.
#
# Returns:
# coroutinefunction
#
# Usage::
#
# coro = paco.identity('foo')
#
# await coro()
# # => 'foo'
# await coro()
# # => 'foo'
#
# """
# return constant(value, delay=delay)
#
# 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 = identity(1) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num * 2
def test_map():
<|code_end|>
, predict the next line using imports from the current file:
import time
import pytest
import asyncio
from paco import map
from .helpers import run_in_loop
and context including class names, function names, and sometimes code from other files:
# 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))
#
# 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 = map(coro, [1, 2, 3, 4, 5]) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num * 2
def test_map():
task = map(coro, [1, 2, 3, 4, 5])
<|code_end|>
. Use current file imports:
(import time
import pytest
import asyncio
from paco import map
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets from other files:
# 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))
#
# 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, 8, 10] |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(*args, **kw):
return args, kw
def test_partial():
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
from paco import partial
from .helpers import run_in_loop
and context (classes, functions, sometimes code) from other files:
# 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 = partial(coro, 1, 2, foo='bar') |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(*args, **kw):
return args, kw
def test_partial():
task = partial(coro, 1, 2, foo='bar')
<|code_end|>
using the current file's imports:
import asyncio
from paco import partial
from .helpers import run_in_loop
and any relevant context from other files:
# 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. | args, kw = run_in_loop(task, 3, 4, bar='baz') |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
yield from asyncio.sleep(0.1)
return num * 2
def test_series():
init = time.time()
<|code_end|>
using the current file's imports:
import time
import asyncio
from paco import series
from .helpers import run_in_loop
and any relevant context from other files:
# Path: paco/series.py
# @asyncio.coroutine
# def series(*coros_or_futures, timeout=None,
# loop=None, return_exceptions=False):
# """
# Run the given coroutine functions in series, each one
# running once the previous execution has completed.
#
# If any coroutines raises an exception, no more
# coroutines are executed. Otherwise, the coroutines returned values
# will be returned as `list`.
#
# ``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.
#
# 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 basically the sequential execution version of
# ``asyncio.gather()``. Interface compatible with ``asyncio.gather()``.
#
# This function is a coroutine.
#
# Arguments:
# *coros_or_futures (iter|list):
# an iterable collection yielding coroutines functions.
# 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]
#
# """
# return (yield from gather(*coros_or_futures,
# loop=loop, limit=1, timeout=timeout,
# return_exceptions=return_exceptions))
#
# 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 = series(coro(1), coro(2), coro(3)) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
yield from asyncio.sleep(0.1)
return num * 2
def test_series():
init = time.time()
task = series(coro(1), coro(2), coro(3))
<|code_end|>
, predict the next line using imports from the current file:
import time
import asyncio
from paco import series
from .helpers import run_in_loop
and context including class names, function names, and sometimes code from other files:
# Path: paco/series.py
# @asyncio.coroutine
# def series(*coros_or_futures, timeout=None,
# loop=None, return_exceptions=False):
# """
# Run the given coroutine functions in series, each one
# running once the previous execution has completed.
#
# If any coroutines raises an exception, no more
# coroutines are executed. Otherwise, the coroutines returned values
# will be returned as `list`.
#
# ``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.
#
# 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 basically the sequential execution version of
# ``asyncio.gather()``. Interface compatible with ``asyncio.gather()``.
#
# This function is a coroutine.
#
# Arguments:
# *coros_or_futures (iter|list):
# an iterable collection yielding coroutines functions.
# 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]
#
# """
# return (yield from gather(*coros_or_futures,
# loop=loop, limit=1, timeout=timeout,
# return_exceptions=return_exceptions))
#
# 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 for this snippet: <|code_start|>
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]
"""
<|code_end|>
with the help of current file imports:
import asyncio
from .filter import filter
from .decorator import overload
and context 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):
, which may contain function names, class names, or code. Output only the next line. | return (yield from filter(coro, iterable, |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def assert_false(element):
"""
Asserts that a given coroutine yields a non-true value.
"""
return not element
<|code_end|>
using the current file's imports:
import asyncio
from .filter import filter
from .decorator import overload
and any relevant context 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. | @overload |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
yield from asyncio.sleep(0.1)
return num * 2
def test_wait(limit=0):
<|code_end|>
, determine the next line of code. You have imports:
import time
import pytest
import asyncio
from paco import wait
from .helpers import run_in_loop
and context (class names, function names, or code) available:
# Path: paco/wait.py
# @asyncio.coroutine
# def wait(*coros_or_futures, limit=0, timeout=None, loop=None,
# return_exceptions=False, return_when='ALL_COMPLETED'):
# """
# Wait for the Futures and coroutine objects given by the sequence
# futures to complete, with optional concurrency limit.
# Coroutines will be wrapped in Tasks.
#
# ``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.
#
# 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.
#
# ``return_when`` indicates when this function should return.
# It must be one of the following constants of the concurrent.futures module.
#
# All futures must share the same event loop.
#
# This functions is mostly compatible with Python standard
# ``asyncio.wait()``.
#
# Arguments:
# *coros_or_futures (iter|list):
# an iterable collection yielding coroutines functions.
# limit (int):
# optional concurrency execution limit. Use ``0`` for no limit.
# 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.
# return_when (str):
# indicates when this function should return.
# loop (asyncio.BaseEventLoop):
# optional event loop to use.
# *args (mixed):
# optional variadic argument to pass to the coroutines function.
#
# Returns:
# tuple: Returns two sets of Future: (done, pending).
#
# 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
#
# done, pending = await paco.wait(
# sum(1, 2),
# sum(3, 4))
# [task.result() for task in done]
# # => [3, 7]
# """
# # 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]
#
# # If no coroutines to schedule, return empty list
# # Mimics asyncio behaviour.
# if len(coros_or_futures) == 0:
# raise ValueError('paco: set of coroutines/futures is empty')
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop,
# coros=coros_or_futures)
#
# # Wait until all the tasks finishes
# return (yield from pool.run(timeout=timeout,
# return_when=return_when,
# return_exceptions=return_exceptions))
#
# 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. | done, pending = run_in_loop(wait([coro(1), coro(2), coro(3)], limit=limit)) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
yield from asyncio.sleep(0.1)
return num * 2
def test_wait(limit=0):
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import pytest
import asyncio
from paco import wait
from .helpers import run_in_loop
and context (classes, functions, sometimes code) from other files:
# Path: paco/wait.py
# @asyncio.coroutine
# def wait(*coros_or_futures, limit=0, timeout=None, loop=None,
# return_exceptions=False, return_when='ALL_COMPLETED'):
# """
# Wait for the Futures and coroutine objects given by the sequence
# futures to complete, with optional concurrency limit.
# Coroutines will be wrapped in Tasks.
#
# ``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.
#
# 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.
#
# ``return_when`` indicates when this function should return.
# It must be one of the following constants of the concurrent.futures module.
#
# All futures must share the same event loop.
#
# This functions is mostly compatible with Python standard
# ``asyncio.wait()``.
#
# Arguments:
# *coros_or_futures (iter|list):
# an iterable collection yielding coroutines functions.
# limit (int):
# optional concurrency execution limit. Use ``0`` for no limit.
# 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.
# return_when (str):
# indicates when this function should return.
# loop (asyncio.BaseEventLoop):
# optional event loop to use.
# *args (mixed):
# optional variadic argument to pass to the coroutines function.
#
# Returns:
# tuple: Returns two sets of Future: (done, pending).
#
# 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
#
# done, pending = await paco.wait(
# sum(1, 2),
# sum(3, 4))
# [task.result() for task in done]
# # => [3, 7]
# """
# # 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]
#
# # If no coroutines to schedule, return empty list
# # Mimics asyncio behaviour.
# if len(coros_or_futures) == 0:
# raise ValueError('paco: set of coroutines/futures is empty')
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop,
# coros=coros_or_futures)
#
# # Wait until all the tasks finishes
# return (yield from pool.run(timeout=timeout,
# return_when=return_when,
# return_exceptions=return_exceptions))
#
# 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. | done, pending = run_in_loop(wait([coro(1), coro(2), coro(3)], limit=limit)) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
def coro(delay=1):
@asyncio.coroutine
def wrapper():
yield from asyncio.sleep(delay)
return delay
return wrapper
def test_race():
faster = run_in_loop(
<|code_end|>
with the help of current file imports:
import pytest
import asyncio
from paco import race
from .helpers import run_in_loop
and context from other files:
# Path: paco/race.py
# @asyncio.coroutine
# def race(iterable, loop=None, timeout=None, *args, **kw):
# """
# Runs coroutines from a given iterable concurrently without waiting until
# the previous one has completed.
#
# Once any of the tasks completes, the main coroutine
# is immediately resolved, yielding the first resolved value.
#
# All coroutines will be executed in the same loop.
#
# This function is a coroutine.
#
# Arguments:
# iterable (iterable): an iterable collection yielding
# coroutines functions or coroutine objects.
# *args (mixed): mixed variadic arguments to pass to coroutines.
# 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.
# *args (mixed): optional variadic argument to pass to coroutine
# function, if provided.
#
# Raises:
# TypeError: if ``iterable`` argument is not iterable.
# asyncio.TimoutError: if wait timeout is exceeded.
#
# Returns:
# filtered values (list): ordered list of resultant values.
#
# Usage::
#
# async def coro1():
# await asyncio.sleep(2)
# return 1
#
# async def coro2():
# return 2
#
# async def coro3():
# await asyncio.sleep(1)
# return 3
#
# await paco.race([coro1, coro2, coro3])
# # => 2
#
# """
# assert_iter(iterable=iterable)
#
# # Store coros and internal state
# coros = []
# resolved = False
# result = None
#
# # Resolve first yielded data from coroutine and stop pending ones
# @asyncio.coroutine
# def resolver(index, coro):
# nonlocal result
# nonlocal resolved
#
# value = yield from coro
# if not resolved:
# resolved = True
#
# # Flag as not test passed
# result = value
#
# # Force canceling pending coroutines
# for _index, future in enumerate(coros):
# if _index != index:
# future.cancel()
#
# # Iterate and attach coroutine for defer scheduling
# for index, coro in enumerate(iterable):
# # Validate yielded object
# isfunction = asyncio.iscoroutinefunction(coro)
# if not isfunction and not asyncio.iscoroutine(coro):
# raise TypeError(
# 'paco: coro must be a coroutine or coroutine function')
#
# # Init coroutine function, if required
# if isfunction:
# coro = coro(*args, **kw)
#
# # Store future tasks
# coros.append(ensure_future(resolver(index, coro)))
#
# # Run coroutines concurrently
# yield from asyncio.wait(coros, timeout=timeout, loop=loop)
#
# return result
#
# 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. | race((coro(0.8), coro(0.5), coro(1), coro(3), coro(0.2))) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
def coro(delay=1):
@asyncio.coroutine
def wrapper():
yield from asyncio.sleep(delay)
return delay
return wrapper
def test_race():
<|code_end|>
. Write the next line using the current file imports:
import pytest
import asyncio
from paco import race
from .helpers import run_in_loop
and context from other files:
# Path: paco/race.py
# @asyncio.coroutine
# def race(iterable, loop=None, timeout=None, *args, **kw):
# """
# Runs coroutines from a given iterable concurrently without waiting until
# the previous one has completed.
#
# Once any of the tasks completes, the main coroutine
# is immediately resolved, yielding the first resolved value.
#
# All coroutines will be executed in the same loop.
#
# This function is a coroutine.
#
# Arguments:
# iterable (iterable): an iterable collection yielding
# coroutines functions or coroutine objects.
# *args (mixed): mixed variadic arguments to pass to coroutines.
# 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.
# *args (mixed): optional variadic argument to pass to coroutine
# function, if provided.
#
# Raises:
# TypeError: if ``iterable`` argument is not iterable.
# asyncio.TimoutError: if wait timeout is exceeded.
#
# Returns:
# filtered values (list): ordered list of resultant values.
#
# Usage::
#
# async def coro1():
# await asyncio.sleep(2)
# return 1
#
# async def coro2():
# return 2
#
# async def coro3():
# await asyncio.sleep(1)
# return 3
#
# await paco.race([coro1, coro2, coro3])
# # => 2
#
# """
# assert_iter(iterable=iterable)
#
# # Store coros and internal state
# coros = []
# resolved = False
# result = None
#
# # Resolve first yielded data from coroutine and stop pending ones
# @asyncio.coroutine
# def resolver(index, coro):
# nonlocal result
# nonlocal resolved
#
# value = yield from coro
# if not resolved:
# resolved = True
#
# # Flag as not test passed
# result = value
#
# # Force canceling pending coroutines
# for _index, future in enumerate(coros):
# if _index != index:
# future.cancel()
#
# # Iterate and attach coroutine for defer scheduling
# for index, coro in enumerate(iterable):
# # Validate yielded object
# isfunction = asyncio.iscoroutinefunction(coro)
# if not isfunction and not asyncio.iscoroutine(coro):
# raise TypeError(
# 'paco: coro must be a coroutine or coroutine function')
#
# # Init coroutine function, if required
# if isfunction:
# coro = coro(*args, **kw)
#
# # Store future tasks
# coros.append(ensure_future(resolver(index, coro)))
#
# # Run coroutines concurrently
# yield from asyncio.wait(coros, timeout=timeout, loop=loop)
#
# return result
#
# 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. | faster = run_in_loop( |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num
def test_throttle():
<|code_end|>
. Use current file imports:
import time
import pytest
import asyncio
from paco import throttle
from .helpers import run_in_loop
and context (classes, functions, or code) from other files:
# Path: paco/throttle.py
# @decorate
# def throttle(coro, limit=1, timeframe=1,
# return_value=None, raise_exception=False):
# """
# Creates a throttled coroutine function that only invokes
# ``coro`` at most once per every time frame of seconds or milliseconds.
#
# Provide options to indicate whether func should be invoked on the
# leading and/or trailing edge of the wait timeout.
#
# Subsequent calls to the throttled coroutine
# return the result of the last coroutine invocation.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction):
# coroutine function to wrap with throttle strategy.
# limit (int):
# number of coroutine allowed execution in the given time frame.
# timeframe (int|float):
# throttle limit time frame in seconds.
# return_value (mixed):
# optional return if the throttle limit is reached.
# Returns the latest returned value by default.
# raise_exception (bool):
# raise exception if throttle limit is reached.
#
# Raises:
# RuntimeError: if cannot throttle limit reached (optional).
#
# Returns:
# coroutinefunction
#
# Usage::
#
# async def mul_2(num):
# return num * 2
#
# # Use as simple wrapper
# throttled = paco.throttle(mul_2, limit=1, timeframe=2)
# await throttled(2)
# # => 4
# await throttled(3) # ignored!
# # => 4
# await asyncio.sleep(2)
# await throttled(3) # executed!
# # => 6
#
# # Use as decorator
# @paco.throttle(limit=1, timeframe=2)
# async def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
# await mul_2(3) # ignored!
# # => 4
# await asyncio.sleep(2)
# await mul_2(3) # executed!
# # => 6
#
# """
# assert_corofunction(coro=coro)
#
# # Store execution limits
# limit = max(int(limit), 1)
# remaning = limit
#
# # Turn seconds in milliseconds
# timeframe = timeframe * 1000
#
# # Keep call state
# last_call = now()
# # Cache latest retuned result
# result = None
#
# def stop():
# if raise_exception:
# raise RuntimeError('paco: coroutine throttle limit exceeded')
# if return_value:
# return return_value
# return result
#
# def elapsed():
# return now() - last_call
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# nonlocal result
# nonlocal remaning
# nonlocal last_call
#
# if elapsed() > timeframe:
# # Reset reamining calls counter
# remaning = limit
# # Update last call time
# last_call = now()
# elif elapsed() < timeframe and remaning <= 0:
# return stop()
#
# # Decrease remaining limit
# remaning -= 1
#
# # Schedule coroutine passing arguments and cache 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 = throttle(coro, limit=2, timeframe=0.2) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num
def test_throttle():
task = throttle(coro, limit=2, timeframe=0.2)
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import pytest
import asyncio
from paco import throttle
from .helpers import run_in_loop
and context (classes, functions, sometimes code) from other files:
# Path: paco/throttle.py
# @decorate
# def throttle(coro, limit=1, timeframe=1,
# return_value=None, raise_exception=False):
# """
# Creates a throttled coroutine function that only invokes
# ``coro`` at most once per every time frame of seconds or milliseconds.
#
# Provide options to indicate whether func should be invoked on the
# leading and/or trailing edge of the wait timeout.
#
# Subsequent calls to the throttled coroutine
# return the result of the last coroutine invocation.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction):
# coroutine function to wrap with throttle strategy.
# limit (int):
# number of coroutine allowed execution in the given time frame.
# timeframe (int|float):
# throttle limit time frame in seconds.
# return_value (mixed):
# optional return if the throttle limit is reached.
# Returns the latest returned value by default.
# raise_exception (bool):
# raise exception if throttle limit is reached.
#
# Raises:
# RuntimeError: if cannot throttle limit reached (optional).
#
# Returns:
# coroutinefunction
#
# Usage::
#
# async def mul_2(num):
# return num * 2
#
# # Use as simple wrapper
# throttled = paco.throttle(mul_2, limit=1, timeframe=2)
# await throttled(2)
# # => 4
# await throttled(3) # ignored!
# # => 4
# await asyncio.sleep(2)
# await throttled(3) # executed!
# # => 6
#
# # Use as decorator
# @paco.throttle(limit=1, timeframe=2)
# async def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
# await mul_2(3) # ignored!
# # => 4
# await asyncio.sleep(2)
# await mul_2(3) # executed!
# # => 6
#
# """
# assert_corofunction(coro=coro)
#
# # Store execution limits
# limit = max(int(limit), 1)
# remaning = limit
#
# # Turn seconds in milliseconds
# timeframe = timeframe * 1000
#
# # Keep call state
# last_call = now()
# # Cache latest retuned result
# result = None
#
# def stop():
# if raise_exception:
# raise RuntimeError('paco: coroutine throttle limit exceeded')
# if return_value:
# return return_value
# return result
#
# def elapsed():
# return now() - last_call
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# nonlocal result
# nonlocal remaning
# nonlocal last_call
#
# if elapsed() > timeframe:
# # Reset reamining calls counter
# remaning = limit
# # Update last call time
# last_call = now()
# elif elapsed() < timeframe and remaning <= 0:
# return stop()
#
# # Decrease remaining limit
# remaning -= 1
#
# # Schedule coroutine passing arguments and cache 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. | assert run_in_loop(task, 1) == 1 |
Based on the snippet: <|code_start|> Returns a coroutine function wrapper that will defer the given coroutine
execution for a certain amount of seconds in a non-blocking way.
This function can be used as decorator.
Arguments:
coro (coroutinefunction): coroutine function to defer.
delay (int/float): number of seconds to defer execution.
Raises:
TypeError: if coro argument is not a coroutine function.
Returns:
filtered values (list): ordered list of resultant values.
Usage::
# Usage as function
await paco.defer(coro, delay=1)
await paco.defer(coro, delay=0.5)
# Usage as decorator
@paco.defer(delay=1)
async def mul_2(num):
return num * 2
await mul_2(2)
# => 4
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction
and context (classes, functions, sometimes 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) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num * 2
def test_flat_map():
<|code_end|>
, generate the next line using the imports in this file:
import pytest
import asyncio
from paco import flat_map
from .helpers import run_in_loop
and context (functions, classes, or occasionally code) from other files:
# Path: paco/flat_map.py
# @overload
# @asyncio.coroutine
# def flat_map(coro, iterable, limit=0, loop=None, timeout=None,
# return_exceptions=False, initializer=None, *args, **kw):
# """
# Concurrently iterates values yielded from an iterable, passing them to
# an asynchronous coroutine.
#
# This function is the flatten version of 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.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# # => [2, 4, 6, 8, 10]
#
# # Pipeline style
# await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# # => [2, 4, 6, 8, 10]
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # By default do not collect yielded values from coroutines
# results = initializer if isiter(initializer) else []
#
# @asyncio.coroutine
# def reducer(buf, value):
# if isiter(value):
# yield from _reduce(value)
# else:
# buf.append((yield from coro(value)))
# return buf
#
# def _reduce(iterable):
# return reduce(reducer, iterable,
# initializer=results, limit=limit, loop=loop)
#
# # Returns list of mapped reduced results
# return (yield from _reduce(iterable))
#
# 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 = flat_map(coro, [1, [2, 3, 4], 5, 6, (7, [8, [(9,)]])]) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num * 2
def test_flat_map():
task = flat_map(coro, [1, [2, 3, 4], 5, 6, (7, [8, [(9,)]])])
<|code_end|>
. Use current file imports:
(import pytest
import asyncio
from paco import flat_map
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets from other files:
# Path: paco/flat_map.py
# @overload
# @asyncio.coroutine
# def flat_map(coro, iterable, limit=0, loop=None, timeout=None,
# return_exceptions=False, initializer=None, *args, **kw):
# """
# Concurrently iterates values yielded from an iterable, passing them to
# an asynchronous coroutine.
#
# This function is the flatten version of 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.flat_map(mul_2, [1, [2], [3, [4]], [(5,)]])
# # => [2, 4, 6, 8, 10]
#
# # Pipeline style
# await [1, [2], [3, [4]], [(5,)]] | paco.flat_map(mul_2)
# # => [2, 4, 6, 8, 10]
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # By default do not collect yielded values from coroutines
# results = initializer if isiter(initializer) else []
#
# @asyncio.coroutine
# def reducer(buf, value):
# if isiter(value):
# yield from _reduce(value)
# else:
# buf.append((yield from coro(value)))
# return buf
#
# def _reduce(iterable):
# return reduce(reducer, iterable,
# initializer=results, limit=limit, loop=loop)
#
# # Returns list of mapped reduced results
# return (yield from _reduce(iterable))
#
# 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(task) |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num < 2
@asyncio.coroutine
def coro_false(num):
return num > 10
def test_some_truly():
<|code_end|>
with the help of current file imports:
import pytest
import asyncio
from paco import some
from .helpers import run_in_loop
and context from other files:
# Path: paco/some.py
# @overload
# @asyncio.coroutine
# def some(coro, iterable, limit=0, timeout=None, loop=None):
# """
# Returns `True` if at least one element in the iterable satisfies the
# asynchronous coroutine test. If any iteratee call returns `True`,
# iteration stops and `True` will be returned.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): coroutine function for test values.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# 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.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# bool: `True` if at least on value passes the test, otherwise `False`.
#
# Usage::
#
# async def gt_3(num):
# return num > 3
#
# await paco.some(test, [1, 2, 3, 4, 5])
# # => True
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# passes = False
#
# # If no items in iterable, return False
# if len(iterable) == 0:
# return passes
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# @asyncio.coroutine
# def tester(element):
# nonlocal passes
# if passes:
# return None
#
# if (yield from coro(element)):
# # Flag as not test passed
# passes = True
# # Force stop 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(timeout=timeout)
#
# 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 contain function names, class names, or code. Output only the next line. | task = some(coro, [1, 2, 3, 4, 3, 1]) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num < 2
@asyncio.coroutine
def coro_false(num):
return num > 10
def test_some_truly():
task = some(coro, [1, 2, 3, 4, 3, 1])
<|code_end|>
using the current file's imports:
import pytest
import asyncio
from paco import some
from .helpers import run_in_loop
and any relevant context from other files:
# Path: paco/some.py
# @overload
# @asyncio.coroutine
# def some(coro, iterable, limit=0, timeout=None, loop=None):
# """
# Returns `True` if at least one element in the iterable satisfies the
# asynchronous coroutine test. If any iteratee call returns `True`,
# iteration stops and `True` will be returned.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): coroutine function for test values.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# 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.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# bool: `True` if at least on value passes the test, otherwise `False`.
#
# Usage::
#
# async def gt_3(num):
# return num > 3
#
# await paco.some(test, [1, 2, 3, 4, 5])
# # => True
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# passes = False
#
# # If no items in iterable, return False
# if len(iterable) == 0:
# return passes
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# @asyncio.coroutine
# def tester(element):
# nonlocal passes
# if passes:
# return None
#
# if (yield from coro(element)):
# # Flag as not test passed
# passes = True
# # Force stop 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(timeout=timeout)
#
# 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 |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(acc, num):
return acc + (num * 2,)
@asyncio.coroutine
def sumfn(acc, num):
return acc + num
def test_reduce():
<|code_end|>
, determine the next line of code. You have imports:
import pytest
import asyncio
from paco import reduce
from .helpers import run_in_loop
and context (class names, function names, or code) available:
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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 = reduce(coro, [1, 2, 3, 4, 5], initializer=()) |
Predict the next line after this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(acc, num):
return acc + (num * 2,)
@asyncio.coroutine
def sumfn(acc, num):
return acc + num
def test_reduce():
task = reduce(coro, [1, 2, 3, 4, 5], initializer=())
<|code_end|>
using the current file's imports:
import pytest
import asyncio
from paco import reduce
from .helpers import run_in_loop
and any relevant context from other files:
# Path: paco/reduce.py
# @overload
# @asyncio.coroutine
# def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None):
# """
# Apply function of two arguments cumulatively to the items of sequence,
# from left to right, so as to reduce the sequence to a single value.
#
# Reduction will be executed sequentially without concurrency,
# so passed values would be in order.
#
# This function is the asynchronous coroutine equivalent to Python standard
# `functools.reduce()` function.
#
# This function is a coroutine.
#
# This function can be composed in a pipeline chain with ``|`` operator.
#
# Arguments:
# coro (coroutine function): reducer coroutine binary function.
# iterable (iterable|asynchronousiterable): an iterable collection
# yielding coroutines functions.
# initializer (mixed): initial accumulator value used in
# the first reduction call.
# limit (int): max iteration concurrency limit. Use ``0`` for no limit.
# right (bool): reduce iterable from right to left.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if input arguments are not valid.
#
# Returns:
# mixed: accumulated final reduced value.
#
# Usage::
#
# async def reducer(acc, num):
# return acc + num
#
# await paco.reduce(reducer, [1, 2, 3, 4, 5], initializer=0)
# # => 15
#
# """
# assert_corofunction(coro=coro)
# assert_iter(iterable=iterable)
#
# # Reduced accumulator value
# acc = initializer
#
# # If interable is empty, just return the initializer value
# if len(iterable) == 0:
# return initializer
#
# # Create concurrent executor
# pool = ConcurrentExecutor(limit=limit, loop=loop)
#
# # Reducer partial function for deferred coroutine execution
# def reducer(element):
# @asyncio.coroutine
# def wrapper():
# nonlocal acc
# acc = yield from coro(acc, element)
# return wrapper
#
# # Support right reduction
# if right:
# iterable.reverse()
#
# # Iterate and attach coroutine for defer scheduling
# for element in iterable:
# pool.add(reducer(element))
#
# # Wait until all coroutines finish
# yield from pool.run(ignore_empty=True)
#
# # Returns final reduced value
# return acc
#
# 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, 8, 10) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def test_until():
calls = 0
@asyncio.coroutine
def coro_test():
return calls > 4
@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 until
from .helpers import run_in_loop
and context:
# Path: paco/until.py
# @asyncio.coroutine
# def until(coro, coro_test, assert_coro=None, *args, **kw):
# """
# Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
#
# This function is the inverse of `paco.whilst()`.
#
# 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_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
#
# return (yield from whilst(coro, coro_test,
# assert_coro=assert_coro, *args, **kw))
#
# 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 = until(coro, coro_test) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def test_until():
calls = 0
@asyncio.coroutine
def coro_test():
return calls > 4
@asyncio.coroutine
def coro():
nonlocal calls
calls += 1
return calls
task = until(coro, coro_test)
<|code_end|>
. Use current file imports:
(import pytest
import asyncio
from paco import until
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets from other files:
# Path: paco/until.py
# @asyncio.coroutine
# def until(coro, coro_test, assert_coro=None, *args, **kw):
# """
# Repeatedly call `coro` coroutine function until `coro_test` returns `True`.
#
# This function is the inverse of `paco.whilst()`.
#
# 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_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
#
# return (yield from whilst(coro, coro_test,
# assert_coro=assert_coro, *args, **kw))
#
# 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) == [1, 2, 3, 4, 5] |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
def generator_consumer(coro): # pragma: no cover
"""
Decorator wrapper that consumes sync/async generators provided as
interable input argument.
This function is only intended to be used internally.
Arguments:
coro (coroutinefunction): function to decorate
Raises:
TypeError: if function or coroutine function is not provided.
Returns:
function: decorated function.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('paco: coro must be a coroutine function')
@functools.wraps(coro)
@asyncio.coroutine
def wrapper(*args, **kw):
if len(args) > 1 and isgenerator(args[1]):
args = list(args)
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
import functools
from inspect import isfunction
from .generator import consume
from .assertions import iscoro_or_corofunc, isgenerator
from .pipe import overload # noqa
and context (functions, classes, or occasionally 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 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 isgenerator(x):
# """
# Returns `True` if the given value is sync or async generator coroutine.
#
# Arguments:
# x (mixed): value to check if it is an iterable.
#
# Returns:
# bool
# """
# return any([
# hasattr(x, '__next__'),
# hasattr(x, '__anext__')
# ])
#
# 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. | args[1] = (yield from consume(args[1]) |
Given snippet: <|code_start|> if hasattr(args[1], '__anext__')
else list(args[1]))
args = tuple(args)
return (yield from coro(*args, **kw))
return wrapper
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:
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
import functools
from inspect import isfunction
from .generator import consume
from .assertions import iscoro_or_corofunc, isgenerator
from .pipe import overload # noqa
and context:
# 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 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 isgenerator(x):
# """
# Returns `True` if the given value is sync or async generator coroutine.
#
# Arguments:
# x (mixed): value to check if it is an iterable.
#
# Returns:
# bool
# """
# return any([
# hasattr(x, '__next__'),
# hasattr(x, '__anext__')
# ])
#
# 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
which might include code, classes, or functions. Output only the next line. | if iscoro_or_corofunc(arg): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
def generator_consumer(coro): # pragma: no cover
"""
Decorator wrapper that consumes sync/async generators provided as
interable input argument.
This function is only intended to be used internally.
Arguments:
coro (coroutinefunction): function to decorate
Raises:
TypeError: if function or coroutine function is not provided.
Returns:
function: decorated function.
"""
if not asyncio.iscoroutinefunction(coro):
raise TypeError('paco: coro must be a coroutine function')
@functools.wraps(coro)
@asyncio.coroutine
def wrapper(*args, **kw):
<|code_end|>
with the help of current file imports:
import asyncio
import functools
from inspect import isfunction
from .generator import consume
from .assertions import iscoro_or_corofunc, isgenerator
from .pipe import overload # noqa
and context 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 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 isgenerator(x):
# """
# Returns `True` if the given value is sync or async generator coroutine.
#
# Arguments:
# x (mixed): value to check if it is an iterable.
#
# Returns:
# bool
# """
# return any([
# hasattr(x, '__next__'),
# hasattr(x, '__anext__')
# ])
#
# 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
, which may contain function names, class names, or code. Output only the next line. | if len(args) > 1 and isgenerator(args[1]): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(x):
return x
def test_defer():
<|code_end|>
with the help of current file imports:
import time
import asyncio
from paco import defer
from .helpers import run_in_loop
and context from other files:
# Path: paco/defer.py
# @decorate
# def defer(coro, delay=1):
# """
# Returns a coroutine function wrapper that will defer the given coroutine
# execution for a certain amount of seconds in a non-blocking way.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction): coroutine function to defer.
# delay (int/float): number of seconds to defer execution.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# filtered values (list): ordered list of resultant values.
#
# Usage::
#
# # Usage as function
# await paco.defer(coro, delay=1)
# await paco.defer(coro, delay=0.5)
#
# # Usage as decorator
# @paco.defer(delay=1)
# async def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# assert_corofunction(coro=coro)
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# # Wait until we're done
# yield from asyncio.sleep(delay)
# return (yield from coro(*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 contain function names, class names, or code. Output only the next line. | task = defer(coro, delay=0.2) |
Given the code snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(x):
return x
def test_defer():
task = defer(coro, delay=0.2)
now = time.time()
<|code_end|>
, generate the next line using the imports in this file:
import time
import asyncio
from paco import defer
from .helpers import run_in_loop
and context (functions, classes, or occasionally code) from other files:
# Path: paco/defer.py
# @decorate
# def defer(coro, delay=1):
# """
# Returns a coroutine function wrapper that will defer the given coroutine
# execution for a certain amount of seconds in a non-blocking way.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction): coroutine function to defer.
# delay (int/float): number of seconds to defer execution.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# filtered values (list): ordered list of resultant values.
#
# Usage::
#
# # Usage as function
# await paco.defer(coro, delay=1)
# await paco.defer(coro, delay=0.5)
#
# # Usage as decorator
# @paco.defer(delay=1)
# async def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# assert_corofunction(coro=coro)
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# # Wait until we're done
# yield from asyncio.sleep(delay)
# return (yield from coro(*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. | assert run_in_loop(task, 1) == 1 |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def task(x, y, baz=None, *args, **kw):
return x + y, baz, kw
@asyncio.coroutine
def coro(x, y, baz=None, *args, **kw):
return task(x, y, baz=baz, *args, **kw)
def test_curry_function_arity():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
from paco import curry
from .helpers import run_in_loop
and context:
# Path: paco/curry.py
# def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw):
# """
# Creates a function that accepts one or more arguments of a function and
# either invokes func returning its result if at least arity number of
# arguments have been provided, or returns a function that accepts the
# remaining function arguments until the function arity is satisfied.
#
# This function is overloaded: you can pass a function or coroutine function
# as first argument or an `int` indicating the explicit function arity.
#
# Function arity can be inferred via function signature or explicitly
# passed via `arity_or_fn` param.
#
# You can optionally ignore keyword based arguments as well passsing the
# `ignore_kwargs` param with `True` value.
#
# This function can be used as decorator.
#
# Arguments:
# arity_or_fn (int|function|coroutinefunction): function arity to curry
# or function to curry.
# ignore_kwargs (bool): ignore keyword arguments as arity to satisfy
# during curry.
# evaluator (function): use a custom arity evaluator function.
# *args (mixed): mixed variadic arguments for partial function
# application.
# *kwargs (mixed): keyword variadic arguments for partial function
# application.
#
# Raises:
# TypeError: if function is not a function or a coroutine function.
#
# Returns:
# function or coroutinefunction: function will be returned until all the
# function arity is satisfied, where a coroutine function will be
# returned instead.
#
# Usage::
#
# # Function signature inferred function arity
# @paco.curry
# async def task(x, y, z=0):
# return x * y + z
#
# await task(4)(4)(z=8)
# # => 24
#
# # User defined function arity
# @paco.curry(4)
# async def task(x, y, *args, **kw):
# return x * y + args[0] * args[1]
#
# await task(4)(4)(8)(8)
# # => 80
#
# # Ignore keyword arguments from arity
# @paco.curry(ignore_kwargs=True)
# async def task(x, y, z=0):
# return x * y
#
# await task(4)(4)
# # => 16
#
# """
# def isvalidarg(x):
# return all([
# x.kind != x.VAR_KEYWORD,
# x.kind != x.VAR_POSITIONAL,
# any([
# not ignore_kwargs,
# ignore_kwargs and x.default == x.empty
# ])
# ])
#
# def params(fn):
# return inspect.signature(fn).parameters.values()
#
# def infer_arity(fn):
# return len([x for x in params(fn) if isvalidarg(x)])
#
# def merge_args(acc, args, kw):
# _args, _kw = acc
# _args = _args + args
# _kw = _kw or {}
# _kw.update(kw)
# return _args, _kw
#
# def currier(arity, acc, fn, *args, **kw):
# """
# Function either continues curring of the arguments
# or executes function if desired arguments have being collected.
# If function curried is variadic then execution without arguments
# will finish curring and trigger the function
# """
# # Merge call arguments with accumulated ones
# _args, _kw = merge_args(acc, args, kw)
#
# # Get current function call accumulated arity
# current_arity = len(args)
#
# # Count keyword params as arity to satisfy, if required
# if not ignore_kwargs:
# current_arity += len(kw)
#
# # Decrease function arity to satisfy
# arity -= current_arity
#
# # Use user-defined custom arity evaluator strategy, if present
# currify = evaluator and evaluator(acc, fn)
#
# # If arity is not satisfied, return recursive partial function
# if currify is not False and arity > 0:
# return functools.partial(currier, arity, (_args, _kw), fn)
#
# # If arity is satisfied, instanciate coroutine and return it
# return fn(*_args, **_kw)
#
# def wrapper(fn, *args, **kw):
# if not iscallable(fn):
# raise TypeError('paco: first argument must a coroutine function, '
# 'a function or a method.')
#
# # Infer function arity, if required
# arity = (arity_or_fn if isinstance(arity_or_fn, int)
# else infer_arity(fn))
#
# # Wraps function as coroutine function, if needed.
# fn = wraps(fn) if isfunc(fn) else fn
#
# # Otherwise return recursive currier function
# return currier(arity, (args, kw), fn, *args, **kw) if arity > 0 else fn
#
# # Return currier function or decorator wrapper
# return (wrapper(arity_or_fn, *args, **kw)
# if iscallable(arity_or_fn)
# else 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. | num, val, kw = run_in_loop(curry(task)(2)(4)(baz='foo')) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
def task(x, y, baz=None, *args, **kw):
return x + y, baz, kw
@asyncio.coroutine
def coro(x, y, baz=None, *args, **kw):
return task(x, y, baz=baz, *args, **kw)
def test_curry_function_arity():
<|code_end|>
. Use current file imports:
(import asyncio
from paco import curry
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets from other files:
# Path: paco/curry.py
# def curry(arity_or_fn=None, ignore_kwargs=False, evaluator=None, *args, **kw):
# """
# Creates a function that accepts one or more arguments of a function and
# either invokes func returning its result if at least arity number of
# arguments have been provided, or returns a function that accepts the
# remaining function arguments until the function arity is satisfied.
#
# This function is overloaded: you can pass a function or coroutine function
# as first argument or an `int` indicating the explicit function arity.
#
# Function arity can be inferred via function signature or explicitly
# passed via `arity_or_fn` param.
#
# You can optionally ignore keyword based arguments as well passsing the
# `ignore_kwargs` param with `True` value.
#
# This function can be used as decorator.
#
# Arguments:
# arity_or_fn (int|function|coroutinefunction): function arity to curry
# or function to curry.
# ignore_kwargs (bool): ignore keyword arguments as arity to satisfy
# during curry.
# evaluator (function): use a custom arity evaluator function.
# *args (mixed): mixed variadic arguments for partial function
# application.
# *kwargs (mixed): keyword variadic arguments for partial function
# application.
#
# Raises:
# TypeError: if function is not a function or a coroutine function.
#
# Returns:
# function or coroutinefunction: function will be returned until all the
# function arity is satisfied, where a coroutine function will be
# returned instead.
#
# Usage::
#
# # Function signature inferred function arity
# @paco.curry
# async def task(x, y, z=0):
# return x * y + z
#
# await task(4)(4)(z=8)
# # => 24
#
# # User defined function arity
# @paco.curry(4)
# async def task(x, y, *args, **kw):
# return x * y + args[0] * args[1]
#
# await task(4)(4)(8)(8)
# # => 80
#
# # Ignore keyword arguments from arity
# @paco.curry(ignore_kwargs=True)
# async def task(x, y, z=0):
# return x * y
#
# await task(4)(4)
# # => 16
#
# """
# def isvalidarg(x):
# return all([
# x.kind != x.VAR_KEYWORD,
# x.kind != x.VAR_POSITIONAL,
# any([
# not ignore_kwargs,
# ignore_kwargs and x.default == x.empty
# ])
# ])
#
# def params(fn):
# return inspect.signature(fn).parameters.values()
#
# def infer_arity(fn):
# return len([x for x in params(fn) if isvalidarg(x)])
#
# def merge_args(acc, args, kw):
# _args, _kw = acc
# _args = _args + args
# _kw = _kw or {}
# _kw.update(kw)
# return _args, _kw
#
# def currier(arity, acc, fn, *args, **kw):
# """
# Function either continues curring of the arguments
# or executes function if desired arguments have being collected.
# If function curried is variadic then execution without arguments
# will finish curring and trigger the function
# """
# # Merge call arguments with accumulated ones
# _args, _kw = merge_args(acc, args, kw)
#
# # Get current function call accumulated arity
# current_arity = len(args)
#
# # Count keyword params as arity to satisfy, if required
# if not ignore_kwargs:
# current_arity += len(kw)
#
# # Decrease function arity to satisfy
# arity -= current_arity
#
# # Use user-defined custom arity evaluator strategy, if present
# currify = evaluator and evaluator(acc, fn)
#
# # If arity is not satisfied, return recursive partial function
# if currify is not False and arity > 0:
# return functools.partial(currier, arity, (_args, _kw), fn)
#
# # If arity is satisfied, instanciate coroutine and return it
# return fn(*_args, **_kw)
#
# def wrapper(fn, *args, **kw):
# if not iscallable(fn):
# raise TypeError('paco: first argument must a coroutine function, '
# 'a function or a method.')
#
# # Infer function arity, if required
# arity = (arity_or_fn if isinstance(arity_or_fn, int)
# else infer_arity(fn))
#
# # Wraps function as coroutine function, if needed.
# fn = wraps(fn) if isfunc(fn) else fn
#
# # Otherwise return recursive currier function
# return currier(arity, (args, kw), fn, *args, **kw) if arity > 0 else fn
#
# # Return currier function or decorator wrapper
# return (wrapper(arity_or_fn, *args, **kw)
# if iscallable(arity_or_fn)
# else 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. | num, val, kw = run_in_loop(curry(task)(2)(4)(baz='foo')) |
Here is a snippet: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
ensure_future = asyncio.async
@asyncio.coroutine
def coro(delay=1):
yield from asyncio.sleep(delay)
def test_timeout():
<|code_end|>
. Write the next line using the current file imports:
import time
import pytest
import asyncio
from paco import timeout, TimeoutLimit, run
from .helpers import run_in_loop
from asyncio import ensure_future
and context from other files:
# Path: paco/timeout.py
# @decorate
# def timeout(coro, timeout=None, loop=None):
# """
# Wraps a given coroutine function, that when executed, if it takes more
# than the given timeout in seconds to execute, it will be canceled and
# raise an `asyncio.TimeoutError`.
#
# This function is equivalent to Python standard
# `asyncio.wait_for()` function.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction|coroutine): coroutine to wrap.
# timeout (int|float): max wait timeout in seconds.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# coroutinefunction: wrapper coroutine function.
#
# Usage::
#
# await paco.timeout(coro, timeout=10)
#
# """
# @asyncio.coroutine
# def _timeout(coro):
# return (yield from asyncio.wait_for(coro, timeout, loop=loop))
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# return (yield from _timeout(coro(*args, **kw)))
#
# return _timeout(coro) if asyncio.iscoroutine(coro) else wrapper
#
# class TimeoutLimit(object):
# """
# Timeout limit context manager.
#
# Useful in cases when you want to apply timeout logic around block
# of code or in cases when asyncio.wait_for is not suitable.
#
# Originally based on: https://github.com/aio-libs/async-timeout
#
# Arguments:
# timeout (int): value in seconds or None to disable timeout logic.
# loop (asyncio.BaseEventLoop): asyncio compatible event loop.
#
# Usage::
#
# with paco.TimeoutLimit(0.1):
# await paco.wait(task1, task2)
# """
#
# def __init__(self, timeout, loop=None):
# self._timeout = timeout
# self._loop = loop or asyncio.get_event_loop()
# self._task = None
# self._cancelled = False
# self._cancel_handler = None
#
# def __enter__(self):
# self._task = asyncio.Task.current_task(loop=self._loop)
# if self._task is None:
# raise RuntimeError('paco: timeout context manager should '
# 'be used inside a task')
# if self._timeout is not None:
# self._cancel_handler = self._loop.call_later(
# self._timeout, self.cancel)
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# if exc_type is asyncio.CancelledError and self._cancelled:
# self._cancel_handler = None
# self._task = None
# raise asyncio.TimeoutError from None
# if self._timeout is not None:
# self._cancel_handler.cancel()
# self._cancel_handler = None
# self._task = None
#
# def cancel(self):
# """
# Cancels current task running task in the context manager.
# """
# self._cancelled = self._task.cancel()
#
# 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)
#
# 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 = timeout(coro, timeout=1) |
Based on the snippet: <|code_start|>
assert time.time() - now >= 0.2
def test_timeout_decorator():
task = timeout(timeout=1)(coro)
now = time.time()
run_in_loop(task, delay=0.2)
assert time.time() - now >= 0.2
def test_timeout_coroutine_object():
now = time.time()
with pytest.raises(asyncio.TimeoutError):
@asyncio.coroutine
def _run():
task = timeout(coro(delay=1), timeout=0.2)
return (yield from task)
run(_run())
assert time.time() - now >= 0.2
def test_timeout_limit_context():
now = time.time()
@asyncio.coroutine
def test():
<|code_end|>
, predict the immediate next line with the help of imports:
import time
import pytest
import asyncio
from paco import timeout, TimeoutLimit, run
from .helpers import run_in_loop
from asyncio import ensure_future
and context (classes, functions, sometimes code) from other files:
# Path: paco/timeout.py
# @decorate
# def timeout(coro, timeout=None, loop=None):
# """
# Wraps a given coroutine function, that when executed, if it takes more
# than the given timeout in seconds to execute, it will be canceled and
# raise an `asyncio.TimeoutError`.
#
# This function is equivalent to Python standard
# `asyncio.wait_for()` function.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction|coroutine): coroutine to wrap.
# timeout (int|float): max wait timeout in seconds.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# coroutinefunction: wrapper coroutine function.
#
# Usage::
#
# await paco.timeout(coro, timeout=10)
#
# """
# @asyncio.coroutine
# def _timeout(coro):
# return (yield from asyncio.wait_for(coro, timeout, loop=loop))
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# return (yield from _timeout(coro(*args, **kw)))
#
# return _timeout(coro) if asyncio.iscoroutine(coro) else wrapper
#
# class TimeoutLimit(object):
# """
# Timeout limit context manager.
#
# Useful in cases when you want to apply timeout logic around block
# of code or in cases when asyncio.wait_for is not suitable.
#
# Originally based on: https://github.com/aio-libs/async-timeout
#
# Arguments:
# timeout (int): value in seconds or None to disable timeout logic.
# loop (asyncio.BaseEventLoop): asyncio compatible event loop.
#
# Usage::
#
# with paco.TimeoutLimit(0.1):
# await paco.wait(task1, task2)
# """
#
# def __init__(self, timeout, loop=None):
# self._timeout = timeout
# self._loop = loop or asyncio.get_event_loop()
# self._task = None
# self._cancelled = False
# self._cancel_handler = None
#
# def __enter__(self):
# self._task = asyncio.Task.current_task(loop=self._loop)
# if self._task is None:
# raise RuntimeError('paco: timeout context manager should '
# 'be used inside a task')
# if self._timeout is not None:
# self._cancel_handler = self._loop.call_later(
# self._timeout, self.cancel)
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# if exc_type is asyncio.CancelledError and self._cancelled:
# self._cancel_handler = None
# self._task = None
# raise asyncio.TimeoutError from None
# if self._timeout is not None:
# self._cancel_handler.cancel()
# self._cancel_handler = None
# self._task = None
#
# def cancel(self):
# """
# Cancels current task running task in the context manager.
# """
# self._cancelled = self._task.cancel()
#
# 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)
#
# 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. | with TimeoutLimit(timeout=0.2): |
Here is a snippet: <|code_start|> run_in_loop(task, delay=0.2)
assert time.time() - now >= 0.2
def test_timeout_exceeded():
task = timeout(coro, timeout=0.2)
now = time.time()
with pytest.raises(asyncio.TimeoutError):
run_in_loop(task, delay=1)
assert time.time() - now >= 0.2
def test_timeout_decorator():
task = timeout(timeout=1)(coro)
now = time.time()
run_in_loop(task, delay=0.2)
assert time.time() - now >= 0.2
def test_timeout_coroutine_object():
now = time.time()
with pytest.raises(asyncio.TimeoutError):
@asyncio.coroutine
def _run():
task = timeout(coro(delay=1), timeout=0.2)
return (yield from task)
<|code_end|>
. Write the next line using the current file imports:
import time
import pytest
import asyncio
from paco import timeout, TimeoutLimit, run
from .helpers import run_in_loop
from asyncio import ensure_future
and context from other files:
# Path: paco/timeout.py
# @decorate
# def timeout(coro, timeout=None, loop=None):
# """
# Wraps a given coroutine function, that when executed, if it takes more
# than the given timeout in seconds to execute, it will be canceled and
# raise an `asyncio.TimeoutError`.
#
# This function is equivalent to Python standard
# `asyncio.wait_for()` function.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction|coroutine): coroutine to wrap.
# timeout (int|float): max wait timeout in seconds.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# coroutinefunction: wrapper coroutine function.
#
# Usage::
#
# await paco.timeout(coro, timeout=10)
#
# """
# @asyncio.coroutine
# def _timeout(coro):
# return (yield from asyncio.wait_for(coro, timeout, loop=loop))
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# return (yield from _timeout(coro(*args, **kw)))
#
# return _timeout(coro) if asyncio.iscoroutine(coro) else wrapper
#
# class TimeoutLimit(object):
# """
# Timeout limit context manager.
#
# Useful in cases when you want to apply timeout logic around block
# of code or in cases when asyncio.wait_for is not suitable.
#
# Originally based on: https://github.com/aio-libs/async-timeout
#
# Arguments:
# timeout (int): value in seconds or None to disable timeout logic.
# loop (asyncio.BaseEventLoop): asyncio compatible event loop.
#
# Usage::
#
# with paco.TimeoutLimit(0.1):
# await paco.wait(task1, task2)
# """
#
# def __init__(self, timeout, loop=None):
# self._timeout = timeout
# self._loop = loop or asyncio.get_event_loop()
# self._task = None
# self._cancelled = False
# self._cancel_handler = None
#
# def __enter__(self):
# self._task = asyncio.Task.current_task(loop=self._loop)
# if self._task is None:
# raise RuntimeError('paco: timeout context manager should '
# 'be used inside a task')
# if self._timeout is not None:
# self._cancel_handler = self._loop.call_later(
# self._timeout, self.cancel)
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# if exc_type is asyncio.CancelledError and self._cancelled:
# self._cancel_handler = None
# self._task = None
# raise asyncio.TimeoutError from None
# if self._timeout is not None:
# self._cancel_handler.cancel()
# self._cancel_handler = None
# self._task = None
#
# def cancel(self):
# """
# Cancels current task running task in the context manager.
# """
# self._cancelled = self._task.cancel()
#
# 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)
#
# 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. | run(_run()) |
Given the following code snippet before the placeholder: <|code_start|># -*- coding: utf-8 -*-
try:
except ImportError:
ensure_future = asyncio.async
@asyncio.coroutine
def coro(delay=1):
yield from asyncio.sleep(delay)
def test_timeout():
task = timeout(coro, timeout=1)
now = time.time()
<|code_end|>
, predict the next line using imports from the current file:
import time
import pytest
import asyncio
from paco import timeout, TimeoutLimit, run
from .helpers import run_in_loop
from asyncio import ensure_future
and context including class names, function names, and sometimes code from other files:
# Path: paco/timeout.py
# @decorate
# def timeout(coro, timeout=None, loop=None):
# """
# Wraps a given coroutine function, that when executed, if it takes more
# than the given timeout in seconds to execute, it will be canceled and
# raise an `asyncio.TimeoutError`.
#
# This function is equivalent to Python standard
# `asyncio.wait_for()` function.
#
# This function can be used as decorator.
#
# Arguments:
# coro (coroutinefunction|coroutine): coroutine to wrap.
# timeout (int|float): max wait timeout in seconds.
# loop (asyncio.BaseEventLoop): optional event loop to use.
#
# Raises:
# TypeError: if coro argument is not a coroutine function.
#
# Returns:
# coroutinefunction: wrapper coroutine function.
#
# Usage::
#
# await paco.timeout(coro, timeout=10)
#
# """
# @asyncio.coroutine
# def _timeout(coro):
# return (yield from asyncio.wait_for(coro, timeout, loop=loop))
#
# @asyncio.coroutine
# def wrapper(*args, **kw):
# return (yield from _timeout(coro(*args, **kw)))
#
# return _timeout(coro) if asyncio.iscoroutine(coro) else wrapper
#
# class TimeoutLimit(object):
# """
# Timeout limit context manager.
#
# Useful in cases when you want to apply timeout logic around block
# of code or in cases when asyncio.wait_for is not suitable.
#
# Originally based on: https://github.com/aio-libs/async-timeout
#
# Arguments:
# timeout (int): value in seconds or None to disable timeout logic.
# loop (asyncio.BaseEventLoop): asyncio compatible event loop.
#
# Usage::
#
# with paco.TimeoutLimit(0.1):
# await paco.wait(task1, task2)
# """
#
# def __init__(self, timeout, loop=None):
# self._timeout = timeout
# self._loop = loop or asyncio.get_event_loop()
# self._task = None
# self._cancelled = False
# self._cancel_handler = None
#
# def __enter__(self):
# self._task = asyncio.Task.current_task(loop=self._loop)
# if self._task is None:
# raise RuntimeError('paco: timeout context manager should '
# 'be used inside a task')
# if self._timeout is not None:
# self._cancel_handler = self._loop.call_later(
# self._timeout, self.cancel)
# return self
#
# def __exit__(self, exc_type, exc_val, exc_tb):
# if exc_type is asyncio.CancelledError and self._cancelled:
# self._cancel_handler = None
# self._task = None
# raise asyncio.TimeoutError from None
# if self._timeout is not None:
# self._cancel_handler.cancel()
# self._cancel_handler = None
# self._task = None
#
# def cancel(self):
# """
# Cancels current task running task in the context manager.
# """
# self._cancelled = self._task.cancel()
#
# 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)
#
# 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(task, delay=0.2) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num
def test_each():
calls = 0
@asyncio.coroutine
def coro(num):
nonlocal calls
calls += 1
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import time
import pytest
import asyncio
from paco import each
from .helpers import run_in_loop
and context:
# 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: 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 = each(coro, [1, 2, 3, 4, 5]) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def coro(num):
return num
def test_each():
calls = 0
@asyncio.coroutine
def coro(num):
nonlocal calls
calls += 1
task = each(coro, [1, 2, 3, 4, 5])
<|code_end|>
. Use current file imports:
(import time
import pytest
import asyncio
from paco import each
from .helpers import run_in_loop)
and context including class names, function names, or small code snippets 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: 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 None |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def run_test(limit=3, times=10, timespan=0.1):
p = concurrent(limit)
for i in range(times):
<|code_end|>
with the help of current file imports:
import time
import pytest
import asyncio
from paco import concurrent
from .helpers import sleep_coro, run_in_loop
and context from other files:
# Path: paco/concurrent.py
# def safe_run(coro, return_exceptions=False):
# def collect(coro, index, results,
# preserve_order=False,
# return_exceptions=False):
# def __init__(self, limit=10, loop=None, coros=None, ignore_empty=False):
# def __len__(self):
# def reset(self):
# def cancel(self):
# def on(self, event, fn):
# def off(self, event):
# def extend(self, *coros):
# def add(self, coro, *args, **kw):
# def _run_sequentially(self):
# def _run_concurrently(self, timeout=None, return_when='ALL_COMPLETED'):
# def _run_coro(self, task):
# def _schedule_coro(self, task):
# def run(self,
# timeout=None,
# return_when=None,
# return_exceptions=None,
# ignore_empty=None):
# def is_running(self):
# class ConcurrentExecutor(object):
#
# Path: tests/helpers.py
# @asyncio.coroutine
# def sleep_coro(timespan=0.1):
# start = time.time()
# yield from asyncio.sleep(timespan)
# return time.time() - start
#
# 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. | p.add(sleep_coro, timespan) |
Next line prediction: <|code_start|># -*- coding: utf-8 -*-
@asyncio.coroutine
def run_test(limit=3, times=10, timespan=0.1):
p = concurrent(limit)
for i in range(times):
p.add(sleep_coro, timespan)
return (yield from p.run())
def test_concurrent_single():
@asyncio.coroutine
def coro(num):
return num * 2
p = concurrent(10)
p.add(coro, 2)
assert len(p) == 1
assert p.__len__() == 1
assert len(p.pool) == 1
<|code_end|>
. Use current file imports:
(import time
import pytest
import asyncio
from paco import concurrent
from .helpers import sleep_coro, run_in_loop)
and context including class names, function names, or small code snippets from other files:
# Path: paco/concurrent.py
# def safe_run(coro, return_exceptions=False):
# def collect(coro, index, results,
# preserve_order=False,
# return_exceptions=False):
# def __init__(self, limit=10, loop=None, coros=None, ignore_empty=False):
# def __len__(self):
# def reset(self):
# def cancel(self):
# def on(self, event, fn):
# def off(self, event):
# def extend(self, *coros):
# def add(self, coro, *args, **kw):
# def _run_sequentially(self):
# def _run_concurrently(self, timeout=None, return_when='ALL_COMPLETED'):
# def _run_coro(self, task):
# def _schedule_coro(self, task):
# def run(self,
# timeout=None,
# return_when=None,
# return_exceptions=None,
# ignore_empty=None):
# def is_running(self):
# class ConcurrentExecutor(object):
#
# Path: tests/helpers.py
# @asyncio.coroutine
# def sleep_coro(timespan=0.1):
# start = time.time()
# yield from asyncio.sleep(timespan)
# return time.time() - start
#
# 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. | done, pending = run_in_loop(p.run()) |
Given snippet: <|code_start|># -*- coding: utf-8 -*-
def task(*args, **kw):
return args, kw
def test_wraps():
<|code_end|>
, continue by predicting the next line. Consider current file imports:
import asyncio
from paco import wraps
from .helpers import run_in_loop
and context:
# Path: paco/wraps.py
# def wraps(fn):
# """
# Wraps a given function as coroutine function.
#
# This function can be used as decorator.
#
# Arguments:
# fn (function): function object to wrap.
#
# Returns:
# coroutinefunction: wrapped function as coroutine.
#
# Usage::
#
# def mul_2(num):
# return num * 2
#
# # Use as function wrapper
# coro = paco.wraps(mul_2)
# await coro(2)
# # => 4
#
# # Use as decorator
# @paco.wraps
# def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# return asyncio.coroutine(fn)
#
# 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 = wraps(task) |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
def task(*args, **kw):
return args, kw
def test_wraps():
coro = wraps(task)
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
from paco import wraps
from .helpers import run_in_loop
and context (classes, functions, sometimes code) from other files:
# Path: paco/wraps.py
# def wraps(fn):
# """
# Wraps a given function as coroutine function.
#
# This function can be used as decorator.
#
# Arguments:
# fn (function): function object to wrap.
#
# Returns:
# coroutinefunction: wrapped function as coroutine.
#
# Usage::
#
# def mul_2(num):
# return num * 2
#
# # Use as function wrapper
# coro = paco.wraps(mul_2)
# await coro(2)
# # => 4
#
# # Use as decorator
# @paco.wraps
# def mul_2(num):
# return num * 2
#
# await mul_2(2)
# # => 4
#
# """
# return asyncio.coroutine(fn)
#
# 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(coro, 1, 2, foo='bar') |
Next line prediction: <|code_start|> """
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'
"""
<|code_end|>
. Use current file imports:
(import asyncio
from .assertions import assert_corofunction)
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))
. Output only the next line. | assert_corofunction(coro=coro) |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
try:
ensure_future = asyncio.ensure_future
except:
ensure_future = getattr(asyncio, 'async')
<|code_end|>
. Use current file imports:
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction
and context (classes, functions, or 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. | @decorate |
Based on the snippet: <|code_start|> 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()
"""
<|code_end|>
, predict the immediate next line with the help of imports:
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction
and context (classes, functions, sometimes 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|> limit (int): concurrency limit. Defaults to 10.
coros (list[coroutine], optional): list of coroutines to schedule.
loop (asyncio.BaseEventLoop, optional): loop to run.
Defaults to asyncio.get_event_loop().
ignore_empty (bool, optional): do not raise an exception if there are
no coroutines to schedule are empty.
Returns:
ConcurrentExecutor
Usage::
async def sum(x, y):
return x + y
pool = paco.ConcurrentExecutor(limit=2)
pool.add(sum, 1, 2)
pool.add(sum, None, 'str')
done, pending = await pool.run(return_exceptions=True)
[task.result() for task in done]
# => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa
"""
def __init__(self, limit=10, loop=None, coros=None, ignore_empty=False):
self.errors = []
self.running = False
self.return_exceptions = False
self.limit = max(int(limit), 0)
self.pool = deque()
<|code_end|>
. Use current file imports:
import asyncio
from collections import deque, namedtuple
from .observer import Observer
from .assertions import isiter
and context (classes, functions, or code) from other files:
# Path: paco/observer.py
# class Observer(object):
# """
# Observer implements a simple observer pub/sub pattern with a minimal
# interface and built-in coroutines support for asynchronous-first approach,
# desiged as abstract class to be inherited or embed by observable classes.
# """
#
# def __init__(self):
# self._pool = {}
#
# def observe(self, event, fn):
# """
# Arguments:
# event (str): event to subscribe.
# fn (function|coroutinefunction): function to trigger.
#
# Raises:
# TypeError: if fn argument is not valid
# """
# iscoroutine = asyncio.iscoroutinefunction(fn)
# if not iscoroutine and not isfunction(fn):
# raise TypeError('paco: fn param must be a callable '
# 'object or coroutine function')
#
# observers = self._pool.get(event)
# if not observers:
# observers = self._pool[event] = []
#
# # Register the observer
# observers.append(fn if iscoroutine else coroutine_wrapper(fn))
#
# def remove(self, event=None):
# """
# Remove all the registered observers for the given event name.
#
# Arguments:
# event (str): event name to remove.
# """
# observers = self._pool.get(event)
# if observers:
# self._pool[event] = []
#
# def clear(self):
# """
# Clear all the registered observers.
# """
# self._pool = {}
#
# # Shortcut methods
# on = observe
# off = remove
#
# @asyncio.coroutine
# def trigger(self, event, *args, **kw):
# """
# Triggers event observers for the given event name,
# passing custom variadic arguments.
# """
# observers = self._pool.get(event)
#
# # If no observers registered for the event, do no-op
# if not observers or len(observers) == 0:
# return None
#
# # Trigger observers coroutines in FIFO sequentially
# for fn in observers:
# # Review: perhaps this should not wait
# yield from fn(*args, **kw)
#
# 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. | self.observer = Observer() |
Given the code snippet: <|code_start|>
Returns:
ConcurrentExecutor
Usage::
async def sum(x, y):
return x + y
pool = paco.ConcurrentExecutor(limit=2)
pool.add(sum, 1, 2)
pool.add(sum, None, 'str')
done, pending = await pool.run(return_exceptions=True)
[task.result() for task in done]
# => [3, TypeError("unsupported operand type(s) for +: 'NoneType' and 'str'")] # noqa
"""
def __init__(self, limit=10, loop=None, coros=None, ignore_empty=False):
self.errors = []
self.running = False
self.return_exceptions = False
self.limit = max(int(limit), 0)
self.pool = deque()
self.observer = Observer()
self.ignore_empty = ignore_empty
self.loop = loop or asyncio.get_event_loop()
self.semaphore = asyncio.Semaphore(self.limit, loop=self.loop)
# Register coroutines in the pool
<|code_end|>
, generate the next line using the imports in this file:
import asyncio
from collections import deque, namedtuple
from .observer import Observer
from .assertions import isiter
and context (functions, classes, or occasionally code) from other files:
# Path: paco/observer.py
# class Observer(object):
# """
# Observer implements a simple observer pub/sub pattern with a minimal
# interface and built-in coroutines support for asynchronous-first approach,
# desiged as abstract class to be inherited or embed by observable classes.
# """
#
# def __init__(self):
# self._pool = {}
#
# def observe(self, event, fn):
# """
# Arguments:
# event (str): event to subscribe.
# fn (function|coroutinefunction): function to trigger.
#
# Raises:
# TypeError: if fn argument is not valid
# """
# iscoroutine = asyncio.iscoroutinefunction(fn)
# if not iscoroutine and not isfunction(fn):
# raise TypeError('paco: fn param must be a callable '
# 'object or coroutine function')
#
# observers = self._pool.get(event)
# if not observers:
# observers = self._pool[event] = []
#
# # Register the observer
# observers.append(fn if iscoroutine else coroutine_wrapper(fn))
#
# def remove(self, event=None):
# """
# Remove all the registered observers for the given event name.
#
# Arguments:
# event (str): event name to remove.
# """
# observers = self._pool.get(event)
# if observers:
# self._pool[event] = []
#
# def clear(self):
# """
# Clear all the registered observers.
# """
# self._pool = {}
#
# # Shortcut methods
# on = observe
# off = remove
#
# @asyncio.coroutine
# def trigger(self, event, *args, **kw):
# """
# Triggers event observers for the given event name,
# passing custom variadic arguments.
# """
# observers = self._pool.get(event)
#
# # If no observers registered for the event, do no-op
# if not observers or len(observers) == 0:
# return None
#
# # Trigger observers coroutines in FIFO sequentially
# for fn in observers:
# # Review: perhaps this should not wait
# yield from fn(*args, **kw)
#
# 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 isiter(coros): |
Predict the next line for this snippet: <|code_start|># -*- coding: utf-8 -*-
def now():
"""
Returns the current machine time in milliseconds.
"""
return int(round(time.time() * 1000))
<|code_end|>
with the help of current file imports:
import time
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction
and 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))
, which may contain function names, class names, or code. Output only the next line. | @decorate |
Here is a snippet: <|code_start|>
Usage::
async def mul_2(num):
return num * 2
# Use as simple wrapper
throttled = paco.throttle(mul_2, limit=1, timeframe=2)
await throttled(2)
# => 4
await throttled(3) # ignored!
# => 4
await asyncio.sleep(2)
await throttled(3) # executed!
# => 6
# Use as decorator
@paco.throttle(limit=1, timeframe=2)
async def mul_2(num):
return num * 2
await mul_2(2)
# => 4
await mul_2(3) # ignored!
# => 4
await asyncio.sleep(2)
await mul_2(3) # executed!
# => 6
"""
<|code_end|>
. Write the next line using the current file imports:
import time
import asyncio
from .decorator import decorate
from .assertions import assert_corofunction
and 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))
, which may include functions, classes, or code. Output only the next line. | assert_corofunction(coro=coro) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.