_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 pure elements. Calp... | 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 in self._Cp_reco... | 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. Calphad, 15(4),
... | 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_recor... | 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. Calphad, 15(4),
... | 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, ... | 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.
"""
if phase not in se... | 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'.
:param T: [K] temperature
:returns: [J/mol] Enthalpy.
"""
try:
return self._p... | 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.
... | 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"])
... | 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 ... | 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.
:return: HEX representat... | 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 representat... | 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 representa... | 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 value.
:rtype: tuple
"""
_hex = _hex.s... | 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.
:return: RGB r... | 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... | 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... | 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)
else:
db = self._read_file()
return 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
with open(self.db_path, 'w') as f:
f.write(json.dumps(db, ensure_ascii=False, indent=2)) | 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':
return make_html_tag('li', a_tag, **{'class': 'blue white-text'})
return make_html_tag('li', a_tag) | 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))
status_code = str(arequest.status_code)
if status_code !... | 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)
if status_code == '401':
_LOGGER.error("Token expired.")
retur... | 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)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
... | 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)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... | 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)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... | 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 create vacation. " + status_code)
... | python | {
"resource": ""
} |
q262528 | EcoNetApiInterface.delete_vacation | validation | def delete_vacation(_id):
"""
Delete a vacation by ID.
"""
arequest = requests.delete(VACATIONS_URL + "/" + _id, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code != '202':
_LOGGER.error("Failed to delete vacation. " + status_code)
... | 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, head... | 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 devi... | 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)
if not getattr(resource, '__parent__', None):
resource.__parent__ = parent
ret... | 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 t... | 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 in seconds. They may requir... | python | {
"resource": ""
} |
q262534 | _setRTSDTR | validation | def _setRTSDTR(port, RTS, DTR):
"""Set RTS and DTR to the requested state."""
port.setRTS(RTS)
port.setDTR(DTR) | 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 Di... | 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 com... | 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, b... | 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 ... | 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/moc... | python | {
"resource": ""
} |
q262540 | get_parser | validation | def get_parser():
"""
Generate an appropriate parser.
:returns: an argument parser
:rtype: `ArgumentParser`
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"package",
choices=arg_map.keys(),
help="designates the package to test")
parser.add_argument("... | 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]
if namespace.ignore:
cmd.append("--ignore=%s" % namespace.ignore)
return cmd | 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):
"""
The actual function.
:param object expr: the 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.
:rtype: list of tuple of a function * str
Each function catches all TypeErrors it encounters and raises
corresponding... | 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(signatu... | 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 for this level if variant
:returns: a level for the object and one for the function
:rtype: int * int
"""
r... | 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... | 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... | 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]
... | 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 obj... | 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=t... | python | {
"resource": ""
} |
q262551 | lower | validation | def lower(option,value):
'''
Enforces lower case options and option values where appropriate
'''
if type(option) is str:
option=option.lower()
if type(value) is str:
value=value.lower()
return (option,value) | python | {
"resource": ""
} |
q262552 | to_float | validation | def to_float(option,value):
'''
Converts string values to floats when appropriate
'''
if type(value) is str:
try:
value=float(value)
except ValueError:
pass
return (option,value) | python | {
"resource": ""
} |
q262553 | to_bool | validation | def to_bool(option,value):
'''
Converts string values to booleans when appropriate
'''
if type(value) is str:
if value.lower() == 'true':
value=True
elif value.lower() == 'false':
value=False
return (option,value) | python | {
"resource": ""
} |
q262554 | Config.fork | validation | def fork(self,name):
'''
Create fork and store it in current instance
'''
fork=deepcopy(self)
self[name]=fork
return fork | 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])
dl = {key:[d[key] for d in ld] for key in keys}
return dl
else:
return {} | 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))))
s=[l[g[i]:g[i+1]] for i in range(N)]
if npmode:
s=[np.array(sl) for sl in s]
ret... | 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('[]... | 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 f... | 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')
function(self,*args,**kwargs)
self.log.log(group=function.__name__,message='Exit')
return wrapper | 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()
pr.enable()
output = function(*args,**kwargs)
pr.disable()
return pr,output
return wrapper | 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()
temp_func = memory_profiler.profile(func = function,stream=m,precision=4)
output = temp_func(*args,**kw... | 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,... | 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 ... | 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)
pr.disable()
ps = pstats.Stats(pr)
ps.sort_sta... | 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 ... | 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' in field_names:
field_names.remove('id')
return field_names | 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.
"""
... | 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 ... | 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 in self.__prefixesValid:
raise WrongSceneNameError('AWS: Prefix of %s (%s) is invalid'
% (self.sceneInfo.name, self.sceneInfo.prefix)) | 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.sceneIn... | 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): ... | python | {
"resource": ""
} |
q262574 | iso_name_slugify | validation | def iso_name_slugify(name):
"""Slugify a name in the ISO-9660 way.
Example:
>>> slugify('épatant')
"_patant"
"""
name = name.encode('ascii', 'replace').replace(b'?', b'_')
return name.decode('ascii') | 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'
"""... | 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_tabl... | 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)
try:
with open(path, 'w'):
pass
except (OSError, IOError):
return False
else:
os.remove(path)
return True | 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:
handle.write(b'')
except (io.UnsupportedOperation, IOError):
return False
else:
return True | 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`. ... | 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) =... | 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` ar... | 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)
... | 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:
self._unique_token = self._random_token()
return self._unique_token | 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 64, so each letter provides lg... | 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 returned instead.
"""
if self.id is None:
return ''
return '{}/{}'.format(strawpoll.API._BASE_URL, self.id) | 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... | 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:`Request... | 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 pol... | 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... | 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:`shap... | 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... | 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.
... | 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
from the start point ... | 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
cwd = os.p... | 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... | 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 con... | 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]
self.field = np.zeros(self._image.shape)
for a in range(4):
s... | 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()
rp = self.pos[ind].copy()
#2. delete
self.pos = np.delete(self.pos, ind,... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.