text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_conda_deps(deps):
""" Format dependencies into a common binstar format """ |
depends = []
for dep in deps:
dep = dep.strip()
name_spec = dep.split(' ', 1)
if len(name_spec) == 1:
name, = name_spec
depends.append({'name':name, 'specs': []})
elif len(name_spec) == 2:
name, spec = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [[op, spec]]})
elif len(name_spec) == 3:
name, spec, build_str = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [['==', '%s+%s' % (spec, build_str)]]})
return {'depends': depends} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_or_token(value):
""" If value is a file path and the file exists its contents are stripped and returned, otherwise value is returned. """ |
if isfile(value):
with open(value) as fd:
return fd.read().strip()
if any(char in value for char in '/\\.'):
# This chars will never be in a token value, but may be in a path
# The error message will be handled by the parser
raise ValueError()
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
""" Get the anaconda server api class """ |
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
if token:
logger.debug("Using token from command line args")
elif 'BINSTAR_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable BINSTAR_API_TOKEN")
token = os.environ['BINSTAR_API_TOKEN']
elif 'ANACONDA_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable ANACONDA_API_TOKEN")
token = os.environ['ANACONDA_API_TOKEN']
else:
token = load_token(url)
verify = config.get('ssl_verify', config.get('verify_ssl', True))
return cls(token, domain=url, verify=verify, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_conda_root():
"""Get the PREFIX of the conda installation. Returns: str: the ROOT_PREFIX of the conda installation """ |
try:
# Fast-path
# We're in the root environment
conda_root = _import_conda_root()
except ImportError:
# We're not in the root environment.
envs_dir = dirname(CONDA_PREFIX)
if basename(envs_dir) == 'envs':
# We're in a named environment: `conda create -n <name>`
conda_root = dirname(envs_dir)
else:
# We're in an isolated environment: `conda create -p <path>`
# The only way we can find out is by calling conda.
conda_root = _conda_root_from_conda_info()
return conda_root |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, dist):
""" Download file into location. """ |
filename = dist['basename']
requests_handle = self.aserver_api.download(
self.username, self.notebook, dist['version'], filename
)
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
with open(os.path.join(self.output, filename), 'wb') as fdout:
for chunk in requests_handle.iter_content(4096):
fdout.write(chunk) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ensure_output(self):
""" Ensure output's directory exists """ |
if not os.path.exists(self.output):
os.makedirs(self.output) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_segments(segments, exif=b""):
"""Merges Exif with APP0 and APP1 manipulations. """ |
if segments[1][0:2] == b"\xff\xe0" and \
segments[2][0:2] == b"\xff\xe1" and \
segments[2][4:10] == b"Exif\x00\x00":
if exif:
segments[2] = exif
segments.pop(1)
elif exif is None:
segments.pop(2)
else:
segments.pop(1)
elif segments[1][0:2] == b"\xff\xe0":
if exif:
segments[1] = exif
elif segments[1][0:2] == b"\xff\xe1" and \
segments[1][4:10] == b"Exif\x00\x00":
if exif:
segments[1] = exif
elif exif is None:
segments.pop(1)
else:
if exif:
segments.insert(1, exif)
return b"".join(segments) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(cls, data):
""" Convert "UserComment" value in exif format to str. :param bytes data: "UserComment" value from exif :return: u"foobar" :rtype: str(Unicode) :raises: ValueError if the data does not conform to the EXIF specification, or the encoding is unsupported. """ |
if len(data) < cls._PREFIX_SIZE:
raise ValueError('not enough data to decode UserComment')
prefix = data[:cls._PREFIX_SIZE]
body = data[cls._PREFIX_SIZE:]
if prefix == cls._UNDEFINED_PREFIX:
raise ValueError('prefix is UNDEFINED, unable to decode UserComment')
try:
encoding = {
cls._ASCII_PREFIX: cls.ASCII, cls._JIS_PREFIX: cls._JIS, cls._UNICODE_PREFIX: cls._UNICODE,
}[prefix]
except KeyError:
raise ValueError('unable to determine appropriate encoding')
return body.decode(encoding, errors='replace') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump(cls, data, encoding="ascii"):
""" Convert str to appropriate format for "UserComment". :param data: Like u"foobar" :param str encoding: "ascii", "jis", or "unicode" :return: b"ASCII\x00\x00\x00foobar" :rtype: bytes :raises: ValueError if the encoding is unsupported. """ |
if encoding not in cls.ENCODINGS:
raise ValueError('encoding {!r} must be one of {!r}'.format(encoding, cls.ENCODINGS))
prefix = {cls.ASCII: cls._ASCII_PREFIX, cls.JIS: cls._JIS_PREFIX, cls.UNICODE: cls._UNICODE_PREFIX}[encoding]
internal_encoding = {cls.UNICODE: cls._UNICODE, cls.JIS: cls._JIS}.get(encoding, encoding)
return prefix + data.encode(internal_encoding, errors='replace') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fs(path):
"""Find the file system implementation for this path.""" |
scheme = ''
if '://' in path:
scheme = path.partition('://')[0]
for schemes, fs_class in FILE_EXTENSIONS:
if scheme in schemes:
return fs_class
return FileSystem |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def awaitTermination(self, timeout=None):
"""Wait for context to stop. :param float timeout: in seconds """ |
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop)
IOLoop.current().start()
IOLoop.clear_current() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def binaryRecordsStream(self, directory, recordLength=None, process_all=False):
"""Monitor a directory and process all binary files. File names starting with ``.`` are ignored. :param string directory: a path :param recordLength: None, int or struct format string :param bool process_all: whether to process pre-existing files :rtype: DStream .. warning:: Only ``int`` ``recordLength`` are supported in PySpark API. The ``process_all`` parameter does not exist in the PySpark API. """ |
deserializer = FileBinaryStreamDeserializer(self._context,
recordLength)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def queueStream(self, rdds, oneAtATime=True, default=None):
"""Create stream iterable over RDDs. :param rdds: Iterable over RDDs or lists. :param oneAtATime: Process one at a time or all. :param default: If no more RDDs in ``rdds``, return this. Can be None. :rtype: DStream Example: [4] [2] [7] Example testing the default value: [4] [2] ['placeholder'] """ |
deserializer = QueueStreamDeserializer(self._context)
if default is not None:
default = deserializer(default)
if Queue is False:
log.error('Run "pip install tornado" to install tornado.')
q = Queue()
for i in rdds:
q.put(i)
qstream = QueueStream(q, oneAtATime, default)
return DStream(qstream, self, deserializer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def socketBinaryStream(self, hostname, port, length):
"""Create a TCP socket server for binary input. .. warning:: This is not part of the PySpark API. :param string hostname: Hostname of TCP server. :param int port: Port of TCP server. :param length: Message length. Length in bytes or a format string for ``struct.unpack()``. For variable length messages where the message length is sent right before the message itself, ``length`` is a format string that can be passed to ``struct.unpack()``. For example, use ``length='<I'`` for a little-endian (standard on x86) 32-bit unsigned int. :rtype: DStream """ |
deserializer = TCPDeserializer(self._context)
tcp_binary_stream = TCPBinaryStream(length)
tcp_binary_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_binary_stream.stop)
return DStream(tcp_binary_stream, self, deserializer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def socketTextStream(self, hostname, port):
"""Create a TCP socket server. :param string hostname: Hostname of TCP server. :param int port: Port of TCP server. :rtype: DStream """ |
deserializer = TCPDeserializer(self._context)
tcp_text_stream = TCPTextStream()
tcp_text_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_text_stream.stop)
return DStream(tcp_text_stream, self, deserializer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start(self):
"""Start processing streams.""" |
def cb():
time_ = time.time()
log.debug('Step {}'.format(time_))
# run a step on all streams
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)
self._pcb.start()
self._on_stop_cb.append(self._pcb.stop)
StreamingContext._activeContext = self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop(self, stopSparkContext=True, stopGraceFully=False):
"""Stop processing streams. :param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED) :param stopGracefully: stop gracefully (NOT IMPLEMENTED) """ |
while self._on_stop_cb:
cb = self._on_stop_cb.pop()
log.debug('calling on_stop_cb {}'.format(cb))
cb()
IOLoop.current().stop()
StreamingContext._activeContext = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def textFileStream(self, directory, process_all=False):
"""Monitor a directory and process all text files. File names starting with ``.`` are ignored. :param string directory: a path :param bool process_all: whether to process pre-existing files :rtype: DStream .. warning:: The ``process_all`` parameter does not exist in the PySpark API. """ |
deserializer = FileTextStreamDeserializer(self._context)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_codec(path):
"""Find the codec implementation for this path.""" |
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in FILE_ENDINGS:
if any(path.endswith(e) for e in endings):
log.debug('Using {0} codec: {1}'.format(endings, path))
return codec_class
return NoCodec |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self):
"""Count elements per RDD. Creates a new RDD stream where each RDD has a single entry that is the count of the elements. :rtype: DStream """ |
return (
self
.mapPartitions(lambda p: [sum(1 for _ in p)])
.reduce(operator.add)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def countByValue(self):
"""Apply countByValue to every RDD.abs :rtype: DStream .. warning:: Implemented as a local operation. Example: [(1, 2), (2, 1), (5, 3)] """ |
return self.transform(
lambda rdd: self._context._context.parallelize(
rdd.countByValue().items())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatMap(self, f, preservesPartitioning=False):
"""Apply function f and flatten. :param f: mapping function :rtype: DStream """ |
return self.mapPartitions(
lambda p: (e for pp in p for e in f(pp)),
preservesPartitioning,
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(self, f, preservesPartitioning=False):
"""Apply function f :param f: mapping function :rtype: DStream Example: [5] [3] [8] """ |
return (
self
.mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mapPartitions(self, f, preservesPartitioning=False):
"""Map partitions. :param f: mapping function :rtype: DStream """ |
return (
self
.mapPartitionsWithIndex(lambda i, p: f(p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pprint(self, num=10):
"""Print the first ``num`` elements of each RDD. :param int num: Set number of elements to be printed. """ |
def pprint_map(time_, rdd):
print('>>> Time: {}'.format(time_))
data = rdd.take(num + 1)
for d in data[:num]:
py_pprint.pprint(d)
if len(data) > num:
print('...')
print('')
self.foreachRDD(pprint_map) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduce(self, func):
"""Return a new DStream where each RDD was reduced with ``func``. :rtype: DStream """ |
# avoid RDD.reduce() which does not return an RDD
return self.transform(
lambda rdd: (
rdd
.map(lambda i: (None, i))
.reduceByKey(func)
.map(lambda none_i: none_i[1])
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reduceByKey(self, func, numPartitions=None):
"""Apply reduceByKey to every RDD. :param func: reduce function to apply :param int numPartitions: number of partitions :rtype: DStream """ |
return self.transform(lambda rdd: rdd.reduceByKey(func)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def repartition(self, numPartitions):
"""Repartition every RDD. :rtype: DStream Example: 2 0 """ |
return self.transform(
lambda rdd: (rdd.repartition(numPartitions)
if not isinstance(rdd, EmptyRDD) else rdd)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def slice(self, begin, end):
"""Filter RDDs to between begin and end. :param datetime.datetime|int begin: datetiem or unix timestamp :param datetime.datetime|int end: datetiem or unix timestamp :rtype: DStream """ |
return self.transform(lambda time_, rdd:
rdd if begin <= time_ <= end
else EmptyRDD(self._context._context)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def union(self, other):
"""Union of two DStreams. :param DStream other: Another DStream. Example: [1, 2] [3, 4] [5, 6] """ |
def union_rdds(rdd_a, rdd_b):
return self._context._context.union((rdd_a, rdd_b))
return self.transformWith(union_rdds, other) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_filenames(all_expr):
"""resolve expression for a filename :param all_expr: A comma separated list of expressions. The expressions can contain the wildcard characters ``*`` and ``?``. It also resolves Spark datasets to the paths of the individual partitions (i.e. ``my_data`` gets resolved to ``[my_data/part-00000, my_data/part-00001]``). :returns: A list of file names. :rtype: list """ |
files = []
for expr in all_expr.split(','):
expr = expr.strip()
files += fs.get_fs(expr).resolve_filenames(expr)
log.debug('Filenames: {0}'.format(files))
return files |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def database_caller_creator(self, host, port, name=None):
'''creates a mongodb database
returns the related connection object
which will be later used to spawn the cursor
'''
client = pymongo.MongoClient(host, port)
if name:
db = client[name]
else:
db = client['mongodb_' + str_generator(self)]
return db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def database_caller_creator(self, host, port, name=None):
'''creates a redis connection object
which will be later used to modify the db
'''
name = name or 0
client = redis.StrictRedis(host=host, port=port, db=name)
pipe = client.pipeline(transaction=False)
return client, pipe |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_simple_registration(self, number_of_rows, pipe):
'''creates keys with simple regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('simple_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False)
})
pipe.execute()
logger.warning('simple_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_detailed_registration(self, number_of_rows, pipe):
'''creates keys with detailed regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('detailed_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False),
'lastname': self.faker.last_name(),
'name': self.faker.first_name(),
'address': self.faker.address(),
'phone': self.faker.phone_number()
})
pipe.execute()
logger.warning('detailed_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_user_agent(self, number_of_rows, pipe):
'''creates keys with user agent data
'''
try:
for i in range(number_of_rows):
pipe.hmset('user_agent:%s' % i, {
'id': rnd_id_generator(self),
'ip': self.faker.ipv4(),
'countrycode': self.faker.country_code(),
'useragent': self.faker.user_agent()
})
pipe.execute()
logger.warning('user_agent Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_company(self, number_of_rows, pipe):
'''creates keys with company data
'''
try:
for i in range(number_of_rows):
pipe.hmset('company:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.company(),
'date': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.company_email(),
'domain': self.faker.safe_email(),
'city': self.faker.city()
})
pipe.execute()
logger.warning('companies Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_customer(self, number_of_rows, pipe):
'''creates keys with customer data
'''
try:
for i in range(number_of_rows):
pipe.hmset('customer:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.first_name(),
'lastname': self.faker.last_name(),
'address': self.faker.address(),
'country': self.faker.country(),
'city': self.faker.city(),
'registry_date': self.faker.date(pattern="%d-%m-%Y"),
'birthdate': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.safe_email(),
'phone_number': self.faker.phone_number(),
'locale': self.faker.locale()
})
pipe.execute()
logger.warning('customer Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None):
'''creates a postgresql db
returns the related connection object
which will be later used to spawn the cursor
'''
cursor = None
conn = None
if name:
dbname = name
else:
dbname = 'postgresql_' + str_generator(self).lower()
try:
# createdb
conn = psycopg2.connect(
user=username, password=password, host=host, port=port)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute('CREATE DATABASE %s;' % dbname)
cur.close()
conn.close()
# reconnect to the new database
conn = psycopg2.connect(user=username, password=password,
host=host, port=port, database=dbname)
cursor = conn.cursor()
logger.warning('Database created and opened succesfully: %s' % dbname, extra=d)
except Exception as err:
logger.error(err, extra=d)
raise
if custom:
self.custom_db_creator(number_of_rows, cursor, conn, custom)
cursor.close()
conn.close()
sys.exit(0)
return cursor, conn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_customer(self, number_of_rows, cursor, conn):
'''creates and fills the table with customer
'''
customer_data = []
try:
for i in range(0, number_of_rows):
customer_data.append((
rnd_id_generator(self), self.faker.first_name(), self.faker.last_name(), self.faker.address(),
self.faker.country(), self.faker.city(), self.faker.date(pattern="%d-%m-%Y"),
self.faker.date(pattern="%d-%m-%Y"), self.faker.safe_email(), self.faker.phone_number(),
self.faker.locale()))
customer_payload = ("INSERT INTO customer "
"(id, name, lastname, address, country, city, registry_date, birthdate, email, "
"phone_number, locale)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
cursor.executemany(customer_payload, customer_data)
conn.commit()
logger.warning('detailed_registration Commits are successful after write job!', extra=extra_information)
except Exception as e:
logger.error(e, extra=extra_information) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _mysqld_process_checkpoint():
'''this helper method checks if
mysql server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep mysqld", shell=True)
except Exception:
logger.warning(
'Your mysql server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("mysqld", close_fds=True, shell=True)
time.sleep(3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _redis_process_checkpoint(host, port):
'''this helper method checks if
redis server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep redis", shell=True)
except Exception:
logger.warning(
'Your redis server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("redis-server --bind %s --port %s" % (host, port),
close_fds=True,
shell=True)
time.sleep(3) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def database_caller_creator(self, name=None):
'''creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor
'''
try:
if name:
database = name + '.db'
else:
database = 'sqlite_' + str_generator(self) + '.db'
conn = sqlite3.connect(database)
logger.warning('Database created and opened succesfully: %s' % database, extra=d)
except Exception:
logger.error('Failed to connect or create database / sqlite3', extra=d)
raise DbConnException
return conn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def database_caller_creator(self, name=None):
'''creates a couchdb database
returns the related connection object
which will be later used to spawn the cursor
'''
couch = couchdb.Server()
if name:
db = couch.create(name)
else:
n = 'couchdb_' + lower_str_generator(self)
db = couch.create(n)
logger.warning('couchdb database created with the name: %s', n,
extra=d)
return db |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_detailed_registration(self, number_of_rows, db):
'''creates and fills the table with detailed regis. information
'''
try:
detailed_registration = db
data_list = list()
for i in range(0, number_of_rows):
post_det_reg = {
"id": rnd_id_generator(self),
"email": self.faker.safe_email(),
"password": self.faker.md5(raw_output=False),
"lastname": self.faker.last_name(),
"name": self.faker.first_name(),
"adress": self.faker.address(),
"phone": self.faker.phone_number()
}
detailed_registration.save(post_det_reg)
logger.warning(
'detailed_registration Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def data_filler_customer(self, number_of_rows, db):
'''creates and fills the table with customer data
'''
try:
customer = db
data_list = list()
for i in range(0, number_of_rows):
post_cus_reg = {
"id": rnd_id_generator(self),
"name": self.faker.first_name(),
"lastname": self.faker.last_name(),
"address": self.faker.address(),
"country": self.faker.country(),
"city": self.faker.city(),
"registry_date": self.faker.date(pattern="%d-%m-%Y"),
"birthdate": self.faker.date(pattern="%d-%m-%Y"),
"email": self.faker.safe_email(),
"phone_number": self.faker.phone_number(),
"locale": self.faker.locale()
}
customer.save(post_cus_reg)
logger.warning('customer Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit(self, node):
"""Walk a parse tree, transforming it into another representation. Recursively descend a parse tree, dispatching to the method named after the rule in the :class:`~parsimonious.grammar.Grammar` that produced bold = '<b>' responsibility to subclass :class:`NodeVisitor` and implement those methods. """ |
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where in the tree it failed if it blows
# up.
try:
return method(node, [self.visit(n) for n in node])
except (VisitationError, UndefinedLabel):
# Don't catch and re-wrap already-wrapped exceptions.
raise
except self.unwrapped_exceptions:
raise
except Exception:
# Catch any exception, and tack on a parse tree so it's easier to
# see where it went wrong.
exc_class, exc, tb = exc_info()
reraise(VisitationError, VisitationError(exc, exc_class, node), tb) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_or_match(self, text, pos, method_name):
"""Execute a parse or match on the default grammar, followed by a visitation. Raise RuntimeError if there is no default grammar specified. """ |
if not self.grammar:
raise RuntimeError(
"The {cls}.{method}() shortcut won't work because {cls} was "
"never associated with a specific " "grammar. Fill out its "
"`grammar` attribute, and try again.".format(
cls=self.__class__.__name__,
method=method_name))
return self.visit(getattr(self.grammar, method_name)(text, pos=pos)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _expressions_from_rules(self, rule_syntax, custom_rules):
"""Return the rules for parsing the grammar definition syntax. Return a 2-tuple: a dict of rule names pointing to their expressions, and then the top-level expression for the first rule. """ |
# Hard-code enough of the rules to parse the grammar that describes the
# grammar description language, to bootstrap:
comment = Regex(r'#[^\r\n]*', name='comment')
meaninglessness = OneOf(Regex(r'\s+'), comment, name='meaninglessness')
_ = ZeroOrMore(meaninglessness, name='_')
equals = Sequence(Literal('='), _, name='equals')
label = Sequence(Regex(r'[a-zA-Z_][a-zA-Z_0-9]*'), _, name='label')
reference = Sequence(label, Not(equals), name='reference')
quantifier = Sequence(Regex(r'[*+?]'), _, name='quantifier')
# This pattern supports empty literals. TODO: A problem?
spaceless_literal = Regex(r'u?r?"[^"\\]*(?:\\.[^"\\]*)*"',
ignore_case=True,
dot_all=True,
name='spaceless_literal')
literal = Sequence(spaceless_literal, _, name='literal')
regex = Sequence(Literal('~'),
literal,
Regex('[ilmsuxa]*', ignore_case=True),
_,
name='regex')
atom = OneOf(reference, literal, regex, name='atom')
quantified = Sequence(atom, quantifier, name='quantified')
term = OneOf(quantified, atom, name='term')
not_term = Sequence(Literal('!'), term, _, name='not_term')
term.members = (not_term,) + term.members
sequence = Sequence(term, OneOrMore(term), name='sequence')
or_term = Sequence(Literal('/'), _, term, name='or_term')
ored = Sequence(term, OneOrMore(or_term), name='ored')
expression = OneOf(ored, sequence, term, name='expression')
rule = Sequence(label, equals, expression, name='rule')
rules = Sequence(_, OneOrMore(rule), name='rules')
# Use those hard-coded rules to parse the (more extensive) rule syntax.
# (For example, unless I start using parentheses in the rule language
# definition itself, I should never have to hard-code expressions for
# those above.)
rule_tree = rules.parse(rule_syntax)
# Turn the parse tree into a map of expressions:
return RuleVisitor().visit(rule_tree) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_parenthesized(self, node, parenthesized):
"""Treat a parenthesized subexpression as just its contents. Its position in the tree suffices to maintain its grouping semantics. """ |
left_paren, _, expression, right_paren, _ = parenthesized
return expression |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_rule(self, node, rule):
"""Assign a name to the Expression and return it.""" |
label, equals, expression = rule
expression.name = label # Assign a name to the expr.
return expression |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def visit_regex(self, node, regex):
"""Return a ``Regex`` expression.""" |
tilde, literal, flags, _ = regex
flags = flags.text.upper()
pattern = literal.literal # Pull the string back out of the Literal
# object.
return Regex(pattern, ignore_case='I' in flags,
locale='L' in flags,
multiline='M' in flags,
dot_all='S' in flags,
unicode='U' in flags,
verbose='X' in flags,
ascii='A' in flags) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _resolve_refs(self, rule_map, expr, done):
"""Return an expression with all its lazy references recursively resolved. Resolve any lazy references in the expression ``expr``, recursing into all subexpressions. :arg done: The set of Expressions that have already been or are currently being resolved, to ward off redundant work and prevent infinite recursion for circular refs """ |
if isinstance(expr, LazyReference):
label = text_type(expr)
try:
reffed_expr = rule_map[label]
except KeyError:
raise UndefinedLabel(expr)
return self._resolve_refs(rule_map, reffed_expr, done)
else:
if getattr(expr, 'members', ()) and expr not in done:
# Prevents infinite recursion for circular refs. At worst, one
# of `expr.members` can refer back to `expr`, but it can't go
# any farther.
done.add(expr)
expr.members = tuple(self._resolve_refs(rule_map, member, done)
for member in expr.members)
return expr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expression(callable, rule_name, grammar):
"""Turn a plain callable into an Expression. The callable can be of this simple form:: def foo(text, pos):
'''If this custom expression matches starting at text[pos], return the index where it stops matching. Otherwise, return None.''' if the expression matched: return end_pos If there child nodes to return, return a tuple:: return end_pos, children return None If your callable needs to make sub-calls to other rules in the grammar or do error reporting, it can take this form, gaining additional arguments:: def foo(text, pos, cache, error, grammar):
# Call out to other rules: node = grammar['another_rule'].match_core(text, pos, cache, error) # Return values as above. The return value of the callable, if an int or a tuple, will be automatically transmuted into a :class:`~parsimonious.Node`. If it returns a Node-like class directly, it will be passed through unchanged. :arg rule_name: The rule name to attach to the resulting :class:`~parsimonious.Expression` :arg grammar: The :class:`~parsimonious.Grammar` this expression will be a part of, to make delegating to other rules possible """ |
num_args = len(getargspec(callable).args)
if num_args == 2:
is_simple = True
elif num_args == 5:
is_simple = False
else:
raise RuntimeError("Custom rule functions must take either 2 or 5 "
"arguments, not %s." % num_args)
class AdHocExpression(Expression):
def _uncached_match(self, text, pos, cache, error):
result = (callable(text, pos) if is_simple else
callable(text, pos, cache, error, grammar))
if isinstance(result, integer_types):
end, children = result, None
elif isinstance(result, tuple):
end, children = result
else:
# Node or None
return result
return Node(self, text, pos, end, children=children)
def _as_rhs(self):
return '{custom function "%s"}' % callable.__name__
return AdHocExpression(name=rule_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match.""" |
m = self.re.match(text, pos)
if m is not None:
span = m.span()
node = RegexNode(self, text, pos, pos + span[1] - span[0])
node.match = m # TODO: A terrible idea for cache size?
return node |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _regex_flags_from_bits(self, bits):
"""Return the textual equivalent of numerically encoded regex flags.""" |
flags = 'ilmsuxa'
return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _gegetate_args(self, options):
""" Generator of args parts based on options specification. """ |
for optkey, optval in self._normalize_options(options):
yield optkey
if isinstance(optval, (list, tuple)):
assert len(optval) == 2 and optval[0] and optval[
1], 'Option value can only be either a string or a (tuple, list) of 2 items'
yield optval[0]
yield optval[1]
else:
yield optval |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_options_in_meta(self, content):
"""Reads 'content' and extracts options encoded in HTML meta tags :param content: str or file-like object - contains HTML to parse returns: dict: {config option: value} """ |
if (isinstance(content, io.IOBase)
or content.__class__.__name__ == 'StreamReaderWriter'):
content = content.read()
found = {}
for x in re.findall('<meta [^>]*>', content):
if re.search('name=["\']%s' % self.config.meta_tag_prefix, x):
name = re.findall('name=["\']%s([^"\']*)' %
self.config.meta_tag_prefix, x)[0]
found[name] = re.findall('content=["\']([^"\']*)', x)[0]
return found |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def authenticate_credentials(self, token):
'''
Due to the random nature of hashing a salted value, this must inspect
each auth_token individually to find the correct one.
Tokens that have expired will be deleted and skipped
'''
msg = _('Invalid token.')
token = token.decode("utf-8")
for auth_token in AuthToken.objects.filter(
token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
if self._cleanup_token(auth_token):
continue
try:
digest = hash_token(token, auth_token.salt)
except (TypeError, binascii.Error):
raise exceptions.AuthenticationFailed(msg)
if compare_digest(digest, auth_token.digest):
if knox_settings.AUTO_REFRESH and auth_token.expiry:
self.renew_token(auth_token)
return self.validate_user(auth_token)
raise exceptions.AuthenticationFailed(msg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def Check(self, stream):
"""Implements synchronous periodic checks""" |
request = await stream.recv_message()
checks = self._checks.get(request.service)
if checks is None:
await stream.send_trailing_metadata(status=Status.NOT_FOUND)
elif len(checks) == 0:
await stream.send_message(HealthCheckResponse(
status=HealthCheckResponse.SERVING,
))
else:
for check in checks:
await check.__check__()
await stream.send_message(HealthCheckResponse(
status=_status(checks),
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set(self, value: Optional[bool]):
"""Sets current status of a check :param value: ``True`` (healthy), ``False`` (unhealthy), or ``None`` (unknown) """ |
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all watchers that this check was changed
for event in self._events:
event.set() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def graceful_exit(servers, *, loop, signals=frozenset({signal.SIGINT, signal.SIGTERM})):
"""Utility context-manager to help properly shutdown server in response to the OS signals By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals. There are two stages: 1. first received signal closes servers 2. subsequent signals raise ``SystemExit`` exception Example: .. code-block:: python3 with graceful_exit([server], loop=loop):
await server.start(host, port) print('Serving on {}:{}'.format(host, port)) await server.wait_closed() print('Server closed') First stage calls ``server.close()`` and ``await server.wait_closed()`` should complete successfully without errors. If server wasn't started yet, second stage runs to prevent server start. Second stage raises ``SystemExit`` exception, but you will receive ``asyncio.CancelledError`` in your ``async def main()`` coroutine. You can use ``try..finally`` constructs and context-managers to properly handle this error. This context-manager is designed to work in cooperation with :py:func:`python:asyncio.run` function: .. code-block:: python3 if __name__ == '__main__': asyncio.run(main()) :param servers: list of servers :param loop: asyncio-compatible event loop :param signals: set of the OS signals to handle """ |
signals = set(signals)
flag = []
for sig_num in signals:
loop.add_signal_handler(sig_num, _exit_handler, sig_num, servers, flag)
try:
yield
finally:
for sig_num in signals:
loop.remove_signal_handler(sig_num) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def recv_message(self):
"""Coroutine to receive incoming message from the client. If client sends UNARY request, then you can call this coroutine only once. If client sends STREAM request, then you should call this coroutine several times, until it returns None. To simplify your code in this case, :py:class:`Stream` class implements async iteration protocol, so you can use it like this: .. code-block:: python3 async for massage in stream: do_smth_with(message) or even like this: .. code-block:: python3 messages = [msg async for msg in stream] HTTP/2 has flow control mechanism, so server will acknowledge received DATA frames as a message only after user consumes this coroutine. :returns: message """ |
message = await recv_message(self._stream, self._codec, self._recv_type)
message, = await self._dispatch.recv_message(message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_initial_metadata(self, *, metadata=None):
"""Coroutine to send headers with initial metadata to the client. In gRPC you can send initial metadata as soon as possible, because gRPC doesn't use `:status` pseudo header to indicate success or failure of the current request. gRPC uses trailers for this purpose, and trailers are sent during :py:meth:`send_trailing_metadata` call, which should be called in the end. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before explicitly. :param metadata: custom initial metadata, dict or list of pairs """ |
if self._send_initial_metadata_done:
raise ProtocolError('Initial metadata was already sent')
headers = [
(':status', '200'),
('content-type', self._content_type),
]
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_initial_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers)
self._send_initial_metadata_done = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_message(self, message, **kwargs):
"""Coroutine to send message to the client. If server sends UNARY response, then you should call this coroutine only once. If server sends STREAM response, then you can call this coroutine as many times as you need. :param message: message object """ |
if 'end' in kwargs:
warnings.warn('"end" argument is deprecated, use '
'"stream.send_trailing_metadata" explicitly',
stacklevel=2)
end = kwargs.pop('end', False)
assert not kwargs, kwargs
if not self._send_initial_metadata_done:
await self.send_initial_metadata()
if not self._cardinality.server_streaming:
if self._send_message_count:
raise ProtocolError('Server should send exactly one message '
'in response')
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message, self._send_type)
self._send_message_count += 1
if end:
await self.send_trailing_metadata() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_trailing_metadata(self, *, status=Status.OK, status_message=None, metadata=None):
"""Coroutine to send trailers with trailing metadata to the client. This coroutine allows sending trailers-only responses, in case of some failure conditions during handling current request, i.e. when ``status is not OK``. .. note:: This coroutine will be called implicitly at exit from request handler, with appropriate status code, if not called explicitly during handler execution. :param status: resulting status of this coroutine call :param status_message: description for a status :param metadata: custom trailing metadata, dict or list of pairs """ |
if self._send_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already sent')
if (
not self._cardinality.server_streaming
and not self._send_message_count
and status is Status.OK
):
raise ProtocolError('Unary response with OK status requires '
'a single message to be sent')
if self._send_initial_metadata_done:
headers = []
else:
# trailers-only response
headers = [(':status', '200')]
headers.append(('grpc-status', str(status.value)))
if status_message is not None:
headers.append(('grpc-message',
encode_grpc_message(status_message)))
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_trailing_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers, end_stream=True)
self._send_trailing_metadata_done = True
if status != Status.OK and self._stream.closable:
self._stream.reset_nowait() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def start(self, host=None, port=None, *, path=None, family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE, sock=None, backlog=100, ssl=None, reuse_address=None, reuse_port=None):
"""Coroutine to start the server. :param host: can be a string, containing IPv4/v6 address or domain name. If host is None, server will be bound to all available interfaces. :param port: port number. :param path: UNIX domain socket path. If specified, host and port should be omitted (must be None). :param family: can be set to either :py:data:`python:socket.AF_INET` or :py:data:`python:socket.AF_INET6` to force the socket to use IPv4 or IPv6. If not set it will be determined from host. :param flags: is a bitmask for :py:meth:`~python:asyncio.AbstractEventLoop.getaddrinfo`. :param sock: sock can optionally be specified in order to use a preexisting socket object. If specified, host and port should be omitted (must be None). :param backlog: is the maximum number of queued connections passed to listen(). :param ssl: can be set to an :py:class:`~python:ssl.SSLContext` to enable SSL over the accepted connections. :param reuse_address: tells the kernel to reuse a local socket in TIME_WAIT state, without waiting for its natural timeout to expire. :param reuse_port: tells the kernel to allow this endpoint to be bound to the same port as other existing endpoints are bound to, so long as they all set this flag when being created. """ |
if path is not None and (host is not None or port is not None):
raise ValueError("The 'path' parameter can not be used with the "
"'host' or 'port' parameters.")
if self._server is not None:
raise RuntimeError('Server is already started')
if path is not None:
self._server = await self._loop.create_unix_server(
self._protocol_factory, path, sock=sock, backlog=backlog,
ssl=ssl
)
else:
self._server = await self._loop.create_server(
self._protocol_factory, host, port,
family=family, flags=flags, sock=sock, backlog=backlog, ssl=ssl,
reuse_address=reuse_address, reuse_port=reuse_port
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Stops accepting new connections, cancels all currently running requests. Request handlers are able to handle `CancelledError` and exit properly. """ |
if self._server is None:
raise RuntimeError('Server is not started')
self._server.close()
for handler in self._handlers:
handler.close() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def wait_closed(self):
"""Coroutine to wait until all existing request handlers will exit properly. """ |
if self._server is None:
raise RuntimeError('Server is not started')
await self._server.wait_closed()
if self._handlers:
await asyncio.wait({h.wait_closed() for h in self._handlers},
loop=self._loop) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_request(self):
"""Coroutine to send request headers with metadata to the server. New HTTP/2 stream will be created during this coroutine call. .. note:: This coroutine will be called implicitly during first :py:meth:`send_message` coroutine call, if not called before explicitly. """ |
if self._send_request_done:
raise ProtocolError('Request is already sent')
with self._wrapper:
protocol = await self._channel.__connect__()
stream = protocol.processor.connection\
.create_stream(wrapper=self._wrapper)
headers = [
(':method', 'POST'),
(':scheme', self._channel._scheme),
(':path', self._method_name),
(':authority', self._channel._authority),
]
if self._deadline is not None:
timeout = self._deadline.time_remaining()
headers.append(('grpc-timeout', encode_timeout(timeout)))
content_type = (GRPC_CONTENT_TYPE
+ '+' + self._codec.__content_subtype__)
headers.extend((
('te', 'trailers'),
('content-type', content_type),
('user-agent', USER_AGENT),
))
metadata, = await self._dispatch.send_request(
self._metadata,
method_name=self._method_name,
deadline=self._deadline,
content_type=content_type,
)
headers.extend(encode_metadata(metadata))
release_stream = await stream.send_request(
headers, _processor=protocol.processor,
)
self._stream = stream
self._release_stream = release_stream
self._send_request_done = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def send_message(self, message, *, end=False):
"""Coroutine to send message to the server. If client sends UNARY request, then you should call this coroutine only once. If client sends STREAM request, then you can call this coroutine as many times as you need. .. warning:: It is important to finally end stream from the client-side when you finished sending messages. You can do this in two ways: - specify ``end=True`` argument while sending last message - and last DATA frame will include END_STREAM flag; - call :py:meth:`end` coroutine after sending last message - and extra HEADERS frame with END_STREAM flag will be sent. First approach is preferred, because it doesn't require sending additional HTTP/2 frame. """ |
if not self._send_request_done:
await self.send_request()
if end and self._end_done:
raise ProtocolError('Stream was already ended')
with self._wrapper:
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message,
self._send_type, end=end)
self._send_message_count += 1
if end:
self._end_done = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def end(self):
"""Coroutine to end stream from the client-side. It should be used to finally end stream from the client-side when we're finished sending messages to the server and stream wasn't closed with last DATA frame. See :py:meth:`send_message` for more details. HTTP/2 stream will have half-closed (local) state after this coroutine call. """ |
if self._end_done:
raise ProtocolError('Stream was already ended')
if (
not self._cardinality.client_streaming
and not self._send_message_count
):
raise ProtocolError('Unary request requires a single message '
'to be sent')
await self._stream.end()
self._end_done = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def recv_initial_metadata(self):
"""Coroutine to wait for headers with initial metadata from the server. .. note:: This coroutine will be called implicitly during first :py:meth:`recv_message` coroutine call, if not called before explicitly. May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers-only response. When this coroutine finishes, you can access received initial metadata by using :py:attr:`initial_metadata` attribute. """ |
if not self._send_request_done:
raise ProtocolError('Request was not sent yet')
if self._recv_initial_metadata_done:
raise ProtocolError('Initial metadata was already received')
try:
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_initial_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_initial_metadata(metadata)
self.initial_metadata = metadata
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
content_type = headers_map.get('content-type')
if content_type is None:
raise GRPCError(Status.UNKNOWN,
'Missing content-type header')
base_content_type, _, sub_type = content_type.partition('+')
sub_type = sub_type or ProtoCodec.__content_subtype__
if (
base_content_type != GRPC_CONTENT_TYPE
or sub_type != self._codec.__content_subtype__
):
raise GRPCError(Status.UNKNOWN,
'Invalid content-type: {!r}'
.format(content_type))
except StreamTerminatedError:
# Server can send RST_STREAM frame right after sending trailers-only
# response, so we have to check received headers and probably raise
# more descriptive error
headers = self._stream.recv_headers_nowait()
if headers is None:
raise
else:
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
# If there are no errors in the headers, just reraise original
# StreamTerminatedError
raise |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def recv_message(self):
"""Coroutine to receive incoming message from the server. If server sends UNARY response, then you can call this coroutine only once. If server sends STREAM response, then you should call this coroutine several times, until it returns None. To simplify you code in this case, :py:class:`Stream` implements async iterations protocol, so you can use it like this: .. code-block:: python3 async for massage in stream: do_smth_with(message) or even like this: .. code-block:: python3 messages = [msg async for msg in stream] HTTP/2 has flow control mechanism, so client will acknowledge received DATA frames as a message only after user consumes this coroutine. :returns: message """ |
# TODO: check that messages were sent for non-stream-stream requests
if not self._recv_initial_metadata_done:
await self.recv_initial_metadata()
with self._wrapper:
message = await recv_message(self._stream, self._codec,
self._recv_type)
self._recv_message_count += 1
message, = await self._dispatch.recv_message(message)
return message |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
async def recv_trailing_metadata(self):
"""Coroutine to wait for trailers with trailing metadata from the server. .. note:: This coroutine will be called implicitly at exit from this call (context manager's exit), if not called before explicitly. May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers. When this coroutine finishes, you can access received trailing metadata by using :py:attr:`trailing_metadata` attribute. """ |
if not self._end_done:
raise ProtocolError('Outgoing stream was not ended')
if (
not self._cardinality.server_streaming
and not self._recv_message_count
):
raise ProtocolError('No messages were received before waiting '
'for trailing metadata')
if self._recv_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already received')
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_trailing_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_trailing_metadata(metadata)
self.trailing_metadata = metadata
self._raise_for_grpc_status(dict(headers)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self):
"""Closes connection to the server. """ |
if self._protocol is not None:
self._protocol.processor.close()
del self._protocol |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_config():
""" Reads and preprocesses the pydoc-markdown configuration file. """ |
with open(PYDOCMD_CONFIG) as fp:
config = yaml.load(fp)
return default_config(config) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_temp_mkdocs_config(inconf):
""" Generates a configuration for MkDocs on-the-fly from the pydoc-markdown configuration and makes sure it gets removed when this program exists. """ |
ignored_keys = ('gens_dir', 'pages', 'headers', 'generate', 'loader',
'preprocessor', 'additional_search_paths')
config = {key: value for key, value in inconf.items() if key not in ignored_keys}
config['docs_dir'] = inconf['gens_dir']
if 'pages' in inconf:
config['nav'] = inconf['pages']
with open('mkdocs.yml', 'w') as fp:
yaml.dump(config, fp)
atexit.register(lambda: os.remove('mkdocs.yml')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def import_object_with_scope(name):
""" Imports a Python object by an absolute identifier. # Arguments name (str):
The name of the Python object to import. # Returns (any, Module):
The object and the module that contains it. Note that for plain modules loaded with this function, both elements of the tuple may be the same object. """ |
# Import modules until we can no longer import them. Prefer existing
# attributes over importing modules at each step.
parts = name.split('.')
current_name = parts[0]
obj = import_module(current_name)
scope = None
for part in parts[1:]:
current_name += '.' + part
try:
if hasattr(obj, '__dict__'):
# Using directly __dict__ for descriptors, where we want to get the descriptor's instance
# and not calling the descriptor's __get__ method.
sub_obj = obj.__dict__[part]
else:
sub_obj = getattr(obj, part)
scope, obj = obj, sub_obj
except (AttributeError, KeyError):
try:
obj = scope = import_module(current_name)
except ImportError as exc:
if 'named {}'.format(part) in str(exc):
raise ImportError(current_name)
raise
return obj, scope |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def force_lazy_import(name):
""" Import any modules off of "name" by iterating a new list rather than a generator so that this library works with lazy imports. """ |
obj = import_object(name)
module_items = list(getattr(obj, '__dict__', {}).items())
for key, value in module_items:
if getattr(value, '__module__', None):
import_object(name + '.' + key) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocess_section(self, section):
""" Preprocessors a given section into it's components. """ |
lines = []
in_codeblock = False
keyword = None
components = {}
for line in section.content.split('\n'):
line = line.strip()
if line.startswith("```"):
in_codeblock = not in_codeblock
if not in_codeblock:
match = re.match(r':(?:param|parameter)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Arguments'
param = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(param, text))
components[keyword] = component
continue
match = re.match(r':(?:return|returns)\s*:(.*)?$', line)
if match:
keyword = 'Returns'
text = match.group(1)
text = text.strip()
component = components.get(keyword, [])
component.append(text)
components[keyword] = component
continue
match = re.match(':(?:raises|raise)\s+(\w+)\s*:(.*)?$', line)
if match:
keyword = 'Raises'
exception = match.group(1)
text = match.group(2)
text = text.strip()
component = components.get(keyword, [])
component.append('- `{}`: {}'.format(exception, text))
components[keyword] = component
continue
if keyword is not None:
components[keyword].append(line)
else:
lines.append(line)
for key in components:
self._append_section(lines, key, components)
section.content = '\n'.join(lines) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Go data Data keys handled here: _type Set the object class consts, types, vars, funcs Recurse into :py:meth:`create_class` to create child object instances :param data: dictionary data from godocjson output """ |
_type = kwargs.get("_type")
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
# Contextual type data from children recursion
if _type:
LOGGER.debug("Forcing Go Type %s" % _type)
cls = obj_map[_type]
else:
cls = obj_map[data["type"]]
except KeyError:
LOGGER.warning("Unknown Type: %s" % data)
else:
if cls.inverted_names and "names" in data:
# Handle types that have reversed names parameter
for name in data["names"]:
data_inv = {}
data_inv.update(data)
data_inv["name"] = name
if "names" in data_inv:
del data_inv["names"]
for obj in self.create_class(data_inv):
yield obj
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
for child_type in ["consts", "types", "vars", "funcs"]:
for child_data in data.get(child_type, []):
obj.children += list(
self.create_class(
child_data,
_type=child_type.replace("consts", "const")
.replace("types", "type")
.replace("vars", "variable")
.replace("funcs", "func"),
)
)
yield obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pathname(self):
"""Sluggified path for filenames Slugs to a filename using the follow steps * Decode unicode to approximate ascii * Remove existing hypens * Substitute hyphens for non-word characters * Break up the string as paths """ |
slug = self.name
slug = unidecode.unidecode(slug)
slug = slug.replace("-", "")
slug = re.sub(r"[^\w\.]+", "-", slug).strip("-")
return os.path.join(*slug.split(".")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include_dir(self, root):
"""Return directory of file""" |
parts = [root]
parts.extend(self.pathname.split(os.path.sep))
return "/".join(parts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def include_path(self):
"""Return 'absolute' path without regarding OS path separator This is used in ``toctree`` directives, as Sphinx always expects Unix path separators """ |
parts = [self.include_dir(root=self.url_root)]
parts.append("index")
return "/".join(parts) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_class(self, data, options=None, **kwargs):
"""Return instance of class based on Javascript data Data keys handled here: type Set the object class consts, types, vars, funcs Recurse into :py:meth:`create_class` to create child object instances :param data: dictionary data from godocjson output """ |
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["kind"]]
except (KeyError, TypeError):
LOGGER.warning("Unknown Type: %s" % data)
else:
# Recurse for children
obj = cls(data, jinja_env=self.jinja_env)
if "children" in data:
for child_data in data["children"]:
for child_obj in self.create_class(child_data, options=options):
obj.children.append(child_obj)
yield obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_class(self, data, options=None, path=None, **kwargs):
""" Return instance of class based on Roslyn type property Data keys handled here: type Set the object class items Recurse into :py:meth:`create_class` to create child object instances :param data: dictionary data from Roslyn output artifact """ |
obj_map = dict((cls.type, cls) for cls in ALL_CLASSES)
try:
cls = obj_map[data["type"].lower()]
except KeyError:
LOGGER.warning("Unknown type: %s" % data)
else:
obj = cls(
data,
jinja_env=self.jinja_env,
options=options,
url_root=self.url_root,
**kwargs
)
# Append child objects
# TODO this should recurse in the case we're getting back more
# complex argument listings
yield obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def organize_objects(self):
"""Organize objects and namespaces""" |
def _render_children(obj):
for child in obj.children_strings:
child_object = self.objects.get(child)
if child_object:
obj.item_map[child_object.plural].append(child_object)
obj.children.append(child_object)
for key in obj.item_map:
obj.item_map[key].sort()
def _recurse_ns(obj):
if not obj:
return
namespace = obj.top_namespace
if namespace is not None:
ns_obj = self.top_namespaces.get(namespace)
if ns_obj is None or not isinstance(ns_obj, DotNetNamespace):
for ns_obj in self.create_class(
{"uid": namespace, "type": "namespace"}
):
self.top_namespaces[ns_obj.id] = ns_obj
if obj not in ns_obj.children and namespace != obj.id:
ns_obj.children.append(obj)
for obj in self.objects.values():
_render_children(obj)
_recurse_ns(obj)
# Clean out dead namespaces
for key, ns in self.top_namespaces.copy().items():
if not ns.children:
del self.top_namespaces[key]
for key, ns in self.namespaces.items():
if not ns.children:
del self.namespaces[key] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transform_doc_comments(text):
""" Parse XML content for references and other syntax. This avoids an LXML dependency, we only need to parse out a small subset of elements here. Iterate over string to reduce regex pattern complexity and make substitutions easier .. seealso:: `Doc comment reference <https://msdn.microsoft.com/en-us/library/5ast78ax.aspx>` Reference on XML documentation comment syntax """ |
try:
while True:
found = DOC_COMMENT_SEE_PATTERN.search(text)
if found is None:
break
ref = found.group("attr_value").replace("<", "\<").replace("`", "\`")
reftype = "any"
replacement = ""
# Given the pattern of `\w:\w+`, inspect first letter of
# reference for identity type
if ref[1] == ":" and ref[0] in DOC_COMMENT_IDENTITIES:
reftype = DOC_COMMENT_IDENTITIES[ref[:1]]
ref = ref[2:]
replacement = ":{reftype}:`{ref}`".format(reftype=reftype, ref=ref)
elif ref[:2] == "!:":
replacement = ref[2:]
else:
replacement = ":any:`{ref}`".format(ref=ref)
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join([text_start, replacement, text_end])
while True:
found = DOC_COMMENT_PARAM_PATTERN.search(text)
if found is None:
break
# Escape following text
text_end = text[found.end() :]
text_start = text[: found.start()]
text_end = re.sub(r"^(\S)", r"\\\1", text_end)
text_start = re.sub(r"(\S)$", r"\1 ", text_start)
text = "".join(
[text_start, "``", found.group("attr_value"), "``", text_end]
)
except TypeError:
pass
return text |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_spec_identifier(self, obj_name):
"""Find reference name based on spec identifier Spec identifiers are used in parameter and return type definitions, but should be a user-friendly version instead. Use docfx ``references`` lookup mapping for resolution. If the spec identifier reference has a ``spec.csharp`` key, this implies a compound reference that should be linked in a special way. Resolve to a nested reference, with the corrected nodes. .. note:: This uses a special format that is interpreted by the domain for parameter type and return type fields. :param obj_name: spec identifier to resolve to a correct reference :returns: resolved string with one or more references :rtype: str """ |
ref = self.references.get(obj_name)
if ref is None:
return obj_name
resolved = ref.get("fullName", obj_name)
spec = ref.get("spec.csharp", [])
parts = []
for part in spec:
if part.get("name") == "<":
parts.append("{")
elif part.get("name") == ">":
parts.append("}")
elif "fullName" in part and "uid" in part:
parts.append("{fullName}<{uid}>".format(**part))
elif "uid" in part:
parts.append(part["uid"])
elif "fullName" in part:
parts.append(part["fullName"])
if parts:
resolved = "".join(parts)
return resolved |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display(self):
"""Whether this object should be displayed in documentation. This attribute depends on the configuration options given in :confval:`autoapi_options`. :type: bool """ |
if self.is_undoc_member and "undoc-members" not in self.options:
return False
if self.is_private_member and "private-members" not in self.options:
return False
if self.is_special_member and "special-members" not in self.options:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def summary(self):
"""The summary line of the docstring. The summary line is the first non-empty line, as-per :pep:`257`. This will be the empty string if the object does not have a docstring. :type: str """ |
for line in self.docstring.splitlines():
line = line.strip()
if line:
return line
return "" |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_import_alias(name, import_names):
"""Resolve a name from an aliased import to its original name. :param name: The potentially aliased name to resolve. :type name: str :param import_names: The pairs of original names and aliases from the import. :type import_names: iterable(tuple(str, str or None)) :returns: The original name. :rtype: str """ |
resolved_name = name
for import_name, imported_as in import_names:
if import_name == name:
break
if imported_as == name:
resolved_name = import_name
break
return resolved_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_full_import_name(import_from, name):
"""Get the full path of a name from a ``from x import y`` statement. :param import_from: The astroid node to resolve the name of. :type import_from: astroid.nodes.ImportFrom :param name: :type name: str :returns: The full import path of the name. :rtype: str """ |
partial_basename = resolve_import_alias(name, import_from.names)
module_name = import_from.modname
if import_from.level:
module = import_from.root()
assert isinstance(module, astroid.nodes.Module)
module_name = module.relative_to_absolute_name(
import_from.modname, level=import_from.level
)
return "{}.{}".format(module_name, partial_basename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_full_basename(node, basename):
"""Resolve a partial base name to the full path. :param node: The node representing the base name. :type node: astroid.NodeNG :param basename: The partial base name to resolve. :type basename: str :returns: The fully resolved base name. :rtype: str """ |
full_basename = basename
top_level_name = re.sub(r"\(.*\)", "", basename).split(".", 1)[0]
lookup_node = node
while not hasattr(lookup_node, "lookup"):
lookup_node = lookup_node.parent
assigns = lookup_node.lookup(top_level_name)[1]
for assignment in assigns:
if isinstance(assignment, astroid.nodes.ImportFrom):
import_name = get_full_import_name(assignment, top_level_name)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.Import):
import_name = resolve_import_alias(top_level_name, assignment.names)
full_basename = basename.replace(top_level_name, import_name, 1)
break
elif isinstance(assignment, astroid.nodes.ClassDef):
full_basename = "{}.{}".format(assignment.root().name, assignment.name)
break
if isinstance(node, astroid.nodes.Call):
full_basename = re.sub(r"\(.*\)", "()", full_basename)
if full_basename.startswith("builtins."):
return full_basename[len("builtins.") :]
if full_basename.startswith("__builtin__."):
return full_basename[len("__builtin__.") :]
return full_basename |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_full_basenames(bases, basenames):
"""Resolve the base nodes and partial names of a class to full names. :param bases: The astroid node representing something that a class inherits from. :type bases: iterable(astroid.NodeNG) :param basenames: The partial name of something that a class inherits from. :type basenames: iterable(str) :returns: The full names. :rtype: iterable(str) """ |
for base, basename in zip(bases, basenames):
yield get_full_basename(base, basename) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_assign_value(node):
"""Get the name and value of the assignment of the given node. Assignments to multiple names are ignored, as per PEP 257. :param node: The node to get the assignment value from. :type node: astroid.nodes.Assign or astroid.nodes.AnnAssign :returns: The name that is assigned to, and the value assigned to the name (if it can be converted). :rtype: tuple(str, object or None) or None """ |
try:
targets = node.targets
except AttributeError:
targets = [node.target]
if len(targets) == 1:
target = targets[0]
if isinstance(target, astroid.nodes.AssignName):
name = target.name
elif isinstance(target, astroid.nodes.AssignAttr):
name = target.attrname
else:
return None
return (name, _get_const_values(node.value))
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_assign_annotation(node):
"""Get the type annotation of the assignment of the given node. :param node: The node to get the annotation for. :type node: astroid.nodes.Assign or astroid.nodes.AnnAssign :returns: The type annotation as a string, or None if one does not exist. :type: str or None """ |
annotation = None
annotation_node = None
try:
annotation_node = node.annotation
except AttributeError:
# Python 2 has no support for type annotations, so use getattr
annotation_node = getattr(node, "type_annotation", None)
if annotation_node:
if isinstance(annotation_node, astroid.nodes.Const):
annotation = node.value
else:
annotation = annotation_node.as_string()
return annotation |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_decorated_with_property(node):
"""Check if the function is decorated as a property. :param node: The node to check. :type node: astroid.nodes.FunctionDef :returns: True if the function is a property, False otherwise. :rtype: bool """ |
if not node.decorators:
return False
for decorator in node.decorators.nodes:
if not isinstance(decorator, astroid.Name):
continue
try:
if _is_property_decorator(decorator):
return True
except astroid.InferenceError:
pass
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.