output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Create a new entity. | Can you generate a brief explanation for the following Python 3 code
def create_entity(self, **kwargs):
data = kwargs
headers = kwargs.get('headers', {})
if 'headers' in data:
del data['headers']
return self._create("/entities", data=data, coerce=self.get_entity, headers=head... | As a python code expert, you are capable of creating scripts from specifications. |
Create a GTFS feed from the source file and write it to the target file. | Explain what the following Python 3 code does
def make_gtfs(source_path, target_path, buffer, ndigits):
pfeed = pf.read_protofeed(source_path)
feed = m.build_feed(pfeed, buffer=buffer)
gt.write_gtfs(feed, target_path, ndigits=ndigits) | As a Python code composer, you craft elegant and concise scripts. |
Calculate the power spectrum density of a set of data. | Explain what the following Python 3 code does
def psd(data, dt, ndivide=1, window=hanning, overlap_half=False):
logger = getLogger('decode.utils.ndarray.psd')
if overlap_half:
step = int(len(data) / (ndivide + 1))
size = step * 2
else:
step = int(len(data) / ndivide)
size = ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def allan_variance(data, dt, tmax=10):
"""Calculate Allan variance.
Args:
data (np.ndarray): Input data.
dt (float): Time between each data.
tmax (float): Maximum time.
Returns:
vk (np.ndarray): Frequency.
allanvar (np.ndarray): Allan variance.
"""
allanvar ... | How would you code a function in Python 3 to
calculate the Allan variance. | You are a Python code analyst, evaluating scripts for potential improvements. |
Discover a list of collections under the given path. | Explain what the following Python 3 code does
def discover(cls, path, depth="0"):
# Path should already be sanitized
attributes = _get_attributes_from_path(path)
try:
if len(attributes) == 3:
# If an item, create a collection for the item.
item = att... | You are a Python code architect, reviewing and designing scalable and efficient code |
def etag(self):
"""Encoded as quoted-string (see RFC 2616)."""
if self.is_fake:
return
entry = None
for entry in self.journal.list():
pass
return entry.uid if entry is not None else hashlib.sha256(b"").hexdigest() | Write a Python 3 script to
encode as quoted - string ( see RFC 2616 ). | As a Python code translator, you convert algorithms and pseudocode into Python. |
Create a new collection. | Can you generate a brief explanation for the following Python 3 code
def create_collection(cls, href, collection=None, props=None):
# Path should already be sanitized
attributes = _get_attributes_from_path(href)
if len(attributes) <= 1:
raise PrincipalNotAllowedError
# Try t... | As a Python code composer, you craft elegant and concise scripts. |
def sync(self, old_token=None):
"""Get the current sync token and changed items for synchronization.
``old_token`` an old sync token which is used as the base of the
delta update. If sync token is missing, all items are returned.
ValueError is raised for invalid or old tokens.
"... | Can you implement a function in Python 3 that
gets the current sync token and changed items for synchronization. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(self, href):
"""Fetch a single item."""
if self.is_fake:
return
uid = _trim_suffix(href, ('.ics', '.ical', '.vcf'))
etesync_item = self.collection.get(uid)
if etesync_item is None:
return None
try:
item = vobject.readOne(etesy... | How would you code a function in Python 3 to
fetch a single item. | As a python code expert, you are capable of creating scripts from specifications. |
def upload(self, href, vobject_item):
"""Upload a new or replace an existing item."""
if self.is_fake:
return
content = vobject_item.serialize()
try:
item = self.get(href)
etesync_item = item.etesync_item
etesync_item.content = content
... | How would you implement a function in Python 3 that
uploads a new or replace an existing item. | You are a Python code generator, capable of creating scripts from specifications. |
def delete(self, href=None):
"""Delete an item.
When ``href`` is ``None``, delete the collection.
"""
if self.is_fake:
return
if href is None:
self.collection.delete()
return
item = self.get(href)
if item is None:
... | Write a Python 3 script to
delete an item. When ``href`` is ``None``, delete the collection. | You are a Python code generator, capable of creating scripts from specifications. |
def get_meta(self, key=None):
"""Get metadata value for collection."""
if self.is_fake:
return {}
if key == "tag":
return self.tag
elif key is None:
ret = {}
for key in self.journal.info.keys():
ret[key] = self.meta_mapping... | Implement a function in Python 3 to
get metadata value for collection. | As a Python code composer, you craft elegant and concise scripts. |
Set metadata values for collection. | Here you have a function in Python 3, explain what it does
def set_meta(self, _props):
if self.is_fake:
return
props = {}
for key, value in _props.items():
key, value = self.meta_mappings.map_set(key, value)
props[key] = value
# Pop out tag which we ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Set metadata values for all elements in the collection. | Can you generate the documentation for the following Python 3 function
def set_meta_all(self, props):
delta_props = self.get_meta()
for key in delta_props.keys():
if key not in props:
delta_props[key] = None
delta_props.update(props)
self.set_meta(delta_props) | As a Python code composer, you craft elegant and concise scripts. |
def last_modified(self):
"""Get the HTTP-datetime of when the collection was modified."""
# FIXME: Make this sensible
last_modified = time.strftime(
"%a, %d %b %Y %H:%M:%S GMT",
time.gmtime(time.time()))
return last_modified | Implement a function in Python 3 to
get the HTTP - datetime of when the collection was modified. | You are a Python code generator, capable of creating scripts from specifications. |
def serialize(self):
"""Get the unicode string representing the whole collection."""
import datetime
items = []
time_begin = datetime.datetime.now()
for href in self.list():
items.append(self.get(href).item)
time_end = datetime.datetime.now()
self.logg... | Write a Python 3 function that can
get the unicode string representing the whole collection. | You are a Python code analyst, evaluating scripts for potential improvements. |
def acquire_lock(cls, mode, user=None):
"""Set a context manager to lock the whole storage.
``mode`` must either be "r" for shared access or "w" for exclusive
access.
``user`` is the name of the logged in user or empty.
"""
if not user:
return
with... | Can you write a function in Python 3 where it
acquires a lock for the entire storage. | As a Python code composer, you craft elegant and concise scripts. |
Initialize the object variables that are not yet set. | Given the following Python 3 function, write the documentation
def setup(self):
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
self.prefix = self.config['prefix']
self.generic_mode = self.... | You are a Python code generator, capable of creating scripts from specifications. |
Evaluate inline comments at the tail of source code. | Given the following Python 3 function, write the documentation
def evaluate_inline_tail(self, groups):
if self.lines:
self.line_comments.append([groups['line'][2:].replace('\\\n', ''), self.line_num, self.current_encoding]) | You are a Python code analyst, evaluating scripts for potential improvements. |
def evaluate_inline(self, groups):
"""Evaluate inline comments on their own lines."""
# Consecutive lines with only comments with same leading whitespace
# will be captured as a single block.
if self.lines:
if (
self.group_comments and
self.li... | Implement a function in Python 3 to
evaluate inline comments on their own lines. | You are a Python code generator, capable of creating scripts from specifications. |
def evaluate(self, m):
"""Search for comments."""
g = m.groupdict()
if g["strings"]:
self.evaluate_strings(g)
self.line_num += g['strings'].count('\n')
elif g["code"]:
self.line_num += g["code"].count('\n')
else:
if g['block']:
... | Write a Python 3 script to
search for strings code and inline comments. | You are a Python code generator, capable of creating scripts from specifications. |
Extend the source text list with the gathered text data. | Can you generate a brief explanation for the following Python 3 code
def extend_src_text(self, content, context, text_list, category):
prefix = self.prefix + '-' if self.prefix else ''
for comment, line, encoding in text_list:
content.append(
filters.SourceText(
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a cube as an instance of xarray. DataArray with default values. | Can you generate the documentation for the following Python 3 function
def cube(data, xcoords=None, ycoords=None, chcoords=None, scalarcoords=None, datacoords=None, attrs=None, name=None):
# initialize coords with default values
cube = xr.DataArray(data, dims=('x', 'y', 'ch'), attrs=attrs, name=name)
cube.d... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a decode array to decode cube. | Make a summary of the following Python 3 code
def tocube(array, **kwargs):
# pick up kwargs
unit = kwargs.pop('unit', 'deg')
unit2deg = getattr(u, unit).to('deg')
xc = kwargs.pop('xc', float(array.xref)) * unit2deg
yc = kwargs.pop('yc', float(array.yref)) * unit2deg
xarr = kwargs.pop('x... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Make a continuum array. | Can you generate the documentation for the following Python 3 function
def makecontinuum(cube, **kwargs):
### pick up kwargs
inchs = kwargs.pop('inchs', None)
exchs = kwargs.pop('exchs', None)
if (inchs is not None) or (exchs is not None):
raise KeyError('Inchs and exchs are no longer supported... | You are a Python code analyst, evaluating scripts for potential improvements. |
Verify encoding is okay. | Given the following Python 3 function, write the documentation
def _verify_encoding(self, enc):
enc = PYTHON_ENCODING_NAMES.get(enc, enc)
try:
codecs.getencoder(enc)
encoding = enc
except LookupError:
encoding = None
return encoding | As a python code expert, you are capable of creating scripts from specifications. |
def has_bom(self, f):
"""Check for UTF8, UTF16, and UTF32 BOMs."""
content = f.read(4)
encoding = None
m = RE_UTF_BOM.match(content)
if m is not None:
if m.group(1):
encoding = 'utf-8-sig'
elif m.group(2):
encoding = 'utf-3... | Can you write a function in Python 3 where it
checks for UTF8 UTF16 and UTF32 BOMs. | As a Python code composer, you craft elegant and concise scripts. |
Return an encoding that will ignore the BOM. | Can you generate the documentation for the following Python 3 function
def _utf_strip_bom(self, encoding):
if encoding is None:
pass
elif encoding.lower() == 'utf-8':
encoding = 'utf-8-sig'
elif encoding.lower().startswith('utf-16'):
encoding = 'utf-16'
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Guess by checking BOM and checking _special_encode_check and using memory map. | Given the following Python 3 function, write the documentation
def _detect_buffer_encoding(self, f):
encoding = None
with contextlib.closing(mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)) as m:
encoding = self._analyze_file(m)
return encoding | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _analyze_file(self, f):
"""Analyze the file."""
f.seek(0)
# Check for BOMs
if self.CHECK_BOM:
encoding = self.has_bom(f)
f.seek(0)
else:
util.warn_deprecated(
"'CHECK_BOM' attribute is deprecated. "
"Please ... | Implement a function in Python 3 to
analyze the file and return the content of the object. | As a Python code composer, you craft elegant and concise scripts. |
def _run_first(self, source_file):
"""Run on as first in chain."""
self.reset()
self.current_encoding = self.default_encoding
encoding = None
try:
encoding = self._detect_encoding(source_file)
content = self.filter(source_file, encoding)
except Un... | How would you implement a function in Python 3 that
runs on as first in chain. | You are a Python code generator, capable of creating scripts from specifications. |
def _guess(self, filename):
"""Guess the encoding and decode the content of the file."""
encoding = None
file_size = os.path.getsize(filename)
# If the file is really big, lets just call it binary.
# We don't have time to let Python chug through a massive file.
if not s... | Create a Python 3 function for
guessing the encoding and decode the content of the file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def run(config, **kwargs):
"""Run."""
names = kwargs.get('names', [])
groups = kwargs.get('groups', [])
binary = kwargs.get('binary', '')
spellchecker = kwargs.get('spellchecker', '')
verbose = kwargs.get('verbose', 0)
sources = kwargs.get('sources', [])
debug = kwargs.get('debug', Fals... | Create a Python 3 function for
running the spellcheck command. | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorator to mark a function as deprecated. | Can you generate the documentation for the following Python 3 function
def deprecated(message): # pragma: no cover
def deprecated_decorator(func):
"""Deprecation decorator."""
@wraps(func)
def deprecated_func(*args, **kwargs):
"""Display deprecation warning."""
wa... | As a Python code composer, you craft elegant and concise scripts. |
Get a command process. | Here you have a function in Python 3, explain what it does
def get_process(cmd):
if sys.platform.startswith('win'):
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
process = subprocess.Popen(
cmd,
startupinfo=startupinfo,... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get the output from the process. | Given the following Python 3 function, write the documentation
def get_process_output(process, encoding=None):
output = process.communicate()
returncode = process.returncode
if not encoding:
try:
encoding = sys.stdout.encoding
except Exception:
encoding = locale.get... | You are a Python code analyst, evaluating scripts for potential improvements. |
Call spell checker with arguments. | Make a summary of the following Python 3 code
def call_spellchecker(cmd, input_text=None, encoding=None):
process = get_process(cmd)
# A buffer has been provided
if input_text is not None:
for line in input_text.splitlines():
# Hunspell truncates lines at `0x1fff` (at least on Windows ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def random_name_gen(size=6):
"""Generate a random python attribute name."""
return ''.join(
[random.choice(string.ascii_uppercase)] +
[random.choice(string.ascii_uppercase + string.digits) for i in range(size - 1)]
) if size > 0 else '' | Can you write a function in Python 3 where it
generates a random python attribute name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def yaml_load(source, loader=yaml.Loader):
"""
Wrap PyYaml's loader so we can extend it to suit our needs.
Load all strings as Unicode: http://stackoverflow.com/a/2967461/3609487.
"""
def construct_yaml_str(self, node):
"""Override the default string handling function to always return Unic... | Create a Python 3 function to
load a YAML file into a dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
Fix timedelta in docstrings. | Can you tell what is the following Python 3 function doing
def fix_timedelta_repr(func):
# We don't need to do anything if we're not on 3.7 or above
if version < (3, 7):
return func
def fix_timedelta(match):
values = match.group(1).split(", ")
param_repr = ", ".join(
"{}... | You are a Python code generator, capable of creating scripts from specifications. |
def _get_tag(self, url, tag, print_warn=True):
"""Check if url is available and returns given tag type
:param url: url to content relative to base url
:param anchor: anchor type to return
:param print_warn: if True print warn when url is unavailable
"""
# construct comple... | Write a Python 3 script for
checking if url is available and returns given tag type | As a Python code translator, you convert algorithms and pseudocode into Python. |
Include resources in pages in codemirror. js and codemirror. css. | Make a summary of the following Python 3 code
def include_codemirror(self):
contents = []
# base
js = self._get_tag('codemirror.js', 'script')
css = self._get_tag('codemirror.css', 'stylesheet')
if js and css:
contents.append(js)
contents.append(css)
... | As a Python code composer, you craft elegant and concise scripts. |
Register CodeMirror as a Flask extension
| Can you tell what is the following Python 3 function doing
def init_app(self, app):
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['codemirror'] = CodeMirrorHeaders(app.config)
app.context_processor(self.context_processor) | As a Python code composer, you craft elegant and concise scripts. |
def format(self):
"""Dump the class data in the format of a .netrc file."""
self._netrc.hosts = dedictify_machines(self.machines)
rep = ""
for host in self._netrc.hosts.keys():
attrs = self._netrc.hosts[host]
rep += "machine {host}\n\tlogin {attrs[0]}\n".format(ho... | Write a Python 3 function that can
dump the class data in the format of a. netrc file. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a Public Address String to a ScriptHash String. | Given the following Python 3 function, write the documentation
def neo_get_scripthash_from_address(address):
hash_bytes = binascii.hexlify(base58.b58decode_check(address))
return reverse_hex(hash_bytes[2:].decode('utf-8')) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts a number to a big endian hexstring of a suitable size optionally little endian | Can you generate the documentation for the following Python 3 function
def num2hexstring(number, size=1, little_endian=False):
# if (type(number) != = 'number') throw new Error('num must be numeric')
# if (num < 0) throw new RangeError('num is unsigned (>= 0)')
# if (size % 1 !== 0) throw new Error('size mu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a number to a variable length Int. Used for array length header. | Can you generate a brief explanation for the following Python 3 code
def num2varint(num):
# if (typeof num !== 'number') throw new Error('VarInt must be numeric')
# if (num < 0) throw new RangeError('VarInts are unsigned (> 0)')
# if (!Number.isSafeInteger(num)) throw new RangeError('VarInt must be a safe i... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get(self, path, params=None):
"""Perform GET request"""
r = requests.get(url=self.url + path, params=params, timeout=self.timeout)
r.raise_for_status()
return r.json() | Can you implement a function in Python 3 that
performs a GET request on the object store | As a Python code composer, you craft elegant and concise scripts. |
Perform a POST request to the Switcheo API. | Can you tell what is the following Python 3 function doing
def post(self, path, data=None, json_data=None, params=None):
r = requests.post(url=self.url + path, data=data, json=json_data, params=params, timeout=self.timeout)
try:
r.raise_for_status()
except requests.exceptions.HTTPErr... | You are a Python code generator, capable of creating scripts from specifications. |
def is_break_tag(self, el):
"""Check if tag is an element we should break on."""
name = sv.util.lower(el.name) if self.type != 'xhtml' else el.name
return name in self.break_tags or name in self.user_break_tags | Can you implement a function in Python 3 that
checks if tag is an element we should break on. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Construct an selector for context. | How would you explain what the following Python 3 function does
def construct_selector(self, el, attr=''):
selector = deque()
ancestor = el
while ancestor and ancestor.parent:
if ancestor is not el:
selector.appendleft(ancestor.name)
else:
... | As a Python code composer, you craft elegant and concise scripts. |
def has_bom(self, filestream):
"""Check if has BOM."""
content = filestream.read(4)
if content == b'PK\x03\x04':
# Zip file found.
# Return `BINARY_ENCODE` as content is binary type,
# but don't return None which means we don't know what we have.
... | Write a Python 3 script to
check if the file has BOM. | You are a Python code architect, reviewing and designing scalable and efficient code |
Get the context of the current file. | Explain what the following Python 3 code does
def get_context(self, filename):
if self.type == 'pptx':
context = '{}: '.format(RE_SLIDE.search(filename).group(1))
elif self.type == 'docx':
context = '{}: '.format(RE_DOCS.match(filename).group(1))
else:
contex... | You are a Python code generator, capable of creating scripts from specifications. |
Reads the data files in the given directory path and builds a ProtoFeed from them. | Given the following Python 3 function, write the documentation
def read_protofeed(path):
path = Path(path)
service_windows = pd.read_csv(
path/'service_windows.csv')
meta = pd.read_csv(path/'meta.csv',
dtype={'start_date': str, 'end_date': str})
shapes = gpd.read_file(str(path/'shapes.geo... | As a python code expert, you are capable of creating scripts from specifications. |
def copy(self):
"""
Return a copy of this ProtoFeed, that is, a feed with all the
same attributes.
"""
other = ProtoFeed()
for key in cs.PROTOFEED_ATTRS:
value = getattr(self, key)
if isinstance(value, pd.DataFrame):
# Pandas copy D... | Create a Python 3 function to
return a copy of this ProtoFeed with all the same attributes. | As a python code expert, you are capable of creating scripts from specifications. |
Return a class which is a jsontree but with a supplied attribute name mapping. | Can you generate a brief explanation for the following Python 3 code
def mapped_jsontree_class(mapping):
mapper = mapping
if not callable(mapping):
if not isinstance(mapping, collections.Mapping):
raise TypeError("Argument mapping is not collable or an instance "
... | As a python code expert, you are capable of creating scripts from specifications. |
def clone(root, jsontreecls=jsontree, datetimeencoder=_datetimeencoder,
datetimedecoder=_datetimedecoder):
"""Clone an object by first searializing out and then loading it back in.
"""
return json.loads(json.dumps(root, cls=JSONTreeEncoder,
datetimeencoder=datetime... | Create a Python 3 function for
cloning an object by first searializing out and then loading it back in. | You are a Python code analyst, evaluating scripts for potential improvements. |
JSON load from string function that defaults the loading class to be
JSONTreeDecoder | How would you explain what the following Python 3 function does
def loads(s, encoding=None, cls=JSONTreeDecoder, object_hook=None,
parse_float=None, parse_int=None, parse_constant=None,
object_pairs_hook=None, **kargs):
"""JSON load from string function that defaults the loading class to be
JS... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def setup(self):
"""Setup."""
self.comments = self.config['comments']
self.docstrings = self.config['docstrings']
self.strings = self.config['strings']
self.group_comments = self.config['group_comments']
self.string_types, self.wild_string_types = self.eval_string_type(s... | Write a Python 3 script to
initialize the object variables that are only set once. | As a Python code analyst, you investigate and solve complex coding mysteries |
Replace escapes with unicode. | Make a summary of the following Python 3 code
def replace_unicode(self, m):
groups = m.groupdict()
esc = m.group(0)
if groups.get('fesc'):
value = m.group(0)
elif groups.get('format'):
value = ' '
elif groups.get('special'):
value = BACK_SLASH... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Filter the Python docstrings and strings. | Given the following Python 3 function, write the documentation
def _filter(self, text, context, encoding):
docstrings = []
strings = []
comments = []
prev_token_type = tokenize.NEWLINE
indent = ''
name = None
stack = [(context, 0, self.MODULE)]
last_comme... | You are a Python code generator, capable of creating scripts from specifications. |
Return a set of all slots for a given class and its parents | Here you have a function in Python 3, explain what it does
def find_slots(cls):
slots = set()
for c in cls.__mro__:
cslots = getattr(c, "__slots__", tuple())
if not cslots:
continue
elif isinstance(cslots, (bstr, ustr)):
cslots = (cslots,)
slots.update(... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _is_valid_date(obj, accept_none=True):
"""
Check if an object is an instance of, or a subclass deriving from, a
``date``. However, it does not consider ``datetime`` or subclasses thereof
as valid dates.
:param obj: Object to test as date.
:param accept_none: If True None is considered as a ... | Write a Python 3 function that can
check if an object is an instance of date or datetime. | You are a Python code architect, reviewing and designing scalable and efficient code |
def empty(cls):
"""
Returns an empty set. An empty set is unbounded and only contain the
empty set.
>>> intrange.empty() in intrange.empty()
True
It is unbounded but the boundaries are not infinite. Its boundaries are
returned as ``None``. Every set cont... | Can you implement a function in Python 3 that
returns an empty set. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a new instance of this instance with the given arguments replaced. | Explain what the following Python 3 code does
def replace(self, *args, **kwargs):
replacements = {
"lower" : self.lower,
"upper" : self.upper,
"lower_inc" : self.lower_inc,
"upper_inc" : self.upper_inc
}
replacements.update(
dict(zip((... | As a Python code composer, you craft elegant and concise scripts. |
Return True if this object contains other. | Can you generate the documentation for the following Python 3 function
def contains(self, other):
if self.is_valid_range(other):
if not self:
return not other
elif not other or other.startsafter(self) and other.endsbefore(self):
return True
el... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def within(self, other):
"""
Tests if this range is within `other`.
>>> a = intrange(1, 10)
>>> b = intrange(3, 8)
>>> a.contains(b)
True
>>> b.within(a)
True
This is the same as the ``self <@ other`` in PostgreSQL. One di... | Can you implement a function in Python 3 that
tests if this range is completely within the given range. | As a Python code composer, you craft elegant and concise scripts. |
def overlap(self, other):
"""
Returns True if both ranges share any points.
>>> intrange(1, 10).overlap(intrange(5, 15))
True
>>> intrange(1, 5).overlap(intrange(5, 10))
False
This is the same as the ``&&`` operator for two ranges in PostgreSQL.
... | Write a Python 3 script for
returning True if both ranges share any points. | As a python code expert, you are capable of creating scripts from specifications. |
def adjacent(self, other):
"""
Returns True if ranges are directly next to each other but does not
overlap.
>>> intrange(1, 5).adjacent(intrange(5, 10))
True
>>> intrange(1, 5).adjacent(intrange(10, 15))
False
The empty set is not adjacen... | Create a Python 3 function for
returning True if this range is adjacent with other. | You are a Python code generator, capable of creating scripts from specifications. |
def union(self, other):
"""
Merges this range with a given range.
>>> intrange(1, 5).union(intrange(5, 10))
intrange([1,10))
>>> intrange(1, 10).union(intrange(5, 15))
intrange([1,15))
Two ranges can not be merged if the resulting range would be ... | Implement a Python 3 function for
returning the union of this and other. | As a Python code analyst, you investigate and solve complex coding mysteries |
Compute the difference between two sets of intractions. | How would you explain what the following Python 3 function does
def difference(self, other):
if not self.is_valid_range(other):
msg = "Unsupported type to test for difference '{.__class__.__name__}'"
raise TypeError(msg.format(other))
# Consider empty ranges or no overlap
... | You are a Python code generator, capable of creating scripts from specifications. |
def intersection(self, other):
"""
Returns a new range containing all points shared by both ranges. If no
points are shared an empty range is returned.
>>> intrange(1, 5).intersection(intrange(1, 10))
intrange([1,5))
>>> intrange(1, 5).intersection(intrange(5... | Create a Python 3 function for
returning a new range containing all points shared by both ranges. | You are a Python code architect, reviewing and designing scalable and efficient code |
def startswith(self, other):
"""
Test if this range starts with `other`. `other` may be either range or
scalar.
>>> intrange(1, 5).startswith(1)
True
>>> intrange(1, 5).startswith(intrange(1, 10))
True
:param other: Range or scalar to tes... | Write a Python 3 function that can
test if this range starts with other. | You are a Python code generator, capable of creating scripts from specifications. |
def endswith(self, other):
"""
Test if this range ends with `other`. `other` may be either range or
scalar.
>>> intrange(1, 5).endswith(4)
True
>>> intrange(1, 10).endswith(intrange(5, 10))
True
:param other: Range or scalar to test.
... | Implement a function in Python 3 to
test if this range ends with other. | As a Python code composer, you craft elegant and concise scripts. |
Test if this range starts after other. | Given the following Python 3 function, write the documentation
def startsafter(self, other):
if self.is_valid_range(other):
if self.lower == other.lower:
return other.lower_inc or not self.lower_inc
elif self.lower_inf:
return False
elif other... | You are a Python code architect, reviewing and designing scalable and efficient code |
def endsbefore(self, other):
"""
Test if this range ends before `other`. `other` may be either range or
scalar. This only takes the upper end of the ranges into consideration.
If the scalar or the upper end of the given range is less than or equal
to this range's upper end, ``Tru... | Can you create a Python 3 function that
tests if this range ends before other. | As a Python code composer, you craft elegant and concise scripts. |
Test if this range is strictly left of other. | Can you generate the documentation for the following Python 3 function
def left_of(self, other):
if not self.is_valid_range(other):
msg = (
"Left of is not supported for '{}', provide a proper range "
"class").format(other.__class__.__name__)
raise TypeEr... | You are a Python code architect, reviewing and designing scalable and efficient code |
Shift the range to the left or right with the given offset. | Given the following Python 3 function, write the documentation
def offset(self, offset):
# If range is empty it can't be offset
if not self:
return self
offset_type = self.type if self.offset_type is None else self.offset_type
if offset is not None and not isinstance(offse... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def from_date(cls, date, period=None):
"""
Create a day long daterange from for the given date.
>>> daterange.from_date(date(2000, 1, 1))
daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2)))
:param date: A date to convert.
:param period: The period t... | Write a Python 3 function that can
create a day long daterange from a given date and optional period. | You are a Python code architect, reviewing and designing scalable and efficient code |
def from_week(cls, year, iso_week):
"""
Create ``daterange`` based on a year and an ISO week
:param year: Year as an integer
:param iso_week: ISO week number
:return: A new ``daterange`` for the given week
.. versionadded:: 0.4.0
"""
first_day = date_fr... | Can you write a function in Python 3 where it
creates a daterange based on a year and an ISO week number. | As a Python code composer, you craft elegant and concise scripts. |
Create a daterange based on a year and month. | Can you generate the documentation for the following Python 3 function
def from_month(cls, year, month):
first_day = date(year, month, 1)
return cls.from_date(first_day, period="month") | As a Python code composer, you craft elegant and concise scripts. |
def from_quarter(cls, year, quarter):
"""
Create ``daterange`` based on a year and quarter.
A quarter is considered to be:
- January through March (Q1),
- April through June (Q2),
- July through September (Q3) or,
- October through December (Q4)
:param ... | Write a Python 3 function for
creating a daterange from a year and quarter. | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a daterange based on a year. | How would you explain what the following Python 3 function does
def from_year(cls, year):
first_day = date(year, 1, 1)
return cls.from_date(first_day, period="year") | You are a Python code generator, capable of creating scripts from specifications. |
def daterange(self):
"""
This ``PeriodRange`` represented as a naive
:class:`~spans.types.daterange`.
"""
return daterange(
lower=self.lower,
upper=self.upper,
lower_inc=self.lower_inc,
upper_inc=self.upper_inc) | Can you implement a function in Python 3 that
returns a naive version of the daterange. | As a Python code analyst, you investigate and solve complex coding mysteries |
Offset the date range by the given amount of periods. | Make a summary of the following Python 3 code
def offset(self, offset):
span = self
if offset > 0:
for i in iter_range(offset):
span = span.next_period()
elif offset < 0:
for i in iter_range(-offset):
span = span.prev_period()
retu... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a new PeriodRange for the period before this range. | Explain what the following Python 3 code does
def prev_period(self):
return self.from_date(self.prev(self.lower), period=self.period) | You are a Python code analyst, evaluating scripts for potential improvements. |
Provides hash of given filename. | How would you explain what the following Python 3 function does
def get_package_hashes(filename):
log.debug('Getting package hashes')
filename = os.path.abspath(filename)
with open(filename, 'rb') as f:
data = f.read()
_hash = hashlib.sha256(data).hexdigest()
log.debug('Hash for file %s: %s... | As a Python code analyst, you investigate and solve complex coding mysteries |
Setup the object variables. | Can you generate the documentation for the following Python 3 function
def setup(self):
self.blocks = self.config['block_comments']
self.lines = self.config['line_comments']
self.group_comments = self.config['group_comments']
# If the style isn't found, just go with CSS, then use the ap... | You are a Python code architect, reviewing and designing scalable and efficient code |
def loaddfits(fitsname, coordtype='azel', loadtype='temperature', starttime=None, endtime=None,
pixelids=None, scantypes=None, mode=0, **kwargs):
"""Load a decode array from a DFITS file.
Args:
fitsname (str): Name of DFITS file.
coordtype (str): Coordinate type included into a de... | Can you create a Python 3 function that
loads a decode array from a DFITS file. | As a Python code analyst, you investigate and solve complex coding mysteries |
def savefits(cube, fitsname, **kwargs):
"""Save a cube to a 3D-cube FITS file.
Args:
cube (xarray.DataArray): Cube to be saved.
fitsname (str): Name of output FITS file.
kwargs (optional): Other arguments common with astropy.io.fits.writeto().
"""
### pick up kwargs
dropdeg ... | Write a Python 3 script to
save a 3D - cube FITS file. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def loadnetcdf(filename, copy=True):
"""Load a dataarray from a NetCDF file.
Args:
filename (str): Filename (*.nc).
copy (bool): If True, dataarray is copied in memory. Default is True.
Returns:
dataarray (xarray.DataArray): Loaded dataarray.
"""
filename = str(Path(filenam... | Create a Python 3 function for
loading a dataarray from a NetCDF file. | You are a Python code generator, capable of creating scripts from specifications. |
def savenetcdf(dataarray, filename=None):
"""Save a dataarray to a NetCDF file.
Args:
dataarray (xarray.DataArray): Dataarray to be saved.
filename (str): Filename (used as <filename>.nc).
If not spacified, random 8-character name will be used.
"""
if filename is None:
... | Implement a Python 3 function for
saving a xarray. DataArray to a NetCDF file. | You are a Python code architect, reviewing and designing scalable and efficient code |
def sign_create_cancellation(cancellation_params, private_key):
"""
Function to sign the parameters required to create a cancellation request from the Switcheo Exchange.
Execution of this function is as follows::
sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_... | Write a Python 3 script to
function to sign the parameters required to create a cancellation request from the Switcheo Exchange. Execution of this function is as follows:: sign_create_cancellation(cancellation_params=signable_params, private_key=eth_private_key) The expected return result for this function is as follow... | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is used to sign the parameters required to execute a cancellation request on the Switcheo Exchange. | Given the following Python 3 function, write the documentation
def sign_execute_cancellation(cancellation_params, private_key):
cancellation_sha256 = cancellation_params['transaction']['sha256']
signed_sha256 = binascii.hexlify(
Account.signHash(cancellation_sha256, private_key=private_key)['signature']... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to sign the deposit request by sending the transaction to the Switcheo API. | Can you generate the documentation for the following Python 3 function
def sign_execute_deposit(deposit_params, private_key, infura_url):
create_deposit_upper = deposit_params.copy()
create_deposit_upper['transaction']['from'] = to_checksum_address(create_deposit_upper['transaction']['from'])
create_deposit... | You are a Python code analyst, evaluating scripts for potential improvements. |
This function is used to sign the execute order request by signing the transaction generated by the create order function. | Here you have a function in Python 3, explain what it does
def sign_execute_order(order_params, private_key):
execute_params = {
'signatures': {
'fill_groups': sign_txn_array(messages=order_params['fill_groups'], private_key=private_key),
'fills': {},
'makes': sign_txn_ar... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def sign_execute_withdrawal(withdrawal_params, private_key):
"""
Function to execute the withdrawal request by signing the transaction generated from the create withdrawal function.
Execution of this function is as follows::
sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth... | Can you write a function in Python 3 where it
functions to execute the withdrawal request by signing the transaction generated from the create withdrawal function. Execution of this function is as follows:: sign_execute_withdrawal(withdrawal_params=signable_params, private_key=eth_private_key) The expected return resul... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the content of the file in the zip. | Can you generate the documentation for the following Python 3 function
def get_zip_content(self, filename):
with zipfile.ZipFile(filename, 'r') as z:
self.determine_file_type(z)
for item in z.infolist():
if glob.globmatch(item.filename, self.filepattern, flags=self.FLAGS... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get content from the given zip. | Can you tell what is the following Python 3 function doing
def get_content(self, zipbundle):
for content, filename in self.get_zip_content(zipbundle):
with io.BytesIO(content) as b:
encoding = self._analyze_file(b)
if encoding is None:
encoding = ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Break on specified boundaries. | Can you generate a brief explanation for the following Python 3 code
def content_break(self, el):
should_break = False
if self.type == 'odp':
if el.name == 'page' and el.namespace and el.namespace == self.namespaces['draw']:
should_break = True
return should_break | As a python code expert, you are capable of creating scripts from specifications. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.