output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def psychrometrics (Tdb_in, w_in, P):
"""
Modified version of Psychometrics by Tea Zakula
MIT Building Technology Lab
Input: Tdb_in, w_in, P
Output: Tdb, w, phi, h, Tdp, v
where:
Tdb_in = [K] dry bulb temperature
w_in = [kgv/kgda] Humidity Ratio
P = [P] Atmospheric Station Pressure
... | How would you code a function in Python 3 to
modify version of Psychometrics by Tea Zakula MIT Building Technology Lab Input: Tdb_in, w_in, P Output: Tdb, w, phi, h, Tdp, v where: Tdb_in = [K] dry bulb temperature w_in = [kgv/kgda] Humidity Ratio P = [P] Atmospheric Station Pressure Tdb: [C] dry bulb temperature w: [kg... | You are a Python code generator, capable of creating scripts from specifications. |
def search(term, country='US', media='all', entity=None, attribute=None, limit=50):
"""
Returns the result of the search of the specified term in an array of result_item(s)
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take ... | Can you write a function in Python 3 where it
searches for a term in an array of result_item objects. | You are a Python code generator, capable of creating scripts from specifications. |
Returns the result of the lookup of the specified id artist_amg_id or upc in an array of result_item objects. | Explain what the following Python 3 code does
def lookup(id=None, artist_amg_id=None, upc=None, country='US', media='all', entity=None, attribute=None, limit=50):
# If none of the basic lookup arguments are provided, raise a ValueError
if id is None and artist_amg_id is None and upc is None:
raise Value... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_result_list(json):
"""
Analyzes the provided JSON data and returns an array of result_item(s) based on its content
:param json: Raw JSON data to analyze
:return: An array of result_item(s) from the provided JSON data
"""
result_list = []
for item in json:
if 'wrapperType' i... | Write a Python 3 script for
analyzing the provided JSON data and returns an array of result_item s based on its content | As a Python code composer, you craft elegant and concise scripts. |
def _url_search_builder(term, country='US', media='all', entity=None, attribute=None, limit=50):
"""
Builds the URL to perform the search based on the provided data
:param term: String. The URL-encoded text string you want to search for. Example: Steven Wilson.
The method will take care of ... | Write a Python 3 function that can
build the URL to perform the search based on the provided data. | As a Python code analyst, you investigate and solve complex coding mysteries |
Builds the URL to perform the lookup based on the provided data. | Here you have a function in Python 3, explain what it does
def _url_lookup_builder(id=None, artist_amg_id=None, upc=None, country='US', media='music', entity=None, attribute=None,
limit=50):
"""
Builds the URL to perform the lookup based on the provided data
:param id: String. iTunes... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_albums(self):
"""
Retrieves all the albums by the artist
:return: List. Albums published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['album'])[1:] | Can you write a function in Python 3 where it
retrieves all the albums published by the artist | As a Python code translator, you convert algorithms and pseudocode into Python. |
Recurses through lists and converts lists of strings to float | Can you generate a brief explanation for the following Python 3 code
def str2fl(x):
def helper_to_fl(s_):
""" deals with odd string imports converts to float"""
if s_ == "":
return "null"
elif "," in s_:
s_ = s_.replace(",", "")
try:
return float(... | You are a Python code analyst, evaluating scripts for potential improvements. |
Processes a material layer so that it is too narrowed and that it is too narrowed. | Explain what the following Python 3 code does
def procMat(materials, max_thickness, min_thickness):
newmat = []
newthickness = []
k = materials.layerThermalCond
Vhc = materials.layerVolHeat
if len(materials.layerThickness) > 1:
for j in range(len(materials.layerThickness)):
... | As a Python code analyst, you investigate and solve complex coding mysteries |
def read_input(self):
"""Section 3 - Read Input File (.m, file)
Note: UWG_Matlab input files are xlsm, XML, .m, file.
properties:
self._init_param_dict # dictionary of simulation initialization parameters
self.sensAnth # non-building sensible heat (W/m^... | Create a Python 3 function for
reading the UWG_Matlab input file and populate self. _init_param_dict with the values extracted from the UWG_Matlab parameter file. | As a Python code composer, you craft elegant and concise scripts. |
def set_input(self):
""" Set inputs from .uwg input file if not already defined, the check if all
the required input parameters are there.
"""
# If a uwgParamFileName is set, then read inputs from .uwg file.
# User-defined class properties will override the inputs from the... | Write a Python 3 function for
setting inputs from. uwg input file if not already defined. | As a Python code analyst, you investigate and solve complex coding mysteries |
Initialize the instance variables for the BEM and Sch objects. | Explain what the following Python 3 code does
def init_BEM_obj(self):
if not os.path.exists(self.readDOE_file_path):
raise Exception("readDOE.pkl file: '{}' does not exist.".format(readDOE_file_path))
readDOE_file = open(self.readDOE_file_path, 'rb') # open pickle file in binary form... | You are a Python code generator, capable of creating scripts from specifications. |
def init_input_obj(self):
"""Section 4 - Create uwg objects from input parameters
self.simTime # simulation time parameter obj
self.weather # weather obj for simulation time period
self.forcIP # Forcing obj
self.forc ... | Write a Python 3 function that can
create uwg objects from input parameters and return the new object. | As a python code expert, you are capable of creating scripts from specifications. |
A method to set the cooling and heating cap of all the related resources. | Can you generate the documentation for the following Python 3 function
def hvac_autosize(self):
for i in range(len(self.BEM)):
if self.is_near_zero(self.autosize) == False:
self.BEM[i].building.coolCap = 9999.
self.BEM[i].building.heatCap = 9999. | As a Python code analyst, you investigate and solve complex coding mysteries |
Create a new object instance with the given information. | How would you explain what the following Python 3 function does
def simulate(self):
self.N = int(self.simTime.days * 24) # total number of hours in simulation
n = 0 # weather time step counter
self.ph = self.simTime.dt/3600. # dt (simula... | You are a Python code generator, capable of creating scripts from specifications. |
def write_epw(self):
""" Section 8 - Writing new EPW file
"""
epw_prec = self.epw_precision # precision of epw file input
for iJ in range(len(self.UCMData)):
# [iJ+self.simTime.timeInitial-8] = increments along every weather timestep in epw
# [6 to 21] ... | How would you code a function in Python 3 to
write the new EPW file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def SurfFlux(self,forc,parameter,simTime,humRef,tempRef,windRef,boundCond,intFlux):
""" Calculate net heat flux, and update element layer temperatures
"""
# Calculated per unit area (m^2)
dens = forc.pres/(1000*0.287042*tempRef*(1.+1.607858*humRef)) # air density (kgd m-3)
self.... | Create a Python 3 function to
calculate net heat flux and updates element layer temperatures with new values. | You are a Python code architect, reviewing and designing scalable and efficient code |
Solve the conductance of heat based on the element layers. | Given the following Python 3 function, write the documentation
def Conduction(self, dt, flx1, bc, temp2, flx2):
t = self.layerTemp # vector of layer temperatures (K)
hc = self.layerVolHeat # vector of layer volumetric heat (J m-3 K-1)
tc = self.layerThermalCond # vector of layer t... | As a python code expert, you are capable of creating scripts from specifications. |
def qsat(self,temp,pres,parameter):
"""
Calculate (qsat_lst) vector of saturation humidity from:
temp = vector of element layer temperatures
pres = pressure (at current timestep).
"""
gamw = (parameter.cl - parameter.cpv) / parameter.rv
betaw = (parameter.... | Can you create a Python 3 function that
calculates the QSAT vector of saturation humidity from a set of temperature and pressure. | As a python code expert, you are capable of creating scripts from specifications. |
Read all DOE data and return a list of dicts. | Make a summary of the following Python 3 code
def readDOE(serialize_output=True):
#Nested, nested lists of Building, SchDef, BEMDef objects
refDOE = [[[None]*16 for k_ in range(3)] for j_ in range(16)] #refDOE(16,3,16) = Building
Schedule = [[[None]*16 for k_ in range(3)] for j_ in range(1... | As a Python code composer, you craft elegant and concise scripts. |
Reads a single item from a plist file. | Given the following Python 3 function, write the documentation
def readPlist(pathOrFile):
didOpen = False
result = None
if isinstance(pathOrFile, (bytes, unicode)):
pathOrFile = open(pathOrFile, 'rb')
didOpen = True
try:
reader = PlistReader(pathOrFile)
result = reader.pa... | As a python code expert, you are capable of creating scripts from specifications. |
Returns the integer in bytes of size byteSize. | Make a summary of the following Python 3 code
def getSizedInteger(self, data, byteSize, as_number=False):
result = 0
if byteSize == 0:
raise InvalidPlistException("Encountered integer with byte size of 0.")
# 1, 2, and 4 byte integers are unsigned
elif byteSize == 1:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the root object to the file. | Can you generate the documentation for the following Python 3 function
def writeRoot(self, root):
output = self.header
wrapped_root = self.wrapRoot(root)
self.computeOffsets(wrapped_root, asReference=True, isRoot=True)
self.trailer = self.trailer._replace(**{'objectRefSize':self.intSize(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Tries to write an object reference to the output. Returns a tuple of whether the object was a new reference or not. | Given the following Python 3 function, write the documentation
def writeObjectReference(self, obj, output):
position = self.positionOfObjectReference(obj)
if position is None:
self.writtenReferences[obj] = len(self.writtenReferences)
output += self.binaryInt(len(self.writtenRefer... | You are a Python code architect, reviewing and designing scalable and efficient code |
Serializes the given object to the output. | Can you generate the documentation for the following Python 3 function
def writeObject(self, obj, output, setReferencePosition=False):
def proc_variable_length(format, length):
result = b''
if length > 0b1110:
result += pack('!B', (format << 4) | 0b1111)
r... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def writeOffsetTable(self, output):
"""Writes all of the object reference offsets."""
all_positions = []
writtenReferences = list(self.writtenReferences.items())
writtenReferences.sort(key=lambda x: x[1])
for obj,order in writtenReferences:
# Porting note: Elsewhere w... | Create a Python 3 function for
writing all of the object reference offsets. | As a Python code analyst, you investigate and solve complex coding mysteries |
def intSize(self, obj):
"""Returns the number of bytes necessary to store the given integer."""
# SIGNED
if obj < 0: # Signed integer, always 8 bytes
return 8
# UNSIGNED
elif obj <= 0xFF: # 1 byte
return 1
elif obj <= 0xFFFF: # 2 bytes
... | Implement a function in Python 3 to
return the number of bytes needed to store the given integer. | As a python code expert, you are capable of creating scripts from specifications. |
def load_z_meso(self,z_meso_path):
""" Open the z_meso.txt file and return heights as list """
self.z_meso = []
z_meso_file_path = os.path.join(z_meso_path, self.Z_MESO_FILE_NAME)
# Check if exists
if not os.path.exists(z_meso_file_path):
raise Exception("z_meso.txt... | Create a Python 3 function to
open the z_meso. txt file and return heights as list | As a python code expert, you are capable of creating scripts from specifications. |
Calculate the surface heat fluxes of the urban and the wall | Can you tell what is the following Python 3 function doing
def urbflux(UCM, UBL, BEM, forc, parameter, simTime, RSM):
T_can = UCM.canTemp
Cp = parameter.cp
UCM.Q_roof = 0.
sigma = 5.67e-8 # Stephan-Boltzman constant
UCM.roofTemp = 0. # Average urban roof temperature
UCM.wallTemp = ... | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_books(self):
"""
Retrieves all the books published by the artist
:return: List. Books published by the artist
"""
return itunespy.lookup(id=self.artist_id, entity=itunespy.entities['ebook'])[1:] | Write a Python 3 script to
retrieve all the books published by the artist | You are a Python code generator, capable of creating scripts from specifications. |
def get_tasks(task_id='', completed=True):
""" Get a list of tasks, optionally filtered by task id.
The task_id can be the abbrevated. Example: If a task named 'sleep' is
scaled to 3 in marathon, there will be be 3 tasks starting with 'sleep.'
:param task_id: task ID
:type task_id:... | Can you create a Python 3 function that
gets a list of tasks optionally filtered by task id. | As a Python code analyst, you investigate and solve complex coding mysteries |
Get a task by task id where a task_id is required. | Make a summary of the following Python 3 code
def get_task(task_id, completed=True):
tasks = get_tasks(task_id=task_id, completed=completed)
if len(tasks) == 0:
return None
assert len(tasks) == 1, 'get_task should return at max 1 task for a task id'
return tasks[0] | You are a Python code generator, capable of creating scripts from specifications. |
Check whether a task has completed. | Make a summary of the following Python 3 code
def task_completed(task_id):
tasks = get_tasks(task_id=task_id)
completed_states = ('TASK_FINISHED',
'TASK_FAILED',
'TASK_KILLED',
'TASK_LOST',
'TASK_ERROR')
for ta... | You are a Python code analyst, evaluating scripts for potential improvements. |
True if the json_element passed in is present for the task specified. | Here you have a function in Python 3, explain what it does
def task_property_present_predicate(service, task, prop):
try:
response = get_service_task(service, task)
except Exception as e:
pass
return (response is not None) and (prop in response) | As a Python code translator, you convert algorithms and pseudocode into Python. |
def wait_for_task(service, task, timeout_sec=120):
"""Waits for a task which was launched to be launched"""
return time_wait(lambda: task_predicate(service, task), timeout_seconds=timeout_sec) | Write a Python 3 function that can
wait for a task to be launched | You are a Python code generator, capable of creating scripts from specifications. |
Waits for a task to have the specified property. | Can you generate the documentation for the following Python 3 function
def wait_for_task_property(service, task, prop, timeout_sec=120):
return time_wait(lambda: task_property_present_predicate(service, task, prop), timeout_seconds=timeout_sec) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Copy a file via SCP | Can you generate the documentation for the following Python 3 function
def copy_file(
host,
file_path,
remote_path='.',
username=None,
key_path=None,
action='put'
):
""" Copy a file via SCP, proxied through the mesos master
:param host: host or IP of the mach... | You are a Python code analyst, evaluating scripts for potential improvements. |
Copy a file to the master | Given the following Python 3 function, write the documentation
def copy_file_to_master(
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_ip(), file_path, remote_path, username, key_path) | As a Python code translator, you convert algorithms and pseudocode into Python. |
Copy a file to a Mesos agent | Given the following Python 3 function, write the documentation
def copy_file_to_agent(
host,
file_path,
remote_path='.',
username=None,
key_path=None
):
""" Copy a file to a Mesos agent, proxied through the master
"""
return copy_file(host, file_path, remote_path, us... | You are a Python code architect, reviewing and designing scalable and efficient code |
Copy a file from the master to the Mesos master | Explain what the following Python 3 code does
def copy_file_from_master(
remote_path,
file_path='.',
username=None,
key_path=None
):
""" Copy a file to the Mesos master
"""
return copy_file(shakedown.master_ip(), file_path, remote_path, username, key_path, 'get') | As a python code expert, you are capable of creating scripts from specifications. |
def copy_file_from_agent(
host,
remote_path,
file_path='.',
username=None,
key_path=None
):
""" Copy a file to a Mesos agent, proxied through the master
"""
return copy_file(host, file_path, remote_path, username, key_path, 'get') | Write a Python 3 function that can
copy a file from a Mesos agent to a master | You are a Python code generator, capable of creating scripts from specifications. |
def __metadata_helper(json_path):
""" Returns json for specific cluster metadata. Important to realize that
this was introduced in dcos-1.9. Clusters prior to 1.9 and missing metadata
will return None
"""
url = shakedown.dcos_url_path('dcos-metadata/{}'.format(json_path))
try:
... | Write a Python 3 function for
returning json for specific cluster metadata. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _get_resources(rtype='resources'):
""" resource types from state summary include: resources, used_resources
offered_resources, reserved_resources, unreserved_resources
The default is resources.
:param rtype: the type of resources to return
:type rtype: str
:param role: the name of the role... | Write a Python 3 function that can
get the list of resources from the state summary | As a Python code translator, you convert algorithms and pseudocode into Python. |
def get_reserved_resources(role=None):
""" resource types from state summary include: reserved_resources
:param role: the name of the role if for reserved and if None all reserved
:type role: str
:return: resources(cpu,mem)
:rtype: Resources
"""
rtype = 'reserved_resources'
cpus = 0.0
... | Create a Python 3 function for
returning the number of resources that are reserved and are reserved and the same as the current state | As a Python code composer, you craft elegant and concise scripts. |
Decorate do_declartion methods for debug logging. | Given the following Python 3 function, write the documentation
def log_decl_method(func):
from functools import wraps
@wraps(func)
def with_logging(*args, **kwargs):
self = args[0]
decl = args[2]
log(DEBUG, u" {}: {} {}".format(
self.state['current_step'], decl.name,
... | As a python code expert, you are capable of creating scripts from specifications. |
def css_to_func(css, flags, css_namespaces, lang):
"""Convert a css selector to an xpath, supporting pseudo elements."""
from cssselect import parse, HTMLTranslator
from cssselect.parser import FunctionalPseudoElement
# FIXME HACK need lessc to support functional-pseudo-selectors instead
# of mark... | Implement a Python 3 function for
converting a css selector to an xpath supporting pseudo elements. | You are a Python code generator, capable of creating scripts from specifications. |
Append a string to a node as text or tail of last child. | Make a summary of the following Python 3 code
def append_string(t, string):
node = t.tree
if string:
if len(node) == 0:
if node.text is not None:
node.text += string
else:
node.text = string
else: # Get last child
child = list(... | You are a Python code generator, capable of creating scripts from specifications. |
def grouped_insert(t, value):
"""Insert value into the target tree 't' with correct grouping."""
collator = Collator.createInstance(Locale(t.lang) if t.lang else Locale())
if value.tail is not None:
val_prev = value.getprevious()
if val_prev is not None:
val_prev.tail = (val_prev... | Can you implement a function in Python 3 that
inserts value into the target tree t with correct grouping. | You are a Python code analyst, evaluating scripts for potential improvements. |
Insert node into sorted position in target tree. | Make a summary of the following Python 3 code
def insert_sort(node, target):
sort = target.sort
lang = target.lang
collator = Collator.createInstance(Locale(lang) if lang else Locale())
for child in target.tree:
if collator.compare(sort(child) or '', sort(node) or '') > 0:
child.addp... | You are a Python code architect, reviewing and designing scalable and efficient code |
def insert_group(node, target):
"""Insert node into in target tree, in appropriate group.
Uses group and lang from target function. This assumes the node and
target share a structure of a first child that determines the grouping,
and a second child that will be accumulated in the group.
"""
gr... | Write a Python 3 script for
inserting node into target tree in appropriate group. | You are a Python code architect, reviewing and designing scalable and efficient code |
def create_group(value):
"""Create the group wrapper node."""
node = etree.Element('div', attrib={'class': 'group-by'})
span = etree.Element('span', attrib={'class': 'group-label'})
span.text = value
node.append(span)
return node | Write a Python 3 script for
creating the group wrapper node. | You are a Python code analyst, evaluating scripts for potential improvements. |
def extract_selector_info(sel):
"""Return selector special pseudo class info (steps and other)."""
# walk the parsed_tree, looking for pseudoClass selectors, check names
# add in steps and/or deferred extras
steps, extras = _extract_sel_info(sel.parsed_tree)
steps = sorted(set(steps))
extras = ... | How would you code a function in Python 3 to
return selector special pseudo class info. | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert integer to roman numerals. | Can you tell what is the following Python 3 function doing
def _to_roman(num):
roman_numeral_map = (
('M', 1000),
('CM', 900),
('D', 500),
('CD', 400),
('C', 100),
('XC', 90),
('L', 50),
('XL', 40),
('X', 10),
('IX', 9),
('... | You are a Python code analyst, evaluating scripts for potential improvements. |
def copy_w_id_suffix(elem, suffix="_copy"):
"""Make a deep copy of the provided tree, altering ids."""
mycopy = deepcopy(elem)
for id_elem in mycopy.xpath('//*[@id]'):
id_elem.set('id', id_elem.get('id') + suffix)
return mycopy | Create a Python 3 function for
making a deep copy of the provided tree with the provided id suffix. | As a Python code analyst, you investigate and solve complex coding mysteries |
Generate a fresh id | Here you have a function in Python 3, explain what it does
def generate_id(self):
if self.use_repeatable_ids:
self.repeatable_id_counter += 1
return 'autobaked-{}'.format(self.repeatable_id_counter)
else:
return str(uuid4()) | As a Python code analyst, you investigate and solve complex coding mysteries |
def clear_state(self):
"""Clear the recipe state."""
self.state = {}
self.state['steps'] = []
self.state['current_step'] = None
self.state['scope'] = []
self.state['counters'] = {}
self.state['strings'] = {}
for step in self.matchers:
self.stat... | Implement a function in Python 3 to
clear the recipe state. | You are a Python code generator, capable of creating scripts from specifications. |
def update_css(self, css_in=None, clear_css=False):
"""Add additional CSS rules, optionally replacing all."""
if clear_css:
self.matchers = {}
# CSS is changing, so clear processing state
self.clear_state()
if css_in is None:
return
try:
... | Can you write a function in Python 3 where it
updates the internal state of the internal state with the CSS rules in css_in. | As a python code expert, you are capable of creating scripts from specifications. |
def bake(self, element, last_step=None):
"""Apply recipes to HTML tree. Will build recipes if needed."""
if last_step is not None:
try:
self.state['steps'] = [s for s in self.state['steps']
if int(s) < int(last_step)]
except... | Implement a function in Python 3 to
apply recipes to HTML tree. Will build recipes if needed. | You are a Python code architect, reviewing and designing scalable and efficient code |
Add entry to coverage_lines if this selector was parsed | Here you have a function in Python 3, explain what it does
def record_coverage_zero(self, rule, offset):
self.coverage_lines.append('DA:{},0'.format(rule.source_line + offset)) | You are a Python code generator, capable of creating scripts from specifications. |
def record_coverage(self, rule):
"""Add entry to coverage saying this selector was matched"""
log(DEBUG, u'Rule ({}): {}'.format(*rule).encode('utf-8'))
self.coverage_lines.append('DA:{},1'.format(rule[0])) | Create a Python 3 function to
add entry to coverage saying this selector was matched | You are a Python code analyst, evaluating scripts for potential improvements. |
Build a set of steps to collate an HTML doc. | Can you tell what is the following Python 3 function doing
def build_recipe(self, element, step, depth=0):
element_id = element.etree_element.get('id')
self.state['lang'] = element.lang
matching_rules = {}
# specificity, order, pseudo, payload = match
# selector_rule, declara... | As a python code expert, you are capable of creating scripts from specifications. |
Place target element onto action stack. | How would you explain what the following Python 3 function does
def push_target_elem(self, element, pseudo=None):
actions = self.state[self.state['current_step']]['actions']
if len(actions) > 0 and actions[-1][0] == 'target':
actions.pop()
actions.append(('target', Target(element.etr... | As a Python code analyst, you investigate and solve complex coding mysteries |
Create and place pending target element onto stack. | Here you have a function in Python 3, explain what it does
def push_pending_elem(self, element, pseudo):
self.push_target_elem(element, pseudo)
elem = etree.Element('div')
actions = self.state[self.state['current_step']]['actions']
actions.append(('move', elem))
actions.append(('... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove empty wrapper element. | Make a summary of the following Python 3 code
def pop_pending_if_empty(self, element):
actions = self.state[self.state['current_step']]['actions']
elem = self.current_target().tree
if actions[-1][0] == ('target') and actions[-1][1].tree == elem:
actions.pop()
actions.pop(... | As a python code expert, you are capable of creating scripts from specifications. |
def find_method(self, decl):
"""Find class method to call for declaration based on name."""
name = decl.name
method = None
try:
method = getattr(self, u'do_{}'.format(
(name).replace('-', '_')))
except AttributeError:
if name.s... | Write a Python 3 script to
find method to call for declaration based on name. | As a Python code composer, you craft elegant and concise scripts. |
def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is retu... | Can you write a function in Python 3 where it
returns value of vname from the variable store vtype. | As a Python code composer, you craft elegant and concise scripts. |
Return counter value in given style. | Here you have a function in Python 3, explain what it does
def counter_style(self, val, style):
if style == 'decimal-leading-zero':
if val < 10:
valstr = "0{}".format(val)
else:
valstr = str(val)
elif style == 'lower-roman':
valstr = _t... | You are a Python code architect, reviewing and designing scalable and efficient code |
Evaluate parsed string.
Returns a list of current and delayed values. | Given the following Python 3 function, write the documentation
def eval_string_value(self, element, value):
strval = ''
vals = []
for term in value:
if type(term) is ast.WhitespaceToken:
pass
elif type(term) is ast.StringToken:
strval += ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Implement string - set declaration. | Explain what the following Python 3 code does
def do_string_set(self, element, decl, pseudo):
args = serialize(decl.value)
step = self.state[self.state['current_step']]
strval = ''
strname = None
for term in decl.value:
if type(term) is ast.WhitespaceToken:
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Implement node - set declaration. | How would you explain what the following Python 3 function does
def do_node_set(self, element, decl, pseudo):
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
_, valstep = self.lookup('pending', target)
if not ... | As a Python code composer, you craft elegant and concise scripts. |
def do_move_to(self, element, decl, pseudo):
"""Implement move-to declaration."""
target = serialize(decl.value).strip()
step = self.state[self.state['current_step']]
elem = self.current_target().tree
# Find if the current node already has a move, and remove it.
actions... | Write a Python 3 function for
implementing move - to declaration. | As a Python code composer, you craft elegant and concise scripts. |
Implement setting tag for new wrapper element. | Make a summary of the following Python 3 code
def do_container(self, element, decl, pseudo):
value = serialize(decl.value).strip()
if '|' in value:
namespace, tag = value.split('|', 1)
try:
namespace = self.css_namespaces[namespace]
except KeyError:
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def do_class(self, element, decl, pseudo):
"""Implement class declaration - pre-match."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', ('class', strval))) | Write a Python 3 function for
implementing class declaration - pre - match. | You are a Python code generator, capable of creating scripts from specifications. |
def do_attr_any(self, element, decl, pseudo):
"""Implement generic attribute setting."""
step = self.state[self.state['current_step']]
actions = step['actions']
strval = self.eval_string_value(element, decl.value)
actions.append(('attrib', (decl.name[5:], strval))) | Implement a function in Python 3 to
implement generic attribute setting. | You are a Python code analyst, evaluating scripts for potential improvements. |
def do_group_by(self, element, decl, pseudo):
"""Implement group-by declaration - pre-match."""
sort_css = groupby_css = flags = ''
if ',' in decl.value:
if decl.value.count(',') == 2:
sort_css, groupby_css, flags = \
map(serialize, split(decl.... | Write a Python 3 script for
implementing group - by declaration - pre - match. | You are a Python code architect, reviewing and designing scalable and efficient code |
Implement sort - by declaration - pre - match. | Given the following Python 3 function, write the documentation
def do_sort_by(self, element, decl, pseudo):
if ',' in decl.value:
css, flags = split(decl.value, ',')
else:
css = decl.value
flags = None
sort = css_to_func(serialize(css), serialize(flags or ''),... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _get_connection(host, username: str, key_path: str) \
-> paramiko.Transport or None:
"""Return an authenticated SSH connection.
:param host: host or IP of the machine
:type host: str
:param username: SSH username
:type username: str
:param key_path: path to the SSH private key for S... | Write a Python 3 script to
return an authenticated SSH connection. | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_command(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command via SSH, proxied through the mesos master
:param host: host or IP of the machine to execute the command on
:type host: str
:param command: the command to exe... | Write a Python 3 function for
running a command on the master and returns the output of the command | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_command_on_master(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos master
"""
return run_command(shakedown.master_ip(), command, username, key_path, noisy) | How would you implement a function in Python 3 that
runs a command on the master node | As a Python code translator, you convert algorithms and pseudocode into Python. |
Run a command on the Mesos leader. | Here you have a function in Python 3, explain what it does
def run_command_on_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Mesos leader. Important for Multi-Master.
"""
return run_command(shakedown.master_leader_ip(), command, userna... | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_command_on_marathon_leader(
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on the Marathon leader
"""
return run_command(shakedown.marathon_leader_ip(), command, username, key_path, noisy) | Write a Python 3 script for
running a command on the Marathon leader | You are a Python code architect, reviewing and designing scalable and efficient code |
def run_command_on_agent(
host,
command,
username=None,
key_path=None,
noisy=True
):
""" Run a command on a Mesos agent, proxied through the master
"""
return run_command(host, command, username, key_path, noisy) | Implement a function in Python 3 to
run a command on a Mesos agent | You are a Python code generator, capable of creating scripts from specifications. |
def run_dcos_command(command, raise_on_error=False, print_output=True):
""" Run `dcos {command}` via DC/OS CLI
:param command: the command to execute
:type command: str
:param raise_on_error: whether to raise a DCOSException if the return code is nonzero
:type raise_on_error: bool
... | Create a Python 3 function to
execute a command via DC - OS and return the stdout and stderr of the command. | You are a Python code generator, capable of creating scripts from specifications. |
Wait for the result of a command execution. | Can you tell what is the following Python 3 function doing
def _wait_for_recv(self):
while True:
time.sleep(0.2)
if self.session.recv_ready() or self.session.closed:
return | You are a Python code generator, capable of creating scripts from specifications. |
def attach_cluster(url):
"""Attach to an already set-up cluster
:return: True if successful, else False
"""
with shakedown.stdchannel_redirected(sys.stderr, os.devnull):
clusters = [c.dict() for c in dcos.cluster.get_clusters()]
for c in clusters:
if url == c['url']:
try:... | Write a Python 3 function that can
attach to an already set - up cluster | As a Python code composer, you craft elegant and concise scripts. |
def dcos_version():
"""Return the version of the running cluster.
:return: DC/OS cluster version as a string
"""
url = _gen_url('dcos-metadata/dcos-version.json')
response = dcos.http.request('get', url)
if response.status_code == 200:
return response.json()['version']
else:
... | Can you write a function in Python 3 where it
returns the version of the running cluster. | You are a Python code architect, reviewing and designing scalable and efficient code |
def authenticate(username, password):
"""Authenticate with a DC/OS cluster and return an ACS token.
return: ACS token
"""
url = _gen_url('acs/api/v1/auth/login')
creds = {
'uid': username,
'password': password
}
response = dcos.http.request('post', url, json=creds)
if ... | Implement a function in Python 3 to
authenticate with a DC / OS cluster and return an ACS token. | You are a Python code generator, capable of creating scripts from specifications. |
Authenticate by checking for a valid OAuth token. | Can you tell what is the following Python 3 function doing
def authenticate_oauth(oauth_token):
url = _gen_url('acs/api/v1/auth/login')
creds = {
'token': oauth_token
}
response = dcos.http.request('post', url, json=creds)
if response.status_code == 200:
return response.json()['to... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _gen_url(url_path):
"""Return an absolute URL by combining DC/OS URL and url_path.
:param url_path: path to append to DC/OS URL
:type url_path: str
:return: absolute URL
:rtype: str
"""
from six.moves import urllib
return urllib.parse.urljoin(dcos_url(), url_path) | Write a Python 3 function that can
generate an absolute URL by combining DC OS URL and url_path. | You are a Python code analyst, evaluating scripts for potential improvements. |
def partition_master(incoming=True, outgoing=True):
""" Partition master's port alone. To keep DC/OS cluster running.
:param incoming: Partition incoming traffic to master process. Default True.
:param outgoing: Partition outgoing traffic from master process. Default True.
"""
echo('Partitioning m... | Create a Python 3 function to
partition master's port alone. To keep DC/OS cluster running. :param incoming: Partition incoming traffic to master process. Default True. :param outgoing: Partition outgoing traffic from master process. Default True. | As a python code expert, you are capable of creating scripts from specifications. |
Returns the json object that represents each of the masters. | Can you tell what is the following Python 3 function doing
def get_all_masters():
masters = []
for master in __master_zk_nodes_keys():
master_zk_str = get_zk_node_data(master)['str']
masters.append(json.loads(master_zk_str))
return masters | You are a Python code analyst, evaluating scripts for potential improvements. |
Provides a list public IPs for public agents in the cluster | Can you generate a brief explanation for the following Python 3 code
def get_public_agents_public_ip():
public_ip_list = []
agents = get_public_agents()
for agent in agents:
status, public_ip = shakedown.run_command_on_agent(agent, "/opt/mesosphere/bin/detect_ip_public")
public_ip_list.appen... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_public_agents():
"""Provides a list of hostnames / private IPs that are public agents in the cluster"""
agent_list = []
agents = __get_all_agents()
for agent in agents:
for reservation in agent["reserved_resources"]:
if "slave_public" in reservation:
agent_lis... | Can you implement a function in Python 3 that
provides a list of hostnames / private IPs that are public agents in the cluster | You are a Python code analyst, evaluating scripts for potential improvements. |
def get_private_agents():
"""Provides a list of hostnames / IPs that are private agents in the cluster"""
agent_list = []
agents = __get_all_agents()
for agent in agents:
if(len(agent["reserved_resources"]) == 0):
agent_list.append(agent["hostname"])
else:
privat... | Create a Python 3 function to
provide a list of hostnames / IPs that are private agents in the cluster | As a Python code analyst, you investigate and solve complex coding mysteries |
Provides a list of hostnames / IPs of all agents in the cluster | Explain what the following Python 3 code does
def get_agents():
agent_list = []
agents = __get_all_agents()
for agent in agents:
agent_list.append(agent["hostname"])
return agent_list | As a Python code translator, you convert algorithms and pseudocode into Python. |
def partition_agent(host):
""" Partition a node from all network traffic except for SSH and loopback
:param hostname: host or IP of the machine to partition from the cluster
"""
network.save_iptables(host)
network.flush_all_rules(host)
network.allow_all_traffic(host)
network.run_iptabl... | Create a Python 3 function to
partition agent from all network traffic except for SSH and loopback. | You are a Python code architect, reviewing and designing scalable and efficient code |
def kill_process_on_host(
hostname,
pattern
):
""" Kill the process matching pattern at ip
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pattern: a regular expression matching the name of the process to kill
"""
status, stdout = ... | Can you write a function in Python 3 where it
kills the process matching pattern at ip | You are a Python code architect, reviewing and designing scalable and efficient code |
def kill_process_from_pid_file_on_host(hostname, pid_file='app.pid'):
""" Retrieves the PID of a process from a pid file on host and kills it.
:param hostname: the hostname or ip address of the host on which the process will be killed
:param pid_file: pid file to use holding the pid number to kill
"""
... | How would you code a function in Python 3 to
kill a process from a pid file on the host. | You are a Python code analyst, evaluating scripts for potential improvements. |
def wait_for(
predicate,
timeout_seconds=120,
sleep_seconds=1,
ignore_exceptions=True,
inverse_predicate=False,
noisy=False,
required_consecutive_success_count=1):
""" waits or spins for a predicate, returning the result.
Predicate is a function that r... | Write a Python 3 function for
waiting or spins for a predicate returning the result. | As a Python code composer, you craft elegant and concise scripts. |
Return a string representation of the predicate. | Can you generate a brief explanation for the following Python 3 code
def __stringify_predicate(predicate):
funname = getsource(predicate).strip().split(' ')[2].rstrip(',')
params = 'None'
# if args dig in the stack
if '()' not in funname:
stack = getouterframes(currentframe())
for frame... | As a Python code composer, you craft elegant and concise scripts. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.