output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Fetch and return spreadsheet cell values with Google sheets API. | Can you generate the documentation for the following Python 3 function
def values(service, id, ranges):
params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING'}
params.update(spreadsheetId=id, ranges=ranges)
response = service.sp... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_credentials(scopes=None, secrets=None, storage=None, no_webserver=False):
"""Make OAuth 2.0 credentials for scopes from ``secrets`` and ``storage`` files.
Args:
scopes: scope URL(s) or ``'read'``, ``'write'`` (default: ``%r``)
secrets: location of secrets file (default: ``%r``)
... | Implement a function in Python 3 to
make OAuth 2. 0 credentials for scopes from secrets and storage files. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get(cls, scope=None):
"""Return default or predefined URLs from keyword, pass through ``scope``."""
if scope is None:
scope = cls.default
if isinstance(scope, string_types) and scope in cls._keywords:
return getattr(cls, scope)
return scope | Implement a function in Python 3 to
return default or predefined URLs from keyword pass through scope. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a single list containing up to limit Result objects | How would you explain what the following Python 3 function does
def search_all(self, limit=50, format='json'):
''' Returns a single list containing up to 'limit' Result objects'''
desired_limit = limit
results = self._search(limit, format)
limit = limit - len(results)
while len(r... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a list of result objects with the url for the next page bing search url. | Can you generate the documentation for the following Python 3 function
def _search(self, limit, format):
'''
Returns a list of result objects, with the url for the next page bing search url.
'''
url = self.QUERY_URL.format(requests.utils.quote("'{}'".format(self.query)), min(50, limit), ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return string s as int in bijective base26 notation. | Can you tell what is the following Python 3 function doing
def base26int(s, _start=1 - ord('A')):
return sum((_start + ord(c)) * 26**i for i, c in enumerate(reversed(s))) | You are a Python code analyst, evaluating scripts for potential improvements. |
def base26(x, _alphabet=string.ascii_uppercase):
"""Return positive ``int`` ``x`` as string in bijective base26 notation.
>>> [base26(i) for i in [0, 1, 2, 26, 27, 28, 702, 703, 704]]
['', 'A', 'B', 'Z', 'AA', 'AB', 'ZZ', 'AAA', 'AAB']
>>> base26(344799) # 19 * 26**3 + 16 * 26**2 + 1 * 26**1 + 13 * 2... | Implement a function in Python 3 to
return positive int x as string in bijective base26 notation. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse a single sheet coordinate. | How would you explain what the following Python 3 function does
def _parse(coord, _match=_regex.match):
try:
return _match(coord).groups()
except AttributeError:
raise ValueError(coord) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return zero - based column index from bijective base26 string. | Make a summary of the following Python 3 code
def _cint(col, _map={base26(i): i - 1 for i in range(1, 257)}):
try:
return _map[col.upper()]
except KeyError:
raise ValueError(col) | You are a Python code generator, capable of creating scripts from specifications. |
Return a value fetching callable given a slice of coordinate strings. | Explain what the following Python 3 code does
def from_slice(cls, coord):
if coord.step is not None:
raise NotImplementedError('no slice step support')
elif coord.start is not None and coord.stop is not None:
return DoubleSlice.from_slice(coord)
elif coord.start is not No... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return the first worksheet with the given title. | Given the following Python 3 function, write the documentation
def find(self, title):
if title not in self._titles:
raise KeyError(title)
return self._titles[title][0] | As a Python code analyst, you investigate and solve complex coding mysteries |
def findall(self, title=None):
"""Return a list of worksheets with the given title.
Args:
title(str): title/name of the worksheets to return, or ``None`` for all
Returns:
list: list of contained worksheet instances (possibly empty)
"""
if title is None:
... | Write a Python 3 function for
returning a list of contained worksheets with the given title. | You are a Python code architect, reviewing and designing scalable and efficient code |
def to_csv(self, encoding=export.ENCODING, dialect=export.DIALECT,
make_filename=export.MAKE_FILENAME):
"""Dump all worksheets of the spreadsheet to individual CSV files.
Args:
encoding (str): result string encoding
dialect (str): :mod:`csv` dialect name or object... | Can you create a Python 3 function that
dumps all worksheets of the spreadsheet to individual CSV files. | You are a Python code generator, capable of creating scripts from specifications. |
def titles(self, unique=False):
"""Return a list of contained worksheet titles.
Args:
unique (bool): drop duplicates
Returns:
list: list of titles/name strings
"""
if unique:
return tools.uniqued(s.title for s in self._items)
return [s... | Create a Python 3 function for
returning a list of contained worksheet titles. | You are a Python code architect, reviewing and designing scalable and efficient code |
def at(self, row, col):
"""Return the value at the given cell position.
Args:
row (int): zero-based row number
col (int): zero-based column number
Returns:
cell value
Raises:
TypeError: if ``row`` or ``col`` is not an ``int``
Ind... | Can you create a Python 3 function that
returns the value at the given cell position. | As a Python code composer, you craft elegant and concise scripts. |
Return a nested list with the worksheet values. | Can you generate a brief explanation for the following Python 3 code
def values(self, column_major=False):
if column_major:
return list(map(list, zip(*self._values)))
return [row[:] for row in self._values] | As a Python code composer, you craft elegant and concise scripts. |
Dump the worksheet to a CSV file. | Given the following Python 3 function, write the documentation
def to_csv(self, filename=None,
encoding=export.ENCODING, dialect=export.DIALECT,
make_filename=export.MAKE_FILENAME):
"""Dump the worksheet to a CSV file.
Args:
filename (str): result filename (if ... | As a Python code composer, you craft elegant and concise scripts. |
r Return a pandas DataFrame loaded from the worksheet data. | Explain what the following Python 3 code does
def to_frame(self, **kwargs):
df = export.write_dataframe(self._values, **kwargs)
df.name = self.title
return df | You are a Python code generator, capable of creating scripts from specifications. |
def from_files(cls, secrets=None, storage=None, scopes=None, no_webserver=False):
"""Return a spreadsheet collection making OAauth 2.0 credentials.
Args:
secrets (str): location of secrets file (default: ``%r``)
storage (str): location of storage file (default: ``%r``)
... | Write a Python 3 function that can
return a spreadsheet collection making OAauth 2. 0 credentials. | As a Python code analyst, you investigate and solve complex coding mysteries |
Fetch and return the new SpreadSheet instance with the given id or url. | Make a summary of the following Python 3 code
def get(self, id_or_url, default=None):
if '/' in id_or_url:
id = urls.SheetUrl.from_string(id_or_url).id
else:
id = id_or_url
try:
return self[id]
except KeyError:
return default | As a python code expert, you are capable of creating scripts from specifications. |
def find(self, title):
"""Fetch and return the first spreadsheet with the given title.
Args:
title(str): title/name of the spreadsheet to return
Returns:
SpreadSheet: new SpreadSheet instance
Raises:
KeyError: if no spreadsheet with the given ``title`... | Write a Python 3 function that can
fetch and return the first spreadsheet with the given title. | You are a Python code architect, reviewing and designing scalable and efficient code |
def findall(self, title=None):
"""Fetch and return a list of spreadsheets with the given title.
Args:
title(str): title/name of the spreadsheets to return, or ``None`` for all
Returns:
list: list of new SpreadSheet instances (possibly empty)
"""
if title ... | Can you write a function in Python 3 where it
fetches and return a list of spreadsheets with the given title. | You are a Python code generator, capable of creating scripts from specifications. |
def titles(self, unique=False):
"""Return a list of all available spreadsheet titles.
Args:
unique (bool): drop duplicates
Returns:
list: list of title/name strings
"""
if unique:
return tools.uniqued(title for _, title in self.iterfiles())
... | Implement a function in Python 3 to
return a list of all available spreadsheet titles. | As a Python code composer, you craft elegant and concise scripts. |
def create(self, name, description, data_source_type,
url, credential_user=None, credential_pass=None,
is_public=None, is_protected=None, s3_credentials=None):
"""Create a Data Source."""
data = {
'name': name,
'description': description,
... | Write a Python 3 function for
creating a new Data Source. | You are a Python code generator, capable of creating scripts from specifications. |
def update(self, data_source_id, update_data):
"""Update a Data Source.
:param dict update_data: dict that contains fields that should be
updated with new values.
Fields that can be updated:
* name
* description
* type
* url
... | Implement a Python 3 function for
updating a specific data source. | You are a Python code architect, reviewing and designing scalable and efficient code |
Access item in d using path. | Make a summary of the following Python 3 code
def getitem_by_path(d, path):
return reduce(
lambda d, k: d[k],
path,
d
) | You are a Python code architect, reviewing and designing scalable and efficient code |
def clean_empty(self, d=DEFAULT):
"""Returns a copy of d without empty leaves.
https://stackoverflow.com/questions/27973988/python-how-to-remove-all-empty-fields-in-a-nested-dict/35263074
"""
if d is DEFAULT:
d = self
if isinstance(d, list):
return [v for... | Can you create a Python 3 function that
returns a copy of d without empty leaves. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a copy of d with compressed leaves. | Make a summary of the following Python 3 code
def compress(self, d=DEFAULT):
if d is DEFAULT:
d = self
if isinstance(d, list):
l = [v for v in (self.compress(v) for v in d)]
try:
return list(set(l))
except TypeError:
# list ... | As a Python code composer, you craft elegant and concise scripts. |
def cast_dicts(self, to=DEFAULT, d=DEFAULT):
"""Returns a copy of d with all dicts casted to the type 'to'."""
if to is DEFAULT:
to = type(self)
if d is DEFAULT:
d = self
if isinstance(d, list):
return [v for v in (self.cast_dicts(to, v) for v in d)]
... | Implement a function in Python 3 to
return a copy of d with all dicts casted to the type to. | You are a Python code generator, capable of creating scripts from specifications. |
def merge(self, b, a=DEFAULT):
"""Merges b into a recursively, if a is not given: merges into self.
also merges lists and:
* merge({a:a},{a:b}) = {a:[a,b]}
* merge({a:[a]},{a:b}) = {a:[a,b]}
* merge({a:a},{a:[b]}) = {a:[a,b]}
* merge({a:[a]},{a:[b]}) = {a... | Can you implement a function in Python 3 that
merges b into self. | As a Python code composer, you craft elegant and concise scripts. |
def create(self, name, url, description=None, extra=None, is_public=None,
is_protected=None):
"""Create a Job Binary.
:param dict extra: authentication info needed for some job binaries,
containing the keys `user` and `password` for job binary in Swift
or the keys... | Write a Python 3 function for
creating a Job Binary. | You are a Python code architect, reviewing and designing scalable and efficient code |
Download a Job Binary. | Explain what the following Python 3 code does
def get_file(self, job_binary_id):
resp = self.api.get('/job-binaries/%s/data' % job_binary_id)
if resp.status_code != 200:
self._raise_api_exception(resp)
return resp.content | As a python code expert, you are capable of creating scripts from specifications. |
Update the properties of the job binary with the given data. | Here you have a function in Python 3, explain what it does
def update(self, job_binary_id, data):
if self.version >= 2:
UPDATE_FUNC = self._patch
else:
UPDATE_FUNC = self._update
return UPDATE_FUNC(
'/job-binaries/%s' % job_binary_id, data, 'job_binary') | You are a Python code generator, capable of creating scripts from specifications. |
def set(conf):
"""Applies a configuration to the global config object"""
for name, value in conf.items():
if value is not None:
setattr(Conf, name.upper(), value) | Can you implement a function in Python 3 that
applies a configuration to the global config object | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get():
"""Gets the configuration as a dict"""
return {
attr: getattr(Conf, attr)
for attr in dir(Conf()) if not callable(getattr(Conf, attr)) and not attr.startswith("__")
} | Write a Python 3 function for
getting the configuration as a dict | You are a Python code generator, capable of creating scripts from specifications. |
Loads the global Conf object from command line arguments. | Here you have a function in Python 3, explain what it does
def load(description, add_arguments_cb = lambda x: None, postprocess_conf_cb = lambda x: None):
argparser = ArgumentParser(
description = description,
prefix_chars = '-+'
)
argparser.add_argument(
'-... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the help string without the prefix. | How would you explain what the following Python 3 function does
def _format_usage_without_prefix(parser):
fmt = parser._get_formatter()
fmt.add_usage(parser.usage, parser._actions,
parser._mutually_exclusive_groups, prefix='')
return fmt.format_help().strip() | As a Python code analyst, you investigate and solve complex coding mysteries |
Update a Node Group Template. | Make a summary of the following Python 3 code
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated,
hadoop_version=NotUpdated, flavor_id=NotUpdated,
description=NotUpdated, volumes_per_node=NotUpdated,
volumes_size=NotUpdated, node_processes=NotUpdated,
... | You are a Python code generator, capable of creating scripts from specifications. |
def create(self, name, plugin_name, plugin_version, flavor_id,
description=None, volumes_per_node=None, volumes_size=None,
node_processes=None, node_configs=None, floating_ip_pool=None,
security_groups=None, auto_security_group=None,
availability_zone=None, vo... | Implement a Python 3 function for
creating a new Node Group Template. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update a Node Group Template. | Make a summary of the following Python 3 code
def update(self, ng_template_id, name=NotUpdated, plugin_name=NotUpdated,
plugin_version=NotUpdated, flavor_id=NotUpdated,
description=NotUpdated, volumes_per_node=NotUpdated,
volumes_size=NotUpdated, node_processes=NotUpdated,
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def update_image(self, image_id, user_name, desc=None):
"""Create or update an Image in Image Registry."""
desc = desc if desc else ''
data = {"username": user_name,
"description": desc}
return self._post('/images/%s' % image_id, data) | Can you create a Python 3 function that
creates or update an Image in Image Registry. | As a Python code composer, you craft elegant and concise scripts. |
def update_tags(self, image_id, new_tags):
"""Update an Image tags.
:param new_tags: list of tags that will replace currently
assigned tags
"""
# Do not add :param list in the docstring above until this is solved:
# https://github.com/sphinx-doc/sp... | Implement a function in Python 3 to
update an Image tags. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Hook to add global options. | Can you generate a brief explanation for the following Python 3 code
def build_option_parser(parser):
parser.add_argument(
"--os-data-processing-api-version",
metavar="<data-processing-api-version>",
default=utils.env(
'OS_DATA_PROCESSING_API_VERSION',
default=DEFAULT... | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a Cluster Template. | Make a summary of the following Python 3 code
def create(self, name, plugin_name, hadoop_version, description=None,
cluster_configs=None, node_groups=None, anti_affinity=None,
net_id=None, default_image_id=None, use_autoconfig=None,
shares=None, is_public=None, is_protected=... | As a Python code analyst, you investigate and solve complex coding mysteries |
Update a Cluster Template. | Explain what the following Python 3 code does
def update(self, cluster_template_id, name=NotUpdated,
plugin_name=NotUpdated, plugin_version=NotUpdated,
description=NotUpdated, cluster_configs=NotUpdated,
node_groups=NotUpdated, anti_affinity=NotUpdated,
net_id... | As a python code expert, you are capable of creating scripts from specifications. |
def get(self, cluster_id, show_progress=False):
"""Get information about a Cluster."""
url = ('/clusters/%(cluster_id)s?%(params)s' %
{"cluster_id": cluster_id,
"params": parse.urlencode({"show_progress": show_progress})})
return self._get(url, 'cluster') | Write a Python 3 function for
getting information about a Cluster. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Start a verification for a Cluster. | Can you generate the documentation for the following Python 3 function
def verification_update(self, cluster_id, status):
data = {'verification': {'status': status}}
return self._patch("/clusters/%s" % cluster_id, data) | As a Python code composer, you craft elegant and concise scripts. |
Gets the command for each class in classes | Can you generate a brief explanation for the following Python 3 code
def _get_command(classes):
commands = {}
setup_file = os.path.join(
os.path.abspath(os.path.join(os.path.dirname(__file__), '../..')),
'setup.cfg')
for line in open(setup_file, 'r'):
for cl in classes:
i... | You are a Python code architect, reviewing and designing scalable and efficient code |
Provide backward compatibility with old versions of requests library. | Here you have a function in Python 3, explain what it does
def get_json(response):
json_field_or_function = getattr(response, 'json', None)
if callable(json_field_or_function):
return response.json()
else:
return jsonutils.loads(response.content) | You are a Python code generator, capable of creating scripts from specifications. |
def create(self, name, data):
"""Create a Job Binary Internal.
:param str data: raw data of script text
"""
return self._update('/job-binary-internals/%s' %
urlparse.quote(name.encode('utf-8')), data,
'job_binary_internal', dump_js... | Create a Python 3 function for
creating a Job Binary Internal. | You are a Python code analyst, evaluating scripts for potential improvements. |
def update(self, job_binary_id, name=NotUpdated, is_public=NotUpdated,
is_protected=NotUpdated):
"""Update a Job Binary Internal."""
data = {}
self._copy_if_updated(data, name=name, is_public=is_public,
is_protected=is_protected)
return self... | Implement a Python 3 function for
updating a Job Binary Internal. | As a python code expert, you are capable of creating scripts from specifications. |
def autoconvert(string):
"""Try to convert variables into datatypes."""
for fn in (boolify, int, float):
try:
return fn(string)
except ValueError:
pass
return string | How would you code a function in Python 3 to
try to convert variables into datatypes. | As a Python code composer, you craft elegant and concise scripts. |
Calls function f from plugin returns None if plugin does not implement f. | Can you generate the documentation for the following Python 3 function
def call_plugin(plugin, f, *args, **kwargs):
try:
getattr(plugin, f)
except AttributeError:
return None
if kwargs:
getattr(plugin, f)(
*args,
**kwargs
)
else:
return get... | As a python code expert, you are capable of creating scripts from specifications. |
def update(self, obj_id, is_public=NotUpdated, is_protected=NotUpdated):
"""Update a Job Execution."""
data = {}
self._copy_if_updated(data, is_public=is_public,
is_protected=is_protected)
return self._patch('/job-executions/%s' % obj_id, data) | Write a Python 3 script to
update a Job Execution. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Converts case insensitive keywords and identifiers to lowercase
| Can you tell what is the following Python 3 function doing
def visitTerminal(self, ctx):
text = str(super().visitTerminal(ctx))
quotes = ["'", '"']
if not (text[0] in quotes and text[-1] in quotes):
text = text.lower()
return Terminal.from_text(text, ctx) | You are a Python code architect, reviewing and designing scalable and efficient code |
def list(self, search_opts=None):
"""Get a list of Plugins."""
query = base.get_query_string(search_opts)
return self._list('/plugins%s' % query, 'plugins') | Can you write a function in Python 3 where it
gets a list of Plugins. | You are a Python code analyst, evaluating scripts for potential improvements. |
def convert_to_cluster_template(self, plugin_name, hadoop_version,
template_name, filecontent):
"""Convert to cluster template
Create Cluster Template directly, avoiding Cluster Template
mechanism.
"""
resp = self.api.post('/plugins/%s/%s/conv... | Can you write a function in Python 3 where it
converts to cluster template | You are a Python code generator, capable of creating scripts from specifications. |
def list(self, search_opts=None, limit=None,
marker=None, sort_by=None, reverse=None):
"""Get a list of Jobs."""
query = base.get_query_string(search_opts, limit=limit, marker=marker,
sort_by=sort_by, reverse=reverse)
url = "/jobs%s" % query
... | Create a Python 3 function to
get a list of Jobs. | As a python code expert, you are capable of creating scripts from specifications. |
def _query_for_reverse_geocoding(lat, lng):
"""
Given a lat & lng, what's the string search query.
If the API changes, change this function. Only for internal use.
"""
# have to do some stupid f/Decimal/str stuff to (a) ensure we get as much
# decimal places as the user already specified and (b... | Implement a Python 3 function for
giving a lat & lng what s the string search query. | As a python code expert, you are capable of creating scripts from specifications. |
Convert lat and lng into floats. | Explain what the following Python 3 code does
def floatify_latlng(input_value):
if isinstance(input_value, collections.Mapping):
if len(input_value) == 2 and sorted(input_value.keys()) == ['lat', 'lng']:
# This dict has only 2 keys 'lat' & 'lon'
return {'lat': float_if_float(input_va... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Given a string to search for return the results from OpenCage s Geocoder. | Given the following Python 3 function, write the documentation
def geocode(self, query, **kwargs):
if six.PY2:
# py3 doesn't have unicode() function, and instead we check the text_type later
try:
query = unicode(query)
except UnicodeDecodeError:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def reverse_geocode(self, lat, lng, **kwargs):
"""
Given a latitude & longitude, return an address for that point from OpenCage's Geocoder.
:param lat: Latitude
:param lng: Longitude
:return: Results from OpenCageData
:rtype: dict
:raises RateLimitExceededError: ... | Write a Python 3 function that can
give a latitude & longitude return an address for that point from OpenCage s Geocoder. | As a Python code composer, you craft elegant and concise scripts. |
Get a new connection from the pool. This will return an existing connection if one is available in the pool. If the pool is empty or if there is no longer than the maxsize limit a new connection will be created. | Given the following Python 3 function, write the documentation
def acquire(self):
'''
Get a new connection from the pool.
This will return an existing connection, if one is available in the
pool, or create a new connection.
.. warning:: If the pool was created with `maxsize` and... | As a python code expert, you are capable of creating scripts from specifications. |
def release(self, connection):
'''
Return a connection back to the pool.
Prior to release, :py:meth:`ctds.Connection.rollback()` is called to
rollback any pending transaction.
.. note:: This must be called once for every successful call to
:py:meth:`.acquire()`.
... | How would you implement a function in Python 3 that
returns a connection back to the pool. | You are a Python code analyst, evaluating scripts for potential improvements. |
def finalize(self):
'''
Release all connections contained in the pool.
.. note:: This should be called to cleanly shutdown the pool, i.e.
on process exit.
'''
self._condition.acquire()
try:
if self._nconnections != len(self._pool):
... | Write a Python 3 script for
closing all connections contained in the pool. | As a python code expert, you are capable of creating scripts from specifications. |
def _parse_schema(schema, method):
"""
Convert a Schema Object to a Python object.
Args:
schema: An ``OrderedDict`` representing the schema object.
"""
if method and schema.get('readOnly', False):
return _READONLY_PROPERTY
# allOf: Must be valid against all of the subschemas
... | Implement a Python 3 function for
converting a schema object to a Python object. | You are a Python code architect, reviewing and designing scalable and efficient code |
Generate a single example for the given media type objects. | Here you have a function in Python 3, explain what it does
def _example(media_type_objects, method=None, endpoint=None, status=None,
nb_indent=0):
"""
Format examples in `Media Type Object` openapi v3 to HTTP request or
HTTP response example.
If method and endpoint is provided, this fonctio... | As a python code expert, you are capable of creating scripts from specifications. |
Resolve JSON references in a given dictionary. | Can you generate the documentation for the following Python 3 function
def _resolve_refs(uri, spec):
resolver = jsonschema.RefResolver(uri, spec)
def _do_resolve(node):
if isinstance(node, collections.Mapping) and '$ref' in node:
with resolver.resolving(node['$ref']) as resolved:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def convert_double_to_two_registers(doubleValue):
"""
Convert 32 Bit Value to two 16 Bit Value to send as Modbus Registers
doubleValue: Value to be converted
return: 16 Bit Register values int[]
"""
myList = list()
myList.append(int(doubleValue & 0x0000FFFF)) #Append Least Signific... | How would you implement a function in Python 3 that
converts a 32 Bit value to two 16 Bit value | As a python code expert, you are capable of creating scripts from specifications. |
Converts a 32 Bit real value to two 16 Bit value | Can you generate a brief explanation for the following Python 3 code
def convert_float_to_two_registers(floatValue):
myList = list()
s = bytearray(struct.pack('<f', floatValue) ) #little endian
myList.append(s[0] | (s[1]<<8)) #Append Least Significant Word
myList.append(s[2] | (s[3]<<8)) ... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def convert_registers_to_float(registers):
"""
Convert two 16 Bit Registers to 32 Bit real value - Used to receive float values from Modbus (Modbus Registers are 16 Bit long)
registers: 16 Bit Registers
return: 32 bit value real
"""
b = bytearray(4)
b [0] = registers[0] & 0xff
b [1] = ... | Write a Python 3 function for
converting two 16 Bit Registers to 32 Bit real value | As a Python code translator, you convert algorithms and pseudocode into Python. |
Connects to a Modbus - TCP Server or Modbus - RTU Slave with the given Parameters
| Can you generate a brief explanation for the following Python 3 code
def connect(self):
if (self.__ser is not None):
serial = importlib.import_module("serial")
if self.__stopbits == 0:
self.__ser.stopbits = serial.STOPBITS_ONE
elif self.__stopbits == 1:
... | As a python code expert, you are capable of creating scripts from specifications. |
def close(self):
"""
Closes Serial port, or TCP-Socket connection
"""
if (self.__ser is not None):
self.__ser.close()
if (self.__tcpClientSocket is not None):
self.__stoplistening = True
self.__tcpClientSocket.shutdown(socket.SHUT_RDWR)
... | Write a Python 3 function for
closing Serial port TCP - Socket connection. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def read_discreteinputs(self, starting_address, quantity):
"""
Read Discrete Inputs from Master device (Function code 2)
starting_address: First discrete input to be read
quantity: Numer of discrete Inputs to be read
returns: Boolean Array [0..quantity-1] which contains the discr... | Can you implement a function in Python 3 that
reads Discrete Inputs from Master device (Function code 2) starting_address: First discrete input to be read quantity: Numer of discrete Inputs to be read returns: Boolean Array [0..quantity-1] which contains the discrete Inputs | As a python code expert, you are capable of creating scripts from specifications. |
Write a single Coil to the Master device. | Can you generate the documentation for the following Python 3 function
def write_single_coil(self, starting_address, value):
self.__transactionIdentifier+=1
if (self.__ser is not None):
if (self.__ser.closed):
raise Exception.SerialPortNotOpenedException("serial port not open... | As a Python code composer, you craft elegant and concise scripts. |
Write multiple coils to Master device. | Can you generate a brief explanation for the following Python 3 code
def write_multiple_coils(self, starting_address, values):
self.__transactionIdentifier+=1
if (self.__ser is not None):
if (self.__ser.closed):
raise Exception.SerialPortNotOpenedException("serial port not op... | As a python code expert, you are capable of creating scripts from specifications. |
Returns a flattened dictionary of all services in a service group | Can you generate the documentation for the following Python 3 function
def services(self, service_group=None):
# Specific service group requested
if service_group is not None:
if service_group not in EFConfig.SERVICE_GROUPS:
raise RuntimeError("service registry: {} doesn't have '{}' section listed... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def iter_services(self, service_group=None):
"""
Args:
service_group: optional name of service group
Returns:
if service_group is omitted or None, an Iterator over all flattened service records in the service registry
if service_group is present, an Iterator over all service records in tha... | Create a Python 3 function for
returning an iterator over all services in a service group | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a list of valid environments for the given service in the service registry | Can you generate a brief explanation for the following Python 3 code
def valid_envs(self, service_name):
service_record = self.service_record(service_name)
if service_record is None:
raise RuntimeError("service registry doesn't have service: {}".format(service_name))
# Return empty list if service ha... | As a Python code composer, you craft elegant and concise scripts. |
Returns the service record for the given service name | Given the following Python 3 function, write the documentation
def service_record(self, service_name):
if not self.services().has_key(service_name):
return None
return self.services()[service_name] | As a Python code translator, you convert algorithms and pseudocode into Python. |
Returns the name of the group that the service is in | How would you explain what the following Python 3 function does
def service_group(self, service_name):
for group in EFConfig.SERVICE_GROUPS:
if self.services(group).has_key(service_name):
return group
return None | As a Python code translator, you convert algorithms and pseudocode into Python. |
def service_region(self, service_name):
"""
Args:
service_name: the name of the service in the service registry
Returns:
the region the service is in, or EFConfig.DEFAULT_REGION if the region was not found
"""
if not self.services()[service_name].has_key("region"):
return EFConfig.... | Can you implement a function in Python 3 that
returns the region of the service in the service registry | As a Python code analyst, you investigate and solve complex coding mysteries |
This function is used to train and evaluate a keras model. | Explain what the following Python 3 code does
def easy_train_and_evaluate(hyper_params, Model=None, create_loss=None,
training_data=None, validation_data=None,
inline_plotting=False, session_config=None, log_suffix=None,
continue_train... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def create_prediction_estimator(hyper_params, model, checkpoint_path=None):
"""
Create an estimator for prediction purpose only.
:param hyper_params: The hyper params file.
:param model: The keras model.
:param checkpoint_path: (Optional) Path to the specific checkpoint to use.
:return:
"""
... | Create a Python 3 function to
create an estimator for prediction purpose only. | As a python code expert, you are capable of creating scripts from specifications. |
Returns a class decorator for creating new class of the same name as the given service. | Can you generate the documentation for the following Python 3 function
def ef_plugin(service_name):
def class_rebuilder(cls):
class EFPlugin(cls):
"""
Base class of ef-plugins. Defines which service is extended and provides access to the current instance of
EFContext to the plugin.
Args:... | As a Python code composer, you craft elegant and concise scripts. |
def run_plugins(context_obj, boto3_clients):
"""
Executes all loaded plugins designated for the service calling the function.
Args:
context_obj (obj:EFContext): The EFContext object created by the service.
boto3_clients (dict): Dictionary of boto3 clients created by ef_utils.create_aws_clients()
"""
... | Write a Python 3 script for
executing all loaded plugins for the given service. | You are a Python code architect, reviewing and designing scalable and efficient code |
This function is used to train and evaluate a keras model. | Here you have a function in Python 3, explain what it does
def easy_train_and_evaluate(hyper_params, Model=None, define_loss_fn=None,
training_data=None, validation_data=None,
continue_training=False,
session_config=None, log_suffix=Non... | As a Python code composer, you craft elegant and concise scripts. |
def crop(img, start_y, start_x, h, w):
"""
Crop an image given the top left corner.
:param img: The image
:param start_y: The top left corner y coord
:param start_x: The top left corner x coord
:param h: The result height
:param w: The result width
:return: The cropped image.
"""
... | Can you implement a function in Python 3 that
crops an image given the top left corner. | As a python code expert, you are capable of creating scripts from specifications. |
def resize_image_with_crop_or_pad(img, target_height, target_width):
"""
Crops and/or pads an image to a target width and height.
Resizes an image to a target width and height by either cropping the image or padding it with zeros.
NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom r... | Create a Python 3 function for
cropping and/or pads an image to a target width and height. Resizes an image to a target width and height by either cropping the image or padding it with zeros. NO CENTER CROP. NO CENTER PAD. (Just fill bottom right or crop bottom right) :param img: Numpy array representing the image. :pa... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _rotatedRectWithMaxArea(w, h, angle):
"""
Given a rectangle of size wxh that has been rotated by 'angle' (in
radians), computes the width and height of the largest possible
axis-aligned rectangle (maximal area) within the rotated rectangle.
Answer from: https://stackoverflow.com/questions/16702966/rotate... | Can you write a function in Python 3 where it
gives a rectangle of size wxh that has been rotated by 'angle' (in radians), computes the width and height of the largest possible axis-aligned rectangle (maximal area) within the rotated rectangle. Answer from: https://stackoverflow.com/questions/16702966/rotate-image-and-... | You are a Python code analyst, evaluating scripts for potential improvements. |
Rotate an image and then crop it so that there is no black area. | Can you generate a brief explanation for the following Python 3 code
def rotate_img_and_crop(img, angle):
h, w, _ = img.shape
img = scipy.ndimage.interpolation.rotate(img, angle)
w, h = _rotatedRectWithMaxArea(w, h, math.radians(angle))
return crop_center(img, int(h), int(w)) | You are a Python code generator, capable of creating scripts from specifications. |
def diff_string_templates(string_a, string_b):
"""
Determine the diff of two strings. Return an empty string if the strings
are identical, and the diff output string if they are not.
"""
s1 = string_a.strip().splitlines()
s2 = string_b.strip().splitlines()
diffs = unified_diff(s2, s1, fromf... | How would you code a function in Python 3 to
determine the diff of two strings. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def render_local_template(service_name, environment, repo_root, template_file):
"""
Render a given service's template for a given environment and return it
"""
cmd = 'cd {} && ef-cf {} {} --devel --verbose'.format(repo_root, template_file, environment)
p = subprocess.Popen(cmd, shell=True, stdout=su... | Can you create a Python 3 function that
renders a given service s template for a given environment and return it | You are a Python code architect, reviewing and designing scalable and efficient code |
def fetch_current_cloudformation_template(service_name, environment, cf_client):
"""
Fetch the currently-deployed template for the given service in the given
environment and return it.
"""
stack_name = get_stack_name(environment, service_name)
logger.debug('Fetching template for `%s`', stack_nam... | Can you implement a function in Python 3 that
fetches the currently - deployed template for the given service in the given environment and return it. | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a list of strings that are different from the local template that was last applied in the target environment. | Can you generate the documentation for the following Python 3 function
def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root):
global ret_code
logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`',
service['type'], service_name, environment)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Given a service name and an environment name return a CloudFormation
client object. | Can you generate the documentation for the following Python 3 function
def get_cloudformation_client(service_name, environment_name):
region = service_registry.service_region(service_name)
if whereami() == 'ec2':
profile = None
else:
profile = get_account_alias(environment_name)
client... | You are a Python code analyst, evaluating scripts for potential improvements. |
def evaluate_service_changes(services, envs, repo_root, func):
"""
Given a dict of services, and a list of environments, apply the diff
function to evaluate the differences between the target environments
and the rendered templates.
Sub-services (names with '.' in them) are skipped.
"""
for... | How would you implement a function in Python 3 that
evaluates the differences between the target environments and the rendered templates. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the template file that goes with the given service name or None if there s no match. | Make a summary of the following Python 3 code
def get_matching_service_template_file(service_name, template_files):
# If this is a subservice, use the parent service's template
service_name = service_name.split('.')[0]
if service_name in template_files:
return template_files[service_name]
return... | You are a Python code architect, reviewing and designing scalable and efficient code |
Returns a dict mapping service name to a dict containing the type of service template file and the list of environments to which the service is intended to deploy. | Can you generate a brief explanation for the following Python 3 code
def get_dict_registry_services(registry, template_files, warn_missing_files=True):
with open(registry) as fr:
parsed_registry = json.load(fr)
services = {}
for type, type_services in parsed_registry.iteritems():
for name, ... | As a python code expert, you are capable of creating scripts from specifications. |
Scan the directory for template files. | Explain what the following Python 3 code does
def scan_dir_for_template_files(search_dir):
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
template_dir = os.path.join(cf_dir, type, 'templates')
for x in os.listdir(template_dir):
... | 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.