output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Convert a EUC - CN hex string to a Python unicode string. | Given the following Python 3 function, write the documentation
def euc_to_python(hexstr):
hi = hexstr[0:2]
lo = hexstr[2:4]
gb_enc = b'\\x' + hi + b'\\x' + lo
return gb_enc.decode("gb2312") | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert EUC hex to UTF8 hex. | Can you generate the documentation for the following Python 3 function
def euc_to_utf8(euchex):
utf8 = euc_to_python(euchex).encode("utf-8")
uf8 = utf8.decode('unicode_escape')
uf8 = uf8.encode('latin1')
uf8 = uf8.decode('euc-jp')
return uf8 | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert a Unicode Universal Character Number to a Python unicode character. | Can you generate the documentation for the following Python 3 function
def ucn_to_unicode(ucn):
if isinstance(ucn, string_types):
ucn = ucn.strip("U+")
if len(ucn) > int(4):
char = b'\U' + format(int(ucn, 16), '08x').encode('latin1')
char = char.decode('unicode_escape')
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert an EUC - CN hex string to a Python unicode string. | Explain what the following Python 3 code does
def euc_to_unicode(hexstr):
hi = hexstr[0:2]
lo = hexstr[2:4]
# hi and lo are only 2 characters long, no risk with eval-ing them
gb_enc = b'\\x' + hi + b'\\x' + lo
assert isinstance(gb_enc, bytes)
# Requires coercing back to text_type in 2.7
gb... | You are a Python code architect, reviewing and designing scalable and efficient code |
Converts a Python Unicode character to a UCN character. | Can you generate a brief explanation for the following Python 3 code
def python_to_ucn(uni_char, as_bytes=False):
ucn = uni_char.encode('unicode_escape').decode('latin1')
ucn = text_type(ucn).replace('\\', '').upper().lstrip('U')
if len(ucn) > int(4):
# get rid of the zeroes that Python uses to pad ... | As a Python code analyst, you investigate and solve complex coding mysteries |
Converts a Python Unicode character to an EUC character. | Can you generate a brief explanation for the following Python 3 code
def python_to_euc(uni_char, as_bytes=False):
euc = repr(uni_char.encode("gb2312"))[1:-1].replace("\\x", "").strip("'")
if as_bytes:
euc = euc.encode('utf-8')
assert isinstance(euc, bytes)
return euc | As a python code expert, you are capable of creating scripts from specifications. |
def ucnstring_to_unicode(ucn_string):
"""Return ucnstring as Unicode."""
ucn_string = ucnstring_to_python(ucn_string).decode('utf-8')
assert isinstance(ucn_string, text_type)
return ucn_string | Create a Python 3 function for
returning ucnstring as Unicode. | As a Python code composer, you craft elegant and concise scripts. |
Convert Unicode UCN to native Python Unicode Unicode
| Can you generate the documentation for the following Python 3 function
def ucnstring_to_python(ucn_string):
res = re.findall("U\+[0-9a-fA-F]*", ucn_string)
for r in res:
ucn_string = ucn_string.replace(text_type(r), text_type(ucn_to_unicode(r)))
ucn_string = ucn_string.encode('utf-8')
assert i... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse a UCN - style variable into a tuple consisting of a string and a tag. | Here you have a function in Python 3, explain what it does
def parse_var(var):
bits = var.split("<", 1)
if len(bits) < 2:
tag = None
else:
tag = bits[1]
return ucn_to_unicode(bits[0]), tag | As a Python code composer, you craft elegant and concise scripts. |
def from_file(cls, config_path=None, *args, **kwargs):
"""
Create a Cihai instance from a JSON or YAML config.
Parameters
----------
config_path : str, optional
path to custom config file
Returns
-------
:class:`Cihai` :
applicati... | How would you implement a function in Python 3 that
creates a Cihai instance from a JSON or YAML config file. | As a Python code composer, you craft elegant and concise scripts. |
Return True if this locale should be processed. | Can you generate the documentation for the following Python 3 function
def _process_locale(self, locale):
if locale.lower().startswith('en'):
return False
return (locale in self.enabled_locales or
self.reverse_locale_map.get(locale.lower(), None)
in self.en... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def desk_locale(self, locale):
"""Return the Desk-style locale for locale."""
locale = locale.lower().replace('-', '_')
return self.vendor_locale_map.get(locale, locale) | Write a Python 3 function for
returning the Desk - style locale for locale. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Push topics to Transifex. | Explain what the following Python 3 code does
def push(self):
tx = Tx(self.tx_project_slug)
# asssemble the template catalog
template = babel.messages.catalog.Catalog()
for topic in self.desk.topics():
if topic.show_in_portal:
template.add(topic.name)
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Pulls topics from Transifex and uploads them to Desk. | Can you tell what is the following Python 3 function doing
def pull(self):
topic_stats = txlib.api.statistics.Statistics.get(
project_slug=self.tx_project_slug,
resource_slug=self.TOPIC_STRINGS_SLUG,
)
translated = {}
# for each language
for locale in s... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a single HTML document containing the title and content. | Explain what the following Python 3 code does
def make_resource_document(self, title, content, tags=[],):
assert "<html>" not in content
assert "<body>" not in content
return """
<html>
<head><title>%(title)s</title></head>
<body>
%(content)s
</body>
... | You are a Python code generator, capable of creating scripts from specifications. |
def parse_resource_document(self, content):
"""Return a dict with the keys title, content, tags for content."""
content = content.strip()
if not content.startswith('<html>'):
# this is not a full HTML doc, probably content w/o title, tags, etc
return dict(body=content)
... | Write a Python 3 script for
parsing the resource document. | You are a Python code architect, reviewing and designing scalable and efficient code |
def push(self):
"""Push tutorials to Transifex."""
tx = Tx(self.tx_project_slug)
if self.options.resources:
articles = [
self.desk.articles().by_id(r.strip())
for r in self.options.resources.split(',')
]
else:
articles... | Write a Python 3 function for
pushing tutorials to Transifex. | As a python code expert, you are capable of creating scripts from specifications. |
def get_project(self, locale, source_language_code=DEFAULT_SOURCE_LANGUAGE, **kwargs):
"""
Gets or creates the Transifex project for the current project prefix and locale
:param locale: A locale to which content is to be translated
:type locale: string
:param source_language_cod... | Create a Python 3 function to
get or creates a Transifex project for the current project prefix and locale | As a Python code analyst, you investigate and solve complex coding mysteries |
def translation_exists(self, slug, lang):
"""Return True if the translation exists for this slug."""
try:
return translations.Translation.get(
project_slug=self.get_project_slug(lang),
slug=slug,
lang=lang,
)
except (NotFo... | Can you create a Python 3 function that
returns True if the translation exists for this slug. | You are a Python code architect, reviewing and designing scalable and efficient code |
def list_resources(self, lang):
"""Return a sequence of resources for a given lang.
Each Resource is a dict containing the slug, name, i18n_type,
source_language_code and the category.
"""
return registry.registry.http_handler.get(
'/api/2/project/%s/resources/' % (... | How would you code a function in Python 3 to
return a sequence of resources for a given lang. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate a list of Resources in the Project. | Here you have a function in Python 3, explain what it does
def resources(self, lang, slug):
resource = resources.Resource.get(
project_slug=self.get_project_slug(lang),
slug=slug,
)
return resource | You are a Python code architect, reviewing and designing scalable and efficient code |
def resource_exists(self, slug, locale, project_slug=None):
"""Return True if a Resource with the given slug exists in locale."""
try:
resource = resources.Resource.get(
project_slug=project_slug or self.get_project_slug(locale),
slug=slug,
)
... | Write a Python 3 script for
returning True if a Resource with the given slug exists in locale. | You are a Python code architect, reviewing and designing scalable and efficient code |
def session_request(session, url, **kwargs):
"""Do HTTP/S request and return response as a string."""
try:
response = session(url, **kwargs)
response.raise_for_status()
return response.text
except requests.exceptions.HTTPError as errh:
_LOGGER.debug("%s, %s", response, err... | Implement a Python 3 function for
doing HTTP request and return response as a string. | You are a Python code analyst, evaluating scripts for potential improvements. |
Get a dict of supported events from device. | Make a summary of the following Python 3 code
def get_event_list(config):
eventinstances = session_request(
config.session.post, device_event_url.format(
proto=config.web_proto, host=config.host, port=config.port),
auth=config.session.auth, headers=headers, data=request_xml)
raw_eve... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _prepare_event(eventinstances):
"""Converts event instances to a relevant dictionary."""
import xml.etree.ElementTree as ET
def parse_event(events):
"""Find all events inside of an topicset list.
MessageInstance signals that subsequent children will
contain source and data desc... | Implement a function in Python 3 to
convert an event instance list to a relevant dictionary. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Represent device base url. | Given the following Python 3 function, write the documentation
def url(self):
return URL.format(http=self.web_proto, host=self.host, port=self.port) | As a Python code composer, you craft elegant and concise scripts. |
def process_raw(self, raw: dict) -> None:
"""Pre-process raw dict.
Prepare parameters to work with APIItems.
"""
raw_ports = {}
for param in raw:
port_index = REGEX_PORT_INDEX.search(param).group(0)
if port_index not in raw_ports:
raw_po... | Write a Python 3 script for
processing the raw dict. | You are a Python code architect, reviewing and designing scalable and efficient code |
Return name relevant to direction. | Here you have a function in Python 3, explain what it does
def name(self) -> str:
if self.direction == DIRECTION_IN:
return self.raw.get('Input.Name', '')
return self.raw.get('Output.Name', '') | You are a Python code analyst, evaluating scripts for potential improvements. |
Load device parameters and initialize parameter management. | Given the following Python 3 function, write the documentation
def initialize_params(self, preload_data=True) -> None:
params = ''
if preload_data:
params = self.request('get', param_url)
self.params = Params(params, self.request) | You are a Python code architect, reviewing and designing scalable and efficient code |
Load IO port parameters for device. | Can you generate the documentation for the following Python 3 function
def initialize_ports(self) -> None:
if not self.params:
self.initialize_params(preload_data=False)
self.params.update_ports()
self.ports = Ports(self.params, self.request) | You are a Python code analyst, evaluating scripts for potential improvements. |
Load device user data and initialize user management. | Given the following Python 3 function, write the documentation
def initialize_users(self) -> None:
users = self.request('get', pwdgrp_url)
self.users = Users(users, self.request) | As a python code expert, you are capable of creating scripts from specifications. |
Process a new event. | How would you explain what the following Python 3 function does
def new_event(self, event_data: str) -> None:
event = self.parse_event_xml(event_data)
if EVENT_OPERATION in event:
self.manage_event(event) | As a Python code analyst, you investigate and solve complex coding mysteries |
def manage_event(self, event) -> None:
"""Received new metadata.
Operation initialized means new event, also happens if reconnecting.
Operation changed updates existing events state.
"""
name = EVENT_NAME.format(
topic=event[EVENT_TOPIC], source=event.get(EVENT_SOURC... | Write a Python 3 function that can
receive new metadata. Operation initialized means new event, also happens if reconnecting. Operation changed updates existing events state. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def state(self, state: str) -> None:
"""Update state of event."""
self._state = state
for callback in self._callbacks:
callback() | Write a Python 3 script for
updating state of event. | As a python code expert, you are capable of creating scripts from specifications. |
Remove callback from the list of callbacks. | Make a summary of the following Python 3 code
def remove_callback(self, callback) -> None:
if callback in self._callbacks:
self._callbacks.remove(callback) | You are a Python code generator, capable of creating scripts from specifications. |
Enable events for stream. | How would you explain what the following Python 3 function does
def enable_events(self, event_callback=None) -> None:
self.event = EventManager(event_callback)
self.stream.event = self.event | You are a Python code architect, reviewing and designing scalable and efficient code |
Update brand group of parameters. | Explain what the following Python 3 code does
def update_brand(self) -> None:
self.update(path=URL_GET + GROUP.format(group=BRAND)) | As a Python code analyst, you investigate and solve complex coding mysteries |
Update port groups of parameters. | Can you generate the documentation for the following Python 3 function
def update_ports(self) -> None:
self.update(path=URL_GET + GROUP.format(group=INPUT))
self.update(path=URL_GET + GROUP.format(group=IOPORT))
self.update(path=URL_GET + GROUP.format(group=OUTPUT)) | As a python code expert, you are capable of creating scripts from specifications. |
def ports(self) -> dict:
"""Create a smaller dictionary containing all ports."""
return {
param: self[param].raw
for param in self
if param.startswith(IOPORT)
} | Write a Python 3 function for
creating a smaller dictionary containing all ports. | You are a Python code analyst, evaluating scripts for potential improvements. |
Update properties group of parameters. | Explain what the following Python 3 code does
def update_properties(self) -> None:
self.update(path=URL_GET + GROUP.format(group=PROPERTIES)) | You are a Python code generator, capable of creating scripts from specifications. |
Pre - process raw string.
Prepare parameters to work with APIItems.
| Can you generate the documentation for the following Python 3 function
def process_raw(self, raw: str) -> None:
raw_params = dict(group.split('=', 1) for group in raw.splitlines())
super().process_raw(raw_params) | As a Python code analyst, you investigate and solve complex coding mysteries |
def delete(self, user: str) -> None:
"""Remove user."""
data = {
'action': 'remove',
'user': user
}
self._request('post', URL, data=data) | Can you create a Python 3 function that
removes user from the cache. | You are a Python code analyst, evaluating scripts for potential improvements. |
Pre-process raw string.
Prepare users to work with APIItems.
Create booleans with user levels. | Make a summary of the following Python 3 code
def process_raw(self, raw: str) -> None:
raw_dict = dict(group.split('=') for group in raw.splitlines())
raw_users = {
user: {
group: user in REGEX_STRING.findall(raw_dict[group])
for group in [ADMIN, OPERATOR, VI... | You are a Python code architect, reviewing and designing scalable and efficient code |
Callback when the init process is complete. | How would you explain what the following Python 3 function does
def init_done(self, fut):
try:
if fut.exception():
fut.result()
except OSError as err:
_LOGGER.debug('RTSP got exception %s', err)
self.stop()
self.callback(SIGNAL_FAILED) | You are a Python code analyst, evaluating scripts for potential improvements. |
Connect to device is successful. | Given the following Python 3 function, write the documentation
def connection_made(self, transport):
self.transport = transport
self.transport.write(self.method.message.encode())
self.time_out_handle = self.loop.call_later(
TIME_OUT_LIMIT, self.time_out) | You are a Python code generator, capable of creating scripts from specifications. |
Called when data is received from the server. | Make a summary of the following Python 3 code
def data_received(self, data):
self.time_out_handle.cancel()
self.session.update(data.decode())
if self.session.state == STATE_STARTING:
self.transport.write(self.method.message.encode())
self.time_out_handle = self.loop.call... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def time_out(self):
"""If we don't get a response within time the RTSP request time out.
This usually happens if device isn't available on specified IP.
"""
_LOGGER.warning('Response timed out %s', self.session.host)
self.stop()
self.callback(SIGNAL_FAILED) | How would you implement a function in Python 3 that
stops the RTSP session and send a SIGAL_FAILED signal. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def message(self):
"""Return RTSP method based on sequence number from session."""
message = self.message_methods[self.session.method]()
_LOGGER.debug(message)
return message | Can you write a function in Python 3 where it
returns RTSP method based on sequence number from session. | As a python code expert, you are capable of creating scripts from specifications. |
def OPTIONS(self, authenticate=True):
"""Request options device supports."""
message = "OPTIONS " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication if authenticate else ''
message += self.user_agent
message += self.session_id
... | Can you create a Python 3 function that
requests options device supports. | As a python code expert, you are capable of creating scripts from specifications. |
Request description of what services RTSP server make available. | Can you generate the documentation for the following Python 3 function
def DESCRIBE(self):
message = "DESCRIBE " + self.session.url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += "Accept: application/sdp\r\n"
... | As a Python code composer, you craft elegant and concise scripts. |
Set up stream transport. | Can you tell what is the following Python 3 function doing
def SETUP(self):
message = "SETUP " + self.session.control_url + " RTSP/1.0\r\n"
message += self.sequence
message += self.authentication
message += self.user_agent
message += self.transport
message += '\r\n'
... | As a Python code composer, you craft elegant and concise scripts. |
Generate the transport string. | Given the following Python 3 function, write the documentation
def transport(self):
transport = "Transport: RTP/AVP;unicast;client_port={}-{}\r\n"
return transport.format(
str(self.session.rtp_port), str(self.session.rtcp_port)) | As a Python code analyst, you investigate and solve complex coding mysteries |
def update(self, response):
"""Update session information from device response.
Increment sequence number when starting stream, not when playing.
If device requires authentication resend previous message with auth.
"""
data = response.splitlines()
_LOGGER.debug('Received... | How would you implement a function in Python 3 that
updates the internal state of the object from the device response. | As a Python code analyst, you investigate and solve complex coding mysteries |
RFC 2617. 1. 1 | Here you have a function in Python 3, explain what it does
def generate_digest(self):
from hashlib import md5
ha1 = self.username + ':' + self.realm + ':' + self.password
HA1 = md5(ha1.encode('UTF-8')).hexdigest()
ha2 = self.method + ':' + self.url
HA2 = md5(ha2.encode('UTF-8')).... | As a Python code translator, you convert algorithms and pseudocode into Python. |
RFC 2617. 1. 1 Basic Auth | Can you generate a brief explanation for the following Python 3 code
def generate_basic(self):
from base64 import b64encode
if not self.basic_auth:
creds = self.username + ':' + self.password
self.basic_auth = 'Basic '
self.basic_auth += b64encode(creds.encode('UTF-8'... | You are a Python code generator, capable of creating scripts from specifications. |
def retry(ExceptionToCheck, tries=10, timeout_secs=1.0, logger=None, callback_by_exception=None):
"""
Retry calling the decorated function using an exponential backoff.
:param callback_by_exception: callback/method invocation on certain exceptions
:type callback_by_exception: None or dict
"""
de... | Write a Python 3 script to
retry calling the decorated function using an exponential backoff. :param callback_by_exception: callback/method invocation on certain exceptions :type callback_by_exception: None or dict | As a Python code composer, you craft elegant and concise scripts. |
def stream_url(self):
"""Build url for stream."""
rtsp_url = RTSP_URL.format(
host=self.config.host, video=self.video_query,
audio=self.audio_query, event=self.event_query)
_LOGGER.debug(rtsp_url)
return rtsp_url | Implement a function in Python 3 to
build RTSP url for stream. | You are a Python code generator, capable of creating scripts from specifications. |
Signal from stream session. | How would you explain what the following Python 3 function does
def session_callback(self, signal):
if signal == SIGNAL_DATA:
self.event.new_event(self.data)
elif signal == SIGNAL_FAILED:
self.retry()
if signal in [SIGNAL_PLAYING, SIGNAL_FAILED] and \
se... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Retry connection to the device. | Here you have a function in Python 3, explain what it does
def retry(self):
self.stream = None
self.config.loop.call_later(RETRY_TIMER, self.start)
_LOGGER.debug('Reconnecting to %s', self.config.host) | You are a Python code generator, capable of creating scripts from specifications. |
Connect to MySQL and return an inspector object | How would you explain what the following Python 3 function does
def connect_mysql():
MySQLConnection.get_characterset_info = MySQLConnection.get_charset
db = create_engine(engine_name)
db.echo = True
db.connect()
return db | As a python code expert, you are capable of creating scripts from specifications. |
Checks whether a user has permission to perform an action. | Explain what the following Python 3 code does
def check_perm(user_id, permission_code):
try:
perm = db.DBSession.query(Perm).filter(Perm.code==permission_code).one()
except NoResultFound:
raise PermissionError("Nonexistent permission type: %s"%(permission_code))
try:
res = db.DBSes... | As a Python code analyst, you investigate and solve complex coding mysteries |
Decorator to check if user has required perms | Here you have a function in Python 3, explain what it does
def required_perms(*req_perms):
def dec_wrapper(wfunc):
@wraps(wfunc)
def wrapped(*args, **kwargs):
user_id = kwargs.get("user_id")
for perm in req_perms:
check_perm(user_id, perm)
return ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_time_period(period_name):
"""
Given a time period name, fetch the hydra-compatible time
abbreviation.
"""
time_abbreviation = time_map.get(period_name.lower())
if time_abbreviation is None:
raise Exception("Symbol %s not recognised as a time period"%period_name)
ret... | How would you implement a function in Python 3 that
gives a time period name fetch the hydra - compatible time abbreviation. | You are a Python code generator, capable of creating scripts from specifications. |
def get_datetime(timestamp):
"""
Turn a string timestamp into a date time. First tries to use dateutil.
Failing that it tries to guess the time format and converts it manually
using stfptime.
@returns: A timezone unaware timestamp.
"""
timestamp_is_float = False
try:
... | Can you implement a function in Python 3 that
converts a string timestamp into a date time. | You are a Python code analyst, evaluating scripts for potential improvements. |
def timestamp_to_ordinal(timestamp):
"""Convert a timestamp as defined in the soap interface to the time format
stored in the database.
"""
if timestamp is None:
return None
ts_time = get_datetime(timestamp)
# Convert time to Gregorian ordinal (1 = January 1st, year 1)
ordinal_ts_t... | Write a Python 3 script to
convert a timestamp as defined in the soap interface to the time format stored in the database. | You are a Python code generator, capable of creating scripts from specifications. |
Convert a date to a standard string used by Hydra. | Can you generate a brief explanation for the following Python 3 code
def date_to_string(date, seasonal=False):
seasonal_key = config.get('DEFAULT', 'seasonal_key', '9999')
if seasonal:
FORMAT = seasonal_key+'-%m-%dT%H:%M:%S.%f'
else:
FORMAT = '%Y-%m-%dT%H:%M:%S.%f'
return date.strftime(... | As a Python code analyst, you investigate and solve complex coding mysteries |
Try to guess the time format for a given date string. | Can you generate a brief explanation for the following Python 3 code
def guess_timefmt(datestr):
if isinstance(datestr, float) or isinstance(datestr, int):
return None
seasonal_key = str(config.get('DEFAULT', 'seasonal_key', '9999'))
#replace 'T' with space to handle ISO times.
if datestr.fin... | As a Python code composer, you craft elegant and concise scripts. |
reindex a timeseries with the supplied timestamps | How would you explain what the following Python 3 function does
def reindex_timeseries(ts_string, new_timestamps):
#If a single timestamp is passed in, turn it into a list
#Reindexing can't work if it's not a list
if not isinstance(new_timestamps, list):
new_timestamps = [new_timestamps]
#Conve... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Read in the time step and convert it to seconds. | Here you have a function in Python 3, explain what it does
def parse_time_step(time_step, target='s', units_ref=None):
log.info("Parsing time step %s", time_step)
# export numerical value from string using regex
value = re.findall(r'\d+', time_step)[0]
valuelen = len(value)
try:
value = flo... | You are a Python code generator, capable of creating scripts from specifications. |
def get_time_axis(start_time, end_time, time_step, time_axis=None):
"""
Create a list of datetimes based on an start time, end time and
time step. If such a list is already passed in, then this is not
necessary.
Often either the start_time, end_time, time_step is passed into an
... | Can you write a function in Python 3 where it
creates a list of datetimes based on an start time, end time and time step. If such a list is already passed in, then this is not necessary. Often either the start_time, end_time, time_step is passed into an app or the time_axis is passed in directly. This function returns ... | You are a Python code generator, capable of creating scripts from specifications. |
Get all the complex mode attributes in the network. | Can you generate the documentation for the following Python 3 function
def _get_all_attributes(network):
attrs = network.attributes
for n in network.nodes:
attrs.extend(n.attributes)
for l in network.links:
attrs.extend(l.attributes)
for g in network.resourcegroups:
attrs.extend(... | As a python code expert, you are capable of creating scripts from specifications. |
def add_network(network,**kwargs):
"""
Takes an entire network complex model and saves it to the DB. This
complex model includes links & scenarios (with resource data). Returns
the network's complex model.
As links connect two nodes using the node_ids, if the nodes are new
they will not yet h... | How would you implement a function in Python 3 that
adds a network to the database. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_all_resource_attributes(network_id, template_id=None):
"""
Get all the attributes for the nodes, links and groups of a network.
Return these attributes as a dictionary, keyed on type (NODE, LINK, GROUP)
then by ID of the node or link.
"""
base_qry = db.DBSession.query(
... | Can you write a function in Python 3 where it
gets all the resource attributes for a given network. | You are a Python code generator, capable of creating scripts from specifications. |
Get all the templates for a given network and template. | Here you have a function in Python 3, explain what it does
def _get_all_templates(network_id, template_id):
base_qry = db.DBSession.query(
ResourceType.ref_key.label('ref_key'),
ResourceType.node_id.label('node_id'),
Resour... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Get all the resource group items in the network across all scenarios
| Can you tell what is the following Python 3 function doing
def _get_all_group_items(network_id):
base_qry = db.DBSession.query(ResourceGroupItem)
item_qry = base_qry.join(Scenario).filter(Scenario.network_id==network_id)
x = time.time()
logging.info("Getting all items")
all_items = db.DBSession.ex... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_all_resourcescenarios(network_id, user_id):
"""
Get all the resource scenarios in a network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
"""
rs_qry = db.DBSession.query(
Dataset.type,
Dataset.unit_id,
... | How would you code a function in Python 3 to
get all the resource scenarios in a network across all scenarios | As a python code expert, you are capable of creating scripts from specifications. |
Get all the metadata in a network across all scenarios
| Can you tell what is the following Python 3 function doing
def _get_metadata(network_id, user_id):
log.info("Getting Metadata")
dataset_qry = db.DBSession.query(
Dataset
).outerjoin(DatasetOwner, and_(DatasetOwner.dataset_id==Dataset.id, DatasetOwner.user_id==user_id)).filter(
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get all the nodes in a network | Make a summary of the following Python 3 code
def _get_network_owners(network_id):
owners_i = db.DBSession.query(NetworkOwner).filter(
NetworkOwner.network_id==network_id).options(noload('network')).options(joinedload_all('user')).all()
owners = [JSONObject(owner_i) for owner_i in owner... | As a Python code composer, you craft elegant and concise scripts. |
Get all the nodes in a network | Here you have a function in Python 3, explain what it does
def _get_nodes(network_id, template_id=None):
extras = {'types':[], 'attributes':[]}
node_qry = db.DBSession.query(Node).filter(
Node.network_id==network_id,
Node.status=='A').options(
... | You are a Python code generator, capable of creating scripts from specifications. |
def _get_links(network_id, template_id=None):
"""
Get all the links in a network
"""
extras = {'types':[], 'attributes':[]}
link_qry = db.DBSession.query(Link).filter(
Link.network_id==network_id,
Link.status=='A').o... | How would you implement a function in Python 3 that
gets all the links in a network | As a Python code analyst, you investigate and solve complex coding mysteries |
Get all the resource groups in a network | Can you generate a brief explanation for the following Python 3 code
def _get_groups(network_id, template_id=None):
extras = {'types':[], 'attributes':[]}
group_qry = db.DBSession.query(ResourceGroup).filter(
ResourceGroup.network_id==network_id,
... | You are a Python code generator, capable of creating scripts from specifications. |
Get all the scenarios in a network | Can you generate a brief explanation for the following Python 3 code
def _get_scenarios(network_id, include_data, user_id, scenario_ids=None):
scen_qry = db.DBSession.query(Scenario).filter(
Scenario.network_id == network_id).options(
noload('network')).filter(
... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_network(network_id, summary=False, include_data='N', scenario_ids=None, template_id=None, **kwargs):
"""
Return a whole network as a dictionary.
network_id: ID of the network to retrieve
include_data: 'Y' or 'N'. Indicate whether scenario data is to be returned.
... | Implement a Python 3 function for
getting a single network as a dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_nodes(network_id, template_id=None, **kwargs):
"""
Get all the nodes in a network.
args:
network_id (int): The network in which to search
template_id (int): Only return nodes whose type is in this template.
"""
user_id = kwargs.get('user_id')
try:
... | Create a Python 3 function for
getting all the nodes in a network. | As a python code expert, you are capable of creating scripts from specifications. |
Get all the links in a network. | Can you generate a brief explanation for the following Python 3 code
def get_links(network_id, template_id=None, **kwargs):
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_read_permission(user_id=user_id)
except NoRe... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get all the resource groups in a network. | Can you generate the documentation for the following Python 3 function
def get_groups(network_id, template_id=None, **kwargs):
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_read_permission(user_id=user_id)
except N... | As a Python code composer, you craft elegant and concise scripts. |
Get a network as a complex model. | Can you generate the documentation for the following Python 3 function
def get_network_by_name(project_id, network_name,**kwargs):
try:
res = db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one()
net = get_network(res.id, ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def network_exists(project_id, network_name,**kwargs):
"""
Return a whole network as a complex model.
"""
try:
db.DBSession.query(Network.id).filter(func.lower(Network.name).like(network_name.lower()), Network.project_id == project_id).one()
return 'Y'
except NoResultFound:
r... | How would you implement a function in Python 3 that
checks if a network exists in the database. | You are a Python code analyst, evaluating scripts for potential improvements. |
def update_network(network,
update_nodes = True,
update_links = True,
update_groups = True,
update_scenarios = True,
**kwargs):
"""
Update an entire network
"""
log.info("Updating Network %s", network.name)
user_id = kwargs.get('user_id')
#check_perm('update_network')
... | Can you implement a function in Python 3 that
updates a network in the database. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Activates a network by setting its status attribute to A. | Make a summary of the following Python 3 code
def set_network_status(network_id,status,**kwargs):
user_id = kwargs.get('user_id')
#check_perm(user_id, 'delete_network')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_write_permission(user_id)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_network_extents(network_id,**kwargs):
"""
Given a network, return its maximum extents.
This would be the minimum x value of all nodes,
the minimum y value of all nodes,
the maximum x value of all nodes and
maximum y value of all nodes.
@returns NetworkExtents object
"""
rs =... | Can you implement a function in Python 3 that
gives a network return its maximum extents. | As a Python code composer, you craft elegant and concise scripts. |
Add nodes to network | Can you tell what is the following Python 3 function doing
def add_nodes(network_id, nodes,**kwargs):
start_time = datetime.datetime.now()
names=[] # used to check uniqueness of node name
for n_i in nodes:
if n_i.name in names:
raise HydraError("Duplicate Node Name: %s"%(n_i.name... | As a Python code analyst, you investigate and solve complex coding mysteries |
add links to network
| Here you have a function in Python 3, explain what it does
def add_links(network_id, links,**kwargs):
'''
add links to network
'''
start_time = datetime.datetime.now()
user_id = kwargs.get('user_id')
names=[] # used to check uniqueness of link name before saving links to database
for ... | You are a Python code analyst, evaluating scripts for potential improvements. |
Update a node.
If new attributes are present, they will be added to the node.
The non-presence of attributes does not remove them.
The flush argument indicates whether dbsession.flush should be called. THis
is set to False when update_node is called from another function which does
the flush. | Can you generate a brief explanation for the following Python 3 code
def update_node(node, flush=True, **kwargs):
user_id = kwargs.get('user_id')
try:
node_i = db.DBSession.query(Node).filter(Node.id == node.id).one()
except NoResultFound:
raise ResourceNotFoundError("Node %s not found"%(nod... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Update multiple nodes.
If new attributes are present, they will be added to the node.
The non-presence of attributes does not remove them.
%TODO:merge this with the 'update_nodes' functionality in the 'update_netework'
function, so we're not duplicating functionality. D.R.Y!
returns: a list of upd... | Explain what the following Python 3 code does
def update_nodes(nodes,**kwargs):
user_id = kwargs.get('user_id')
updated_nodes = []
for n in nodes:
updated_node_i = update_node(n, flush=False, user_id=user_id)
updated_nodes.append(updated_node_i)
db.DBSession.flush()
return updated_... | As a Python code analyst, you investigate and solve complex coding mysteries |
Set the status of a node to X | How would you explain what the following Python 3 function does
def set_node_status(node_id, status, **kwargs):
user_id = kwargs.get('user_id')
try:
node_i = db.DBSession.query(Node).filter(Node.id == node_id).one()
except NoResultFound:
raise ResourceNotFoundError("Node %s not found"%(node_... | As a python code expert, you are capable of creating scripts from specifications. |
Remove a network from DB completely | Given the following Python 3 function, write the documentation
def purge_network(network_id, purge_data,**kwargs):
user_id = kwargs.get('user_id')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
except NoResultFound:
raise ResourceNotFoundError("Network %s not... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _purge_datasets_unique_to_resource(ref_key, ref_id):
"""
Find the number of times a a resource and dataset combination
occurs. If this equals the number of times the dataset appears, then
we can say this dataset is unique to this resource, therefore it can be deleted
"""
count_qr... | How would you implement a function in Python 3 that
deletes all the datasets that are unique to a resource. | You are a Python code generator, capable of creating scripts from specifications. |
Delete a node from DB completely | Here you have a function in Python 3, explain what it does
def delete_node(node_id, purge_data,**kwargs):
user_id = kwargs.get('user_id')
try:
node_i = db.DBSession.query(Node).filter(Node.id == node_id).one()
except NoResultFound:
raise ResourceNotFoundError("Node %s not found"%(node_id))
... | As a python code expert, you are capable of creating scripts from specifications. |
def add_link(network_id, link,**kwargs):
"""
Add a link to a network
"""
user_id = kwargs.get('user_id')
#check_perm(user_id, 'edit_topology')
try:
net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
net_i.check_write_permission(user_id)
except NoR... | How would you implement a function in Python 3 that
adds a link to a network | You are a Python code generator, 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.