output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def dump(cursor):
""" Display the AST represented by the cursor
"""
def node_children(node):
return list(node.get_children())
def print_node(node):
text = node.spelling or node.displayname
kind = str(node.kind).split('.')[1]
return '{} {}'.format(kind, text)
return... | Write a Python 3 script to
display the tree represented by the cursor | You are a Python code generator, capable of creating scripts from specifications. |
def coerce_to_pendulum(x: PotentialDatetimeType,
assume_local: bool = False) -> Optional[DateTime]:
"""
Converts something to a :class:`pendulum.DateTime`.
Args:
x: something that may be coercible to a datetime
assume_local: if ``True``, assume local timezone; if ``Fa... | Implement a function in Python 3 to
convert something that may be coercible to a pendulum. DateTime or None. | As a python code expert, you are capable of creating scripts from specifications. |
Converts something to a pendulum. Date. | Make a summary of the following Python 3 code
def coerce_to_pendulum_date(x: PotentialDatetimeType,
assume_local: bool = False) -> Optional[Date]:
"""
Converts something to a :class:`pendulum.Date`.
Args:
x: something that may be coercible to a date
assume_local:... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a pendulum. datetime. DateTime object to a datetime object. | Can you generate a brief explanation for the following Python 3 code
def pendulum_to_datetime(x: DateTime) -> datetime.datetime:
return datetime.datetime(
x.year, x.month, x.day,
x.hour, x.minute, x.second, x.microsecond,
tzinfo=x.tzinfo
) | You are a Python code architect, reviewing and designing scalable and efficient code |
def pendulum_to_utc_datetime_without_tz(x: DateTime) -> datetime.datetime:
"""
Converts a Pendulum ``DateTime`` (which will have timezone information) to
a ``datetime.datetime`` that (a) has no timezone information, and (b) is
in UTC.
Example:
.. code-block:: python
import pendulum
... | Implement a Python 3 function for
converting a Pendulum datetime to a UTC datetime. | As a Python code composer, you craft elegant and concise scripts. |
Takes a pendulum. Date and returns a datetime. date. | Make a summary of the following Python 3 code
def pendulum_date_to_datetime_date(x: Date) -> datetime.date:
return datetime.date(year=x.year, month=x.month, day=x.day) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def pendulum_time_to_datetime_time(x: Time) -> datetime.time:
"""
Takes a :class:`pendulum.Time` and returns a :class:`datetime.time`.
Used, for example, where a database backend insists on
:class:`datetime.time`.
"""
return datetime.time(
hour=x.hour, minute=x.minute, second=x.second,
... | Write a Python 3 function that can
take a pendulum. Time and returns a datetime. time. | You are a Python code analyst, evaluating scripts for potential improvements. |
def format_datetime(d: PotentialDatetimeType,
fmt: str,
default: str = None) -> Optional[str]:
"""
Format a datetime with a ``strftime`` format specification string, or
return ``default`` if the input is ``None``.
"""
d = coerce_to_pendulum(d)
if d is None... | How would you implement a function in Python 3 that
formats a datetime with a strftime format specification string. | You are a Python code generator, capable of creating scripts from specifications. |
Returns a string representation of a datetime. timedelta object or a regular number. | Make a summary of the following Python 3 code
def strfdelta(tdelta: Union[datetime.timedelta, int, float, str],
fmt='{D:02}d {H:02}h {M:02}m {S:02}s',
inputtype='timedelta'):
"""
Convert a ``datetime.timedelta`` object or a regular number to a custom-
formatted string, just like ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert date or time to UTC. | How would you explain what the following Python 3 function does
def convert_datetime_to_utc(dt: PotentialDatetimeType) -> DateTime:
dt = coerce_to_pendulum(dt)
tz = get_tz_utc()
return dt.in_tz(tz) | You are a Python code generator, capable of creating scripts from specifications. |
def convert_datetime_to_local(dt: PotentialDatetimeType) -> DateTime:
"""
Convert date/time with timezone to local timezone.
"""
dt = coerce_to_pendulum(dt)
tz = get_tz_local()
return dt.in_tz(tz) | Write a Python 3 script for
converting date or time with timezone to local timezone. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the time between two dates or times expressed as strings. | Can you tell what is the following Python 3 function doing
def get_duration_h_m(start: Union[str, DateTime],
end: Union[str, DateTime],
default: str = "N/A") -> str:
"""
Calculate the time between two dates/times expressed as strings.
Args:
start: start dat... | As a python code expert, you are capable of creating scripts from specifications. |
def get_age(dob: PotentialDatetimeType,
when: PotentialDatetimeType,
default: str = "") -> Union[int, str]:
"""
Age (in whole years) at a particular date, or ``default``.
Args:
dob: date of birth
when: date/time at which to calculate age
default: value to ret... | Write a Python 3 function that can
return the age of the node in whole years. | You are a Python code generator, capable of creating scripts from specifications. |
Truncate a date to the first of the month. | Can you tell what is the following Python 3 function doing
def truncate_date_to_first_of_month(
dt: Optional[DateLikeType]) -> Optional[DateLikeType]:
"""
Change the day to the first of the month.
"""
if dt is None:
return None
return dt.replace(day=1) | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the UTC time now but without timezone information. | Make a summary of the following Python 3 code
def get_now_utc_notz_datetime() -> datetime.datetime:
now = datetime.datetime.utcnow()
return now.replace(tzinfo=None) | As a python code expert, you are capable of creating scripts from specifications. |
def coerce_to_datetime(x: Any) -> Optional[datetime.datetime]:
"""
Ensure an object is a :class:`datetime.datetime`, or coerce to one, or
raise :exc:`ValueError` or :exc:`OverflowError` (as per
http://dateutil.readthedocs.org/en/latest/parser.html).
"""
if x is None:
return None
elif... | How would you implement a function in Python 3 that
coerces an object to a datetime. datetime. | You are a Python code generator, capable of creating scripts from specifications. |
def request_from_context(context):
"""
Do http requests from context.
:param context: request context.
"""
new_context = copy.deepcopy(context)
assert new_context.method in ALLOWED_METHODS
new_context.url_path = generate_url_path(
new_context.url_path,
prefix=new_context.pr... | How would you code a function in Python 3 to
do http requests from context. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Clear the default values of the related objects. | Explain what the following Python 3 code does
def clear(self, *args):
for field in self.fields_to_clear + list(args):
setattr(self, field, None) | You are a Python code generator, capable of creating scripts from specifications. |
Sets the host for the cache entry. | Here you have a function in Python 3, explain what it does
def host(self, value):
scheme, host, port = get_hostname_parameters_from_url(value)
self._host = "%s://%s:%s" % (scheme, host, port) | You are a Python code analyst, evaluating scripts for potential improvements. |
def cookie(self, value):
"""
Set cookie.
:param value:
"""
if value and not value.is_empty():
self._cookie = value
else:
self._cookie = Cookie() | Write a Python 3 script for
setting cookie. :param value: | As a Python code composer, you craft elegant and concise scripts. |
Sets the default host for the class. | How would you explain what the following Python 3 function does
def set_default_host(cls, value):
if value is None:
cls.DEFAULT_HOST = "http://127.0.0.1:80"
else:
scheme, host, port = get_hostname_parameters_from_url(value)
cls.DEFAULT_HOST = "%s://%s:%s" % (scheme, h... | You are a Python code analyst, evaluating scripts for potential improvements. |
Sets the default proxy for the current object. | Can you generate a brief explanation for the following Python 3 code
def set_default_proxy(cls, value):
if value is None:
cls.DEFAULT_PROXY = None
else:
scheme, host, port = get_hostname_parameters_from_url(value)
cls.DEFAULT_PROXY = "%s://%s:%s" % (scheme, host, port... | As a python code expert, you are capable of creating scripts from specifications. |
Login abstract method with default implementation. | Explain what the following Python 3 code does
def login(self, **kwargs):
assert self.LOGIN_URL_PATH is not None
render_name = kwargs.pop("render", "json")
render = get_renderer(render_name)
params = parse_args(**kwargs)
return self.post(self.LOGIN_URL_PATH, body_params=params, r... | You are a Python code analyst, evaluating scripts for potential improvements. |
def nhs_check_digit(ninedigits: Union[str, List[Union[str, int]]]) -> int:
"""
Calculates an NHS number check digit.
Args:
ninedigits: string or list
Returns:
check digit
Method:
1. Multiply each of the first nine digits by the corresponding
digit weighting (see :const... | Can you implement a function in Python 3 that
calculates a check digit for the given nine digits. | You are a Python code analyst, evaluating scripts for potential improvements. |
Validates an integer as an NHS number. | How would you explain what the following Python 3 function does
def is_valid_nhs_number(n: int) -> bool:
if not isinstance(n, int):
log.debug("is_valid_nhs_number: parameter was not of integer type")
return False
s = str(n)
# Not 10 digits long?
if len(s) != 10:
log.debug("is_va... | You are a Python code analyst, evaluating scripts for potential improvements. |
def generate_random_nhs_number() -> int:
"""
Returns a random valid NHS number, as an ``int``.
"""
check_digit = 10 # NHS numbers with this check digit are all invalid
while check_digit == 10:
digits = [random.randint(1, 9)] # don't start with a zero
digits.extend([random.randint(0... | How would you implement a function in Python 3 that
generates a random valid NHS number as an integer. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generates a valid NHS number given the first 9 digits. | Explain what the following Python 3 code does
def generate_nhs_number_from_first_9_digits(first9digits: str) -> Optional[int]:
if len(first9digits) != 9:
log.warning("Not 9 digits")
return None
try:
first9int = int(first9digits)
except (TypeError, ValueError):
log.warning("No... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a validated NHS number from a string or None if the string is not a 10 - digit number. | Given the following Python 3 function, write the documentation
def nhs_number_from_text_or_none(s: str) -> Optional[int]:
# None in, None out.
funcname = "nhs_number_from_text_or_none: "
if not s:
log.debug(funcname + "incoming parameter was None")
return None
# (a) If it's not a 10-dig... | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns an e - mail message. | Explain what the following Python 3 code does
def make_email(from_addr: str,
date: str = None,
sender: str = "",
reply_to: Union[str, List[str]] = "",
to: Union[str, List[str]] = "",
cc: Union[str, List[str]] = "",
bcc: Union[str,... | You are a Python code analyst, evaluating scripts for potential improvements. |
def send_msg(from_addr: str,
to_addrs: Union[str, List[str]],
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
msg: email.mime.multipart.MIMEMultipart = None,
msg_string: str = None) -> No... | Write a Python 3 function that can
send an e - mail message to the specified addresses. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Sends an e - mail using the SMTP standard. | Explain what the following Python 3 code does
def send_email(from_addr: str,
host: str,
user: str,
password: str,
port: int = None,
use_tls: bool = True,
date: str = None,
sender: str = "",
reply_to: ... | As a python code expert, you are capable of creating scripts from specifications. |
Command - line processor. | Can you generate the documentation for the following Python 3 function
def main() -> None:
logging.basicConfig()
log.setLevel(logging.DEBUG)
parser = argparse.ArgumentParser(
description="Send an e-mail from the command line.")
parser.add_argument("sender", action="store",
... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_string(contents, name='tmp.cpp', **kwargs):
""" Parse a string of C/C++ code
"""
idx = clang.cindex.Index.create()
tu = idx.parse(name, unsaved_files=[(name, contents)], **kwargs)
return _ensure_parse_valid(tu) | Create a Python 3 function for
parsing a string of C ++ code into a sequence of unsaved C ++ code. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def parse(name, **kwargs):
""" Parse a C/C++ file
"""
idx = clang.cindex.Index.create()
assert os.path.exists(name)
tu = idx.parse(name, **kwargs)
return _ensure_parse_valid(tu) | Implement a function in Python 3 to
parse a C ++ file and return a tuple of the first element of the tuple. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a list of IP addresses as strings given the value of an HTTP X - Forwarded - For header or WSGI HTTP_X_FORWARDED - For header. | How would you explain what the following Python 3 function does
def ip_addresses_from_xff(value: str) -> List[str]:
if not value:
return []
return [x.strip() for x in value.split(",")] | You are a Python code analyst, evaluating scripts for potential improvements. |
def necessary(self) -> bool:
"""
Is any special handling (e.g. the addition of
:class:`ReverseProxiedMiddleware`) necessary for thie config?
"""
return any([
self.trusted_proxy_headers,
self.http_host,
self.remote_addr,
self.script_... | Write a Python 3 script to
am any special handling necessary for thie config? | As a Python code translator, you convert algorithms and pseudocode into Python. |
Queue a job in Rhumba | Explain what the following Python 3 code does
def queue(self, queue, message, params={}, uids=[]):
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
yield... | As a Python code composer, you craft elegant and concise scripts. |
def getResult(self, queue, uid, suid=None):
"""
Retrieve the result of a job from its ID
"""
if suid:
r = yield self.client.get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = yield self.client.get('rhumba.q.%s.%s' % (queue, uid))
if r:
... | Write a Python 3 script to
retrieve the result of a job from its ID. | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a dict of cluster nodes and their status information | Explain what the following Python 3 code does
def clusterStatus(self):
servers = yield self.client.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1].rsplit('.', 1)[0]
last = yield self.... | As a Python code analyst, you investigate and solve complex coding mysteries |
def queue(self, queue, message, params={}, uids=[]):
"""
Queue a job in Rhumba
"""
d = {
'id': uuid.uuid1().get_hex(),
'version': 1,
'message': message,
'params': params
}
if uids:
for uid in uids:
... | Can you implement a function in Python 3 that
queues a job in Rhumba | You are a Python code analyst, evaluating scripts for potential improvements. |
Retrieve the result of a job from its ID | Explain what the following Python 3 code does
def getResult(self, queue, uid, suid=None):
if suid:
r = self._get_client().get('rhumba.dq.%s.%s.%s' % (suid, queue, uid))
else:
r = self._get_client().get('rhumba.q.%s.%s' % (queue, uid))
if r:
return json.loads(... | As a Python code analyst, you investigate and solve complex coding mysteries |
def clusterStatus(self):
"""
Returns a dict of cluster nodes and their status information
"""
c = self._get_client()
servers = c.keys('rhumba.server.*.heartbeat')
d = {}
now = time.time()
for s in servers:
sname = s.split('.', 2)[-1]... | Can you implement a function in Python 3 that
returns a dict of cluster nodes and their status information | As a Python code composer, you craft elegant and concise scripts. |
def toposimplify(geojson, p):
"""
Convert geojson and simplify topology.
geojson is a dict representing geojson.
p is a simplification threshold value between 0 and 1.
"""
proc_out = subprocess.run(
['geo2topo'],
input=bytes(
json.... | Implement a Python 3 function for
converting geojson and simplify topology. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns the SQL Server product version of the current SQL Server instance. | Can you generate the documentation for the following Python 3 function
def get_sqlserver_product_version(engine: "Engine") -> Tuple[int]:
assert is_sqlserver(engine), (
"Only call get_sqlserver_product_version() for Microsoft SQL Server "
"instances."
)
sql = "SELECT CAST(SERVERPROPERTY('Pro... | As a python code expert, you are capable of creating scripts from specifications. |
def is_sqlserver_2008_or_later(engine: "Engine") -> bool:
"""
Is the SQLAlchemy :class:`Engine` an instance of Microsoft SQL Server,
version 2008 or later?
"""
if not is_sqlserver(engine):
return False
version_tuple = get_sqlserver_product_version(engine)
return version_tuple >= (SQL... | Can you implement a function in Python 3 that
is the SQLAlchemy Engine an instance of Microsoft SQL Server 2008 or later? | As a Python code analyst, you investigate and solve complex coding mysteries |
def add_ones(a):
"""Adds a column of 1s at the end of the array"""
arr = N.ones((a.shape[0],a.shape[1]+1))
arr[:,:-1] = a
return arr | Can you create a Python 3 function that
adds a column of 1s at the end of the array | As a Python code composer, you craft elegant and concise scripts. |
uninstall the hook if installed | How would you explain what the following Python 3 function does
def _uninstall(cls):
if cls._hook:
sys.meta_path.remove(cls._hook)
cls._hook = None | As a Python code composer, you craft elegant and concise scripts. |
add a couple of fsts to be superimposed on the given module | Make a summary of the following Python 3 code
def add(cls, module_name, fsts, composer):
'''
add a couple of fsts to be superimposed on the module given
by module_name as soon as it is imported.
internal - use featuremonkey.compose_later
'''
cls._to_compose.setdefault(mo... | You are a Python code analyst, evaluating scripts for potential improvements. |
Add a guard to the list of guards that can be imported for the given module. | Here you have a function in Python 3, explain what it does
def add(cls, module_name, msg=''):
'''
Until the guard is dropped again,
disallow imports of the module given by ``module_name``.
If the module is imported while the guard is in place
an ``ImportGuard`` is raised. An add... | As a Python code composer, you craft elegant and concise scripts. |
Removes a previously created guard on module_name. | Explain what the following Python 3 code does
def remove(cls, module_name):
module_guards = cls._guards.get(module_name, False)
if module_guards:
module_guards.pop()
cls._num_entries -= 1
if cls._num_entries < 1:
if cls._num_entries < 0:
... | As a python code expert, you are capable of creating scripts from specifications. |
Random selection from itertools. product(*args **kwds ) | Here you have a function in Python 3, explain what it does
def random_product(*args, repeat=1):
"Random selection from itertools.product(*args, **kwds)"
pools = [tuple(pool) for pool in args] * repeat
return tuple(random.choice(pool) for pool in pools) | As a Python code composer, you craft elegant and concise scripts. |
def copy(
self,
extractor=None,
needs=None,
store=None,
data_writer=None,
persistence=None,
extractor_args=None):
"""
Use self as a template to build a new feature, replacing
values in kwargs
"""
... | Can you write a function in Python 3 where it
creates a copy of this feature. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _can_compute(self, _id, persistence):
"""
Return true if this feature stored, or is unstored, but can be computed
from stored dependencies
"""
if self.store and self._stored(_id, persistence):
return True
if self.is_root:
return False
... | Can you write a function in Python 3 where it
returns True if this feature can be computed from stored dependencies. | As a Python code composer, you craft elegant and concise scripts. |
This method is used to build a partial version of the current node. | Given the following Python 3 function, write the documentation
def _partial(self, _id, features=None, persistence=None):
root = features is None
stored = self._stored(_id, persistence)
is_cached = self.store and stored
if self.store and not stored:
data_writer = None
... | You are a Python code generator, capable of creating scripts from specifications. |
Generator function that generates all rows from a cursor. | Here you have a function in Python 3, explain what it does
def genrows(cursor: Cursor, arraysize: int = 1000) \
-> Generator[List[Any], None, None]:
"""
Generate all rows from a cursor.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
Yields:
... | As a Python code composer, you craft elegant and concise scripts. |
Generate the first value in each row. | How would you explain what the following Python 3 function does
def genfirstvalues(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Any, None, None]:
"""
Generate the first value in each row.
Args:
cursor: the cursor
arraysize: split fetches into chunks of this many records
... | You are a Python code generator, capable of creating scripts from specifications. |
Generate all rows from a cursor as an ordered dict. | Here you have a function in Python 3, explain what it does
def gendicts(cursor: Cursor, arraysize: int = 1000) \
-> Generator[Dict[str, Any], None, None]:
"""
Generate all rows from a cursor as :class:`OrderedDict` objects.
Args:
cursor: the cursor
arraysize: split fetches into chun... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns all rows from a cursor as a list of OrderedDicts. | Can you generate the documentation for the following Python 3 function
def dictfetchall(cursor: Cursor) -> List[Dict[str, Any]]:
columns = get_fieldnames_from_cursor(cursor)
return [
OrderedDict(zip(columns, row))
for row in cursor.fetchall()
] | As a Python code composer, you craft elegant and concise scripts. |
def dictfetchone(cursor: Cursor) -> Optional[Dict[str, Any]]:
"""
Return the next row from a cursor as an :class:`OrderedDict`, or ``None``.
"""
columns = get_fieldnames_from_cursor(cursor)
row = cursor.fetchone()
if not row:
return None
return OrderedDict(zip(columns, row)) | Write a Python 3 script to
return the next row from a cursor as an OrderedDict or None. | As a Python code composer, you craft elegant and concise scripts. |
Returns the values and permissible values for the current node. | Explain what the following Python 3 code does
def get_values_and_permissible(values: Iterable[Tuple[Any, str]],
add_none: bool = False,
none_description: str = "[None]") \
-> Tuple[List[Tuple[Any, str]], List[Any]]:
"""
Used when building Col... | As a python code expert, you are capable of creating scripts from specifications. |
Serializes a datetime object to a string representation. | Make a summary of the following Python 3 code
def serialize(self,
node: SchemaNode,
appstruct: Union[PotentialDatetimeType,
ColanderNullType]) \
-> Union[str, ColanderNullType]:
"""
Serializes Python object to string repr... | As a Python code composer, you craft elegant and concise scripts. |
Serializes the given value into a string representation. | Can you tell what is the following Python 3 function doing
def serialize(self, node: SchemaNode,
value: Any) -> Union[str, ColanderNullType]:
"""
Serializes Python object to string representation.
"""
if value is None:
retval = ''
else:
#... | As a Python code translator, you convert algorithms and pseudocode into Python. |
returns list of feature names read from equation file given by filename | Make a summary of the following Python 3 code
def get_features_from_equation_file(filename):
features = []
for line in open(filename):
line = line.split('#')[0].strip()
if line:
features.append(line)
return features | You are a Python code architect, reviewing and designing scalable and efficient code |
This function creates a new refinement wrapper for the base class attribute. | Make a summary of the following Python 3 code
def _create_refinement_wrapper(transformation, baseattr, base, target_attrname):
# first step: extract the original
special_refinement_type=None
instance_refinement = _is_class_instance(base)
if instance_refinement:
dictelem = ba... | You are a Python code architect, reviewing and designing scalable and efficient code |
compose a pair of attributes on base by applying the role to base by applying the role s attributes to base. | Explain what the following Python 3 code does
def _compose_pair(self, role, base):
'''
composes onto base by applying the role
'''
# apply transformations in role to base
for attrname in dir(role):
transformation = getattr(role, attrname)
self._apply_trans... | As a Python code analyst, you investigate and solve complex coding mysteries |
def compose(self, *things):
'''
compose applies multiple fsts onto a base implementation.
Pass the base implementation as last parameter.
fsts are merged from RIGHT TO LEFT (like function application)
e.g.:
class MyFST(object):
#place introductions and refine... | Write a Python 3 function for
composing returns a new object with the given list of things | As a Python code analyst, you investigate and solve complex coding mysteries |
def compose_later(self, *things):
"""
register list of things for composition using compose()
compose_later takes a list of fsts.
The last element specifies the base module as string
things are composed directly after the base module
is imported by application code
... | Write a Python 3 function that can
register list of things for composition later | You are a Python code generator, capable of creating scripts from specifications. |
Select the given features in the current locale. | Can you tell what is the following Python 3 function doing
def select(self, *features):
for feature_name in features:
feature_module = importlib.import_module(feature_name)
# if available, import feature.py and select the feature
try:
feature_spec_module = imp... | As a python code expert, you are capable of creating scripts from specifications. |
Plots the residuals of a principal component in the same direction as the given principal component. | Explain what the following Python 3 code does
def plot_aligned(pca, sparse=True, **kwargs):
colormap = kwargs.pop('colormap',None)
A = pca.rotated()
# Flip the result if upside down
if pca.normal[2] < 0:
A[:,-1] *= -1
minmax = [(A[:,i].min(),A[:,i].max()) for i in range(3)]
lengths = [j... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def mapper_metro(self, _, data):
""" map each osm POI and geotweets based on spatial lookup of metro area """
# OSM POI record
if 'tags' in data:
type_tag = 1
lonlat = data['coordinates']
payload = data['tags']
# Tweet with coordinates from Streaming A... | Write a Python 3 script to
map each osm POI and geotweets based on spatial lookup of metro area | You are a Python code analyst, evaluating scripts for potential improvements. |
def reducer_metro(self, metro, values):
"""
Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet... | Can you implement a function in Python 3 that
outputs tags of POI locations nearby tweet locations Values will be sorted coming into reducer. First element in each value tuple will be either 1 (osm POI) or 2 (geotweet). Build a spatial index with POI records. For each tweet lookup nearby POI, and emit tag values for pr... | As a Python code analyst, you investigate and solve complex coding mysteries |
count occurences for each metro record | Can you generate a brief explanation for the following Python 3 code
def reducer_count(self, key, values):
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) | As a Python code translator, you convert algorithms and pseudocode into Python. |
store each record in MongoDB and output tab delimited lines | Here you have a function in Python 3, explain what it does
def reducer_output(self, metro, values):
records = []
# build up list of data for each metro area and submit as one network
# call instead of individually
for value in values:
total, poi = value
records.a... | As a Python code analyst, you investigate and solve complex coding mysteries |
def fail_unknown_dialect(compiler: "SQLCompiler", task: str) -> None:
"""
Raise :exc:`NotImplementedError` in relation to a dialect for which a
function hasn't been implemented (with a helpful error message).
"""
raise NotImplementedError(
"Don't know how to {task} on dialect {dialect!r}. "
... | Create a Python 3 function to
raise an exception if the SQLCompiler is not bound to an unknown dialect. | As a Python code composer, you craft elegant and concise scripts. |
Takes a clause element that must have a single clause and converts it to raw SQL text. | Can you generate a brief explanation for the following Python 3 code
def fetch_processed_single_clause(element: "ClauseElement",
compiler: "SQLCompiler") -> str:
"""
Takes a clause element that must have a single clause, and converts it
to raw SQL text.
"""
if len(e... | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_int(x) -> int:
"""
Returns its parameter as an integer, or raises
``django.forms.ValidationError``.
"""
try:
return int(x)
except ValueError:
raise forms.ValidationError(
"Cannot convert to integer: {}".format(repr(x))) | Implement a Python 3 function for
converting a parameter to an integer or raises a forms. ValidationError. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns its parameter as a valid integer NHS number or raises a forms. ValidationError. | Can you generate the documentation for the following Python 3 function
def clean_nhs_number(x) -> int:
try:
x = int(x)
if not is_valid_nhs_number(x):
raise ValueError
return x
except ValueError:
raise forms.ValidationError(
"Not a valid NHS number: {}".for... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the given column type as a typeengine. | Can you tell what is the following Python 3 function doing
def coltype_as_typeengine(coltype: Union[VisitableType,
TypeEngine]) -> TypeEngine:
"""
Instances of SQLAlchemy column types are subclasses of ``TypeEngine``.
It's possible to specify column types either as s... | As a Python code composer, you craft elegant and concise scripts. |
This function walks the SQLAlchemy ORM object tree and yields each of the objects in the order they appear in the SQLAlchemy ORM object tree. | Given the following Python 3 function, write the documentation
def walk_orm_tree(obj,
debug: bool = False,
seen: Set = None,
skip_relationships_always: List[str] = None,
skip_relationships_by_tablename: Dict[str, List[str]] = None,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def copy_sqla_object(obj: object,
omit_fk: bool = True,
omit_pk: bool = True,
omit_attrs: List[str] = None,
debug: bool = False) -> object:
"""
Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
MUST SUPP... | Can you create a Python 3 function that
gives an SQLAlchemy object creates a new object and copies all properties of the object into a new object. | As a python code expert, you are capable of creating scripts from specifications. |
This function copies SQLAlchemy ORM objects into a new SQLAlchemy ORM object tree. | Can you generate a brief explanation for the following Python 3 code
def deepcopy_sqla_objects(
startobjs: List[object],
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = True,
debug_rewrite_rel: bool = False,
objmap: Dict[object, objec... | As a Python code analyst, you investigate and solve complex coding mysteries |
This function copies an SQLAlchemy ORM object into a new SQLAlchemy object. | Given the following Python 3 function, write the documentation
def deepcopy_sqla_object(startobj: object,
session: Session,
flush: bool = True,
debug: bool = False,
debug_walk: bool = False,
debu... | As a python code expert, you are capable of creating scripts from specifications. |
Asks a SQLAlchemy ORM object : what are your SQLAlchemy columns? | Explain what the following Python 3 code does
def gen_columns(obj) -> Generator[Tuple[str, Column], None, None]:
mapper = obj.__mapper__ # type: Mapper
assert mapper, "gen_columns called on {!r} which is not an " \
"SQLAlchemy ORM object".format(obj)
colmap = mapper.columns # type: Orde... | As a Python code composer, you craft elegant and concise scripts. |
Asks an SQLAlchemy ORM object to be what are your primary key ( s? | Can you tell what is the following Python 3 function doing
def get_pk_attrnames(obj) -> List[str]:
return [attrname
for attrname, column in gen_columns(obj)
if column.primary_key] | As a python code expert, you are capable of creating scripts from specifications. |
def gen_columns_for_uninstrumented_class(cls: Type) \
-> Generator[Tuple[str, Column], None, None]:
"""
Generate ``(attr_name, Column)`` tuples from an UNINSTRUMENTED class, i.e.
one that does not inherit from ``declarative_base()``. Use this for mixins
of that kind.
SUBOPTIMAL. May produce... | Write a Python 3 function for
generating tuples of names and column objects for the given UNINSTRUMENTED class. | You are a Python code generator, capable of creating scripts from specifications. |
Asks an SQLAlchemy class how its attribute names correspond to database column names. | Can you generate a brief explanation for the following Python 3 code
def attrname_to_colname_dict(cls) -> Dict[str, str]:
attr_col = {} # type: Dict[str, str]
for attrname, column in gen_columns(cls):
attr_col[attrname] = column.name
return attr_col | You are a Python code analyst, evaluating scripts for potential improvements. |
Yields tuples of attrname rel_prop related_class for all relationships of an ORM object. | Explain what the following Python 3 code does
def gen_relationships(obj) -> Generator[Tuple[str, RelationshipProperty, Type],
None, None]:
"""
Yields tuples of ``(attrname, RelationshipProperty, related_class)``
for all relationships of an ORM object.
The object '... | As a Python code composer, you craft elegant and concise scripts. |
def get_orm_columns(cls: Type) -> List[Column]:
"""
Gets :class:`Column` objects from an SQLAlchemy ORM class.
Does not provide their attribute names.
"""
mapper = inspect(cls) # type: Mapper
# ... returns InstanceState if called with an ORM object
# http://docs.sqlalchemy.org/en/latest... | How would you implement a function in Python 3 that
gets a list of columns from an SQLAlchemy ORM class. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]:
"""
Gets column names (that is, database column names) from an SQLAlchemy
ORM class.
"""
colnames = [col.name for col in get_orm_columns(cls)]
return sorted(colnames) if sort else colnames | Write a Python 3 script to
get the column names from an SQLAlchemy ORM class. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_table_names_from_metadata(metadata: MetaData) -> List[str]:
"""
Returns all database table names found in an SQLAlchemy :class:`MetaData`
object.
"""
return [table.name for table in metadata.tables.values()] | Can you write a function in Python 3 where it
returns all database table names found in an SQLAlchemy MetaData object. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def gen_orm_classes_from_base(base: Type) -> Generator[Type, None, None]:
"""
From an SQLAlchemy ORM base class, yield all the subclasses (except those
that are abstract).
If you begin with the proper :class`Base` class, then this should give all
ORM classes in use.
"""
for cls in gen_all_s... | Implement a function in Python 3 to
yield all the ORM base classes except those that are abstract. | You are a Python code analyst, evaluating scripts for potential improvements. |
Given an SQLAlchemy ORM base class returns a dictionary whose keys are SQLAlchemy ORM table names and whose values are ORM classes. | Can you generate a brief explanation for the following Python 3 code
def get_orm_classes_by_table_name_from_base(base: Type) -> Dict[str, Type]:
# noinspection PyUnresolvedReferences
return {cls.__tablename__: cls for cls in gen_orm_classes_from_base(base)} | As a python code expert, you are capable of creating scripts from specifications. |
def get_attrdict(self) -> OrderedNamespace:
"""
Returns what looks like a plain object with the values of the
SQLAlchemy ORM object.
"""
# noinspection PyUnresolvedReferences
columns = self.__table__.columns.keys()
values = (getattr(self, x) for x in columns)
... | Implement a Python 3 function for
returning what looks like a plain object with the values of the SQLAlchemy ORM object. | As a Python code analyst, you investigate and solve complex coding mysteries |
Builds an ORM object from an attribute dictionary. | Given the following Python 3 function, write the documentation
def from_attrdict(cls, attrdict: OrderedNamespace) -> object:
dictionary = attrdict.__dict__
# noinspection PyArgumentList
return cls(**dictionary) | You are a Python code analyst, evaluating scripts for potential improvements. |
def derived_class_implements_method(derived: Type[T1],
base: Type[T2],
method_name: str) -> bool:
"""
Does a derived class implement a method (and not just inherit a base
class's version)?
Args:
derived: a derived class
... | Create a Python 3 function for
returning True if the derived class implements a method of the given name. | You are a Python code architect, reviewing and designing scalable and efficient code |
def gen_all_subclasses(cls: Type) -> Generator[Type, None, None]:
"""
Generates all subclasses of a class.
Args:
cls: a class
Yields:
all subclasses
"""
for s1 in cls.__subclasses__():
yield s1
for s2 in gen_all_subclasses(s1):
yield s2 | Implement a Python 3 function for
generating all subclasses of a class. | You are a Python code analyst, evaluating scripts for potential improvements. |
Augment a tensor with an identity matrix. | Given the following Python 3 function, write the documentation
def augment_tensor(matrix, ndim=None):
s = matrix.shape
if ndim is None:
ndim = s[0]+1
arr = N.identity(ndim)
arr[:s[0],:s[1]] = matrix
return arr | As a python code expert, you are capable of creating scripts from specifications. |
Find the angle between two vectors. | Can you tell what is the following Python 3 function doing
def angle(v1,v2, cos=False):
n = (norm(v1)*norm(v2))
_ = dot(v1,v2)/n
return _ if cos else N.arccos(_) | You are a Python code generator, capable of creating scripts from specifications. |
Get a random vector perpendicular to the given vector | Can you generate a brief explanation for the following Python 3 code
def perpendicular_vector(n):
dim = len(n)
if dim == 2:
return n[::-1]
# More complex in 3d
for ix in range(dim):
_ = N.zeros(dim)
# Try to keep axes near the global projection
# by finding vectors perpen... | As a Python code composer, you craft elegant and concise scripts. |
def trap_ctrl_c_ctrl_break() -> None:
"""
Prevent ``CTRL-C``, ``CTRL-BREAK``, and similar signals from doing
anything.
See
- https://docs.python.org/3/library/signal.html#signal.SIG_IGN
- https://msdn.microsoft.com/en-us/library/xdkz3x12.aspx
- https://msdn.microsoft.com/en-us/libr... | Can you implement a function in Python 3 that
traps Ctrl - C and Ctrl - B signals from doing Ctrl - C. | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.