_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q262500 | Phase.Cp_mag | validation | def Cp_mag(self, T):
"""
Calculate the phase's magnetic contribution to heat capacity at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic heat capacity of the compound phase.
Dinsdale, A. T. (1991). SGTE data for | python | {
"resource": ""
} |
q262501 | Phase.H | validation | def H(self, T):
"""
Calculate the enthalpy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol] The enthalpy of the compound phase.
"""
result = self.DHref
for Tmax in sorted([float(TT) for TT | python | {
"resource": ""
} |
q262502 | Phase.H_mag | validation | def H_mag(self, T):
"""
Calculate the phase's magnetic contribution to enthalpy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic enthalpy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. | python | {
"resource": ""
} |
q262503 | Phase.S | validation | def S(self, T):
"""
Calculate the entropy of the compound phase at the specified
temperature.
:param T: [K] temperature
:returns: [J/mol/K] The entropy of the compound phase.
"""
result = self.Sref
for Tmax in sorted([float(TT) for TT in self._Cp_records.keys()]): | python | {
"resource": ""
} |
q262504 | Phase.S_mag | validation | def S_mag(self, T):
"""
Calculate the phase's magnetic contribution to entropy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol/K] The magnetic entropy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. | python | {
"resource": ""
} |
q262505 | Phase.G_mag | validation | def G_mag(self, T):
"""
Calculate the phase's magnetic contribution to Gibbs energy at the
specified temperature.
:param T: [K] temperature
:returns: [J/mol] The magnetic Gibbs energy of the compound phase.
Dinsdale, A. T. (1991). SGTE data for pure elements. Calphad, 15(4),
317–425. http://doi.org/10.1016/0364-5916(91)90030-N
"""
tau = T / self.Tc_mag
if tau <= 1.0:
g = 1 - (self._A_mag/tau +
| python | {
"resource": ""
} |
q262506 | Compound.Cp | validation | def Cp(self, phase, T):
"""
Calculate the heat capacity of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
:param T: [K] temperature
:returns: [J/mol/K] Heat capacity.
"""
| python | {
"resource": ""
} |
q262507 | Compound.H | validation | def H(self, phase, T):
"""
Calculate the enthalpy of a phase of the compound at a specified
temperature.
:param phase: A phase of the compound, e.g. 'S', 'L', 'G'.
| python | {
"resource": ""
} |
q262508 | _create_polynomial_model | validation | def _create_polynomial_model(
name: str,
symbol: str,
degree: int,
ds: DataSet,
dss: dict):
"""
Create a polynomial model to describe the specified property based on the
specified data set, and save it to a .json file.
:param name: material name.
:param symbol: property symbol.
:param degree: polynomial degree.
:param ds: the source data set.
:param dss: dictionary of all datasets.
""" | python | {
"resource": ""
} |
q262509 | _create_air | validation | def _create_air():
"""
Create a dictionary of datasets and a material object for air.
:return: (Material, {str, DataSet})
"""
name = "Air"
namel = name.lower()
mm = 28.9645 # g/mol
ds_dict = _create_ds_dict([
"dataset-air-lienhard2015",
"dataset-air-lienhard2018"])
active_ds = "dataset-air-lienhard2018"
# create polynomial models to describe material properties
# comment it out after model creation is complete, so that it does not
# run every time during use.
# _create_polynomial_model(name, "Cp", 13, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "k", 8, ds_dict[active_ds], ds_dict)
# _create_polynomial_model(name, "mu", 8, ds_dict[active_ds], ds_dict)
# | python | {
"resource": ""
} |
q262510 | Report.render | validation | def render(self, format=ReportFormat.printout):
"""
Render the report in the specified format
:param format: The format. The default format is to print
the report to the console.
:returns: If the format was set to 'string' then a string
representation of the report is returned.
"""
table = self._generate_table_()
if format == ReportFormat.printout:
print(tabulate(table, headers="firstrow", tablefmt="simple"))
elif format == ReportFormat.latex:
self._render_latex_(table)
elif format == ReportFormat.txt:
self._render_txt_(table)
elif format == ReportFormat.csv:
| python | {
"resource": ""
} |
q262511 | rgb_to_hex | validation | def rgb_to_hex(rgb):
"""
Convert an RGB color representation to a HEX color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
| python | {
"resource": ""
} |
q262512 | rgb_to_yiq | validation | def rgb_to_yiq(rgb):
"""
Convert an RGB color representation to a YIQ color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: YIQ representation of the input RGB value.
:rtype: tuple
"""
r, g, | python | {
"resource": ""
} |
q262513 | rgb_to_hsv | validation | def rgb_to_hsv(rgb):
"""
Convert an RGB color representation to an HSV color representation.
(r, g, b) :: r -> [0, 255]
g -> [0, 255]
b -> [0, 255]
:param rgb: A tuple of three numeric values corresponding to the red, green, and blue value.
:return: HSV representation of the input RGB value.
:rtype: tuple
"""
r, g, b = rgb[0] / 255, rgb[1] / 255, rgb[2] / 255
_min = min(r, g, b)
_max = max(r, g, b)
v = _max
delta = _max - _min
if _max == 0: | python | {
"resource": ""
} |
q262514 | hex_to_rgb | validation | def hex_to_rgb(_hex):
"""
Convert a HEX color representation to an RGB color representation.
hex :: hex -> [000000, FFFFFF]
:param _hex: The 3- or 6-char hexadecimal string representing the color value.
:return: RGB representation of the input HEX | python | {
"resource": ""
} |
q262515 | yiq_to_rgb | validation | def yiq_to_rgb(yiq):
"""
Convert a YIQ color representation to an RGB color representation.
(y, i, q) :: y -> [0, 1]
i -> [-0.5957, 0.5957]
q -> [-0.5226, 0.5226]
:param yiq: A tuple of three numeric values corresponding to the luma and chrominance. | python | {
"resource": ""
} |
q262516 | hsv_to_rgb | validation | def hsv_to_rgb(hsv):
"""
Convert an HSV color representation to an RGB color representation.
(h, s, v) :: h -> [0, 360)
s -> [0, 1]
v -> [0, 1]
:param hsv: A tuple of three numeric values corresponding to the hue, saturation, and value.
:return: RGB representation of the input HSV value.
:rtype: tuple
"""
| python | {
"resource": ""
} |
q262517 | color_run | validation | def color_run(start_color, end_color, step_count, inclusive=True, to_color=True):
"""
Given a start color, end color, and a number of steps, returns a list of colors which represent a 'scale' between
the start and end color.
:param start_color: The color starting the run
:param end_color: The color ending the run
:param step_count: The number of colors to have between the start and end color
:param inclusive: Flag determining whether to include start and end values in run (default True)
:param to_color: Flag indicating return values should be Color objects (default True)
:return: List of colors between the start and end color
:rtype: list
"""
if isinstance(start_color, Color):
start_color = start_color.rgb
if isinstance(end_color, Color):
| python | {
"resource": ""
} |
q262518 | ForgiveDB.get | validation | def get(self, key, default=None):
""" Get key value, return default if key doesn't exist """
if self.in_memory:
return self._memory_db.get(key, default) | python | {
"resource": ""
} |
q262519 | ForgiveDB.set | validation | def set(self, key, value):
""" Set key value """
if self.in_memory:
self._memory_db[key] = value
else:
db = self._read_file()
db[key] = value | python | {
"resource": ""
} |
q262520 | paginate_link_tag | validation | def paginate_link_tag(item):
"""
Create an A-HREF tag that points to another page usable in paginate.
"""
a_tag = Page.default_link_tag(item)
if item['type'] == 'current_page':
| python | {
"resource": ""
} |
q262521 | EcoNetApiInterface.set_state | validation | def set_state(_id, body):
"""
Set a devices state.
"""
url = DEVICE_URL % _id
if "mode" in body:
url = MODES_URL % _id
arequest = requests.put(url, headers=HEADERS, data=json.dumps(body))
| python | {
"resource": ""
} |
q262522 | EcoNetApiInterface.get_modes | validation | def get_modes(_id):
"""
Pull a water heater's modes from the API.
"""
url = MODES_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
| python | {
"resource": ""
} |
q262523 | EcoNetApiInterface.get_usage | validation | def get_usage(_id):
"""
Pull a water heater's usage report from the API.
"""
url = USAGE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
| python | {
"resource": ""
} |
q262524 | EcoNetApiInterface.get_device | validation | def get_device(_id):
"""
Pull a device from the API.
"""
url = DEVICE_URL % _id
arequest = requests.get(url, headers=HEADERS)
status_code = str(arequest.status_code)
| python | {
"resource": ""
} |
q262525 | EcoNetApiInterface.get_locations | validation | def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
| python | {
"resource": ""
} |
q262526 | EcoNetApiInterface.get_vacations | validation | def get_vacations():
"""
Pull the accounts vacations.
"""
arequest = requests.get(VACATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
| python | {
"resource": ""
} |
q262527 | EcoNetApiInterface.create_vacation | validation | def create_vacation(body):
"""
Create a vacation.
"""
arequest = requests.post(VACATIONS_URL, headers=HEADERS, data=json.dumps(body))
status_code = str(arequest.status_code)
if status_code != '200':
_LOGGER.error("Failed to | python | {
"resource": ""
} |
q262528 | EcoNetApiInterface.delete_vacation | validation | def delete_vacation(_id):
"""
Delete a vacation by ID.
"""
arequest = requests.delete(VACATIONS_URL + "/" + _id, headers=HEADERS)
| python | {
"resource": ""
} |
q262529 | EcoNetApiInterface._authenticate | validation | def _authenticate(self):
"""
Authenticate with the API and return an authentication token.
"""
auth_url = BASE_URL + "/auth/token"
payload = {'username': self.email, 'password': self.password, 'grant_type': 'password'}
arequest = requests.post(auth_url, data=payload, headers=BASIC_HEADERS)
status = arequest.status_code
if status != 200:
_LOGGER.error("Authentication request failed, please check credintials. " + str(status))
return False
response = arequest.json()
_LOGGER.debug(str(response))
| python | {
"resource": ""
} |
q262530 | PyEcoNet.get_water_heaters | validation | def get_water_heaters(self):
"""
Return a list of water heater devices.
Parses the response from the locations endpoint in to a pyeconet.WaterHeater.
"""
water_heaters = []
for location in self.locations:
_location_id = location.get("id")
for device in location.get("equipment"):
if device.get("type") == "Water Heater":
water_heater_modes = self.api_interface.get_modes(device.get("id"))
water_heater_usage = self.api_interface.get_usage(device.get("id"))
water_heater = self.api_interface.get_device(device.get("id"))
vacations = self.api_interface.get_vacations()
device_vacations = []
for vacation in vacations:
for equipment in vacation.get("participatingEquipment"):
| python | {
"resource": ""
} |
q262531 | models_preparing | validation | def models_preparing(app):
""" Wrap all sqlalchemy model in settings.
"""
def wrapper(resource, parent):
if isinstance(resource, DeclarativeMeta):
resource = ListResource(resource)
| python | {
"resource": ""
} |
q262532 | _translateCommands | validation | def _translateCommands(commands):
"""Generate the binary strings for a comma seperated list of commands."""
for command in commands.split(','):
# each command results in 2 bytes of binary data
result = [0, 0]
device, command = command.strip().upper().split(None, 1)
# translate the house code
result[0] = houseCodes[device[0]]
# translate the device number if there is one
if len(device) > 1:
deviceNumber = deviceNumbers[device[1:]]
result[0] |= | python | {
"resource": ""
} |
q262533 | _sendBinaryData | validation | def _sendBinaryData(port, data):
"""Send a string of binary data to the FireCracker with proper timing.
See the diagram in the spec referenced above for timing information.
The module level variables leadInOutDelay and bitDelay represent how
long each type of delay should be | python | {
"resource": ""
} |
q262534 | _setRTSDTR | validation | def _setRTSDTR(port, RTS, DTR):
"""Set RTS and DTR to the requested state."""
| python | {
"resource": ""
} |
q262535 | sendCommands | validation | def sendCommands(comPort, commands):
"""Send X10 commands using the FireCracker on comPort
comPort should be the name of a serial port on the host platform. On
Windows, for example, 'com1'.
commands should be a string consisting of X10 commands separated by
commas. For example. 'A1 On, A Dim, A Dim, A Dim, A Lamps Off'. The
letter is a house code (A-P) and the number is the device number (1-16).
Possible commands for a house code / device number combination are
'On' and 'Off'. The commands 'Bright' and 'Dim' should be used with a
house code alone after sending an On command to a specific device. The
'All On', 'All Off', 'Lamps On', and 'Lamps Off' commands should also
be used with a house code alone.
# Turn on module A1
>>> sendCommands('com1', 'A1 On')
# Turn all modules with house code A off
>>> sendCommands('com1', 'A All Off')
| python | {
"resource": ""
} |
q262536 | main | validation | def main(argv=None):
"""Send X10 commands when module is used from the command line.
This uses syntax similar to sendCommands, for example:
x10.py com2 A1 On, A2 Off, B All Off
"""
if len(argv):
# join all the arguments together by spaces so that quotes
# aren't required on the command line.
| python | {
"resource": ""
} |
q262537 | normalize_housecode | validation | def normalize_housecode(house_code):
"""Returns a normalized house code, i.e. upper case.
Raises exception X10InvalidHouseCode if house code appears to be invalid
"""
if house_code is None:
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if not isinstance(house_code, basestring):
raise X10InvalidHouseCode('%r is not a valid house code' % house_code)
if len(house_code) != 1:
| python | {
"resource": ""
} |
q262538 | normalize_unitnumber | validation | def normalize_unitnumber(unit_number):
"""Returns a normalized unit number, i.e. integers
Raises exception X10InvalidUnitNumber if unit number appears to be invalid
"""
try:
try:
unit_number = int(unit_number)
except ValueError:
raise X10InvalidUnitNumber('%r not a valid unit number' % unit_number)
except | python | {
"resource": ""
} |
q262539 | X10Driver.x10_command | validation | def x10_command(self, house_code, unit_number, state):
"""Send X10 command to ??? unit.
@param house_code (A-P) - example='A'
@param unit_number (1-16)- example=1 (or None to impact entire house code)
@param state - Mochad command/state, See
https://sourceforge.net/p/mochad/code/ci/master/tree/README
examples=OFF, 'OFF', 'ON', ALL_OFF, 'all_units_off', 'xdim 128', etc.
Examples:
x10_command('A', '1', ON)
x10_command('A', '1', OFF)
| python | {
"resource": ""
} |
q262540 | get_parser | validation | def get_parser():
"""
Generate an appropriate parser.
:returns: an argument parser
:rtype: `ArgumentParser`
"""
parser = argparse.ArgumentParser()
| python | {
"resource": ""
} |
q262541 | get_command | validation | def get_command(namespace):
"""
Get the pylint command for these arguments.
:param `Namespace` namespace: the namespace
"""
cmd = ["pylint", namespace.package] + arg_map[namespace.package]
| python | {
"resource": ""
} |
q262542 | _wrapper | validation | def _wrapper(func):
"""
Wraps a generated function so that it catches all Type- and ValueErrors
and raises IntoDPValueErrors.
:param func: the transforming function
"""
@functools.wraps(func)
def the_func(expr):
| python | {
"resource": ""
} |
q262543 | xformers | validation | def xformers(sig):
"""
Get the list of xformer functions for the given signature.
:param str sig: a signature
:returns: a list of xformer functions for the given signature.
| python | {
"resource": ""
} |
q262544 | xformer | validation | def xformer(signature):
"""
Returns a transformer function for the given signature.
:param str signature: a dbus signature
:returns: a function to transform a list of objects to inhabit the signature
:rtype: (list of object) -> (list of object)
"""
funcs = [f for (f, _) in xformers(signature)]
def the_func(objects):
"""
Returns the a list of objects, transformed.
:param objects: a list of objects
:type objects: list of object
:returns: transformed objects
:rtype: list of object (in dbus types)
"""
| python | {
"resource": ""
} |
q262545 | _ToDbusXformer._variant_levels | validation | def _variant_levels(level, variant):
"""
Gets the level for the variant.
:param int level: the current variant level
:param int variant: the value | python | {
"resource": ""
} |
q262546 | _ToDbusXformer._handle_variant | validation | def _handle_variant(self):
"""
Generate the correct function for a variant signature.
:returns: function that returns an appropriate value
:rtype: ((str * object) or list)-> object
"""
def the_func(a_tuple, variant=0):
"""
Function for generating a variant value from a tuple.
:param a_tuple: the parts of the variant
:type a_tuple: (str * object) or list
:param int variant: object's variant index
:returns: a value of the correct type with correct variant level
| python | {
"resource": ""
} |
q262547 | _ToDbusXformer._handle_array | validation | def _handle_array(toks):
"""
Generate the correct function for an array signature.
:param toks: the list of parsed tokens
:returns: function that returns an Array or Dictionary value
:rtype: ((or list dict) -> ((or Array Dictionary) * int)) * str
"""
if len(toks) == 5 and toks[1] == '{' and toks[4] == '}':
subtree = toks[2:4]
signature = ''.join(s for (_, s) in subtree)
[key_func, value_func] = [f for (f, _) in subtree]
def the_dict_func(a_dict, variant=0):
"""
Function for generating a Dictionary from a dict.
:param a_dict: the dictionary to transform
:type a_dict: dict of (`a * `b)
:param int variant: variant level
:returns: a dbus dictionary of transformed values and level
:rtype: Dictionary * int
"""
elements = \
[(key_func(x), value_func(y)) for (x, y) in a_dict.items()]
level = 0 if elements == [] \
else max(max(x, y) for ((_, x), (_, y)) in elements)
(obj_level, func_level) = \
_ToDbusXformer._variant_levels(level, variant)
return (dbus.types.Dictionary(
((x, y) for ((x, _), (y, _)) in elements),
signature=signature,
variant_level=obj_level), func_level)
return (the_dict_func, 'a{' + signature + '}')
if len(toks) == 2:
(func, sig) = toks[1]
def the_array_func(a_list, variant=0):
"""
Function for generating an Array from a list.
:param a_list: the list to transform
:type | python | {
"resource": ""
} |
q262548 | _ToDbusXformer._handle_struct | validation | def _handle_struct(toks):
"""
Generate the correct function for a struct signature.
:param toks: the list of parsed tokens
:returns: function that returns an Array or Dictionary value
:rtype: ((list or tuple) -> (Struct * int)) * str
"""
subtrees = toks[1:-1]
signature = ''.join(s for (_, s) in subtrees)
funcs = [f for (f, _) in subtrees]
def the_func(a_list, variant=0):
"""
Function for generating a Struct from a list.
:param a_list: the list to transform
:type a_list: list or tuple
:param int variant: variant index
:returns: a dbus Struct of transformed values and variant level
:rtype: Struct * int
:raises IntoDPValueError:
"""
if isinstance(a_list, dict):
raise IntoDPValueError(a_list, "a_list",
"must be a simple sequence, is a dict")
if len(a_list) != | python | {
"resource": ""
} |
q262549 | _ToDbusXformer._handle_base_case | validation | def _handle_base_case(klass, symbol):
"""
Handle a base case.
:param type klass: the class constructor
:param str symbol: the type code
"""
def the_func(value, variant=0):
"""
Base case.
:param int variant: variant level for this object
:returns: a tuple of a dbus object and the variant level
:rtype: dbus object * int
"""
| python | {
"resource": ""
} |
q262550 | signature | validation | def signature(dbus_object, unpack=False):
"""
Get the signature of a dbus object.
:param dbus_object: the object
:type dbus_object: a dbus object
:param bool unpack: if True, unpack from enclosing variant type
:returns: the corresponding signature
:rtype: str
"""
# pylint: disable=too-many-return-statements
# pylint: disable=too-many-branches
if dbus_object.variant_level != 0 and not unpack:
return 'v'
if isinstance(dbus_object, dbus.Array):
sigs = frozenset(signature(x) for x in dbus_object)
len_sigs = len(sigs)
if len_sigs > 1: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_sigs == 0:
return 'a' + dbus_object.signature
return 'a' + [x for x in sigs][0]
if isinstance(dbus_object, dbus.Struct):
sigs = (signature(x) for x in dbus_object)
return '(' + "".join(x for x in sigs) + ')'
if isinstance(dbus_object, dbus.Dictionary):
key_sigs = frozenset(signature(x) for x in dbus_object.keys())
value_sigs = frozenset(signature(x) for x in dbus_object.values())
len_key_sigs = len(key_sigs)
len_value_sigs = len(value_sigs)
if len_key_sigs != len_value_sigs: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_key_sigs > 1: # pragma: no cover
raise IntoDPValueError(dbus_object, "dbus_object",
"has bad signature")
if len_key_sigs == 0:
return 'a{' + dbus_object.signature + '}'
return 'a{' + [x for x in key_sigs][0] + [x
for x in value_sigs][0] + '}'
if | python | {
"resource": ""
} |
q262551 | lower | validation | def lower(option,value):
'''
Enforces lower case options and option values where appropriate
'''
if type(option) is str:
| python | {
"resource": ""
} |
q262552 | to_float | validation | def to_float(option,value):
'''
Converts string values to floats when appropriate
'''
if type(value) is str:
try:
| python | {
"resource": ""
} |
q262553 | to_bool | validation | def to_bool(option,value):
'''
Converts string values to booleans when appropriate
'''
if type(value) is str: | python | {
"resource": ""
} |
q262554 | Config.fork | validation | def fork(self,name):
'''
Create fork and store it in current instance
'''
| python | {
"resource": ""
} |
q262555 | ld_to_dl | validation | def ld_to_dl(ld):
'''
Convert list of dictionaries to dictionary of lists
'''
if ld:
keys = list(ld[0])
| python | {
"resource": ""
} |
q262556 | split_list | validation | def split_list(l,N):
'''
Subdivide list into N lists
'''
npmode = isinstance(l,np.ndarray)
if npmode:
l=list(l)
g=np.concatenate((np.array([0]),np.cumsum(split_integer(len(l),length=N))))
| python | {
"resource": ""
} |
q262557 | path_from_keywords | validation | def path_from_keywords(keywords,into='path'):
'''
turns keyword pairs into path or filename
if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy
'''
subdirs = []
def prepare_string(s):
s = str(s)
s = re.sub('[][{},*"'+f"'{os.sep}]",'_',s)#replace characters that make bash life difficult by underscore
if into=='file':
s = s.replace('_', ' ')#Remove underscore because they will be used as separator
if ' ' in s:
s = s.title()
s = s.replace(' ','')
return s
if isinstance(keywords,set):
keywords_list = sorted(keywords)
for property in keywords_list:
subdirs.append(prepare_string(property))
else:
keywords_list = sorted(keywords.items())
for property,value in keywords_list: # | python | {
"resource": ""
} |
q262558 | grid_evaluation | validation | def grid_evaluation(X, Y, f,vectorized=True):
'''
Evaluate function on given grid and return values in grid format
Assume X and Y are 2-dimensional arrays containing x and y coordinates,
respectively, of a two-dimensional grid, and f is a function that takes
1-d arrays with two entries. This function evaluates f on the grid points
described by X and Y and returns another 2-dimensional array of | python | {
"resource": ""
} |
q262559 | log_calls | validation | def log_calls(function):
'''
Decorator that logs function calls in their self.log
'''
def wrapper(self,*args,**kwargs):
self.log.log(group=function.__name__,message='Enter')
| python | {
"resource": ""
} |
q262560 | add_runtime | validation | def add_runtime(function):
'''
Decorator that adds a runtime profile object to the output
'''
def wrapper(*args,**kwargs):
pr=cProfile.Profile()
| python | {
"resource": ""
} |
q262561 | print_memory | validation | def print_memory(function):
'''
Decorator that prints memory information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m = StringIO()
| python | {
"resource": ""
} |
q262562 | print_profile | validation | def print_profile(function):
'''
Decorator that prints memory and runtime information at each call of the function
'''
import memory_profiler
def wrapper(*args,**kwargs):
m=StringIO()
pr=cProfile.Profile()
pr.enable()
temp_func = memory_profiler.profile(func=function,stream=m,precision=4)
output = temp_func(*args,**kwargs)
| python | {
"resource": ""
} |
q262563 | declaration | validation | def declaration(function):
'''
Declare abstract function.
Requires function to be empty except for docstring describing semantics.
To apply function, first argument must come with implementation of semantics.
'''
function,name=_strip_function(function)
if not function.__code__.co_code in [empty_function.__code__.co_code, | python | {
"resource": ""
} |
q262564 | print_runtime | validation | def print_runtime(function):
'''
Decorator that prints running time information at each call of the function
'''
def wrapper(*args,**kwargs):
pr=cProfile.Profile()
pr.enable()
output = function(*args,**kwargs)
| python | {
"resource": ""
} |
q262565 | _validate_many | validation | def _validate_many(args, specs, defaults,passed_conditions,value_conditions,
allow_unknowns,unknowns_spec):
'''
Similar to validate but validates multiple objects at once, each with their own specification.
Fill objects that were specified but not provided with NotPassed or default values
Apply `value_condition` to object dictionary as a whole
'''
validated_args = builtins.dict()
passed_but_not_specified = set(args.keys()) - set(specs.keys())
if passed_but_not_specified:
if not allow_unknowns:
raise ValueError(('Arguments {} were passed but not specified (use ' +
'`allow_unknowns=True` to avoid this error)'.format(passed_but_not_specified)))
else:
for arg in passed_but_not_specified:
if unknowns_spec is not None:
specs[arg] = unknowns_spec
if passed_conditions:
validate(args, Dict(passed_conditions=passed_conditions))
for arg in specs:
if (not arg in args) or NotPassed(args[arg]):
if arg in defaults:
if isinstance(defaults[arg],DefaultGenerator):
| python | {
"resource": ""
} |
q262566 | ModelMixin.get_default_fields | validation | def get_default_fields(self):
"""
get all fields of model, execpt id
"""
field_names = self._meta.get_all_field_names()
if 'id' | python | {
"resource": ""
} |
q262567 | DownloaderBase.fetch | validation | def fetch(self, url, path, filename):
"""Verify if the file is already downloaded and complete. If they don't
exists or if are not complete, use homura download function to fetch
files. Return a list with the path of the downloaded file and the size
of the remote file.
"""
logger.debug('initializing download in ', url)
remote_file_size = self.get_remote_file_size(url)
if exists(join(path, filename)):
size = getsize(join(path, filename))
if size == remote_file_size:
logger.error('%s already exists on your system' % filename)
| python | {
"resource": ""
} |
q262568 | DownloaderBase.validate_bands | validation | def validate_bands(self, bands):
"""Validate bands parameter."""
if not isinstance(bands, list):
logger.error('Parameter bands must be a "list"')
raise TypeError('Parameter bands must be a "list"')
valid_bands = list(range(1, 12)) + ['BQA']
for band in bands:
| python | {
"resource": ""
} |
q262569 | GoogleDownloader.validate_sceneInfo | validation | def validate_sceneInfo(self):
"""Check scene name and whether remote file exists. Raises
WrongSceneNameError if the scene name is wrong.
"""
if self.sceneInfo.prefix not in self.__satellitesMap:
logger.error('Google Downloader: Prefix of %s (%s) is invalid'
| python | {
"resource": ""
} |
q262570 | GoogleDownloader.download | validation | def download(self, bands, download_dir=None, metadata=False):
"""Download remote .tar.bz file."""
super(GoogleDownloader, self).validate_bands(bands)
pattern = re.compile('^[^\s]+_(.+)\.tiff?', re.I)
image_list = []
band_list = ['B%i' % (i,) if isinstance(i, int) else i for i in bands]
if download_dir is None:
download_dir = DOWNLOAD_DIR
check_create_folder(join(download_dir, self.sceneInfo.name))
filename = "%s%s" % (self.sceneInfo.name, self.__remote_file_ext)
downloaded = self.fetch(self.remote_file_url, download_dir, filename)
| python | {
"resource": ""
} |
q262571 | AWSDownloader.validate_sceneInfo | validation | def validate_sceneInfo(self):
"""Check whether sceneInfo is valid to download from AWS Storage."""
if self.sceneInfo.prefix not | python | {
"resource": ""
} |
q262572 | AWSDownloader.download | validation | def download(self, bands, download_dir=None, metadata=False):
"""Download each specified band and metadata."""
super(AWSDownloader, self).validate_bands(bands)
if download_dir is None:
download_dir = DOWNLOAD_DIR
dest_dir = check_create_folder(join(download_dir, self.sceneInfo.name))
downloaded = []
for band in bands:
if band == 'BQA':
filename = '%s_%s.%s' % (self.sceneInfo.name, band, self.__remote_file_ext)
else:
filename = '%s_B%s.%s' % (self.sceneInfo.name, | python | {
"resource": ""
} |
q262573 | open_archive | validation | def open_archive(fs_url, archive):
"""Open an archive on a filesystem.
This function tries to mimick the behaviour of `fs.open_fs` as closely
as possible: it accepts either a FS URL or a filesystem instance, and
will close all resources it had to open.
Arguments:
fs_url (FS or text_type): a FS URL, or a filesystem
instance, where the archive file is located.
archive (text_type): the path to the archive file on the
given filesystem.
Raises:
`fs.opener._errors.Unsupported`: when the archive type is not supported
(either the file extension is unknown or the opener requires unmet
dependencies).
Example:
>>> from fs.archive import open_archive
>>> with open_archive('mem://', 'test.tar.gz') as archive_fs:
... type(archive_fs)
<class 'fs.archive.tarfs.TarFS'>
Hint:
This function finds the entry points defined in group
``fs.archive.open_archive``, using the names of the entry point
as the registered extension.
"""
it = pkg_resources.iter_entry_points('fs.archive.open_archive')
entry_point = next((ep for ep in it if archive.endswith(ep.name)), None)
if entry_point is None:
raise UnsupportedProtocol(
'unknown archive extension: {}'.format(archive))
try:
archive_opener = entry_point.load()
except pkg_resources.DistributionNotFound as df: # pragma: no cover
six.raise_from(UnsupportedProtocol(
'extension {} requires {}'.format(entry_point.name, df.req)), None)
try:
| python | {
"resource": ""
} |
q262574 | iso_name_slugify | validation | def iso_name_slugify(name):
"""Slugify a name in the ISO-9660 way.
Example:
>>> slugify('épatant')
"_patant"
"""
| python | {
"resource": ""
} |
q262575 | iso_name_increment | validation | def iso_name_increment(name, is_dir=False, max_length=8):
"""Increment an ISO name to avoid name collision.
Example:
>>> iso_name_increment('foo.txt')
'foo1.txt'
>>> iso_name_increment('bar10')
'bar11'
>>> iso_name_increment('bar99', max_length=5)
'ba100'
"""
# Split the extension if needed
if not is_dir and '.' in name:
name, ext = name.rsplit('.')
ext = '.{}'.format(ext)
else:
ext = ''
# Find the position of the last letter
for position, char in reversed(list(enumerate(name))):
if char not in string.digits:
| python | {
"resource": ""
} |
q262576 | iso_path_slugify | validation | def iso_path_slugify(path, path_table, is_dir=False, strict=True):
"""Slugify a path, maintaining a map with the previously slugified paths.
The path table is used to prevent slugified names from collisioning,
using the `iso_name_increment` function to deduplicate slugs.
Example:
>>> path_table = {'/': '/'}
>>> iso_path_slugify('/ébc.txt', path_table)
'/_BC.TXT'
>>> iso_path_slugify('/àbc.txt', path_table)
'/_BC2.TXT'
"""
# Split the path to extract the parent and basename
parent, base = split(path)
# Get the parent in slugified form
slug_parent = path_table[parent]
# Slugify the base name
if is_dir:
slug_base = iso_name_slugify(base)[:8]
else:
name, ext | python | {
"resource": ""
} |
q262577 | writable_path | validation | def writable_path(path):
"""Test whether a path can be written to.
"""
if os.path.exists(path):
return os.access(path, os.W_OK)
| python | {
"resource": ""
} |
q262578 | writable_stream | validation | def writable_stream(handle):
"""Test whether a stream can be written to.
"""
if isinstance(handle, io.IOBase) and sys.version_info >= (3, 5):
return handle.writable()
try: | python | {
"resource": ""
} |
q262579 | QuadContourGenerator.from_curvilinear | validation | def from_curvilinear(cls, x, y, z, formatter=numpy_formatter):
"""Construct a contour generator from a curvilinear grid.
Note
----
This is an alias for the default constructor.
Parameters
----------
x : array_like
x coordinates of each point in `z`. Must be the same size as `z`.
y : array_like
y coordinates of each point in `z`. Must be the same size as `z`.
z : array_like
The 2-dimensional curvilinear grid of data to compute
contours for. Masked arrays are supported.
formatter : | python | {
"resource": ""
} |
q262580 | QuadContourGenerator.from_rectilinear | validation | def from_rectilinear(cls, x, y, z, formatter=numpy_formatter):
"""Construct a contour generator from a rectilinear grid.
Parameters
----------
x : array_like
x coordinates of each column of `z`. Must be the same length as
the number of columns in `z`. (len(x) == z.shape[1])
y : array_like
y coordinates of each row of `z`. Must be the same length as the
number of columns in `z`. (len(y) == z.shape[0])
z : array_like
The 2-dimensional rectilinear grid of data to compute contours for.
Masked arrays are supported.
formatter : callable
A conversion function to convert from the internal `Matplotlib`_
contour format to an external format. See :ref:`formatters` for
more information.
Returns
-------
: :class:`QuadContourGenerator`
Initialized contour generator.
"""
x = np.asarray(x, dtype=np.float64)
y = np.asarray(y, dtype=np.float64)
z = np.ma.asarray(z, dtype=np.float64)
# Check arguments.
if x.ndim != 1:
raise TypeError(
"'x' must be a 1D array but is a {:d}D array".format(x.ndim))
if y.ndim != 1: | python | {
"resource": ""
} |
q262581 | QuadContourGenerator.from_uniform | validation | def from_uniform(
cls, z, origin=(0, 0), step=(1, 1), formatter=numpy_formatter):
"""Construct a contour generator from a uniform grid.
NOTE
----
The default `origin` and `step` values is equivalent to calling
:meth:`matplotlib.axes.Axes.contour` with only the `z` argument.
Parameters
----------
z : array_like
The 2-dimensional uniform grid of data to compute contours for.
Masked arrays are supported.
origin : (number.Number, number.Number)
The (x, y) coordinate of data point `z[0,0]`.
step : (number.Number, number.Number)
The (x, y) distance between data points in `z`.
formatter : callable
A conversion function to convert from the internal `Matplotlib`_
contour format to an external format. See :ref:`formatters` for
more information.
Returns
-------
: :class:`QuadContourGenerator`
Initialized contour generator.
"""
z = np.ma.asarray(z, dtype=np.float64)
# Check arguments.
if z.ndim != 2:
raise TypeError(
| python | {
"resource": ""
} |
q262582 | SphinxSearchPlugin._wait_for_connection | validation | def _wait_for_connection(self, port):
"""
Wait until we can make a socket connection to sphinx.
"""
connected = False
max_tries = 10
num_tries = 0
wait_time = 0.5
while not connected or num_tries >= max_tries:
time.sleep(wait_time)
try:
af = socket.AF_INET
addr = ('127.0.0.1', port)
sock = socket.socket(af, socket.SOCK_STREAM)
| python | {
"resource": ""
} |
q262583 | Plugin.get_unique_token | validation | def get_unique_token(self):
"""
Get a unique token for usage in differentiating test runs that need to
run in parallel.
"""
if self._unique_token is None:
| python | {
"resource": ""
} |
q262584 | Plugin._random_token | validation | def _random_token(self, bits=128):
"""
Generates a random token, using the url-safe base64 alphabet.
The "bits" argument specifies the bits of randomness to use.
"""
alphabet = string.ascii_letters + string.digits + '-_'
# alphabet length is | python | {
"resource": ""
} |
q262585 | Poll.url | validation | def url(self):
"""Returns the url of the poll. If the poll has not been submitted yet,
an empty string is | python | {
"resource": ""
} |
q262586 | API.get_poll | validation | def get_poll(self, arg, *, request_policy=None):
"""Retrieves a poll from strawpoll.
:param arg: Either the ID of the poll or its strawpoll url.
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises HTTPException: Requesting the poll failed.
:returns: A poll constructed with the requested data.
:rtype: :class:`Poll`
"""
if isinstance(arg, str):
# Maybe we received an url to parse
| python | {
"resource": ""
} |
q262587 | API.submit_poll | validation | def submit_poll(self, poll, *, request_policy=None):
"""Submits a poll on strawpoll.
:param poll: The poll to submit.
:type poll: :class:`Poll`
:param request_policy: Overrides :attr:`API.requests_policy` for that \
request.
:type request_policy: Optional[:class:`RequestsPolicy`]
:raises ExistingPoll: This poll instance has already been submitted.
:raises HTTPException: The submission failed.
:returns: The given poll updated with the data sent back from the submission.
:rtype: :class:`Poll`
.. note::
Only polls that have a non empty title and between 2 and 30 options
can be submitted.
"""
if poll.id is not None:
raise ExistingPoll()
options = poll.options
data = {
'title': poll.title,
| python | {
"resource": ""
} |
q262588 | numpy_formatter | validation | def numpy_formatter(_, vertices, codes=None):
"""`NumPy`_ style contour formatter.
Contours are returned as a list of Nx2 arrays containing the x and y
vertices of the contour line.
For filled contours the direction of vertices matters:
* CCW (ACW): The vertices give the exterior of a contour polygon.
* CW: The vertices give a hole of a contour polygon. This hole will
always be inside the exterior of the last contour exterior.
.. note:: This is the fastest format.
.. _NumPy: http://www.numpy.org
"""
if codes is None:
return vertices
numpy_vertices = [] | python | {
"resource": ""
} |
q262589 | matlab_formatter | validation | def matlab_formatter(level, vertices, codes=None):
"""`MATLAB`_ style contour formatter.
Contours are returned as a single Nx2, `MATLAB`_ style, contour array.
There are two types of rows in this format:
* Header: The first element of a header row is the level of the contour
(the lower level for filled contours) and the second element is the
number of vertices (to follow) belonging to this contour line.
* Vertex: x,y coordinate pairs of the vertex.
A header row is always followed by the coresponding number of vertices.
Another header row may follow if there are more contour lines.
For filled contours the direction of vertices matters:
* CCW (ACW): The vertices give the exterior of a contour polygon.
* CW: The vertices give a hole of a contour polygon. This hole will
always be inside the exterior of the last contour exterior.
For further explanation of this format see the `Mathworks documentation
| python | {
"resource": ""
} |
q262590 | shapely_formatter | validation | def shapely_formatter(_, vertices, codes=None):
"""`Shapely`_ style contour formatter.
Contours are returned as a list of :class:`shapely.geometry.LineString`,
:class:`shapely.geometry.LinearRing`, and :class:`shapely.geometry.Point`
geometry elements.
Filled contours return a list of :class:`shapely.geometry.Polygon`
elements instead.
.. note:: If possible, `Shapely speedups`_ will be enabled.
.. _Shapely: http://toblerity.org/shapely/manual.html
.. _Shapely speedups: http://toblerity.org/shapely/manual.html#performance
See Also
--------
`descartes <https://bitbucket.org/sgillies/descartes/>`_ : Use `Shapely`_
or GeoJSON-like geometric objects as matplotlib paths and patches.
"""
elements = []
if codes is None:
for vertices_ in vertices:
if np.all(vertices_[0, :] == vertices_[-1, :]):
# Contour is single point.
if len(vertices) < 3:
| python | {
"resource": ""
} |
q262591 | ContourMixin.contour | validation | def contour(self, level):
"""Get contour lines at the given level.
Parameters
----------
level : numbers.Number
The data level to calculate the contour lines for.
Returns
-------
:
The result of the :attr:`formatter` called on the contour at the
given `level`.
"""
if not isinstance(level, numbers.Number):
raise TypeError(
| python | {
"resource": ""
} |
q262592 | ContourMixin.filled_contour | validation | def filled_contour(self, min=None, max=None):
"""Get contour polygons between the given levels.
Parameters
----------
min : numbers.Number or None
The minimum data level of the contour polygon. If :obj:`None`,
``numpy.finfo(numpy.float64).min`` will be used.
max : numbers.Number or None
The maximum data level of the contour polygon. If :obj:`None`,
``numpy.finfo(numpy.float64).max`` will be used.
Returns
-------
:
The result of the :attr:`formatter` called on the filled contour
| python | {
"resource": ""
} |
q262593 | Axis.add_node | validation | def add_node(self, node, offset):
"""Add a Node object to nodes dictionary, calculating its coordinates using offset
Parameters
----------
node : a Node object
offset : float
number between 0 and 1 that sets the distance
| python | {
"resource": ""
} |
q262594 | get_settings_path | validation | def get_settings_path(settings_module):
'''
Hunt down the settings.py module by going up the FS path
'''
cwd = os.getcwd()
settings_filename = '%s.py' % (
settings_module.split('.')[-1]
)
while cwd:
if settings_filename in os.listdir(cwd):
break | python | {
"resource": ""
} |
q262595 | NoseDjango._should_use_transaction_isolation | validation | def _should_use_transaction_isolation(self, test, settings):
"""
Determine if the given test supports transaction management for
database rollback test isolation and also whether or not the test has
opted out of that support.
Transactions make database rollback much quicker when supported, with
the caveat that any tests that are explicitly testing transactions
won't work properly and any tests that depend on external access to the
test database won't be able to view data created/altered during the
test.
"""
if not getattr(test.context, 'use_transaction_isolation', True):
# The test explicitly says not to | python | {
"resource": ""
} |
q262596 | NoseDjango.finalize | validation | def finalize(self, result=None):
"""
Clean up any created database and schema.
"""
if not self.settings_path:
# short circuit if no settings file can be found
return
from django.test.utils import teardown_test_environment
from django.db import connection
from django.conf import settings
self.call_plugins_method('beforeDestroyTestDb', settings, connection)
try:
connection.creation.destroy_test_db(
self.old_db,
verbosity=self.verbosity,
)
| python | {
"resource": ""
} |
q262597 | make_clean_figure | validation | def make_clean_figure(figsize, remove_tooltips=False, remove_keybindings=False):
"""
Makes a `matplotlib.pyplot.Figure` without tooltips or keybindings
Parameters
----------
figsize : tuple
Figsize as passed to `matplotlib.pyplot.figure`
remove_tooltips, remove_keybindings : bool
| python | {
"resource": ""
} |
q262598 | OrthoPrefeature.update_field | validation | def update_field(self, poses=None):
"""updates self.field"""
m = np.clip(self.particle_field, 0, 1)
part_color = np.zeros(self._image.shape)
for a in range(4): part_color[:,:,:,a] = self.part_col[a]
| python | {
"resource": ""
} |
q262599 | OrthoPrefeature._remove_closest_particle | validation | def _remove_closest_particle(self, p):
"""removes the closest particle in self.pos to ``p``"""
#1. find closest pos:
dp = self.pos - p
dist2 = (dp*dp).sum(axis=1)
ind = dist2.argmin()
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.