text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _getconf(self, rscpath, logger=None, conf=None):
"""Get specific conf from one driver path. :param str rscpath: resource path. :param Logger logger: logger to use. """ |
result = None
resource = self.pathresource(rscpath=rscpath, logger=logger)
if resource is not None:
for cname in self._cnames(resource=resource):
category = Category(name=cname)
if result is None:
result = Configuration()
result += category
for param in self._params(resource=resource, cname=cname):
if conf is not None:
confparam = None
if cname in conf and param.name in conf[cname]:
confparam = conf[cname][param.name]
else:
confparam = conf.param(pname=param.name)
if confparam is not None:
svalue = param.svalue
param.update(confparam)
if svalue is not None:
param.svalue = svalue
param.resolve()
category += param
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, delete_zip_import=True, *args, **kwargs):
""" If a zip file is uploaded, extract any images from it and add them to the gallery, before removing the zip file. """ |
super(BaseGallery, self).save(*args, **kwargs)
if self.zip_import:
zip_file = ZipFile(self.zip_import)
for name in zip_file.namelist():
data = zip_file.read(name)
try:
from PIL import Image
image = Image.open(BytesIO(data))
image.load()
image = Image.open(BytesIO(data))
image.verify()
except ImportError:
pass
except:
continue
name = os.path.split(name)[1]
# In python3, name is a string. Convert it to bytes.
if not isinstance(name, bytes):
try:
name = name.encode('cp437')
except UnicodeEncodeError:
# File name includes characters that aren't in cp437,
# which isn't supported by most zip tooling. They will
# not appear correctly.
tempname = name
# Decode byte-name.
if isinstance(name, bytes):
encoding = charsetdetect(name)['encoding']
tempname = name.decode(encoding)
# A gallery with a slug of "/" tries to extract files
# to / on disk; see os.path.join docs.
slug = self.slug if self.slug != "/" else ""
path = os.path.join(GALLERIES_UPLOAD_DIR, slug, tempname)
try:
saved_path = default_storage.save(path, ContentFile(data))
except UnicodeEncodeError:
from warnings import warn
warn("A file was saved that contains unicode "
"characters in its path, but somehow the current "
"locale does not support utf-8. You may need to set "
"'LC_ALL' to a correct value, eg: 'en_US.UTF-8'.")
# The native() call is needed here around str because
# os.path.join() in Python 2.x (in posixpath.py)
# mixes byte-strings with unicode strings without
# explicit conversion, which raises a TypeError as it
# would on Python 3.
path = os.path.join(GALLERIES_UPLOAD_DIR, slug,
native(str(name, errors="ignore")))
saved_path = default_storage.save(path, ContentFile(data))
self.images.create(file=saved_path)
if delete_zip_import:
zip_file.close()
self.zip_import.delete(save=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def seconds_to_DHMS(seconds, as_str=True):
"""converts seconds to Days, Hours, Minutes, Seconds :param int seconds: number of seconds :param bool as_string: to return a formated string defaults to True :returns: a formated string if as_str else a dictionary :Example: 001-00:00:00 {'hours': 0, 'seconds': 0, 'minutes': 0, 'days': 1} """ |
d = DotDot()
d.days = int(seconds // (3600 * 24))
d.hours = int((seconds // 3600) % 24)
d.minutes = int((seconds // 60) % 60)
d.seconds = int(seconds % 60)
return FMT_DHMS_DICT.format(**d) if as_str else d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def relations_dict(rel_lst):
"""constructs a relation's dictionary from a list that describes amphidromus relations between objects :param list rel_lst: a relationships list of the form [[a,b],[c, a, b]] # can include duplicates :returns: a dictionary :Example: {'a': ['x', 'c', 'b', 'y'], 'c': ['a', 'b'], 'b': ['a', 'c'], 'y': ['a', 'x', 'z'], 'x': ['a', 'z', 'y'], 'z': ['y', 'x']} """ |
dc = {}
for c in rel_lst:
for i in c:
for k in c:
dc.setdefault(i, [])
dc[i].append(k)
do = {}
for k in list(dc.keys()):
if dc[k]:
vl = list(set(dc[k])) # remove duplicates
vl.remove(k)
do[k] = vl
return do |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks(sliceable, n):
""" returns a list of lists of any slice-able object each of max lentgh n :Parameters: -sliceable: (string|list|tuple) any sliceable object - n max elements of ech chunk :Example: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 'x']] ['123', '456', '789', 'X'] """ |
return [sliceable[i:i+n] for i in range(0, len(sliceable), n)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chunks_str(str, n, separator="\n", fill_blanks_last=True):
"""returns lines with max n characters :Example: 123 456 X """ |
return separator.join(chunks(str, n)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def class_name_str(obj, skip_parent=False):
""" return's object's class name as string """ |
rt = str(type(obj)).split(" ")[1][1:-2]
if skip_parent:
rt = rt.split(".")[-1]
return rt |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value_name(cls, value):
""" Returns the label from a value if label exists otherwise returns the value since method does a reverse look up it is slow """ |
for k, v in list(cls.__dict__.items()):
if v == value:
return k
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_visible(cls, property_name):
""" private method to check visible object property to be visible """ |
if isinstance(property_name, list):
return [cls._is_visible(p) for p in property_name]
if property_name.startswith('__') and property_name.endswith('__'):
return False
return property_name.startswith(cls.STARTS_WITH) and property_name.endswith(cls.ENDS_WITH) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _from_class(cls, class_name, module_name=None, *args, **kwargs):
""" class method to create object of a given class """ |
def _get_module(module_name):
names = module_name.split(".")
module = __import__(names[0])
for i in xrange(1, len(names)):
module = getattr(module, names[i])
return module
if module_name:
# module = globals()[module_name]
# module = __import__(module_name)
module = _get_module(module_name)
class_ = getattr(module, class_name)
else:
class_ = globals()[class_name]
if not issubclass(class_, PersistentObject):
t = class_.__name__, PersistentObject.__name__
raise TypeError, 'Requested object type %s must be subtype of %s ' % t
# workaround to mimic FactoryType to work well with FactoryObject.
name = str(args[0]) if args else cls.__name__
name = kwargs['name'] if 'name' in kwargs else name
if hasattr(cls, 'get'):
instance = cls.get(name)
if instance:
return instance
instance = class_.__new__(class_, *args, **kwargs)
instance.__init__(*args, **kwargs)
return instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_serializable(cls, object_dict):
""" core class method to create visible objects from a dictionary """ |
key_class = cls._from_visible(cls.STARTS_WITH + 'class' + cls.ENDS_WITH)
key_module = cls._from_visible(cls.STARTS_WITH + 'module' + cls.ENDS_WITH)
obj_class = object_dict.pop(key_class)
obj_module = object_dict.pop(key_module) if key_module in object_dict else None
obj = cls._from_class(obj_class, obj_module)
obj.modify_object(object_dict)
return obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_object(self, property_name, property_value_variant=None):
""" api visible method for modifying visible object properties :param property_name: property name :type property_name: string, list or dict :param property_value_variant: property value, must be `None` if property_name is of type `dict` :type property_value_variant: various or None :return: modified object :rtype: unicum.lfojbect.VisibleObject """ |
if type(property_name) is dict:
property_value_variant = property_name.values()
property_name = property_name.keys()
if isinstance(property_name, str):
property_name, property_value_variant = [property_name], [property_value_variant]
assert len(property_name) == len(property_value_variant)
# convert names into visible
property_name = self.__class__._to_visible(property_name)
# loop over properties to set
for n, v in zip(property_name, property_value_variant):
self._modify_property(n.encode('ascii','ignore'), v)
# rebuild object in order to maintain consistency
self._rebuild_object()
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arg_types(**kwargs):
""" Mark the expected types of certain arguments. Arguments for which no types are provided default to strings. To specify an argument type, give this decorator a keyword argument, where the argument name is the name of the function argument and the value is a callable taking one argument, which will convert a string to a value of that type. Note that the 'bool' type is treated specially. """ |
def decorator(func):
if not hasattr(func, '_bark_types'):
func._bark_types = {}
func._bark_types.update(kwargs)
return func
return decorator |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def boolean(text):
""" An alternative to the "bool" argument type which interprets string values. """ |
tmp = text.lower()
if tmp.isdigit():
return bool(int(tmp))
elif tmp in ('t', 'true', 'on', 'yes'):
return True
elif tmp in ('f', 'false', 'off', 'no'):
return False
raise ValueError("invalid Boolean value %r" % text) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def file_handler(name, logname, filename, mode='a', encoding=None, delay=False):
""" A Bark logging handler logging output to a named file. Similar to logging.FileHandler. """ |
return wrap_log_handler(logging.FileHandler(
filename, mode=mode, encoding=encoding, delay=delay)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def watched_file_handler(name, logname, filename, mode='a', encoding=None, delay=False):
""" A Bark logging handler logging output to a named file. If the file has changed since the last log message was written, it will be closed and reopened. Similar to logging.handlers.WatchedFileHandler. """ |
return wrap_log_handler(logging.handlers.WatchedFileHandler(
filename, mode=mode, encoding=encoding, delay=delay)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rotating_file_handler(name, logname, filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=False):
""" A Bark logging handler logging output to a named file. When the file grows close to 'maxBytes', it will be rotated, under control of 'backupCount'. Similar to logging.handlers.RotatingFileHandler. """ |
return wrap_log_handler(logging.handlers.RotatingFileHandler(
filename, mode=mode, maxBytes=maxBytes, backupCount=backupCount,
encoding=encoding, delay=delay)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False):
""" A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file will be rotated, under control of 'backupCount'. Similar to logging.handlers.TimedRotatingFileHandler. """ |
return wrap_log_handler(logging.handlers.TimedRotatingFileHandler(
filename, when=when, interval=interval, backupCount=backupCount,
encoding=encoding, delay=delay, utc=utc)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nt_event_log_handler(name, logname, appname, dllname=None, logtype="Application"):
""" A Bark logging handler logging output to the NT Event Log. Similar to logging.handlers.NTEventLogHandler. """ |
return wrap_log_handler(logging.handlers.NTEventLogHandler(
appname, dllname=dllname, logtype=logtype)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def http_handler(name, logname, host, url, method="GET"):
""" A Bark logging handler logging output to an HTTP server, using either GET or POST semantics. Similar to logging.handlers.HTTPHandler. """ |
return wrap_log_handler(logging.handlers.HTTPHandler(
host, url, method=method)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _lookup_handler(name):
""" Look up the implementation of a named handler. Broken out for testing purposes. :param name: The name of the handler to look up. :returns: A factory function for the log handler. """ |
# Look up and load the handler factory
for ep in pkg_resources.iter_entry_points('bark.handler', name):
try:
# Load and return the handler factory
return ep.load()
except (ImportError, pkg_resources.UnknownExtra):
# Couldn't load it...
continue
raise ImportError("Unknown log file handler %r" % name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_keys_safe(dct):
"""Modify the keys in |dct| to be valid attribute names.""" |
result = {}
for key, val in dct.items():
key = key.replace('-', '_')
if key in keyword.kwlist:
key = key + '_'
result[key] = val
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _apply_args_to_func(global_args, func):
""" Unpacks the argparse Namespace object and applies its contents as normal arguments to the function func """ |
global_args = vars(global_args)
local_args = dict()
for argument in inspect.getargspec(func).args:
local_args[argument] = global_args[argument]
return func(**local_args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, path, mode='r', *args, **kwargs):
"""Proxy to function `open` with path to the current file.""" |
return open(os.path.join(os.path.dirname(self.path), path),
mode=mode, *args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def abspath(self, path):
"""Return absolute path for a path relative to the current file.""" |
return os.path.abspath(os.path.join(os.path.dirname(self.path), path)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lot(self, id, user=True, dependencies=True, comments=True, votes=True, no_strip=False):
""" Retrieve the lot with given identifier :param id: Identifier of the lot to retrieve :param user: Should user (authenticated) information be returned (e.g. last_downloaded) :param dependencies: Should a dependency list be returned :param comments: Should a list of comments be returned :param votes: Should a list of votes be returned :param no_strip: Should XML/HTML tags be stripped in the returned lot description :return: Requested lot :rtype: dict """ |
args = {}
if user:
args['user'] = 'true'
if dependencies:
args['dependencies'] = 'true'
if comments:
args['comments'] = 'true'
if votes:
args['votes'] = 'true'
if no_strip:
args['nostrip'] = 'true'
return self._get_json('lot/{0}', id, **args) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def head(self, wg_uuid, uuid):
""" Get one workgroup node.""" |
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
# return self.core.head(url)
try:
# workaround
return self.core.get(url)
except LinShareException:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def list(self, wg_uuid, parent=None, flat=False, node_types=None):
""" Get a list of workgroup nodes.""" |
url = "%(base)s/%(wg_uuid)s/nodes" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid
}
param = []
if parent:
# I use only the last folder uuid, the first ones are not really useful
if isinstance(parent, (list,)):
if len(parent) >= 1:
parent = parent[-1]
param.append(("parent", parent))
if flat:
param.append(("flat", True))
if node_types:
for node_type in node_types:
param.append(("type", node_type))
encode = urllib.urlencode(param)
if encode:
url += "?"
url += encode
return self.core.list(url) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, data):
""" Update meta of one document.""" |
self.debug(data)
self._check(data)
wg_uuid = data.get('workGroup')
self.log.debug("wg_uuid : %s ", wg_uuid)
uuid = data.get('uuid')
url = "%(base)s/%(wg_uuid)s/nodes/%(uuid)s" % {
'base': self.local_base_url,
'wg_uuid': wg_uuid,
'uuid': uuid
}
return self.core.update(url, data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def arquire_attributes(self, attributes, active=True):
""" Claims a list of attributes for the current client. Can also disable attributes. Returns update response object. """ |
attribute_update = self._post_object(self.update_api.attributes.acquire, attributes)
return ExistAttributeResponse(attribute_update) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def owned_attributes(self):
""" Returns a list of attributes owned by this service. """ |
attributes = self._get_object(self.update_api.attributes.owned)
return [ExistOwnedAttributeResponse(attribute) for attribute in attributes] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_sequence(cycles, program_or_profile='program', unit_converter=None):
""" Makes the command list for a move sequence. Constructs the list of commands to execute the given sequence of motion. Program/command line commands or profile commands can be generated depending on the value of `program_or_profile` so that the commands can be used to construct a program or profile later. Types of motion supported (see Notes for how to specify) are moves from one position to another (the motion will always come to a stop before doing the next motion), waiting a given interval of time till starting the next move, and looping over a sequence of moves. Parameters cycles : iterable of dicts The iterable of cycles of motion to do one after another. See Notes for format. program_or_profile : {'program', 'profile'}, optional Whether program or profile motion commands should be used. Anything other than these two values implies the default. unit_converter : UnitConverter, optional ``GeminiMotorDrive.utilities.UnitConverter`` to use to convert the units in `cycles` to motor units. ``None`` indicates that they are already in motor units. Returns ------- commands : list of str ``list`` of ``str`` commands making up the move sequence. Notes ----- `cycles` is an iterable of individual cycles of motion. Each cycle is a ``dict`` that represents a sequence of moves that could possibly be looped over. The field ``'iterations'`` gives how many times the sequence of moves should be done (a value > 1 implies a loop). Then the field ``'moves'`` is an iterable of the individual moves. Each individual move is a ``dict`` with the acceleration (``'A'``), deceleration (``'AD'`` with 0 meaning the value of the acceleration is used), velocity (``'V'``), and the distance/position (``'D'``). Back in the cycle, the field ``'wait_times'`` is an iterable of numbers giving the time in seconds to wait after each move before going onto the next. See Also -------- get_sequence_time convert_sequence_to_motor_units GeminiMotorDrive.utilities.UnitConverter Examples -------- Simple program style two motions with a pause in between. ['A100', 'AD0', 'V100', 'D-1000', 'GO1', 'WAIT(AS.1=b0)', 'T1', 'A90', 'GO1', 'WAIT(AS.1=b0)'] The same motion but in profile style commands ['A100', 'AD100', 'V100', 'D-1000', 'VF0', 'GOBUF1', 'GOWHEN(T=1000)', 'A90', 'AD90', 'VF0', 'GOBUF1'] Another motion with a back and forth loop (100 iterations) in the middle, done in program style commands. ['A100', 'AD0', 'V100', 'D-1000', 'GO1', 'WAIT(AS.1=b0)', 'T1', 'L100', 'A50', 'AD40', 'V30', 'D-1000', 'GO1', 'WAIT(AS.1=b0)', 'D~', 'GO1', 'WAIT(AS.1=b0)', 'LN', 'A100', 'AD0', 'V100', 'GO1', 'WAIT(AS.1=b0)'] """ |
# If needed, cycles needs to be converted to motor units.
if unit_converter is None:
cv_cycles = cycles
else:
cv_cycles = convert_sequence_to_motor_units(cycles, \
unit_converter=unit_converter)
# Initially, we have no commands in our command list.
commands = []
# The A, AD, D, and V parameters of the previous motion should be
# kept track of because if they don't change from one motion to the
# next, the commands to set them don't need to be included. They
# will be started blank since there are no previous motions yet.
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
# Construct each cycle one by one.
for cycle in cv_cycles:
# If more than one iteration is being done, a loop needs to be
# setup. It will be either 'L' or 'PLOOP' with the number of
# iterations attached if it is a program or a profile
# respectively. Since it will be tough to keep track of what
# motion changed from the end of a loop to the beginning of it,
# it is easier to just forget all previous motion values and set
# them all at the beginning of the loop (clear previous_motion).
iterations = int(cycle['iterations'])
if iterations > 1:
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
if program_or_profile != 'profile':
commands.append('L' + str(iterations))
else:
commands.append('PLOOP' + str(iterations))
# Construct each individual move in the cycle.
for i in range(0, len(cycle['moves'])):
# Grab the motion indicated by the current move.
new_motion = cycle['moves'][i]
# If we are doing a profile, AD must be set explicitly
# to A if it is 0.
if program_or_profile == 'profile' \
and new_motion['AD'] == 0.0:
new_motion['AD'] = new_motion['A']
# Set A, AD, and V if they have changed.
for k in ('A', 'AD', 'V'):
if previous_motion[k] != new_motion[k]:
# Grab it and round it to 4 places after the decimal
# point because that is the most that is
# supported. Then, if it is an integer value,
# convert it to an integer because that is what the
# drive will send back if requested (makes
# comparisons easier). Then add the command.
val = round(float(new_motion[k]), 4)
if val == int(val):
val = int(val)
commands.append(k + str(val))
# If the sign of D has flipped, we just need to issue a 'D~'
# command. If the value has changed in another way, it needs
# to be reset.
if previous_motion['D'] != new_motion['D']:
if previous_motion['D'] == -new_motion['D']:
commands.append('D~')
else:
commands.append('D'
+ str(int(new_motion['D'])))
# Grab the amount of time that should be waited after the
# move is done.
wait_time = cycle['wait_times'][i]
# Give the motion command (GO or GOBUF), tell the drive to
# wait till the motor has stopped (a WAIT command if it is a
# program and a VF0 command if it is a profile), and make it
# wait the period of time wait_time (T and GOWHEN commands).
if program_or_profile != 'profile':
commands.append('GO1')
commands.append('WAIT(AS.1=b0)')
if wait_time != 0:
# The wait time needs to be rounded to 3 places
# after the decimal. If it is an integer, it should
# be converted to an int so that the drive will send
# back what we send (makes compairisons easier).
wait_time = round(float(wait_time), 3)
if wait_time == int(wait_time):
wait_time = int(wait_time)
commands.append('T' + str(wait_time))
else:
commands.append('VF0')
commands.append('GOBUF1')
if wait_time != 0:
commands.append('GOWHEN(T='
+ str(int(1000*wait_time))
+ ')')
# Before going onto the next move, previous_motion needs to
# be set to the one just done.
previous_motion = new_motion
# Done with all the moves of the cycle. If we are looping, the
# loop end needs to be put in.
if iterations > 1:
if program_or_profile != 'profile':
commands.append('LN')
else:
commands.append('PLN')
# Done constructing the command list.
return commands |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sequence_time(cycles, unit_converter=None, eres=None):
""" Calculates the time the move sequence will take to complete. Calculates the amount of time it will take to complete the given move sequence. Types of motion supported are moves from one position to another (the motion will always come to a stop before doing the next motion), waiting a given interval of time till starting the next move, and looping over a sequence of moves. Parameters cycles : list of dicts The ``list`` of cycles of motion to do one after another. See ``compile_sequence`` for format. unit_converter : UnitConverter, optional ``GeminiMotorDrive.utilities.UnitConverter`` to use to convert the units in `cycles` to motor units. ``None`` indicates that they are already in motor units. eres : int Encoder resolution. Only relevant if `unit_converter` is ``None``. Returns ------- time : float Time the move sequence will take in seconds. See Also -------- compile_sequence GeminiMotorDrive.utilities.UnitConverter move_time """ |
# If we are doing unit conversion, then that is equivalent to motor
# units but with eres equal to one.
if unit_converter is not None:
eres = 1
# Starting with 0 time, steadily add the time of each movement.
tme = 0.0
# Go through each cycle and collect times.
for cycle in cycles:
# Add all the wait times.
tme += cycle['iterations']*sum(cycle['wait_times'])
# Add the time for each individual move.
for move in cycle['moves']:
tme += cycle['iterations'] \
* move_time(move, eres=eres)
# Done.
return tme |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def move_time(move, eres):
""" Calculates the time it takes to do a move. Calculates how long it will take to complete a move of the motor. It is assumed that the motor will decerate to a stop for the end of the move as opposed to keep moving at velocity. Everything is in motor units which are encoder counts for distance, pitches/s for velocity, and pitches/s^2 for acceleration. Parameters move : dict Contains the move parameters in its fields: acceleration ('A'), deceleration ('AD' with 0 meaning the value of the acceleration is used), velocity ('V'), and the distance/position ('D'). eres : int Encoder resolution. Returns ------- time : float Time the move will take in seconds. See Also -------- compile_sequence get_sequence_time """ |
# Grab the move parameters. If the deceleration is given as zero,
# that means it has the same value as the acceleration. Distance is
# converted to the same units as the others by dividing by the
# encoder resolution. The absolute value of everything is taken for
# simplicity.
A = abs(move['A'])
AD = abs(move['AD'])
if AD == 0.0:
AD = A
V = abs(move['V'])
D = abs(move['D'])/eres
# Calculate the times it would take to accelerate from stop to V and
# decelerate to stop at rates A and AD respectively.
accel_times = [V/A, V/AD]
# Calculate the distances that would be moved in those times.
dists = [0.5*A*(accel_times[0]**2), 0.5*AD*(accel_times[1]**2)]
# If the sum of those dists is greater than D, then the velocity V
# is never reached. The way the time is calculated depends on which
# case it is.
if sum(dists) <= D:
# The time is just the sum of the acceleration times plus the
# remaining distance divided by V.
return (sum(accel_times) + (D-sum(dists))/V)
else:
# We need to find the time it takes for the acceleration path
# and deceleration path to meet and have the same speeds.
#
# (1) t = t_1 + t_2
# (2) A*t_1 = AD*t_2
# (3) D = 0.5*A*(t_1**2) + 0.5*AD*(t_2**2)
#
# Re-writing t_2 in terms of t_1 using (2)
# (4) t_2 = (A / AD) * t_1
#
# Putting that into (1) and (3)
# (4) t = (1 + (A / AD)) * t_1
# (5) D = 0.5*A*(1 + (A / AD)) * (t_1**2)
#
# Solving (5) for t_1,
# (6) t_1 = sqrt( 2*D / (A * (1 + (A / AD))))
#
# Putting that into (4),
# t = sqrt(2*D*(1 + (A / AD)) / A)
return math.sqrt(2*D * (1 + (A / AD)) / A) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_sequence_to_motor_units(cycles, unit_converter):
""" Converts a move sequence to motor units. Converts a move sequence to motor units using the provied converter. Parameters cycles : iterable of dicts The iterable of cycles of motion to do one after another. See ``compile_sequence`` for format. unit_converter : UnitConverter, optional ``GeminiMotorDrive.utilities.UnitConverter`` to use to convert the units in `cycles` to motor units. Returns ------- motor_cycles : list of dicts A deep copy of `cycles` with all units converted to motor units. See Also -------- compile_sequence GeminiMotorDrive.utilities.UnitConverter """ |
# Make a deep copy of cycles so that the conversions don't damage
# the original one.
cv_cycles = copy.deepcopy(cycles)
# Go through each cycle and do the conversions.
for cycle in cv_cycles:
# Go through each of the moves and do the conversions.
for move in cycle['moves']:
move['A'] = unit_converter.to_motor_velocity_acceleration( \
move['A'])
move['AD'] = \
unit_converter.to_motor_velocity_acceleration( \
move['AD'])
move['V'] = unit_converter.to_motor_velocity_acceleration( \
move['V'])
move['D'] = int(unit_converter.to_motor_distance(move['D']))
# Now return the converted move sequence.
return cv_cycles |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile(self):
"""Return Hip string if already compiled else compile it.""" |
if self.buffer is None:
self.buffer = self._compile_value(self.data, 0)
return self.buffer.strip() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_value(self, data, indent_level):
"""Dispatch to correct compilation method.""" |
if isinstance(data, dict):
return self._compile_key_val(data, indent_level)
elif isinstance(data, list):
return self._compile_list(data, indent_level)
else:
return self._compile_literal(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_literal(self, data):
"""Write correct representation of literal.""" |
if data is None:
return 'nil'
elif data is True:
return 'yes'
elif data is False:
return 'no'
else:
return repr(data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_list(self, data, indent_level):
"""Correctly write possibly nested list.""" |
if len(data) == 0:
return '--'
elif not any(isinstance(i, (dict, list)) for i in data):
return ', '.join(self._compile_literal(value) for value in data)
else:
# 'ere be dragons,
# granted there are fewer dragons than the parser,
# but dragons nonetheless
buffer = ''
i = 0
while i < len(data):
if isinstance(data[i], dict):
buffer += '\n'
buffer += self._indent * indent_level
while i < len(data) and isinstance(data[i], dict):
buffer += '-\n'
buffer += self._compile_key_val(data[i], indent_level)
buffer += self._indent * indent_level + '-'
i += 1
buffer += '\n'
elif (
isinstance(data[i], list) and
any(isinstance(item, (dict, list)) for item in data[i])
):
buffer += self._compile_list(data[i], indent_level+1)
elif isinstance(data[i], list):
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_list(data[i], indent_level+1)
else:
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_literal(data[i])
i += 1
return buffer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compile_key_val(self, data, indent_level):
"""Compile a dictionary.""" |
buffer = ''
for (key, val) in data.items():
buffer += self._indent * indent_level
# TODO: assumes key is a string
buffer += key + ':'
if isinstance(val, dict):
buffer += '\n'
buffer += self._compile_key_val(val, indent_level+1)
elif (
isinstance(val, list) and
any(isinstance(i, (dict, list)) for i in val)
):
buffer += self._compile_list(val, indent_level+1)
else:
buffer += ' '
buffer += self._compile_value(val, indent_level)
buffer += '\n'
return buffer |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def word(cap=False):
""" This function generates a fake word by creating between two and three random syllables and then joining them together. """ |
syllables = []
for x in range(random.randint(2,3)):
syllables.append(_syllable())
word = "".join(syllables)
if cap: word = word[0].upper() + word[1:]
return word |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transaction(data_access):
"""Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback. :param data_access: a DataAccess instance """ |
old_autocommit = data_access.autocommit
data_access.autocommit = False
try:
yield data_access
except RollbackTransaction as ex:
data_access.rollback()
except Exception as ex:
data_access.rollback()
raise ex
else:
data_access.commit()
finally:
data_access.autocommit = old_autocommit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocommit(data_access):
"""Make statements autocommit. :param data_access: a DataAccess instance """ |
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_autocommit |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def autocommit(self, value):
"""Set the autocommit value. :param value: the new autocommit value """ |
logger.debug("Setting autocommit from %s to %s", self.autocommit, value)
self.core.set_autocommit(self.connection, value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _configure_connection(self, name, value):
"""Sets a Postgres run-time connection configuration parameter. :param name: the name of the parameter :param value: a list of values matching the placeholders """ |
self.update("pg_settings", dict(setting=value), dict(name=name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open(self, *, autocommit=False):
"""Sets the connection with the core's open method. :param autocommit: the default autocommit state :type autocommit: boolean :return: self """ |
if self.connection is not None:
raise Exception("Connection already set")
self.connection = self.core.open()
self.autocommit = autocommit
if self._search_path:
self._configure_connection(
"search_path",
self._search_path)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def close(self, *, commit=True):
"""Closes the connection via the core's close method. :param commit: if true the current transaction is commited, otherwise it is rolled back :type commit: boolean :return: self """ |
self.core.close(self.connection, commit=commit)
self.connection = None
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self, query_string, params=None):
"""Executes a query. Returns the resulting cursor. :query_string: the parameterized query string :params: can be either a tuple or a dictionary, and must match the parameterization style of the query :return: a cursor object """ |
cr = self.connection.cursor()
logger.info("SQL: %s (%s)", query_string, params)
self.last_query = (query_string, params)
t0 = time.time()
cr.execute(query_string, params or self.core.empty_params)
ms = (time.time() - t0) * 1000
logger.info("RUNTIME: %.2f ms", ms)
self._update_cursor_stats(cr)
return cr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def callproc(self, name, params, param_types=None):
"""Calls a procedure. :param name: the name of the procedure :param params: a list or tuple of parameters to pass to the procedure. :param param_types: a list or tuple of type names. If given, each param will be cast via sql_writers typecast method. This is useful to disambiguate procedure calls when several parameters are null and therefore cause overload resoluation issues. :return: a 2-tuple of (cursor, params) """ |
if param_types:
placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)
for t in param_types]
else:
placeholders = [self.sql_writer.to_placeholder() for p in params]
# TODO: This may be Postgres specific...
qs = "select * from {0}({1});".format(name, ", ".join(placeholders))
return self.execute(qs, params), params |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_callproc_signature(self, name, param_types):
"""Returns a procedure's signature from the name and list of types. :name: the name of the procedure :params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type). :return: the procedure's signature """ |
if isinstance(param_types[0], (list, tuple)):
params = [self.sql_writer.to_placeholder(*pt) for pt in param_types]
else:
params = [self.sql_writer.to_placeholder(None, pt) for pt in param_types]
return name + self.sql_writer.to_tuple(params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, table_name, constraints=None, *, columns=None, order_by=None):
"""Returns the first record that matches the given criteria. :table_name: the name of the table to search on :constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :columns: either a string or a list of column names :order_by: the order by clause """ |
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by)
query_string += " limit 1;"
return self.execute(query_string, params).fetchone() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find_all(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=None):
"""Returns all records that match a given criteria. :table_name: the name of the table to search on :constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :columns: either a string or a list of column names :order_by: the order by clause """ |
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting)
query_string += ";"
return self.execute(query_string, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def page(self, table_name, paging, constraints=None, *, columns=None, order_by=None, get_count=True):
"""Performs a find_all method with paging. :param table_name: the name of the table to search on :param paging: is a tuple containing (page, page_size). :param constraints: is any construct that can be parsed by SqlWriter.parse_constraints. :param columns: either a string or a list of column names :param order_by: the order by clause :param get_count: if True, the total number of records that would be included without paging are returned. If False, None is returned for the count. :return: a 2-tuple of (records, total_count) """ |
if get_count:
count = self.count(table_name, constraints)
else:
count = None
page, page_size = paging
limiting = None
if page_size > 0:
limiting = (page_size, page * page_size)
records = list(self.find_all(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting))
return (records, count) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, table_name, values, constraints=None, *, returning=None):
"""Builds and executes and update statement. :param table_name: the name of the table to update :param values: can be either a dict or an enuerable of 2-tuples in the form (column, value). :param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints. However, you cannot mix tuples and dicts between values and constraints. :param returning: the columns to return after updating. Only works for cores that support the returning syntax :return: a cursor object """ |
if constraints is None:
constraints = "1=1"
assignments, assignment_params = self.sql_writer.parse_constraints(
values, ", ", is_assignment=True)
where, where_params = self.sql_writer.parse_constraints(constraints, " and ")
returns = ""
if returning and self.core.supports_returning_syntax:
returns = " returning {0}".format(returning)
sql = "update {0} set {1} where {2}{3};".format(table_name, assignments, where, returns)
params = assignment_params
if constraints is None or isinstance(constraints, str):
pass
elif isinstance(constraints, dict):
if isinstance(params, list):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or {}
params.update(where_params)
else:
if isinstance(params, dict):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or []
params.extend(where_params)
cr = self.execute(sql, params)
return cr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, table_name, constraints=None):
"""Builds and executes an delete statement. :param table_name: the name of the table to delete from :param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints. :return: a cursor object """ |
if constraints is None:
constraints = "1=1"
where, params = self.sql_writer.parse_constraints(constraints)
sql = "delete from {0} where {1};".format(table_name, where)
self.execute(sql, params) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count(self, table_name, constraints=None, *, extract="index"):
"""Returns the count of records in a table. If the default cursor is a tuple or named tuple, this method will work without specifying an extract parameter. If it is a dict cursor, it is necessary to specify any value other than 'index' for extract. This method will not work with cursors that aren't like tuple, namedtuple or dict cursors. :param table_name: the name of the table to count records on :param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints. :param extract: the property to pull the count value from the cursor :return: the nuber of records matching the constraints """ |
where, params = self.sql_writer.parse_constraints(constraints)
sql = "select count(*) as count from {0} where {1};".format(table_name, where or "1 = 1")
# NOTE: Won't work right with dict cursor
return self.get_scalar(self.execute(sql, params), 0 if extract == "index" else "count") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_scalar(self, cursor, index=0):
"""Returns a single value from the first returned record from a cursor. By default it will get cursor.fecthone()[0] which works with tuples and namedtuples. For dict cursor it is necessary to specify index. This method will not work with cursors that aren't indexable. :param cursor: a cursor object :param index: the index of the cursor to return the value from """ |
if isinstance(index, int):
return cursor.fetchone()[index]
else:
return get_value(cursor.fetchone(), index) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def target_str(self):
"""Returns the string representation of the target property.""" |
if isinstance(self.target, tuple):
return "({})".format(", ".join(self.target))
else:
return self.target |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cli_certify_core_number( config, min_value, max_value, value, ):
"""Console script for certify_number""" |
verbose = config['verbose']
if verbose:
click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int")
def parser(v):
# Attempt a json/pickle decode:
try:
v = load_json_pickle(v, config)
except Exception:
pass
# Attempt a straight conversion to float or integer:
try:
if v.find('.') != -1:
# Assume is float:
v = float(v)
else:
# Assume is int:
v = int(v)
return v
except Exception as err:
six.raise_from(
CertifierTypeError(
message='Not integer or float: {v}'.format(
v=v,
),
value=v,
),
err,
)
execute_cli_command(
'number',
config,
parser,
certify_number,
value[0] if value else None,
min_value=min_value,
max_value=max_value,
required=config['required'],
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None):
""" Url Resolver Given a url a list of resolved urls is returned for desktop and mobile user agents """ |
if not desktop_user_agent:
desktop_user_agent = DESKTOP_USER_AGENT
if not mobile_user_agent:
mobile_user_agent = MOBILE_USER_AGENT
input_urls = set()
parsed = urlparse(url_with_protocol(url))
netloc = parsed.netloc
if netloc.startswith('www.'):
netloc = netloc[4:]
input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/'))
input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/'))
resolved_urls = set()
for input_url in input_urls:
desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent})
resolved_urls.add(desktop_request.url)
mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent})
resolved_urls.add(mobile_request.url)
return list(resolved_urls) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def token(self):
" Get token when needed."
if hasattr(self, '_token'):
return getattr(self, '_token')
# Json formatted auth.
data = json.dumps({'customer_name': self.customer,
'user_name': self.username,
'password': self.password})
# Start session.
response = requests.post(
'https://api2.dynect.net/REST/Session/', data=data,
headers={'Content-Type': 'application/json'})
# convert to data.
content = json.loads(response.content)
if response.status_code != 200:
# Check for errors.
if self.check_error(content, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(content, 'ERROR'))
raise self.Failure(self.response_message(content, 'ERROR'),
'Unhandled failure')
# Extract token from content
if 'data' in content and 'token' in content['data']:
token = content['data']['token']
else:
raise self.AuthenticationError(response)
setattr(self, '_token', token)
return token |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def parse_error(self, response):
" Parse authentication errors."
# Check invalid credentials.
if self.check_error(response, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(response, 'ERROR')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_error(self, response, status, err_cd):
" Check an error in the response."
if 'status' not in response:
return False
if response['status'] != status:
return False
if 'msgs' not in response:
return False
if not isinstance(response['msgs'], list):
return False
for msg in response['msgs']:
if 'LVL' in msg and msg['LVL'] != 'ERROR':
continue
if 'ERR_CD' in msg and msg['ERR_CD'] == err_cd:
return True
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def hook_response(self, response):
" Detect any failure."
# Decode content with json.
response._content = json.loads(response.content)
return response |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def check_errors(self, response):
" Check some common errors."
# Read content.
content = response.content
if 'status' not in content:
raise self.GeneralError('We expect a status field.')
# Return the decoded content if status is success.
if content['status'] == 'success':
response._content = content
return
# Expect messages if some kind of error.
if 'msgs' not in content:
raise self.GeneralError('We expcet messages in case of error.')
try:
messages = list(content['msgs'])
except:
raise self.GeneralError("Messages must be a list.")
# Try to found common errors in the response.
for msg in messages:
if 'LVL' in msg and msg['LVL'] == 'ERROR':
# Check if is a not found error.
if msg['ERR_CD'] == 'NOT_FOUND':
raise self.NotFoundError(msg['INFO'])
# Duplicated target.
elif msg['ERR_CD'] == 'TARGET_EXISTS':
raise self.TargetExistsError(msg['INFO'])
# Some other error.
else:
raise self.DynectError(msg['INFO'])
raise self.GeneralError("We need at least one error message.") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def add_address(self, fqdn, address, ttl=0):
" Add a new address to a domain."
data = {'rdata': {'address': address}, 'ttl': str(ttl)}
# Make request.
response = self.post('/REST/ARecord/%s/%s' % (
self.zone, fqdn), data=data)
return Address(self, data=response.content['data']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def publish(self):
" Publish last changes."
# Publish changes.
response = self.put('/REST/Zone/%s' % (
self.zone, ), data={'publish': True})
return response.content['data']['serial'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def list_address(self, domain):
" Get the list of addresses of a single domain."
try:
response = self.get('/REST/ARecord/%s/%s' % (
self.zone, domain))
except self.NotFoundError:
return []
# Return a generator with the addresses.
addresses = response.content['data']
return [Address.from_url(self, uri) for uri in addresses] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def remove_address(self, fqdn, address):
" Remove an address of a domain."
# Get a list of addresses.
for record in self.list_address(fqdn):
if record.address == address:
record.delete()
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete(self):
" Delete the address."
response = self.dyn.delete(self.delete_url)
return response.content['job_id'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def delete(self):
" Delete the record."
response = self.dyn.delete(self.url)
return response.content['job_id'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_tstore_conn(params, **kwargs):
""" Returns a triplestore connection args: attr_name: The name the connection will be assigned in the config manager params: The paramaters of the connection kwargs: log_level: logging level to use """ |
log.setLevel(params.get('log_level', __LOG_LEVEL__))
log.debug("\n%s", params)
params.update(kwargs)
try:
vendor = RdfwConnections['triplestore'][params.get('vendor')]
except KeyError:
vendor = RdfwConnections['triplestore']['blazegraph']
conn = vendor(**params)
return conn |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_conn(self, **kwargs):
""" takes a connection and creates the connection """ |
# log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3]))
log.setLevel(kwargs.get('log_level',self.log_level))
conn_name = kwargs.get("name")
if not conn_name:
raise NameError("a connection requires a 'name': %s" % kwargs)
elif self.conns.get(conn_name):
raise KeyError("connection '%s' has already been set" % conn_name)
if not kwargs.get("active", True):
log.warning("Connection '%s' is set as inactive" % conn_name)
return
conn_type = kwargs.get("conn_type")
if not conn_type or conn_type not in self.conn_mapping.nested:
err_msg = ["a connection requires a valid 'conn_type':\n",
"%s"]
raise NameError("".join(err_msg) % (list(self.conn_mapping.nested)))
log.info("Setting '%s' connection", conn_name)
if conn_type == "triplestore":
conn = make_tstore_conn(kwargs)
else:
conn = RdfwConnections[conn_type][kwargs['vendor']](**kwargs)
self.conns[conn_name] = conn
self.__is_initialized__ = True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, conn_name, default=None, **kwargs):
""" returns the specified connection args: conn_name: the name of the connection """ |
if isinstance(conn_name, RdfwConnections):
return conn_name
try:
return self.conns[conn_name]
except KeyError:
if default:
return self.get(default, **kwargs)
raise LookupError("'%s' connection has not been set" % conn_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load(self, conn_list, **kwargs):
""" Takes a list of connections and sets them in the manager args: conn_list: list of connection defitions """ |
for conn in conn_list:
conn['delay_check'] = kwargs.get('delay_check', False)
self.set_conn(**conn)
if kwargs.get('delay_check'):
test = self.wait_for_conns(**kwargs)
if not test:
log.critical("\n\nEXITING:Unable to establish connections \n"
"%s", test) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def failing(self):
""" Tests to see if all connections are working returns: dictionary of all failing connections """ |
log_levels = {key: conn.log_level for key, conn in self.conns.items()
if hasattr(conn, 'log_level')}
for key in log_levels:
self.conns[key].log_level = logging.CRITICAL
failing_conns = {key: conn for key, conn in self.active.items()
if not conn.check_status}
for key, level in log_levels.items():
self.conns[key].log_level = level
return failing_conns |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs):
''' delays unitil all connections are working
args:
timeout: number of seconds to try to connecting. Error out when
timeout is reached
start_delay: number of seconds to wait before checking status
interval: number of seconds to wait between checks
'''
log.setLevel(kwargs.get('log_level',self.log_level))
timestamp = time.time()
last_check = time.time() + start_delay - interval
last_delay_notification = time.time() - interval
timeout += 1
failing = True
up_conns = {}
# loop until the server is up or the timeout is reached
while((time.time()-timestamp) < timeout) and failing:
# if delaying, the start of the check, print waiting to start
if start_delay > 0 and time.time() - timestamp < start_delay \
and (time.time()-last_delay_notification) > 5:
print("Delaying server status check until %ss. Current time: %ss" \
% (start_delay, int(time.time() - timestamp)))
last_delay_notification = time.time()
# check status at the specified 'interval' until the server is up
first_check = True
while ((time.time()-last_check) > interval) and failing:
msg = ["\tChecked status of servers at %ss" % \
int((time.time()-timestamp)),
"\t** CONNECTION STATUS:"]
last_check = time.time()
failing = self.failing
new_up = (self.active.keys() - failing.keys()) - \
up_conns.keys()
msg += ["\t\t UP - %s: %s" % (key, self.conns[key])
for key in new_up]
up_conns.update({key: self.conns[key] for key in new_up})
msg.append("\t*** '%s' connection(s) up" % len(up_conns))
msg += ["\t\t FAILING - %s: %s" % (key, self.conns[key])
for key in failing]
log.info("** CONNECTION STATUS:\n%s", "\n".join(msg))
if not failing:
log.info("**** Servers up at %ss" % \
int((time.time()-timestamp)))
break
if failing:
raise RuntimeError("Unable to establish connection(s): ",
failing)
for conn in up_conns.values():
conn.delay_check_pass()
return not failing |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def active(self):
""" returns a dictionary of connections set as active. """ |
return {key: value for key, value in self.conns.items()
if value.active} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Host a file.""" |
description = """Host a file on the LAN."""
argParser = _argparse.ArgumentParser(description=description)
argParser.add_argument('file',
help='File to host')
argParser.add_argument('-p', '--port',
help='Port to use. (default: 80/8000)',
type=int, default=0)
args = argParser.parse_args()
absFilePath = _path.abspath(_path.expandvars(_path.expanduser(args.file)))
if not _path.isfile(absFilePath):
_sys.stdout.write(u"Couldn't find/access file: " + args.file + "\n")
_sys.exit(-1)
tryDefaultPorts = args.port == 0
# Code from http.server in Python3
handler = FileHTTPServerHandler
handler.protocol_version = "HTTP/1.0"
handler.absFilePath = absFilePath
port = 80 if tryDefaultPorts else args.port
try:
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
except IOError as e:
# If it is a permission denied error, and we had been ambitiously
# trying port, 80, let's try port 8000 instead
if e.errno == 13 and tryDefaultPorts:
port = 8000
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
else:
raise
sa = httpd.socket.getsockname()
_sys.stderr.write("Serving file {} on {}:{} ...\n"
.format(absFilePath, sa[0], sa[1]))
possibleIps = getValidIPs()
if len(possibleIps) == 0:
_sys.stderr.write(u'No IPs for localhost found. ' +
u'Are you connected to LAN?\n')
else:
_sys.stderr.write(u'Download the file by pointing the browser ' +
u'on the remote machine to:\n')
portStr = '' if port == 80 else ':' + str(port)
for ip in possibleIps:
_sys.stderr.write(u'\t' + ip + portStr + '\n')
_sys.stderr.write('Press Ctrl-C to stop hosting.\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
_sys.stderr.write("\nKeyboard interrupt received, exiting.\n")
httpd.server_close()
_sys.exit(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500):
""" An unprogrammend Register Machine with * one OutputRegister to ``sys.stdout`` (``out0``) * 15 General Purpose Register (``r0 - r14``) returns : ``(Processor, ROM, RAM, Flash)`` """ |
rom = memory.ROM(rom_size)
ram = memory.RAM(ram_size)
flash = device.Flash(flash_size)
proc = processor.Processor()
proc.register_memory_device(rom)
proc.register_memory_device(ram)
proc.register_device(flash)
registers = [register.OutputRegister("out0", sys.stdout),
register.Register("r0"),
register.Register("r1"),
register.Register("r2"),
register.Register("r3"),
register.Register("r4"),
register.Register("r5"),
register.Register("r6"),
register.Register("r7"),
register.Register("r8"),
register.Register("r9"),
register.Register("r10"),
register.Register("r11"),
register.Register("r12"),
register.Register("r13"),
register.Register("r14")]
for r in registers:
proc.add_register(r)
for command in basic_commands:
proc.register_command(command)
return (proc, rom, ram, flash) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_edge(self, u, v, **attr):
"""
Add an edge from u to v and update edge attributes
""" |
if u not in self.vertices:
self.vertices[u] = []
self.pred[u] = []
self.succ[u] = []
if v not in self.vertices:
self.vertices[v] = []
self.pred[v] = []
self.succ[v] = []
vertex = (u, v)
self.edges[vertex] = {}
self.edges[vertex].update(attr)
self.vertices[u].append(v)
self.pred[v].append(u)
self.succ[u].append(v) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_successor(self, u, v):
"""
Check if vertex u has successor v
""" |
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return (u in self.succ and v in self.succ[u]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_predecessor(self, u, v):
"""
Check if vertex u has predecessor v
""" |
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return(u in self.pred and v in self.pred[u]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_header(frmt, return_len=False):
"""creates a header string from a new style format string useful when printing dictionaries :param str frmt: a new style format string :returns: a table header string assumptions for frmt specs: - all have a separator = '|' and include a key size format directive i.e.: '{key:size}' - no other character allowed in frmt except separator :Example: | count |percent|depth| | 100| 10.50| 10| """ |
names = re.sub("{(.*?):.*?}", r"\1", frmt)
names = [i for i in names.split("|") if i]
frmt_clean = re.sub("\.\df", r"", frmt) # get read of floats i.e {:8.2f}
sizes = re.findall(r':(\d+)', frmt_clean)
frmt_header = "|{{:^{}}}" * len(sizes) + "|"
header_frmt = frmt_header.format(*sizes)
header = header_frmt.format(*names)
header_len = len(header)
header = "{}\n{}\n{}\n".format("." * header_len, header, "." * header_len)
return header.strip() if return_len is False else (header.strip(), header_len) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_form(self, request, form, change):
"""Here we pluck out the data to create a new cloned repo. Form is an instance of NewRepoForm. """ |
name = form.cleaned_data['name']
origin_url = form.cleaned_data['origin_url']
res = ClonedRepo(name=name, origin=origin_url)
LOG.info("New repo form produced %s" % str(res))
form.save(commit=False)
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_view(self, request, **kwargs):
"""A custom add_view, to catch exceptions from 'save_model'. Just to be clear, this is very filthy. """ |
try:
return super(ClonedRepoAdmin, self).add_view(request, **kwargs)
except ValidationError:
# Rerender the form, having messaged the user.
return redirect(request.path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def git_pull_view(self, request, repo_name):
"""Perform a git pull and redirect back to the repo.""" |
LOG.info("Pull requested for %s." % repo_name)
repo = get_object_or_404(self.model, name=repo_name)
repo.pull()
self.message_user(request, "Repo %s successfully updated." % repo_name,
level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_change', repo_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_all_view(self, request):
"""Update all repositories and redirect back to the repo list.""" |
LOG.info("Total update requested.")
total_count = errors = 0
for repo in self.model.objects.all():
total_count += 1
try:
repo.pull()
except:
LOG.exception('While updating %s.' % repo)
errors += 1
msg = "{0} repos successfully updated, {1} failed.".format(total_count,
errors)
self.message_user(request, msg, level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_changelist') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def clean(self):
"""Validate the new repo form. Might perform a request to upstream Bower.""" |
cleaned_data = super(NewRepoForm, self).clean()
origin_url = cleaned_data['origin_url']
origin_source = cleaned_data['origin_source']
if origin_source == 'origin_url' and not origin_url:
msg = 'Please provide an origin URL.'
self._errors['origin_url'] = self.error_class([msg])
del cleaned_data['origin_url']
del cleaned_data['origin_source']
elif origin_source == 'upstream':
upstream = settings.UPSTREAM_BOWER_REGISTRY
name = cleaned_data['name']
try:
upstream_pkg = bowerlib.get_package(upstream, name)
except IOError as exc:
msg = str(exc)
self._errors['origin_source'] = self.error_class([msg])
else:
if not upstream_pkg:
msg = 'Upstream registry has no knowledge of %s.' % name
self._errors['name'] = self.error_class([msg])
del cleaned_data['name']
else:
upstream_origin_url = upstream_pkg['url']
cleaned_data['origin_url'] = upstream_origin_url
return cleaned_data |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def activate(lang=None):
"""Activate a translation for lang. If lang is None, then the language of locale.getdefaultlocale() is used. If the translation file does not exist, the original messages will be used. """ |
if lang is None:
lang = locale.getlocale()[0]
tr = gettext.translation("argparse", os.path.join(locpath, "locale"),
[lang], fallback=True)
argparse._ = tr.gettext
argparse.ngettext = tr.ngettext |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run until there are no more events. This only looks at events scheduled through the event loop. """ |
self._stop = False
while not self._stop:
have_sources = self._timers or self._readers or self._writers
if not self._processor.pending and not have_sources:
break
events = QEventLoop.AllEvents
if not self._processor.pending:
events |= QEventLoop.WaitForMoreEvents
self._qapp.processEvents(events)
if self._processor.pending:
self._processor.run() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_namedtuple(self):
""" Convert class to namedtuple. Note: This method is neccessary for AMQP communication. Returns: namedtuple: Representation of the class as simple structure. """ |
keys = filter(lambda x: not x.startswith("_"), self.__dict__)
opt_nt = namedtuple(self.__class__.__name__, keys)
filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))
return opt_nt(**filtered_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_hash(self):
""" Create hash of the class. Hash should be unique for given ebook, so ISBN is main component of the hash if provided. Returns: str: Hash. """ |
if self.optionals and self.optionals.ISBN:
isbn = self.optionals.ISBN.replace("-", "")
if len(isbn) <= 10:
return "97880" + isbn
return isbn
if self.optionals and self.optionals.EAN:
return self.optionals.EAN
return self.title + ",".join(map(lambda x: x.name, self.authors)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def luriegold(R):
"""Lurie-Goldberg Algorithm to adjust a correlation matrix to be semipositive definite Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method for Sampling Correlated Random Variables from Partially-Specified Distributions, Management Science, Vol 44, No. 2, February 1998, pp 203-218, URL: http://www.jstor.org/stable/2634496 """ |
# subfunctions
def xtotril(x, idx, mat):
"""Create 'L' lower triangular matrix."""
mat[idx] = x
return mat
def xtocorr(x, idx, mat):
L = xtotril(x, idx, mat)
C = np.dot(L, L.T)
return C, L
def objectivefunc(x, R, idx, mat):
C, _ = xtocorr(x, idx, mat)
f = np.sum((R - C)**2)
return f
def nlcon_diagone(x, idx, mat):
C, _ = xtocorr(x, idx, mat)
return np.diag(C) - 1
# dimension of the correlation matrix
d = R.shape[0]
n = int((d**2 + d) / 2.)
# other arguments
mat = np.zeros((d, d)) # the lower triangular matrix without values
idx = np.tril(np.ones((d, d)), k=0) > 0 # boolean matrix
# idx = np.tril_indices(d,k=0); #row/col ids (same result)
# start values of the optimization are Ones
x0 = np.ones(shape=(n, )) / n
# for each of the k factors, the sum of its d absolute params
# values has to be less than 1
condiag = {'type': 'eq', 'args': (idx, mat), 'fun': nlcon_diagone}
# optimization
algorithm = 'SLSQP'
opt = {'disp': False}
# run the optimization
results = scipy.optimize.minimize(
objectivefunc, x0,
args=(R, idx, mat),
constraints=[condiag],
method=algorithm,
options=opt)
# Compute Correlation Matrix
C, L = xtocorr(results.x, idx, mat)
# done
return C, L, results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_datasets_list(settings, argv):
""" generate datasets list to activate args: settings: dictionary from settings file argv: list from sys.argv """ |
datasets_string_list = settings["DATASETS_LIST"]
datasets_list = []
if len(argv) == 2:
try:
datasets_items = datasets_string_list.iteritems()
except AttributeError:
datasets_items = datasets_string_list.items()
for key, val in datasets_items:
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
for element in val:
datasets_list.append(
(key, element, getattr(key_module, element)())
)
elif len(argv) > 2:
arguments = argv[2:]
for argument in arguments:
argument_list = argument.split(".")
key = ".".join(argument_list[:-1])
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
datasets_list.append(
(key, argument_list[-1],
getattr(key_module, argument_list[-1])())
)
else:
print_help()
return datasets_list |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def manage(settingspath, root_dir, argv):
""" Manage all processes """ |
# add settings.json to environment variables
os.environ[ENV_VAR_SETTINGS] = settingspath
# add root_dir
os.environ[ENV_VAR_ROOT_DIR] = root_dir
# get datasets list
with open(settingspath) as settings_file:
settings = json.load(settings_file)
# manage args
datasets_list = generate_datasets_list(settings, argv)
if "make-data-file" == argv[1]:
make_data_file(datasets_list, argv)
elif "parse-data" == argv[1]:
parse_data(datasets_list, argv)
elif "do-operations" == argv[1]:
do_operations(datasets_list, argv)
else:
print_help() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_pathname_valid(pathname: str) -> bool: """Checks if the given path name is valid. Returns ------- `True` if the passed pathname is a valid pathname for the current OS; `False` otherwise. """ |
# If this pathname is either not a string or is but is empty, this pathname
# is invalid.
try:
if not isinstance(pathname, str) or not pathname:
return False
# Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
# if any. Since Windows prohibits path components from containing `:`
# characters, failing to strip this `:`-suffixed prefix would
# erroneously invalidate all valid absolute Windows pathnames.
_, pathname = os.path.splitdrive(pathname)
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
if sys.platform == 'win32' else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law
# Append a path separator to this directory if needed.
root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep
# Test whether each path component split from this pathname is valid or
# not, ignoring non-existent and non-readable path components.
for pathname_part in pathname.split(os.path.sep):
try:
os.lstat(root_dirname + pathname_part)
# If an OS-specific exception is raised, its error code
# indicates whether this pathname is valid or not. Unless this
# is the case, this exception implies an ignorable kernel or
# filesystem complaint (e.g., path not found or inaccessible).
#
# Only the following exceptions indicate invalid pathnames:
#
# * Instances of the Windows-specific "WindowsError" class
# defining the "winerror" attribute whose value is
# "ERROR_INVALID_NAME". Under Windows, "winerror" is more
# fine-grained and hence useful than the generic "errno"
# attribute. When a too-long pathname is passed, for example,
# "errno" is "ENOENT" (i.e., no such file or directory) rather
# than "ENAMETOOLONG" (i.e., file name too long).
# * Instances of the cross-platform "OSError" class defining the
# generic "errno" attribute whose value is either:
# * Under most POSIX-compatible OSes, "ENAMETOOLONG".
# * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
except OSError as exc:
if hasattr(exc, 'winerror'):
if exc.winerror == ERROR_INVALID_NAME:
return False
elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
else:
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_path_creatable(pathname: str) -> bool: """Checks whether the given path is creatable. Returns ------- `True` if the current user has sufficient permissions to create the passed pathname; `False` otherwise. """ |
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
return os.access(dirname, os.W_OK) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_exists_or_creatable(pathname: str) -> bool: """Checks whether the given path exists or is creatable. This function is guaranteed to _never_ raise exceptions. Returns ------- `True` if the passed pathname is a valid pathname for the current OS _and_ either currently exists or is hypothetically creatable; `False` otherwise. """ |
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught
# here.
except OSError:
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_path_sibling_creatable(pathname: str) -> bool: """Checks whether current user can create siblings of the given path. Returns ------- `True` if the current user has sufficient permissions to create siblings (i.e., arbitrary files in the parent directory) of the passed pathname; `False` otherwise. """ |
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname):
pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass
# the following exception superclass.
except EnvironmentError:
return False |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.