code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def repost(self, token): """ Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request` """ url = '%s/%s/repost' % (REQUESTS_URL, token) response = requests.post(url, headers={ 'Authorization': self.auth.authorize('POST', url), 'User-Agent': USER_AGENT, }) if response.status_code == 200: return return self._unwrap_error(response)
Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request`
Below is the the instruction that describes the task: ### Input: Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request` ### Response: def repost(self, token): """ Repost the job if it has timed out (:py:data:`cloudsight.STATUS_TIMEOUT`). :param token: Job token as returned from :py:meth:`cloudsight.API.image_request` or :py:meth:`cloudsight.API.remote_image_request` """ url = '%s/%s/repost' % (REQUESTS_URL, token) response = requests.post(url, headers={ 'Authorization': self.auth.authorize('POST', url), 'User-Agent': USER_AGENT, }) if response.status_code == 200: return return self._unwrap_error(response)
def solution_to_schedule(solution, events, slots): """Convert a schedule from solution to schedule form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances Returns ------- list A list of instances of :py:class:`resources.ScheduledItem` """ return [ ScheduledItem( event=events[item[0]], slot=slots[item[1]] ) for item in solution ]
Convert a schedule from solution to schedule form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances Returns ------- list A list of instances of :py:class:`resources.ScheduledItem`
Below is the the instruction that describes the task: ### Input: Convert a schedule from solution to schedule form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances Returns ------- list A list of instances of :py:class:`resources.ScheduledItem` ### Response: def solution_to_schedule(solution, events, slots): """Convert a schedule from solution to schedule form Parameters ---------- solution : list or tuple of tuples of event index and slot index for each scheduled item events : list or tuple of :py:class:`resources.Event` instances slots : list or tuple of :py:class:`resources.Slot` instances Returns ------- list A list of instances of :py:class:`resources.ScheduledItem` """ return [ ScheduledItem( event=events[item[0]], slot=slots[item[1]] ) for item in solution ]
def unique_list(input_, key=lambda x:x): """Return the unique elements from the input, in order.""" seen = set() output = [] for x in input_: keyx = key(x) if keyx not in seen: seen.add(keyx) output.append(x) return output
Return the unique elements from the input, in order.
Below is the the instruction that describes the task: ### Input: Return the unique elements from the input, in order. ### Response: def unique_list(input_, key=lambda x:x): """Return the unique elements from the input, in order.""" seen = set() output = [] for x in input_: keyx = key(x) if keyx not in seen: seen.add(keyx) output.append(x) return output
def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False
Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234
Below is the the instruction that describes the task: ### Input: Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ### Response: def unlock(path, zk_hosts=None, # in case you need to unlock without having run lock (failed execution for example) identifier=None, max_concurrency=1, ephemeral_lease=False, scheme=None, profile=None, username=None, password=None, default_acl=None ): ''' Remove lease from semaphore path The path in zookeeper where the lock is zk_hosts zookeeper connect string identifier Name to identify this minion, if unspecified defaults to hostname max_concurrency Maximum number of lock holders timeout timeout to wait for the lock. A None timeout will block forever ephemeral_lease Whether the locks in zookeper should be ephemeral Example: .. code-block: bash salt minion zk_concurrency.unlock /lock/path host1:1234,host2:1234 ''' # if someone passed in zk_hosts, and the path isn't in __context__['semaphore_map'], lets # see if we can find it zk = _get_zk_conn(profile=profile, hosts=zk_hosts, scheme=scheme, username=username, password=password, default_acl=default_acl) if path not in __context__['semaphore_map']: __context__['semaphore_map'][path] = _Semaphore(zk, path, identifier, max_leases=max_concurrency, ephemeral_lease=ephemeral_lease) if path in __context__['semaphore_map']: __context__['semaphore_map'][path].release() del __context__['semaphore_map'][path] return True else: logging.error('Unable to find lease for path %s', path) return False
def assign_objective_requisites(self, objective_id=None, requisite_objective_ids=None): """Creates a requirement dependency between Objective + a list of objectives. NON-standard method impl by cjshaw arg: objective_id (osid.id.Id): the Id of the dependent Objective arg: requisite_objective_id (osid.id.Id): the Id of the required Objective raise: AlreadyExists - objective_id already mapped to requisite_objective_id raise: NotFound - objective_id or requisite_objective_id not found raise: NullArgument - objective_id or requisite_objective_id is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory - This method must be implemented. """ if objective_id is None or requisite_objective_ids is None: raise NullArgument() ors = ObjectiveRequisiteSession(self._objective_bank_id, runtime=self._runtime) ids_arg = {'ids': [str(i) for i in requisite_objective_ids]} url_path = construct_url('requisiteids', bank_id=self._catalog_idstr, obj_id=objective_id) try: result = self._put_request(url_path, ids_arg) except Exception: raise id_list = list() for identifier in result['ids']: id_list.append(Id(idstr=identifier)) return id_objects.IdList(id_list)
Creates a requirement dependency between Objective + a list of objectives. NON-standard method impl by cjshaw arg: objective_id (osid.id.Id): the Id of the dependent Objective arg: requisite_objective_id (osid.id.Id): the Id of the required Objective raise: AlreadyExists - objective_id already mapped to requisite_objective_id raise: NotFound - objective_id or requisite_objective_id not found raise: NullArgument - objective_id or requisite_objective_id is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory - This method must be implemented.
Below is the the instruction that describes the task: ### Input: Creates a requirement dependency between Objective + a list of objectives. NON-standard method impl by cjshaw arg: objective_id (osid.id.Id): the Id of the dependent Objective arg: requisite_objective_id (osid.id.Id): the Id of the required Objective raise: AlreadyExists - objective_id already mapped to requisite_objective_id raise: NotFound - objective_id or requisite_objective_id not found raise: NullArgument - objective_id or requisite_objective_id is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory - This method must be implemented. ### Response: def assign_objective_requisites(self, objective_id=None, requisite_objective_ids=None): """Creates a requirement dependency between Objective + a list of objectives. NON-standard method impl by cjshaw arg: objective_id (osid.id.Id): the Id of the dependent Objective arg: requisite_objective_id (osid.id.Id): the Id of the required Objective raise: AlreadyExists - objective_id already mapped to requisite_objective_id raise: NotFound - objective_id or requisite_objective_id not found raise: NullArgument - objective_id or requisite_objective_id is null raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure compliance: mandatory - This method must be implemented. """ if objective_id is None or requisite_objective_ids is None: raise NullArgument() ors = ObjectiveRequisiteSession(self._objective_bank_id, runtime=self._runtime) ids_arg = {'ids': [str(i) for i in requisite_objective_ids]} url_path = construct_url('requisiteids', bank_id=self._catalog_idstr, obj_id=objective_id) try: result = self._put_request(url_path, ids_arg) except Exception: raise id_list = list() for identifier in result['ids']: id_list.append(Id(idstr=identifier)) return id_objects.IdList(id_list)
def transit_delete_key(self, name, mount_point='transit'): """DELETE /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype: """ url = '/v1/{0}/keys/{1}'.format(mount_point, name) return self._adapter.delete(url)
DELETE /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype:
Below is the the instruction that describes the task: ### Input: DELETE /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype: ### Response: def transit_delete_key(self, name, mount_point='transit'): """DELETE /<mount_point>/keys/<name> :param name: :type name: :param mount_point: :type mount_point: :return: :rtype: """ url = '/v1/{0}/keys/{1}'.format(mount_point, name) return self._adapter.delete(url)
def kind(self): '''The kind of this execution context.''' with self._mutex: kind = self._obj.get_kind() if kind == RTC.PERIODIC: return self.PERIODIC elif kind == RTC.EVENT_DRIVEN: return self.EVENT_DRIVEN else: return self.OTHER
The kind of this execution context.
Below is the the instruction that describes the task: ### Input: The kind of this execution context. ### Response: def kind(self): '''The kind of this execution context.''' with self._mutex: kind = self._obj.get_kind() if kind == RTC.PERIODIC: return self.PERIODIC elif kind == RTC.EVENT_DRIVEN: return self.EVENT_DRIVEN else: return self.OTHER
def simxGetVisionSensorDepthBuffer(clientID, sensorHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' c_buffer = ct.POINTER(ct.c_float)() resolution = (ct.c_int*2)() ret = c_GetVisionSensorDepthBuffer(clientID, sensorHandle, resolution, ct.byref(c_buffer), operationMode) reso = [] buffer = [] if (ret == 0): buffer = [None]*resolution[0]*resolution[1] for i in range(resolution[0] * resolution[1]): buffer[i] = c_buffer[i] for i in range(2): reso.append(resolution[i]) return ret, reso, buffer
Please have a look at the function description/documentation in the V-REP user manual
Below is the the instruction that describes the task: ### Input: Please have a look at the function description/documentation in the V-REP user manual ### Response: def simxGetVisionSensorDepthBuffer(clientID, sensorHandle, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' c_buffer = ct.POINTER(ct.c_float)() resolution = (ct.c_int*2)() ret = c_GetVisionSensorDepthBuffer(clientID, sensorHandle, resolution, ct.byref(c_buffer), operationMode) reso = [] buffer = [] if (ret == 0): buffer = [None]*resolution[0]*resolution[1] for i in range(resolution[0] * resolution[1]): buffer[i] = c_buffer[i] for i in range(2): reso.append(resolution[i]) return ret, reso, buffer
def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls.available: raise ConnectionPluginNotRegistered( f"Connection {name!r} is not registered" ) cls.available.pop(name)
Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered`
Below is the the instruction that describes the task: ### Input: Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` ### Response: def deregister(cls, name: str) -> None: """Deregisters a registered connection plugin by its name Args: name: name of the connection plugin to deregister Raises: :obj:`nornir.core.exceptions.ConnectionPluginNotRegistered` """ if name not in cls.available: raise ConnectionPluginNotRegistered( f"Connection {name!r} is not registered" ) cls.available.pop(name)
def adapt(self, all_ouputs: AllOutputs) -> DataPacket: """Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outputs. Returns: Dictionary with the same keys as `adapting_recipes` and values constructed according to the respective recipes. """ adapted = {} for name, recipe in self.adapting_recipes.items(): adapted[name] = self._construct(all_ouputs, recipe) return adapted
Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outputs. Returns: Dictionary with the same keys as `adapting_recipes` and values constructed according to the respective recipes.
Below is the the instruction that describes the task: ### Input: Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outputs. Returns: Dictionary with the same keys as `adapting_recipes` and values constructed according to the respective recipes. ### Response: def adapt(self, all_ouputs: AllOutputs) -> DataPacket: """Adapt inputs for the transformer included in the step. Args: all_ouputs: Dict of outputs from parent steps. The keys should match the names of these steps and the values should be their respective outputs. Returns: Dictionary with the same keys as `adapting_recipes` and values constructed according to the respective recipes. """ adapted = {} for name, recipe in self.adapting_recipes.items(): adapted[name] = self._construct(all_ouputs, recipe) return adapted
def find_module_defining_flag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ registered_flag = self._flags().get(flagname) if registered_flag is None: return default for module, flags in six.iteritems(self.flags_by_module_dict()): for flag in flags: # It must compare the flag with the one in _flags. This is because a # flag might be overridden only for its long name (or short name), # and only its short name (or long name) is considered registered. if (flag.name == registered_flag.name and flag.short_name == registered_flag.short_name): return module return default
Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default.
Below is the the instruction that describes the task: ### Input: Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. ### Response: def find_module_defining_flag(self, flagname, default=None): """Return the name of the module defining this flag, or default. Args: flagname: str, name of the flag to lookup. default: Value to return if flagname is not defined. Defaults to None. Returns: The name of the module which registered the flag with this name. If no such module exists (i.e. no flag with this name exists), we return default. """ registered_flag = self._flags().get(flagname) if registered_flag is None: return default for module, flags in six.iteritems(self.flags_by_module_dict()): for flag in flags: # It must compare the flag with the one in _flags. This is because a # flag might be overridden only for its long name (or short name), # and only its short name (or long name) is considered registered. if (flag.name == registered_flag.name and flag.short_name == registered_flag.short_name): return module return default
def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: self.set_bounds(kwargs.pop('bounds')) if 'free' in kwargs: self.set_free(kwargs.pop('free')) if 'errors' in kwargs: self.set_errors(kwargs.pop('errors')) if 'value' in kwargs: self.set_value(kwargs.pop('value'))
Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes.
Below is the the instruction that describes the task: ### Input: Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. ### Response: def set(self, **kwargs): """Set the value,bounds,free,errors based on corresponding kwargs The invokes hooks for type-checking and bounds-checking that may be implemented by sub-classes. """ # Probably want to reset bounds if set fails if 'bounds' in kwargs: self.set_bounds(kwargs.pop('bounds')) if 'free' in kwargs: self.set_free(kwargs.pop('free')) if 'errors' in kwargs: self.set_errors(kwargs.pop('errors')) if 'value' in kwargs: self.set_value(kwargs.pop('value'))
def wr_hdrs(self, worksheet, row_idx): """Print row of column headers""" for col_idx, hdr in enumerate(self.hdrs): # print("ROW({R}) COL({C}) HDR({H}) FMT({F})\n".format( # R=row_idx, C=col_idx, H=hdr, F=self.fmt_hdr)) worksheet.write(row_idx, col_idx, hdr, self.fmt_hdr) row_idx += 1 return row_idx
Print row of column headers
Below is the the instruction that describes the task: ### Input: Print row of column headers ### Response: def wr_hdrs(self, worksheet, row_idx): """Print row of column headers""" for col_idx, hdr in enumerate(self.hdrs): # print("ROW({R}) COL({C}) HDR({H}) FMT({F})\n".format( # R=row_idx, C=col_idx, H=hdr, F=self.fmt_hdr)) worksheet.write(row_idx, col_idx, hdr, self.fmt_hdr) row_idx += 1 return row_idx
def rename_tier(self, id_from, id_to): """Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist. """ childs = self.get_child_tiers_for(id_from) self.tiers[id_to] = self.tiers.pop(id_from) self.tiers[id_to][2]['TIER_ID'] = id_to for child in childs: self.tiers[child][2]['PARENT_REF'] = id_to
Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist.
Below is the the instruction that describes the task: ### Input: Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist. ### Response: def rename_tier(self, id_from, id_to): """Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist. """ childs = self.get_child_tiers_for(id_from) self.tiers[id_to] = self.tiers.pop(id_from) self.tiers[id_to][2]['TIER_ID'] = id_to for child in childs: self.tiers[child][2]['PARENT_REF'] = id_to
def membership_score(self, element): """ Fuzzy set gradable membership score See http://code.google.com/p/python-colormath/wiki/ColorDifferences """ other = self.coerce(element) if self.value and other.value: return 1 - (self.value.delta_e(other.value, mode='cmc', pl=1, pc=1) / 200.0) else: return 0.0
Fuzzy set gradable membership score See http://code.google.com/p/python-colormath/wiki/ColorDifferences
Below is the the instruction that describes the task: ### Input: Fuzzy set gradable membership score See http://code.google.com/p/python-colormath/wiki/ColorDifferences ### Response: def membership_score(self, element): """ Fuzzy set gradable membership score See http://code.google.com/p/python-colormath/wiki/ColorDifferences """ other = self.coerce(element) if self.value and other.value: return 1 - (self.value.delta_e(other.value, mode='cmc', pl=1, pc=1) / 200.0) else: return 0.0
def clock_sa_clock_timezone(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") clock_sa = ET.SubElement(config, "clock-sa", xmlns="urn:brocade.com:mgmt:brocade-clock") clock = ET.SubElement(clock_sa, "clock") timezone = ET.SubElement(clock, "timezone") timezone.text = kwargs.pop('timezone') callback = kwargs.pop('callback', self._callback) return callback(config)
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def clock_sa_clock_timezone(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") clock_sa = ET.SubElement(config, "clock-sa", xmlns="urn:brocade.com:mgmt:brocade-clock") clock = ET.SubElement(clock_sa, "clock") timezone = ET.SubElement(clock, "timezone") timezone.text = kwargs.pop('timezone') callback = kwargs.pop('callback', self._callback) return callback(config)
def extrap1d(interpolator): """ Function to extend an interpolation function to an extrapolation function. :param interpolator: scipy interp1d object :returns ufunclike: extension of function to extrapolation """ xs = interpolator.x ys = interpolator.y def pointwise(x): if x < xs[0]: return ys[0] # +(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0]) elif x > xs[-1]: return ys[-1] # +(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2]) else: return interpolator(x) def ufunclike(xs): return N.array(map(pointwise, N.array(xs))) return ufunclike
Function to extend an interpolation function to an extrapolation function. :param interpolator: scipy interp1d object :returns ufunclike: extension of function to extrapolation
Below is the the instruction that describes the task: ### Input: Function to extend an interpolation function to an extrapolation function. :param interpolator: scipy interp1d object :returns ufunclike: extension of function to extrapolation ### Response: def extrap1d(interpolator): """ Function to extend an interpolation function to an extrapolation function. :param interpolator: scipy interp1d object :returns ufunclike: extension of function to extrapolation """ xs = interpolator.x ys = interpolator.y def pointwise(x): if x < xs[0]: return ys[0] # +(x-xs[0])*(ys[1]-ys[0])/(xs[1]-xs[0]) elif x > xs[-1]: return ys[-1] # +(x-xs[-1])*(ys[-1]-ys[-2])/(xs[-1]-xs[-2]) else: return interpolator(x) def ufunclike(xs): return N.array(map(pointwise, N.array(xs))) return ufunclike
def str_to_date(self): """ Returns the date attribute as a date object. :returns: Date of the status if it exists. :rtype: date or NoneType """ if hasattr(self, 'date'): return date(*list(map(int, self.date.split('-')))) else: return None
Returns the date attribute as a date object. :returns: Date of the status if it exists. :rtype: date or NoneType
Below is the the instruction that describes the task: ### Input: Returns the date attribute as a date object. :returns: Date of the status if it exists. :rtype: date or NoneType ### Response: def str_to_date(self): """ Returns the date attribute as a date object. :returns: Date of the status if it exists. :rtype: date or NoneType """ if hasattr(self, 'date'): return date(*list(map(int, self.date.split('-')))) else: return None
def save(self): """Update or create a new object on the JSS. If this object is not yet on the JSS, this method will create a new object with POST, otherwise, it will try to update the existing object with PUT. Data validation is up to the client; The JSS in most cases will at least give you some hints as to what is invalid. """ # Object probably exists if it has an ID (user can't assign # one). The only objects that don't have an ID are those that # cannot list. if self.can_put and (not self.can_list or self.id): # The JSS will reject PUT requests for objects that do not have # a category. The JSS assigns a name of "No category assigned", # which it will reject. Therefore, if that is the category # name, changed it to "", which is accepted. categories = [elem for elem in self.findall("category")] categories.extend([elem for elem in self.findall("category/name")]) for cat_tag in categories: if cat_tag.text == "No category assigned": cat_tag.text = "" try: self.jss.put(self.url, self) updated_data = self.jss.get(self.url) except JSSPutError as put_error: # Something when wrong. raise JSSPutError(put_error) elif self.can_post: url = self.get_post_url() try: updated_data = self.jss.post(self.__class__, url, self) except JSSPostError as err: raise JSSPostError(err) else: raise JSSMethodNotAllowedError(self.__class__.__name__) # Replace current instance's data with new, JSS-validated data. self.clear() for child in updated_data.getchildren(): self._children.append(child)
Update or create a new object on the JSS. If this object is not yet on the JSS, this method will create a new object with POST, otherwise, it will try to update the existing object with PUT. Data validation is up to the client; The JSS in most cases will at least give you some hints as to what is invalid.
Below is the the instruction that describes the task: ### Input: Update or create a new object on the JSS. If this object is not yet on the JSS, this method will create a new object with POST, otherwise, it will try to update the existing object with PUT. Data validation is up to the client; The JSS in most cases will at least give you some hints as to what is invalid. ### Response: def save(self): """Update or create a new object on the JSS. If this object is not yet on the JSS, this method will create a new object with POST, otherwise, it will try to update the existing object with PUT. Data validation is up to the client; The JSS in most cases will at least give you some hints as to what is invalid. """ # Object probably exists if it has an ID (user can't assign # one). The only objects that don't have an ID are those that # cannot list. if self.can_put and (not self.can_list or self.id): # The JSS will reject PUT requests for objects that do not have # a category. The JSS assigns a name of "No category assigned", # which it will reject. Therefore, if that is the category # name, changed it to "", which is accepted. categories = [elem for elem in self.findall("category")] categories.extend([elem for elem in self.findall("category/name")]) for cat_tag in categories: if cat_tag.text == "No category assigned": cat_tag.text = "" try: self.jss.put(self.url, self) updated_data = self.jss.get(self.url) except JSSPutError as put_error: # Something when wrong. raise JSSPutError(put_error) elif self.can_post: url = self.get_post_url() try: updated_data = self.jss.post(self.__class__, url, self) except JSSPostError as err: raise JSSPostError(err) else: raise JSSMethodNotAllowedError(self.__class__.__name__) # Replace current instance's data with new, JSS-validated data. self.clear() for child in updated_data.getchildren(): self._children.append(child)
def check_sla(self, sla, diff_metric): """ Check whether the SLA has passed or failed """ try: if sla.display is '%': diff_val = float(diff_metric['percent_diff']) else: diff_val = float(diff_metric['absolute_diff']) except ValueError: return False if not (sla.check_sla_passed(diff_val)): self.sla_failures += 1 self.sla_failure_list.append(DiffSLAFailure(sla, diff_metric)) return True
Check whether the SLA has passed or failed
Below is the the instruction that describes the task: ### Input: Check whether the SLA has passed or failed ### Response: def check_sla(self, sla, diff_metric): """ Check whether the SLA has passed or failed """ try: if sla.display is '%': diff_val = float(diff_metric['percent_diff']) else: diff_val = float(diff_metric['absolute_diff']) except ValueError: return False if not (sla.check_sla_passed(diff_val)): self.sla_failures += 1 self.sla_failure_list.append(DiffSLAFailure(sla, diff_metric)) return True
def get_zipcodes_for_canton(self, canton): """ Return the list of zipcodes for the given canton code. """ zipcodes = [ zipcode for zipcode, location in self.get_locations().items() if location.canton == canton ] return zipcodes
Return the list of zipcodes for the given canton code.
Below is the the instruction that describes the task: ### Input: Return the list of zipcodes for the given canton code. ### Response: def get_zipcodes_for_canton(self, canton): """ Return the list of zipcodes for the given canton code. """ zipcodes = [ zipcode for zipcode, location in self.get_locations().items() if location.canton == canton ] return zipcodes
def mouseReleaseEvent(self, event): """Go to error""" self.QT_CLASS.mouseReleaseEvent(self, event) text = self.get_line_at(event.pos()) if get_error_match(text) and not self.has_selected_text(): if self.go_to_error is not None: self.go_to_error.emit(text)
Go to error
Below is the the instruction that describes the task: ### Input: Go to error ### Response: def mouseReleaseEvent(self, event): """Go to error""" self.QT_CLASS.mouseReleaseEvent(self, event) text = self.get_line_at(event.pos()) if get_error_match(text) and not self.has_selected_text(): if self.go_to_error is not None: self.go_to_error.emit(text)
def swipe_top(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details. """ self.device(**selectors).swipe.up(steps=steps)
Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details.
Below is the the instruction that describes the task: ### Input: Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details. ### Response: def swipe_top(self, steps=10, *args, **selectors): """ Swipe the UI object with *selectors* from center to top See `Swipe Left` for more details. """ self.device(**selectors).swipe.up(steps=steps)
def get_pipeline(node: Node) -> RenderingPipeline: """Gets rendering pipeline for passed node""" pipeline = _get_registered_pipeline(node) if pipeline is None: msg = _get_pipeline_registration_error_message(node) raise RenderingError(msg) return pipeline
Gets rendering pipeline for passed node
Below is the the instruction that describes the task: ### Input: Gets rendering pipeline for passed node ### Response: def get_pipeline(node: Node) -> RenderingPipeline: """Gets rendering pipeline for passed node""" pipeline = _get_registered_pipeline(node) if pipeline is None: msg = _get_pipeline_registration_error_message(node) raise RenderingError(msg) return pipeline
def loadusers(sources): """Load users.""" from .tasks.users import load_user # Cannot be executed asynchronously due to duplicate emails and usernames # which can create a racing condition. loadcommon(sources, load_user, asynchronous=False)
Load users.
Below is the the instruction that describes the task: ### Input: Load users. ### Response: def loadusers(sources): """Load users.""" from .tasks.users import load_user # Cannot be executed asynchronously due to duplicate emails and usernames # which can create a racing condition. loadcommon(sources, load_user, asynchronous=False)
def remove_route_gateway(self, element, network=None): """ Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool """ if self.level not in ('interface',): raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) node_changed = False element = element_resolver(element) for network in self: # Tunnel Interface binds gateways to the interface if network.level == 'gateway' and network.data.get('href') == element: network.delete() node_changed = True break for gateway in network: if gateway.data.get('href') == element: gateway.delete() node_changed = True return node_changed
Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool
Below is the the instruction that describes the task: ### Input: Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool ### Response: def remove_route_gateway(self, element, network=None): """ Remove a route element by href or Element. Use this if you want to remove a netlink or a routing element such as BGP or OSPF. Removing is done from within the routing interface context. :: interface0 = engine.routing.get(0) interface0.remove_route_gateway(StaticNetlink('mynetlink')) Only from a specific network on a multi-address interface:: interface0.remove_route_gateway( StaticNetlink('mynetlink'), network='172.18.1.0/24') :param str,Element element: element to remove from this routing node :param str network: if network specified, only add OSPF to this network on interface :raises ModificationAborted: Change must be made at the interface level :raises UpdateElementFailed: failure to update routing table :return: Status of whether the entry was removed (i.e. or not found) :rtype: bool """ if self.level not in ('interface',): raise ModificationAborted('You must make this change from the ' 'interface routing level. Current node: {}'.format(self)) node_changed = False element = element_resolver(element) for network in self: # Tunnel Interface binds gateways to the interface if network.level == 'gateway' and network.data.get('href') == element: network.delete() node_changed = True break for gateway in network: if gateway.data.get('href') == element: gateway.delete() node_changed = True return node_changed
def _link_fields(self): """Construct dict of name:field for linkable fields.""" query_params = self.get_request_attribute('query_params', {}) if 'exclude_links' in query_params: return {} else: all_fields = self.get_all_fields() return { name: field for name, field in six.iteritems(all_fields) if isinstance(field, DynamicRelationField) and getattr(field, 'link', True) and not ( # Skip sideloaded fields name in self.fields and self.is_field_sideloaded(name) ) and not ( # Skip included single relations # TODO: Use links, when we can generate canonical URLs name in self.fields and not getattr(field, 'many', False) ) }
Construct dict of name:field for linkable fields.
Below is the the instruction that describes the task: ### Input: Construct dict of name:field for linkable fields. ### Response: def _link_fields(self): """Construct dict of name:field for linkable fields.""" query_params = self.get_request_attribute('query_params', {}) if 'exclude_links' in query_params: return {} else: all_fields = self.get_all_fields() return { name: field for name, field in six.iteritems(all_fields) if isinstance(field, DynamicRelationField) and getattr(field, 'link', True) and not ( # Skip sideloaded fields name in self.fields and self.is_field_sideloaded(name) ) and not ( # Skip included single relations # TODO: Use links, when we can generate canonical URLs name in self.fields and not getattr(field, 'many', False) ) }
def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) return device elif self.type == CONST.ALARM_TYPE: response = self._lupusec.get_panel() self.update(response) return response elif self.type == CONST.TYPE_POWER_SWITCH: response = self._lupusec.get_power_switches() for pss in response: if pss['device_id'] == self._device_id: self.update(pss) return pss
Refresh a device
Below is the the instruction that describes the task: ### Input: Refresh a device ### Response: def refresh(self): """Refresh a device""" # new_device = {} if self.type in CONST.BINARY_SENSOR_TYPES: response = self._lupusec.get_sensors() for device in response: if device['device_id'] == self._device_id: self.update(device) return device elif self.type == CONST.ALARM_TYPE: response = self._lupusec.get_panel() self.update(response) return response elif self.type == CONST.TYPE_POWER_SWITCH: response = self._lupusec.get_power_switches() for pss in response: if pss['device_id'] == self._device_id: self.update(pss) return pss
def _data_to_tensor(data_list, batch_size, name=None): r"""Returns batch queues from the whole data. Args: data_list: A list of ndarrays. Every array must have the same size in the first dimension. batch_size: An integer. name: A name for the operations (optional). Returns: A list of tensors of `batch_size`. """ # convert to constant tensor const_list = [tf.constant(data) for data in data_list] # create queue from constant tensor queue_list = tf.train.slice_input_producer(const_list, capacity=batch_size*128, name=name) # create batch queue return tf.train.shuffle_batch(queue_list, batch_size, capacity=batch_size*128, min_after_dequeue=batch_size*32, name=name)
r"""Returns batch queues from the whole data. Args: data_list: A list of ndarrays. Every array must have the same size in the first dimension. batch_size: An integer. name: A name for the operations (optional). Returns: A list of tensors of `batch_size`.
Below is the the instruction that describes the task: ### Input: r"""Returns batch queues from the whole data. Args: data_list: A list of ndarrays. Every array must have the same size in the first dimension. batch_size: An integer. name: A name for the operations (optional). Returns: A list of tensors of `batch_size`. ### Response: def _data_to_tensor(data_list, batch_size, name=None): r"""Returns batch queues from the whole data. Args: data_list: A list of ndarrays. Every array must have the same size in the first dimension. batch_size: An integer. name: A name for the operations (optional). Returns: A list of tensors of `batch_size`. """ # convert to constant tensor const_list = [tf.constant(data) for data in data_list] # create queue from constant tensor queue_list = tf.train.slice_input_producer(const_list, capacity=batch_size*128, name=name) # create batch queue return tf.train.shuffle_batch(queue_list, batch_size, capacity=batch_size*128, min_after_dequeue=batch_size*32, name=name)
def dotproduct(a, b): "Calculates the dotproduct between two vecors" assert(len(a) == len(b)) out = 0 for i in range(len(a)): out += a[i] * b[i] return out
Calculates the dotproduct between two vecors
Below is the the instruction that describes the task: ### Input: Calculates the dotproduct between two vecors ### Response: def dotproduct(a, b): "Calculates the dotproduct between two vecors" assert(len(a) == len(b)) out = 0 for i in range(len(a)): out += a[i] * b[i] return out
def _build_env(venv_dir): """Create a new virtual environment in `venv_dir`. This uses the base prefix of any virtual environment that you may be using when you call this. """ # NB: We had to create the because the venv modules wasn't doing what we # needed. In particular, if we used it create a venv from an existing venv, # it *always* created symlinks back to the original venv's python # executables. Then, when you used those linked executables, you ended up # interacting with the original venv. I could find no way around this, hence # this function. prefix = getattr(sys, 'real_prefix', sys.prefix) python = Path(prefix) / 'bin' / 'python' command = '{} -m venv {}'.format(python, venv_dir) try: log.info('Creating virtual environment: %s', command) subprocess.run(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True) except subprocess.CalledProcessError as exc: log.error("Error creating virtual environment: %s", exc.output) raise
Create a new virtual environment in `venv_dir`. This uses the base prefix of any virtual environment that you may be using when you call this.
Below is the the instruction that describes the task: ### Input: Create a new virtual environment in `venv_dir`. This uses the base prefix of any virtual environment that you may be using when you call this. ### Response: def _build_env(venv_dir): """Create a new virtual environment in `venv_dir`. This uses the base prefix of any virtual environment that you may be using when you call this. """ # NB: We had to create the because the venv modules wasn't doing what we # needed. In particular, if we used it create a venv from an existing venv, # it *always* created symlinks back to the original venv's python # executables. Then, when you used those linked executables, you ended up # interacting with the original venv. I could find no way around this, hence # this function. prefix = getattr(sys, 'real_prefix', sys.prefix) python = Path(prefix) / 'bin' / 'python' command = '{} -m venv {}'.format(python, venv_dir) try: log.info('Creating virtual environment: %s', command) subprocess.run(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True) except subprocess.CalledProcessError as exc: log.error("Error creating virtual environment: %s", exc.output) raise
def dfs_do_func_on_graph(node, func, *args, **kwargs): ''' invoke func on each node of the dr graph ''' for _node in node.tree_iterator(): func(_node, *args, **kwargs)
invoke func on each node of the dr graph
Below is the the instruction that describes the task: ### Input: invoke func on each node of the dr graph ### Response: def dfs_do_func_on_graph(node, func, *args, **kwargs): ''' invoke func on each node of the dr graph ''' for _node in node.tree_iterator(): func(_node, *args, **kwargs)
def get_canonical_and_alternates_urls( url, drop_ln=True, washed_argd=None, quote_path=False): """ Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given C{url} is quoted according to RFC 2396 """ dummy_scheme, dummy_netloc, path, dummy_params, query, fragment = urlparse( url) canonical_scheme, canonical_netloc = urlparse(cfg.get('CFG_SITE_URL'))[0:2] parsed_query = washed_argd or parse_qsl(query) no_ln_parsed_query = [(key, value) for (key, value) in parsed_query if key != 'ln'] if drop_ln: canonical_parsed_query = no_ln_parsed_query else: canonical_parsed_query = parsed_query if quote_path: path = urllib.quote(path) canonical_query = urlencode(canonical_parsed_query) canonical_url = urlunparse( (canonical_scheme, canonical_netloc, path, dummy_params, canonical_query, fragment)) alternate_urls = {} for ln in cfg.get('CFG_SITE_LANGS'): alternate_query = urlencode(no_ln_parsed_query + [('ln', ln)]) alternate_url = urlunparse( (canonical_scheme, canonical_netloc, path, dummy_params, alternate_query, fragment)) alternate_urls[ln] = alternate_url return canonical_url, alternate_urls
Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given C{url} is quoted according to RFC 2396
Below is the the instruction that describes the task: ### Input: Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given C{url} is quoted according to RFC 2396 ### Response: def get_canonical_and_alternates_urls( url, drop_ln=True, washed_argd=None, quote_path=False): """ Given an Invenio URL returns a tuple with two elements. The first is the canonical URL, that is the original URL with CFG_SITE_URL prefix, and where the ln= argument stripped. The second element element is mapping, language code -> alternate URL @param quote_path: if True, the path section of the given C{url} is quoted according to RFC 2396 """ dummy_scheme, dummy_netloc, path, dummy_params, query, fragment = urlparse( url) canonical_scheme, canonical_netloc = urlparse(cfg.get('CFG_SITE_URL'))[0:2] parsed_query = washed_argd or parse_qsl(query) no_ln_parsed_query = [(key, value) for (key, value) in parsed_query if key != 'ln'] if drop_ln: canonical_parsed_query = no_ln_parsed_query else: canonical_parsed_query = parsed_query if quote_path: path = urllib.quote(path) canonical_query = urlencode(canonical_parsed_query) canonical_url = urlunparse( (canonical_scheme, canonical_netloc, path, dummy_params, canonical_query, fragment)) alternate_urls = {} for ln in cfg.get('CFG_SITE_LANGS'): alternate_query = urlencode(no_ln_parsed_query + [('ln', ln)]) alternate_url = urlunparse( (canonical_scheme, canonical_netloc, path, dummy_params, alternate_query, fragment)) alternate_urls[ln] = alternate_url return canonical_url, alternate_urls
def _run_first(self, source_file): """Run on as first in chain.""" self.reset() self.current_encoding = self.default_encoding encoding = None try: encoding = self._detect_encoding(source_file) content = self.filter(source_file, encoding) except UnicodeDecodeError: if not encoding or encoding != self.default_encoding: content = self.filter(source_file, self.default_encoding) else: raise return content
Run on as first in chain.
Below is the the instruction that describes the task: ### Input: Run on as first in chain. ### Response: def _run_first(self, source_file): """Run on as first in chain.""" self.reset() self.current_encoding = self.default_encoding encoding = None try: encoding = self._detect_encoding(source_file) content = self.filter(source_file, encoding) except UnicodeDecodeError: if not encoding or encoding != self.default_encoding: content = self.filter(source_file, self.default_encoding) else: raise return content
def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.)
Below is the the instruction that describes the task: ### Input: List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) ### Response: def list_private_images(self, guid=None, name=None, **kwargs): """List all private images. :param string guid: filter based on GUID :param string name: filter based on name :param dict \\*\\*kwargs: response-level options (mask, limit, etc.) """ if 'mask' not in kwargs: kwargs['mask'] = IMAGE_MASK _filter = utils.NestedDict(kwargs.get('filter') or {}) if name: _filter['privateBlockDeviceTemplateGroups']['name'] = ( utils.query_filter(name)) if guid: _filter['privateBlockDeviceTemplateGroups']['globalIdentifier'] = ( utils.query_filter(guid)) kwargs['filter'] = _filter.to_dict() account = self.client['Account'] return account.getPrivateBlockDeviceTemplateGroups(**kwargs)
def datetime_string(day, month, year, hour, minute): """Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format. minute (int): Minute of the hour. Returns: str: Date in the format *YYYY-MM-DDThh:mm:ss*. """ # Overflow if hour < 0 or hour > 23: hour = 0 if minute < 0 or minute > 60: minute = 0 return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute)
Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format. minute (int): Minute of the hour. Returns: str: Date in the format *YYYY-MM-DDThh:mm:ss*.
Below is the the instruction that describes the task: ### Input: Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format. minute (int): Minute of the hour. Returns: str: Date in the format *YYYY-MM-DDThh:mm:ss*. ### Response: def datetime_string(day, month, year, hour, minute): """Build a date string using the provided day, month, year numbers. Automatically adds a leading zero to ``day`` and ``month`` if they only have one digit. Args: day (int): Day number. month(int): Month number. year(int): Year number. hour (int): Hour of the day in 24h format. minute (int): Minute of the hour. Returns: str: Date in the format *YYYY-MM-DDThh:mm:ss*. """ # Overflow if hour < 0 or hour > 23: hour = 0 if minute < 0 or minute > 60: minute = 0 return '%d-%02d-%02dT%02d:%02d:00' % (year, month, day, hour, minute)
def rsquare(obsvalues, # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ): # type: (...) -> Union[float, numpy.ScalarType] """Calculate Coefficient of determination. Same as the square of the Pearson correlation coefficient (r), and, the same as the built-in Excel function RSQ(). Programmed according to equation (1) in Legates, D.R. and G.J. McCabe, 1999. Evaluating the use of "goodness of fit" measures in hydrologic and hydroclimatic model variation. Water Resources Research 35:233-241. Args: obsvalues: observe values array simvalues: simulate values array Examples: >>> obs = [2.92, 2.75, 2.01, 1.09, 2.87, 1.43, 1.96,\ 4.00, 2.24, 29.28, 5.88, 0.86, 13.21] >>> sim = [2.90, 2.87, 2.85, 2.83, 3.04, 2.81, 2.85,\ 2.78, 2.76, 13.40, 2.70, 2.09, 1.62] >>> MathClass.rsquare(obs, sim) # doctest: +ELLIPSIS 0.7528851650345053... Returns: R-square value, or raise exception """ if len(obsvalues) != len(simvalues): raise ValueError("The size of observed and simulated values must be " "the same for R-square calculation!") if not isinstance(obsvalues, numpy.ndarray): obsvalues = numpy.array(obsvalues) if not isinstance(simvalues, numpy.ndarray): simvalues = numpy.array(simvalues) obs_avg = numpy.mean(obsvalues) pred_avg = numpy.mean(simvalues) obs_minus_avg_sq = numpy.sum((obsvalues - obs_avg) ** 2) pred_minus_avg_sq = numpy.sum((simvalues - pred_avg) ** 2) obs_pred_minus_avgs = numpy.sum((obsvalues - obs_avg) * (simvalues - pred_avg)) # Calculate R-square yy = obs_minus_avg_sq ** 0.5 * pred_minus_avg_sq ** 0.5 if MathClass.floatequal(yy, 0.): return 1. return (obs_pred_minus_avgs / yy) ** 2.
Calculate Coefficient of determination. Same as the square of the Pearson correlation coefficient (r), and, the same as the built-in Excel function RSQ(). Programmed according to equation (1) in Legates, D.R. and G.J. McCabe, 1999. Evaluating the use of "goodness of fit" measures in hydrologic and hydroclimatic model variation. Water Resources Research 35:233-241. Args: obsvalues: observe values array simvalues: simulate values array Examples: >>> obs = [2.92, 2.75, 2.01, 1.09, 2.87, 1.43, 1.96,\ 4.00, 2.24, 29.28, 5.88, 0.86, 13.21] >>> sim = [2.90, 2.87, 2.85, 2.83, 3.04, 2.81, 2.85,\ 2.78, 2.76, 13.40, 2.70, 2.09, 1.62] >>> MathClass.rsquare(obs, sim) # doctest: +ELLIPSIS 0.7528851650345053... Returns: R-square value, or raise exception
Below is the the instruction that describes the task: ### Input: Calculate Coefficient of determination. Same as the square of the Pearson correlation coefficient (r), and, the same as the built-in Excel function RSQ(). Programmed according to equation (1) in Legates, D.R. and G.J. McCabe, 1999. Evaluating the use of "goodness of fit" measures in hydrologic and hydroclimatic model variation. Water Resources Research 35:233-241. Args: obsvalues: observe values array simvalues: simulate values array Examples: >>> obs = [2.92, 2.75, 2.01, 1.09, 2.87, 1.43, 1.96,\ 4.00, 2.24, 29.28, 5.88, 0.86, 13.21] >>> sim = [2.90, 2.87, 2.85, 2.83, 3.04, 2.81, 2.85,\ 2.78, 2.76, 13.40, 2.70, 2.09, 1.62] >>> MathClass.rsquare(obs, sim) # doctest: +ELLIPSIS 0.7528851650345053... Returns: R-square value, or raise exception ### Response: def rsquare(obsvalues, # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ): # type: (...) -> Union[float, numpy.ScalarType] """Calculate Coefficient of determination. Same as the square of the Pearson correlation coefficient (r), and, the same as the built-in Excel function RSQ(). Programmed according to equation (1) in Legates, D.R. and G.J. McCabe, 1999. Evaluating the use of "goodness of fit" measures in hydrologic and hydroclimatic model variation. Water Resources Research 35:233-241. Args: obsvalues: observe values array simvalues: simulate values array Examples: >>> obs = [2.92, 2.75, 2.01, 1.09, 2.87, 1.43, 1.96,\ 4.00, 2.24, 29.28, 5.88, 0.86, 13.21] >>> sim = [2.90, 2.87, 2.85, 2.83, 3.04, 2.81, 2.85,\ 2.78, 2.76, 13.40, 2.70, 2.09, 1.62] >>> MathClass.rsquare(obs, sim) # doctest: +ELLIPSIS 0.7528851650345053... Returns: R-square value, or raise exception """ if len(obsvalues) != len(simvalues): raise ValueError("The size of observed and simulated values must be " "the same for R-square calculation!") if not isinstance(obsvalues, numpy.ndarray): obsvalues = numpy.array(obsvalues) if not isinstance(simvalues, numpy.ndarray): simvalues = numpy.array(simvalues) obs_avg = numpy.mean(obsvalues) pred_avg = numpy.mean(simvalues) obs_minus_avg_sq = numpy.sum((obsvalues - obs_avg) ** 2) pred_minus_avg_sq = numpy.sum((simvalues - pred_avg) ** 2) obs_pred_minus_avgs = numpy.sum((obsvalues - obs_avg) * (simvalues - pred_avg)) # Calculate R-square yy = obs_minus_avg_sq ** 0.5 * pred_minus_avg_sq ** 0.5 if MathClass.floatequal(yy, 0.): return 1. return (obs_pred_minus_avgs / yy) ** 2.
def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False): """ m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs] """ abf.setsweep(sweep) if m1 is None: m1=0 else: m1=m1*abf.pointsPerSec if m2 is None: m2=-1 else: m2=m2*abf.pointsPerSec # obtain X and Y Yorig=abf.sweepY[int(m1):int(m2)] X=np.arange(len(Yorig))/abf.pointsPerSec # start by lowpass filtering (1 direction) # Klpf=kernel_gaussian(size=abf.pointsPerMs*10,forwardOnly=True) # Ylpf=np.convolve(Yorig,Klpf,mode='same') # Y=Ylpf # commit Kmb=kernel_gaussian(size=abf.pointsPerMs*10,forwardOnly=True) Ymb=np.convolve(Yorig,Kmb,mode='same') Y=Yorig-Ymb # commit #Y1=np.copy(Y) #Y[np.where(Y>0)[0]]=np.power(Y,2) #Y[np.where(Y<0)[0]]=-np.power(Y,2) # event detection thresh=5 # threshold for an event hitPos=np.where(Y>thresh)[0] # area above the threshold hitNeg=np.where(Y<-thresh)[0] # area below the threshold hitPos=np.concatenate((hitPos,[len(Y)-1])) # helps with the diff() coming up hitNeg=np.concatenate((hitNeg,[len(Y)-1])) # helps with the diff() coming up hitsPos=hitPos[np.where(np.abs(np.diff(hitPos))>10)[0]] # time point of EPSC hitsNeg=hitNeg[np.where(np.abs(np.diff(hitNeg))>10)[0]] # time point of IPSC hitsNeg=hitsNeg[1:] # often the first one is in error #print(hitsNeg[0]) if plotToo: plt.figure(figsize=(10,5)) ax1=plt.subplot(211) plt.title("sweep %d: detected %d IPSCs (red) and %d EPSCs (blue)"%(sweep,len(hitsPos),len(hitsNeg))) plt.ylabel("delta pA") plt.grid() plt.plot(X,Yorig,color='k',alpha=.5) for hit in hitsPos: plt.plot(X[hit],Yorig[hit]+20,'r.',ms=20,alpha=.5) for hit in hitsNeg: plt.plot(X[hit],Yorig[hit]-20,'b.',ms=20,alpha=.5) plt.margins(0,.1) plt.subplot(212,sharex=ax1) plt.title("moving gaussian baseline subtraction used for threshold detection") plt.ylabel("delta pA") plt.grid() plt.axhline(thresh,color='r',ls='--',alpha=.5,lw=3) plt.axhline(-thresh,color='r',ls='--',alpha=.5,lw=3) plt.plot(X,Y,color='b',alpha=.5) plt.axis([X[0],X[-1],-thresh*1.5,thresh*1.5]) plt.tight_layout() if type(plotToo) is str and os.path.isdir(plotToo): print('saving %s/%05d.jpg'%(plotToo,sweep)) plt.savefig(plotToo+"/%05d.jpg"%sweep) else: plt.show() plt.close('all') return [len(hitsPos),len(hitsNeg)]
m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs]
Below is the the instruction that describes the task: ### Input: m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs] ### Response: def analyzeSweep(abf,sweep,m1=None,m2=None,plotToo=False): """ m1 and m2, if given, are in seconds. returns [# EPSCs, # IPSCs] """ abf.setsweep(sweep) if m1 is None: m1=0 else: m1=m1*abf.pointsPerSec if m2 is None: m2=-1 else: m2=m2*abf.pointsPerSec # obtain X and Y Yorig=abf.sweepY[int(m1):int(m2)] X=np.arange(len(Yorig))/abf.pointsPerSec # start by lowpass filtering (1 direction) # Klpf=kernel_gaussian(size=abf.pointsPerMs*10,forwardOnly=True) # Ylpf=np.convolve(Yorig,Klpf,mode='same') # Y=Ylpf # commit Kmb=kernel_gaussian(size=abf.pointsPerMs*10,forwardOnly=True) Ymb=np.convolve(Yorig,Kmb,mode='same') Y=Yorig-Ymb # commit #Y1=np.copy(Y) #Y[np.where(Y>0)[0]]=np.power(Y,2) #Y[np.where(Y<0)[0]]=-np.power(Y,2) # event detection thresh=5 # threshold for an event hitPos=np.where(Y>thresh)[0] # area above the threshold hitNeg=np.where(Y<-thresh)[0] # area below the threshold hitPos=np.concatenate((hitPos,[len(Y)-1])) # helps with the diff() coming up hitNeg=np.concatenate((hitNeg,[len(Y)-1])) # helps with the diff() coming up hitsPos=hitPos[np.where(np.abs(np.diff(hitPos))>10)[0]] # time point of EPSC hitsNeg=hitNeg[np.where(np.abs(np.diff(hitNeg))>10)[0]] # time point of IPSC hitsNeg=hitsNeg[1:] # often the first one is in error #print(hitsNeg[0]) if plotToo: plt.figure(figsize=(10,5)) ax1=plt.subplot(211) plt.title("sweep %d: detected %d IPSCs (red) and %d EPSCs (blue)"%(sweep,len(hitsPos),len(hitsNeg))) plt.ylabel("delta pA") plt.grid() plt.plot(X,Yorig,color='k',alpha=.5) for hit in hitsPos: plt.plot(X[hit],Yorig[hit]+20,'r.',ms=20,alpha=.5) for hit in hitsNeg: plt.plot(X[hit],Yorig[hit]-20,'b.',ms=20,alpha=.5) plt.margins(0,.1) plt.subplot(212,sharex=ax1) plt.title("moving gaussian baseline subtraction used for threshold detection") plt.ylabel("delta pA") plt.grid() plt.axhline(thresh,color='r',ls='--',alpha=.5,lw=3) plt.axhline(-thresh,color='r',ls='--',alpha=.5,lw=3) plt.plot(X,Y,color='b',alpha=.5) plt.axis([X[0],X[-1],-thresh*1.5,thresh*1.5]) plt.tight_layout() if type(plotToo) is str and os.path.isdir(plotToo): print('saving %s/%05d.jpg'%(plotToo,sweep)) plt.savefig(plotToo+"/%05d.jpg"%sweep) else: plt.show() plt.close('all') return [len(hitsPos),len(hitsNeg)]
def create_html_from_fragment(tag): """ Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not Args: tag: a bs4.element.Tag Returns:" bs4.element.Tag: A bs4 tag representing a full html document """ try: assert isinstance(tag, bs4.element.Tag) except AssertionError: raise TypeError try: assert tag.find_all('body') == [] except AssertionError: raise ValueError soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser') soup.body.append(tag) return soup
Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not Args: tag: a bs4.element.Tag Returns:" bs4.element.Tag: A bs4 tag representing a full html document
Below is the the instruction that describes the task: ### Input: Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not Args: tag: a bs4.element.Tag Returns:" bs4.element.Tag: A bs4 tag representing a full html document ### Response: def create_html_from_fragment(tag): """ Creates full html tree from a fragment. Assumes that tag should be wrapped in a body and is currently not Args: tag: a bs4.element.Tag Returns:" bs4.element.Tag: A bs4 tag representing a full html document """ try: assert isinstance(tag, bs4.element.Tag) except AssertionError: raise TypeError try: assert tag.find_all('body') == [] except AssertionError: raise ValueError soup = BeautifulSoup('<html><head></head><body></body></html>', 'html.parser') soup.body.append(tag) return soup
def read_cal(cal_yaml_path): '''Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data ''' from collections import OrderedDict import datetime import os import warnings import yamlord from . import utils def __create_cal(cal_yaml_path): cal_dict = OrderedDict() # Add experiment name for calibration reference base_path, _ = os.path.split(cal_yaml_path) _, exp_name = os.path.split(base_path) cal_dict['experiment'] = exp_name return cal_dict # Try reading cal file, else create if os.path.isfile(cal_yaml_path): cal_dict = yamlord.read_yaml(cal_yaml_path) else: cal_dict = __create_cal(cal_yaml_path) cal_dict['parameters'] = OrderedDict() for key, val in utils.parse_experiment_params(cal_dict['experiment']).items(): cal_dict[key] = val fmt = "%Y-%m-%d %H:%M:%S" cal_dict['date_modified'] = datetime.datetime.now().strftime(fmt) return cal_dict
Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data
Below is the the instruction that describes the task: ### Input: Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data ### Response: def read_cal(cal_yaml_path): '''Load calibration file if exists, else create Args ---- cal_yaml_path: str Path to calibration YAML file Returns ------- cal_dict: dict Key value pairs of calibration meta data ''' from collections import OrderedDict import datetime import os import warnings import yamlord from . import utils def __create_cal(cal_yaml_path): cal_dict = OrderedDict() # Add experiment name for calibration reference base_path, _ = os.path.split(cal_yaml_path) _, exp_name = os.path.split(base_path) cal_dict['experiment'] = exp_name return cal_dict # Try reading cal file, else create if os.path.isfile(cal_yaml_path): cal_dict = yamlord.read_yaml(cal_yaml_path) else: cal_dict = __create_cal(cal_yaml_path) cal_dict['parameters'] = OrderedDict() for key, val in utils.parse_experiment_params(cal_dict['experiment']).items(): cal_dict[key] = val fmt = "%Y-%m-%d %H:%M:%S" cal_dict['date_modified'] = datetime.datetime.now().strftime(fmt) return cal_dict
def __set_last_page_screenshot(self): """ self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot log files """ if not self.__last_page_screenshot and ( not self.__last_page_screenshot_png): try: element = self.driver.find_element_by_tag_name('body') if self.is_pytest and self.report_on: self.__last_page_screenshot_png = ( self.driver.get_screenshot_as_png()) self.__last_page_screenshot = element.screenshot_as_base64 else: self.__last_page_screenshot_png = element.screenshot_as_png except Exception: if not self.__last_page_screenshot: if self.is_pytest and self.report_on: try: self.__last_page_screenshot = ( self.driver.get_screenshot_as_base64()) except Exception: pass if not self.__last_page_screenshot_png: try: self.__last_page_screenshot_png = ( self.driver.get_screenshot_as_png()) except Exception: pass
self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot log files
Below is the the instruction that describes the task: ### Input: self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot log files ### Response: def __set_last_page_screenshot(self): """ self.__last_page_screenshot is only for pytest html report logs self.__last_page_screenshot_png is for all screenshot log files """ if not self.__last_page_screenshot and ( not self.__last_page_screenshot_png): try: element = self.driver.find_element_by_tag_name('body') if self.is_pytest and self.report_on: self.__last_page_screenshot_png = ( self.driver.get_screenshot_as_png()) self.__last_page_screenshot = element.screenshot_as_base64 else: self.__last_page_screenshot_png = element.screenshot_as_png except Exception: if not self.__last_page_screenshot: if self.is_pytest and self.report_on: try: self.__last_page_screenshot = ( self.driver.get_screenshot_as_base64()) except Exception: pass if not self.__last_page_screenshot_png: try: self.__last_page_screenshot_png = ( self.driver.get_screenshot_as_png()) except Exception: pass
def dvcrss(s1, s2): """ Compute the cross product of two 3-dimensional vectors and the derivative of this cross product. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of floats :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of floats :return: State associated with cross product of positions. :rtype: 6-Element Array of floats """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) sout = stypes.emptyDoubleVector(6) libspice.dvcrss_c(s1, s2, sout) return stypes.cVectorToPython(sout)
Compute the cross product of two 3-dimensional vectors and the derivative of this cross product. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of floats :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of floats :return: State associated with cross product of positions. :rtype: 6-Element Array of floats
Below is the the instruction that describes the task: ### Input: Compute the cross product of two 3-dimensional vectors and the derivative of this cross product. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of floats :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of floats :return: State associated with cross product of positions. :rtype: 6-Element Array of floats ### Response: def dvcrss(s1, s2): """ Compute the cross product of two 3-dimensional vectors and the derivative of this cross product. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvcrss_c.html :param s1: Left hand state for cross product and derivative. :type s1: 6-Element Array of floats :param s2: Right hand state for cross product and derivative. :type s2: 6-Element Array of floats :return: State associated with cross product of positions. :rtype: 6-Element Array of floats """ assert len(s1) is 6 and len(s2) is 6 s1 = stypes.toDoubleVector(s1) s2 = stypes.toDoubleVector(s2) sout = stypes.emptyDoubleVector(6) libspice.dvcrss_c(s1, s2, sout) return stypes.cVectorToPython(sout)
def register_text_type(content_type, default_encoding, dumper, loader): """ Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dictionary. Calling convention: ``dumper(obj_dict).encode(encoding) -> bytes`` :param loader: called to encode a dictionary to a string. Calling convention: ``loader(obj_bytes.decode(encoding)) -> dict`` The decoding of a text content body takes into account decoding the binary request body into a string before calling the underlying dump/load routines. """ content_type = headers.parse_content_type(content_type) content_type.parameters.clear() key = str(content_type) _content_types[key] = content_type handler = _content_handlers.setdefault(key, _ContentHandler(key)) handler.dict_to_string = dumper handler.string_to_dict = loader handler.default_encoding = default_encoding or handler.default_encoding
Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dictionary. Calling convention: ``dumper(obj_dict).encode(encoding) -> bytes`` :param loader: called to encode a dictionary to a string. Calling convention: ``loader(obj_bytes.decode(encoding)) -> dict`` The decoding of a text content body takes into account decoding the binary request body into a string before calling the underlying dump/load routines.
Below is the the instruction that describes the task: ### Input: Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dictionary. Calling convention: ``dumper(obj_dict).encode(encoding) -> bytes`` :param loader: called to encode a dictionary to a string. Calling convention: ``loader(obj_bytes.decode(encoding)) -> dict`` The decoding of a text content body takes into account decoding the binary request body into a string before calling the underlying dump/load routines. ### Response: def register_text_type(content_type, default_encoding, dumper, loader): """ Register handling for a text-based content type. :param str content_type: content type to register the hooks for :param str default_encoding: encoding to use if none is present in the request :param dumper: called to decode a string into a dictionary. Calling convention: ``dumper(obj_dict).encode(encoding) -> bytes`` :param loader: called to encode a dictionary to a string. Calling convention: ``loader(obj_bytes.decode(encoding)) -> dict`` The decoding of a text content body takes into account decoding the binary request body into a string before calling the underlying dump/load routines. """ content_type = headers.parse_content_type(content_type) content_type.parameters.clear() key = str(content_type) _content_types[key] = content_type handler = _content_handlers.setdefault(key, _ContentHandler(key)) handler.dict_to_string = dumper handler.string_to_dict = loader handler.default_encoding = default_encoding or handler.default_encoding
def from_dict(config_cls, dictionary, validate=False): """ Loads an instance of ``config_cls`` from a dictionary. :param type config_cls: The class to build an instance of :param dict dictionary: The dictionary to load from :param bool validate: Preforms validation before building ``config_cls``, defaults to False, optional :return: An instance of ``config_cls`` :rtype: object """ return _build(config_cls, dictionary, validate=validate)
Loads an instance of ``config_cls`` from a dictionary. :param type config_cls: The class to build an instance of :param dict dictionary: The dictionary to load from :param bool validate: Preforms validation before building ``config_cls``, defaults to False, optional :return: An instance of ``config_cls`` :rtype: object
Below is the the instruction that describes the task: ### Input: Loads an instance of ``config_cls`` from a dictionary. :param type config_cls: The class to build an instance of :param dict dictionary: The dictionary to load from :param bool validate: Preforms validation before building ``config_cls``, defaults to False, optional :return: An instance of ``config_cls`` :rtype: object ### Response: def from_dict(config_cls, dictionary, validate=False): """ Loads an instance of ``config_cls`` from a dictionary. :param type config_cls: The class to build an instance of :param dict dictionary: The dictionary to load from :param bool validate: Preforms validation before building ``config_cls``, defaults to False, optional :return: An instance of ``config_cls`` :rtype: object """ return _build(config_cls, dictionary, validate=validate)
def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]: """Return a dictionary describing the method. This can be used to dump the information into a JSON file. """ return { "service": self.service.name, **self.signature.serialize(), }
Return a dictionary describing the method. This can be used to dump the information into a JSON file.
Below is the the instruction that describes the task: ### Input: Return a dictionary describing the method. This can be used to dump the information into a JSON file. ### Response: def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]: """Return a dictionary describing the method. This can be used to dump the information into a JSON file. """ return { "service": self.service.name, **self.signature.serialize(), }
def is_rpm_installed(): """Tests if the rpm command is present.""" try: version_result = subprocess.run(["rpm", "--usage"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rpm_installed = not version_result.returncode except FileNotFoundError: rpm_installed = False return rpm_installed
Tests if the rpm command is present.
Below is the the instruction that describes the task: ### Input: Tests if the rpm command is present. ### Response: def is_rpm_installed(): """Tests if the rpm command is present.""" try: version_result = subprocess.run(["rpm", "--usage"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) rpm_installed = not version_result.returncode except FileNotFoundError: rpm_installed = False return rpm_installed
def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0): """Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tensor of shape [...]. """ vocab_size = vocab_size or common_layers.shape_list(x)[-1] if sampling_method == "random" and temperature > 0.0: samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]) / temperature, 1) else: samples = tf.argmax(x, axis=-1) reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1]) return reshaped_samples
Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tensor of shape [...].
Below is the the instruction that describes the task: ### Input: Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tensor of shape [...]. ### Response: def multinomial_sample(x, vocab_size=None, sampling_method="random", temperature=1.0): """Multinomial sampling from a n-dimensional tensor. Args: x: Tensor of shape [..., vocab_size]. Parameterizes logits of multinomial. vocab_size: Number of classes in multinomial distribution. sampling_method: String, "random" or otherwise deterministic. temperature: Positive float. Returns: Tensor of shape [...]. """ vocab_size = vocab_size or common_layers.shape_list(x)[-1] if sampling_method == "random" and temperature > 0.0: samples = tf.multinomial(tf.reshape(x, [-1, vocab_size]) / temperature, 1) else: samples = tf.argmax(x, axis=-1) reshaped_samples = tf.reshape(samples, common_layers.shape_list(x)[:-1]) return reshaped_samples
def normalize_pts(pts, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [(x * scaler, ymax - (y * scaler)) for x, y in pts]
scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left)
Below is the the instruction that describes the task: ### Input: scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) ### Response: def normalize_pts(pts, ymax, scaler=2): """ scales all coordinates and flip y axis due to different origin coordinates (top left vs. bottom left) """ return [(x * scaler, ymax - (y * scaler)) for x, y in pts]
def p_scope(p): """scope : ',' SCOPE '(' metaElementList ')'""" slist = p[4] scopes = OrderedDict() for i in ('CLASS', 'ASSOCIATION', 'INDICATION', 'PROPERTY', 'REFERENCE', 'METHOD', 'PARAMETER', 'ANY'): scopes[i] = i in slist p[0] = scopes
scope : ',' SCOPE '(' metaElementList ')
Below is the the instruction that describes the task: ### Input: scope : ',' SCOPE '(' metaElementList ') ### Response: def p_scope(p): """scope : ',' SCOPE '(' metaElementList ')'""" slist = p[4] scopes = OrderedDict() for i in ('CLASS', 'ASSOCIATION', 'INDICATION', 'PROPERTY', 'REFERENCE', 'METHOD', 'PARAMETER', 'ANY'): scopes[i] = i in slist p[0] = scopes
def start_all_linking(self, link_type, group_id): """Start all linking""" self.logger.info("Start_all_linking for device %s type %s group %s", self.device_id, link_type, group_id) self.hub.direct_command(self.device_id, '02', '64' + link_type + group_id)
Start all linking
Below is the the instruction that describes the task: ### Input: Start all linking ### Response: def start_all_linking(self, link_type, group_id): """Start all linking""" self.logger.info("Start_all_linking for device %s type %s group %s", self.device_id, link_type, group_id) self.hub.direct_command(self.device_id, '02', '64' + link_type + group_id)
def prepare(self, data): """Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ ret = self.cache.get(data) if ret is not None: return ret result = self.map(data) if self.normalization: result = self.normalization(result) result = self.prohibit(result) result = self.check_unassigned(result) if self.bidi: result = self.check_bidi(result) if isinstance(result, list): result = u"".join() if len(self.cache_items) >= _stringprep_cache_size: remove = self.cache_items[: -_stringprep_cache_size // 2] for profile, key in remove: try: del profile.cache[key] except KeyError: pass self.cache_items[:] = self.cache_items[ -_stringprep_cache_size // 2 :] self.cache_items.append((self, data)) self.cache[data] = result return result
Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails
Below is the the instruction that describes the task: ### Input: Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails ### Response: def prepare(self, data): """Complete string preparation procedure for 'stored' strings. (includes checks for unassigned codes) :Parameters: - `data`: Unicode string to prepare. :return: prepared string :raise StringprepError: if the preparation fails """ ret = self.cache.get(data) if ret is not None: return ret result = self.map(data) if self.normalization: result = self.normalization(result) result = self.prohibit(result) result = self.check_unassigned(result) if self.bidi: result = self.check_bidi(result) if isinstance(result, list): result = u"".join() if len(self.cache_items) >= _stringprep_cache_size: remove = self.cache_items[: -_stringprep_cache_size // 2] for profile, key in remove: try: del profile.cache[key] except KeyError: pass self.cache_items[:] = self.cache_items[ -_stringprep_cache_size // 2 :] self.cache_items.append((self, data)) self.cache[data] = result return result
def deregister_image(self, ami_id, region='us-east-1'): """ Deregister an AMI by id :param ami_id: :param region: region to deregister from :return: """ deregister_cmd = "aws ec2 --profile {} --region {} deregister-image --image-id {}"\ .format(self.aws_project, region, ami_id) print "De-registering old image, now that the new one exists." print "De-registering cmd: {}".format(deregister_cmd) res = subprocess.check_output(shlex.split(deregister_cmd)) print "Response: {}".format(res) print "Not monitoring de-register command"
Deregister an AMI by id :param ami_id: :param region: region to deregister from :return:
Below is the the instruction that describes the task: ### Input: Deregister an AMI by id :param ami_id: :param region: region to deregister from :return: ### Response: def deregister_image(self, ami_id, region='us-east-1'): """ Deregister an AMI by id :param ami_id: :param region: region to deregister from :return: """ deregister_cmd = "aws ec2 --profile {} --region {} deregister-image --image-id {}"\ .format(self.aws_project, region, ami_id) print "De-registering old image, now that the new one exists." print "De-registering cmd: {}".format(deregister_cmd) res = subprocess.check_output(shlex.split(deregister_cmd)) print "Response: {}".format(res) print "Not monitoring de-register command"
def total_duration(self) -> datetime.timedelta: """ Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware! """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration() return total
Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware!
Below is the the instruction that describes the task: ### Input: Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware! ### Response: def total_duration(self) -> datetime.timedelta: """ Returns a ``datetime.timedelta`` object with the total sum of durations. If there is overlap, time will be double-counted, so beware! """ total = datetime.timedelta() for interval in self.intervals: total += interval.duration() return total
def revoke_access_token(self, **kwargs): """Revoke access token.""" c = self.get_credentials() data = { 'client_id': c.client_id, 'client_secret': c.client_secret, 'token': c.access_token, 'token_type_hint': 'access_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RevokeToken', **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) return r_json
Revoke access token.
Below is the the instruction that describes the task: ### Input: Revoke access token. ### Response: def revoke_access_token(self, **kwargs): """Revoke access token.""" c = self.get_credentials() data = { 'client_id': c.client_id, 'client_secret': c.client_secret, 'token': c.access_token, 'token_type_hint': 'access_token' } r = self._httpclient.request( method='POST', url=self.token_url, json=data, path='/api/oauth2/RevokeToken', **kwargs ) if not r.ok: raise PanCloudError( '%s %s: %s' % (r.status_code, r.reason, r.text) ) try: r_json = r.json() except ValueError as e: raise PanCloudError("Invalid JSON: %s" % e) else: if r.json().get( 'error_description' ) or r.json().get( 'error' ): raise PanCloudError(r.text) return r_json
def get_local_part(value): """ local-part = dot-atom / quoted-string / obs-local-part """ local_part = LocalPart() leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(value) except errors.HeaderParseError: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] != '\\' and value[0] in PHRASE_ENDS: raise token = TokenList() if leader is not None: token[:0] = [leader] local_part.append(token) if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): obs_local_part, value = get_obs_local_part(str(local_part) + value) if obs_local_part.token_type == 'invalid-obs-local-part': local_part.defects.append(errors.InvalidHeaderDefect( "local-part is not dot-atom, quoted-string, or obs-local-part")) else: local_part.defects.append(errors.ObsoleteHeaderDefect( "local-part is not a dot-atom (contains CFWS)")) local_part[0] = obs_local_part try: local_part.value.encode('ascii') except UnicodeEncodeError: local_part.defects.append(errors.NonASCIILocalPartDefect( "local-part contains non-ASCII characters)")) return local_part, value
local-part = dot-atom / quoted-string / obs-local-part
Below is the the instruction that describes the task: ### Input: local-part = dot-atom / quoted-string / obs-local-part ### Response: def get_local_part(value): """ local-part = dot-atom / quoted-string / obs-local-part """ local_part = LocalPart() leader = None if value[0] in CFWS_LEADER: leader, value = get_cfws(value) if not value: raise errors.HeaderParseError( "expected local-part but found '{}'".format(value)) try: token, value = get_dot_atom(value) except errors.HeaderParseError: try: token, value = get_word(value) except errors.HeaderParseError: if value[0] != '\\' and value[0] in PHRASE_ENDS: raise token = TokenList() if leader is not None: token[:0] = [leader] local_part.append(token) if value and (value[0]=='\\' or value[0] not in PHRASE_ENDS): obs_local_part, value = get_obs_local_part(str(local_part) + value) if obs_local_part.token_type == 'invalid-obs-local-part': local_part.defects.append(errors.InvalidHeaderDefect( "local-part is not dot-atom, quoted-string, or obs-local-part")) else: local_part.defects.append(errors.ObsoleteHeaderDefect( "local-part is not a dot-atom (contains CFWS)")) local_part[0] = obs_local_part try: local_part.value.encode('ascii') except UnicodeEncodeError: local_part.defects.append(errors.NonASCIILocalPartDefect( "local-part contains non-ASCII characters)")) return local_part, value
def copy_security(source, target, obj_type='file', copy_owner=True, copy_group=True, copy_dacl=True, copy_sacl=True): r''' Copy the security descriptor of the Source to the Target. You can specify a specific portion of the security descriptor to copy using one of the `copy_*` parameters. .. note:: At least one `copy_*` parameter must be ``True`` .. note:: The user account running this command must have the following privileges: - SeTakeOwnershipPrivilege - SeRestorePrivilege - SeSecurityPrivilege Args: source (str): The full path to the source. This is where the security info will be copied from target (str): The full path to the target. This is where the security info will be applied obj_type (str): file The type of object to query. This value changes the format of the ``obj_name`` parameter as follows: - file: indicates a file or directory - a relative path, such as ``FileName.txt`` or ``..\FileName`` - an absolute path, such as ``C:\DirName\FileName.txt`` - A UNC name, such as ``\\ServerName\ShareName\FileName.txt`` - service: indicates the name of a Windows service - printer: indicates the name of a printer - registry: indicates a registry key - Uses the following literal strings to denote the hive: - HKEY_LOCAL_MACHINE - MACHINE - HKLM - HKEY_USERS - USERS - HKU - HKEY_CURRENT_USER - CURRENT_USER - HKCU - HKEY_CLASSES_ROOT - CLASSES_ROOT - HKCR - Should be in the format of ``HIVE\Path\To\Key``. For example, ``HKLM\SOFTWARE\Windows`` - registry32: indicates a registry key under WOW64. Formatting is the same as it is for ``registry`` - share: indicates a network share copy_owner (bool): True ``True`` copies owner information. Default is ``True`` copy_group (bool): True ``True`` copies group information. Default is ``True`` copy_dacl (bool): True ``True`` copies the DACL. Default is ``True`` copy_sacl (bool): True ``True`` copies the SACL. Default is ``True`` Returns: bool: ``True`` if successful Raises: SaltInvocationError: When parameters are invalid CommandExecutionError: On failure to set security Usage: .. code-block:: python salt.utils.win_dacl.copy_security( source='C:\\temp\\source_file.txt', target='C:\\temp\\target_file.txt', obj_type='file') salt.utils.win_dacl.copy_security( source='HKLM\\SOFTWARE\\salt\\test_source', target='HKLM\\SOFTWARE\\salt\\test_target', obj_type='registry', copy_owner=False) ''' obj_dacl = dacl(obj_type=obj_type) if 'registry' in obj_type.lower(): source = obj_dacl.get_reg_name(source) log.info('Source converted to: %s', source) target = obj_dacl.get_reg_name(target) log.info('Target converted to: %s', target) # Set flags try: obj_type_flag = flags().obj_type[obj_type.lower()] except KeyError: raise SaltInvocationError( 'Invalid "obj_type" passed: {0}'.format(obj_type)) security_flags = 0 if copy_owner: security_flags |= win32security.OWNER_SECURITY_INFORMATION if copy_group: security_flags |= win32security.GROUP_SECURITY_INFORMATION if copy_dacl: security_flags |= win32security.DACL_SECURITY_INFORMATION if copy_sacl: security_flags |= win32security.SACL_SECURITY_INFORMATION if not security_flags: raise SaltInvocationError( 'One of copy_owner, copy_group, copy_dacl, or copy_sacl must be ' 'True') # To set the owner to something other than the logged in user requires # SE_TAKE_OWNERSHIP_NAME and SE_RESTORE_NAME privileges # Enable them for the logged in user # Setup the privilege set new_privs = set() luid = win32security.LookupPrivilegeValue('', 'SeTakeOwnershipPrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) luid = win32security.LookupPrivilegeValue('', 'SeRestorePrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) luid = win32security.LookupPrivilegeValue('', 'SeSecurityPrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) # Get the current token p_handle = win32api.GetCurrentProcess() t_handle = win32security.OpenProcessToken( p_handle, win32security.TOKEN_ALL_ACCESS | win32con.TOKEN_ADJUST_PRIVILEGES) # Enable the privileges win32security.AdjustTokenPrivileges(t_handle, 0, new_privs) # Load object Security Info from the Source sec = win32security.GetNamedSecurityInfo( source, obj_type_flag, security_flags) # The following return None if the corresponding flag is not set sd_sid = sec.GetSecurityDescriptorOwner() sd_gid = sec.GetSecurityDescriptorGroup() sd_dacl = sec.GetSecurityDescriptorDacl() sd_sacl = sec.GetSecurityDescriptorSacl() # Set Security info on the target try: win32security.SetNamedSecurityInfo( target, obj_type_flag, security_flags, sd_sid, sd_gid, sd_dacl, sd_sacl) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to set security info: {0}'.format(exc.strerror)) return True
r''' Copy the security descriptor of the Source to the Target. You can specify a specific portion of the security descriptor to copy using one of the `copy_*` parameters. .. note:: At least one `copy_*` parameter must be ``True`` .. note:: The user account running this command must have the following privileges: - SeTakeOwnershipPrivilege - SeRestorePrivilege - SeSecurityPrivilege Args: source (str): The full path to the source. This is where the security info will be copied from target (str): The full path to the target. This is where the security info will be applied obj_type (str): file The type of object to query. This value changes the format of the ``obj_name`` parameter as follows: - file: indicates a file or directory - a relative path, such as ``FileName.txt`` or ``..\FileName`` - an absolute path, such as ``C:\DirName\FileName.txt`` - A UNC name, such as ``\\ServerName\ShareName\FileName.txt`` - service: indicates the name of a Windows service - printer: indicates the name of a printer - registry: indicates a registry key - Uses the following literal strings to denote the hive: - HKEY_LOCAL_MACHINE - MACHINE - HKLM - HKEY_USERS - USERS - HKU - HKEY_CURRENT_USER - CURRENT_USER - HKCU - HKEY_CLASSES_ROOT - CLASSES_ROOT - HKCR - Should be in the format of ``HIVE\Path\To\Key``. For example, ``HKLM\SOFTWARE\Windows`` - registry32: indicates a registry key under WOW64. Formatting is the same as it is for ``registry`` - share: indicates a network share copy_owner (bool): True ``True`` copies owner information. Default is ``True`` copy_group (bool): True ``True`` copies group information. Default is ``True`` copy_dacl (bool): True ``True`` copies the DACL. Default is ``True`` copy_sacl (bool): True ``True`` copies the SACL. Default is ``True`` Returns: bool: ``True`` if successful Raises: SaltInvocationError: When parameters are invalid CommandExecutionError: On failure to set security Usage: .. code-block:: python salt.utils.win_dacl.copy_security( source='C:\\temp\\source_file.txt', target='C:\\temp\\target_file.txt', obj_type='file') salt.utils.win_dacl.copy_security( source='HKLM\\SOFTWARE\\salt\\test_source', target='HKLM\\SOFTWARE\\salt\\test_target', obj_type='registry', copy_owner=False)
Below is the the instruction that describes the task: ### Input: r''' Copy the security descriptor of the Source to the Target. You can specify a specific portion of the security descriptor to copy using one of the `copy_*` parameters. .. note:: At least one `copy_*` parameter must be ``True`` .. note:: The user account running this command must have the following privileges: - SeTakeOwnershipPrivilege - SeRestorePrivilege - SeSecurityPrivilege Args: source (str): The full path to the source. This is where the security info will be copied from target (str): The full path to the target. This is where the security info will be applied obj_type (str): file The type of object to query. This value changes the format of the ``obj_name`` parameter as follows: - file: indicates a file or directory - a relative path, such as ``FileName.txt`` or ``..\FileName`` - an absolute path, such as ``C:\DirName\FileName.txt`` - A UNC name, such as ``\\ServerName\ShareName\FileName.txt`` - service: indicates the name of a Windows service - printer: indicates the name of a printer - registry: indicates a registry key - Uses the following literal strings to denote the hive: - HKEY_LOCAL_MACHINE - MACHINE - HKLM - HKEY_USERS - USERS - HKU - HKEY_CURRENT_USER - CURRENT_USER - HKCU - HKEY_CLASSES_ROOT - CLASSES_ROOT - HKCR - Should be in the format of ``HIVE\Path\To\Key``. For example, ``HKLM\SOFTWARE\Windows`` - registry32: indicates a registry key under WOW64. Formatting is the same as it is for ``registry`` - share: indicates a network share copy_owner (bool): True ``True`` copies owner information. Default is ``True`` copy_group (bool): True ``True`` copies group information. Default is ``True`` copy_dacl (bool): True ``True`` copies the DACL. Default is ``True`` copy_sacl (bool): True ``True`` copies the SACL. Default is ``True`` Returns: bool: ``True`` if successful Raises: SaltInvocationError: When parameters are invalid CommandExecutionError: On failure to set security Usage: .. code-block:: python salt.utils.win_dacl.copy_security( source='C:\\temp\\source_file.txt', target='C:\\temp\\target_file.txt', obj_type='file') salt.utils.win_dacl.copy_security( source='HKLM\\SOFTWARE\\salt\\test_source', target='HKLM\\SOFTWARE\\salt\\test_target', obj_type='registry', copy_owner=False) ### Response: def copy_security(source, target, obj_type='file', copy_owner=True, copy_group=True, copy_dacl=True, copy_sacl=True): r''' Copy the security descriptor of the Source to the Target. You can specify a specific portion of the security descriptor to copy using one of the `copy_*` parameters. .. note:: At least one `copy_*` parameter must be ``True`` .. note:: The user account running this command must have the following privileges: - SeTakeOwnershipPrivilege - SeRestorePrivilege - SeSecurityPrivilege Args: source (str): The full path to the source. This is where the security info will be copied from target (str): The full path to the target. This is where the security info will be applied obj_type (str): file The type of object to query. This value changes the format of the ``obj_name`` parameter as follows: - file: indicates a file or directory - a relative path, such as ``FileName.txt`` or ``..\FileName`` - an absolute path, such as ``C:\DirName\FileName.txt`` - A UNC name, such as ``\\ServerName\ShareName\FileName.txt`` - service: indicates the name of a Windows service - printer: indicates the name of a printer - registry: indicates a registry key - Uses the following literal strings to denote the hive: - HKEY_LOCAL_MACHINE - MACHINE - HKLM - HKEY_USERS - USERS - HKU - HKEY_CURRENT_USER - CURRENT_USER - HKCU - HKEY_CLASSES_ROOT - CLASSES_ROOT - HKCR - Should be in the format of ``HIVE\Path\To\Key``. For example, ``HKLM\SOFTWARE\Windows`` - registry32: indicates a registry key under WOW64. Formatting is the same as it is for ``registry`` - share: indicates a network share copy_owner (bool): True ``True`` copies owner information. Default is ``True`` copy_group (bool): True ``True`` copies group information. Default is ``True`` copy_dacl (bool): True ``True`` copies the DACL. Default is ``True`` copy_sacl (bool): True ``True`` copies the SACL. Default is ``True`` Returns: bool: ``True`` if successful Raises: SaltInvocationError: When parameters are invalid CommandExecutionError: On failure to set security Usage: .. code-block:: python salt.utils.win_dacl.copy_security( source='C:\\temp\\source_file.txt', target='C:\\temp\\target_file.txt', obj_type='file') salt.utils.win_dacl.copy_security( source='HKLM\\SOFTWARE\\salt\\test_source', target='HKLM\\SOFTWARE\\salt\\test_target', obj_type='registry', copy_owner=False) ''' obj_dacl = dacl(obj_type=obj_type) if 'registry' in obj_type.lower(): source = obj_dacl.get_reg_name(source) log.info('Source converted to: %s', source) target = obj_dacl.get_reg_name(target) log.info('Target converted to: %s', target) # Set flags try: obj_type_flag = flags().obj_type[obj_type.lower()] except KeyError: raise SaltInvocationError( 'Invalid "obj_type" passed: {0}'.format(obj_type)) security_flags = 0 if copy_owner: security_flags |= win32security.OWNER_SECURITY_INFORMATION if copy_group: security_flags |= win32security.GROUP_SECURITY_INFORMATION if copy_dacl: security_flags |= win32security.DACL_SECURITY_INFORMATION if copy_sacl: security_flags |= win32security.SACL_SECURITY_INFORMATION if not security_flags: raise SaltInvocationError( 'One of copy_owner, copy_group, copy_dacl, or copy_sacl must be ' 'True') # To set the owner to something other than the logged in user requires # SE_TAKE_OWNERSHIP_NAME and SE_RESTORE_NAME privileges # Enable them for the logged in user # Setup the privilege set new_privs = set() luid = win32security.LookupPrivilegeValue('', 'SeTakeOwnershipPrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) luid = win32security.LookupPrivilegeValue('', 'SeRestorePrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) luid = win32security.LookupPrivilegeValue('', 'SeSecurityPrivilege') new_privs.add((luid, win32con.SE_PRIVILEGE_ENABLED)) # Get the current token p_handle = win32api.GetCurrentProcess() t_handle = win32security.OpenProcessToken( p_handle, win32security.TOKEN_ALL_ACCESS | win32con.TOKEN_ADJUST_PRIVILEGES) # Enable the privileges win32security.AdjustTokenPrivileges(t_handle, 0, new_privs) # Load object Security Info from the Source sec = win32security.GetNamedSecurityInfo( source, obj_type_flag, security_flags) # The following return None if the corresponding flag is not set sd_sid = sec.GetSecurityDescriptorOwner() sd_gid = sec.GetSecurityDescriptorGroup() sd_dacl = sec.GetSecurityDescriptorDacl() sd_sacl = sec.GetSecurityDescriptorSacl() # Set Security info on the target try: win32security.SetNamedSecurityInfo( target, obj_type_flag, security_flags, sd_sid, sd_gid, sd_dacl, sd_sacl) except pywintypes.error as exc: raise CommandExecutionError( 'Failed to set security info: {0}'.format(exc.strerror)) return True
def extract_possible_actions(self, state_key): ''' Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)] ''' if state_key in self.__state_action_list_dict: return self.__state_action_list_dict[state_key] else: action_list = [] state_key_list = [action_list.extend(self.__state_action_list_dict[k]) for k in self.__state_action_list_dict.keys() if len([s for s in state_key if s in k]) > 0] return action_list
Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)]
Below is the the instruction that describes the task: ### Input: Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)] ### Response: def extract_possible_actions(self, state_key): ''' Concreat method. Args: state_key The key of state. this value is point in map. Returns: [(x, y)] ''' if state_key in self.__state_action_list_dict: return self.__state_action_list_dict[state_key] else: action_list = [] state_key_list = [action_list.extend(self.__state_action_list_dict[k]) for k in self.__state_action_list_dict.keys() if len([s for s in state_key if s in k]) > 0] return action_list
def _request(http, project, method, data, base_url): """Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to make the request for. :type method: str :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK. """ headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } api_url = build_api_url(project, method, base_url) response = http.request(url=api_url, method="POST", headers=headers, data=data) if response.status_code != 200: error_status = status_pb2.Status.FromString(response.content) raise exceptions.from_http_status( response.status_code, error_status.message, errors=[error_status] ) return response.content
Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to make the request for. :type method: str :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK.
Below is the the instruction that describes the task: ### Input: Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to make the request for. :type method: str :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK. ### Response: def _request(http, project, method, data, base_url): """Make a request over the Http transport to the Cloud Datastore API. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to make the request for. :type method: str :param method: The API call method name (ie, ``runQuery``, ``lookup``, etc) :type data: str :param data: The data to send with the API call. Typically this is a serialized Protobuf string. :type base_url: str :param base_url: The base URL where the API lives. :rtype: str :returns: The string response content from the API call. :raises: :class:`google.cloud.exceptions.GoogleCloudError` if the response code is not 200 OK. """ headers = { "Content-Type": "application/x-protobuf", "User-Agent": connection_module.DEFAULT_USER_AGENT, connection_module.CLIENT_INFO_HEADER: _CLIENT_INFO, } api_url = build_api_url(project, method, base_url) response = http.request(url=api_url, method="POST", headers=headers, data=data) if response.status_code != 200: error_status = status_pb2.Status.FromString(response.content) raise exceptions.from_http_status( response.status_code, error_status.message, errors=[error_status] ) return response.content
def expandpath(path): """ Expand a filesystem path that may or may not contain user/env vars. :param str path: path to expand :return str: expanded version of input path """ return os.path.expandvars(os.path.expanduser(path)).replace("//", "/")
Expand a filesystem path that may or may not contain user/env vars. :param str path: path to expand :return str: expanded version of input path
Below is the the instruction that describes the task: ### Input: Expand a filesystem path that may or may not contain user/env vars. :param str path: path to expand :return str: expanded version of input path ### Response: def expandpath(path): """ Expand a filesystem path that may or may not contain user/env vars. :param str path: path to expand :return str: expanded version of input path """ return os.path.expandvars(os.path.expanduser(path)).replace("//", "/")
def generate_schema(table, export_fields, output_format, output_fobj): """Generate table schema for a specific output format and write Current supported output formats: 'txt', 'sql' and 'django'. The table name and all fields names pass for a slugifying process (table name is taken from file name). """ if output_format in ("csv", "txt"): from rows import plugins data = [ { "field_name": fieldname, "field_type": fieldtype.__name__.replace("Field", "").lower(), } for fieldname, fieldtype in table.fields.items() if fieldname in export_fields ] table = plugins.dicts.import_from_dicts( data, import_fields=["field_name", "field_type"] ) if output_format == "txt": plugins.txt.export_to_txt(table, output_fobj) elif output_format == "csv": plugins.csv.export_to_csv(table, output_fobj) elif output_format == "sql": # TODO: may use dict from rows.plugins.sqlite or postgresql sql_fields = { rows.fields.BinaryField: "BLOB", rows.fields.BoolField: "BOOL", rows.fields.IntegerField: "INT", rows.fields.FloatField: "FLOAT", rows.fields.PercentField: "FLOAT", rows.fields.DateField: "DATE", rows.fields.DatetimeField: "DATETIME", rows.fields.TextField: "TEXT", rows.fields.DecimalField: "FLOAT", rows.fields.EmailField: "TEXT", rows.fields.JSONField: "TEXT", } fields = [ " {} {}".format(field_name, sql_fields[field_type]) for field_name, field_type in table.fields.items() if field_name in export_fields ] sql = ( dedent( """ CREATE TABLE IF NOT EXISTS {name} ( {fields} ); """ ) .strip() .format(name=table.name, fields=",\n".join(fields)) + "\n" ) output_fobj.write(sql) elif output_format == "django": django_fields = { rows.fields.BinaryField: "BinaryField", rows.fields.BoolField: "BooleanField", rows.fields.IntegerField: "IntegerField", rows.fields.FloatField: "FloatField", rows.fields.PercentField: "DecimalField", rows.fields.DateField: "DateField", rows.fields.DatetimeField: "DateTimeField", rows.fields.TextField: "TextField", rows.fields.DecimalField: "DecimalField", rows.fields.EmailField: "EmailField", rows.fields.JSONField: "JSONField", } table_name = "".join(word.capitalize() for word in table.name.split("_")) lines = ["from django.db import models"] if rows.fields.JSONField in [ table.fields[field_name] for field_name in export_fields ]: lines.append("from django.contrib.postgres.fields import JSONField") lines.append("") lines.append("class {}(models.Model):".format(table_name)) for field_name, field_type in table.fields.items(): if field_name not in export_fields: continue if field_type is not rows.fields.JSONField: django_type = "models.{}()".format(django_fields[field_type]) else: django_type = "JSONField()" lines.append(" {} = {}".format(field_name, django_type)) result = "\n".join(lines) + "\n" output_fobj.write(result)
Generate table schema for a specific output format and write Current supported output formats: 'txt', 'sql' and 'django'. The table name and all fields names pass for a slugifying process (table name is taken from file name).
Below is the the instruction that describes the task: ### Input: Generate table schema for a specific output format and write Current supported output formats: 'txt', 'sql' and 'django'. The table name and all fields names pass for a slugifying process (table name is taken from file name). ### Response: def generate_schema(table, export_fields, output_format, output_fobj): """Generate table schema for a specific output format and write Current supported output formats: 'txt', 'sql' and 'django'. The table name and all fields names pass for a slugifying process (table name is taken from file name). """ if output_format in ("csv", "txt"): from rows import plugins data = [ { "field_name": fieldname, "field_type": fieldtype.__name__.replace("Field", "").lower(), } for fieldname, fieldtype in table.fields.items() if fieldname in export_fields ] table = plugins.dicts.import_from_dicts( data, import_fields=["field_name", "field_type"] ) if output_format == "txt": plugins.txt.export_to_txt(table, output_fobj) elif output_format == "csv": plugins.csv.export_to_csv(table, output_fobj) elif output_format == "sql": # TODO: may use dict from rows.plugins.sqlite or postgresql sql_fields = { rows.fields.BinaryField: "BLOB", rows.fields.BoolField: "BOOL", rows.fields.IntegerField: "INT", rows.fields.FloatField: "FLOAT", rows.fields.PercentField: "FLOAT", rows.fields.DateField: "DATE", rows.fields.DatetimeField: "DATETIME", rows.fields.TextField: "TEXT", rows.fields.DecimalField: "FLOAT", rows.fields.EmailField: "TEXT", rows.fields.JSONField: "TEXT", } fields = [ " {} {}".format(field_name, sql_fields[field_type]) for field_name, field_type in table.fields.items() if field_name in export_fields ] sql = ( dedent( """ CREATE TABLE IF NOT EXISTS {name} ( {fields} ); """ ) .strip() .format(name=table.name, fields=",\n".join(fields)) + "\n" ) output_fobj.write(sql) elif output_format == "django": django_fields = { rows.fields.BinaryField: "BinaryField", rows.fields.BoolField: "BooleanField", rows.fields.IntegerField: "IntegerField", rows.fields.FloatField: "FloatField", rows.fields.PercentField: "DecimalField", rows.fields.DateField: "DateField", rows.fields.DatetimeField: "DateTimeField", rows.fields.TextField: "TextField", rows.fields.DecimalField: "DecimalField", rows.fields.EmailField: "EmailField", rows.fields.JSONField: "JSONField", } table_name = "".join(word.capitalize() for word in table.name.split("_")) lines = ["from django.db import models"] if rows.fields.JSONField in [ table.fields[field_name] for field_name in export_fields ]: lines.append("from django.contrib.postgres.fields import JSONField") lines.append("") lines.append("class {}(models.Model):".format(table_name)) for field_name, field_type in table.fields.items(): if field_name not in export_fields: continue if field_type is not rows.fields.JSONField: django_type = "models.{}()".format(django_fields[field_type]) else: django_type = "JSONField()" lines.append(" {} = {}".format(field_name, django_type)) result = "\n".join(lines) + "\n" output_fobj.write(result)
def get_abs_template_path(template_name, directory, extension): """ Given a template name, a directory, and an extension, return the absolute path to the template. """ # Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If there is a default extension, but no file extension, then add it file_name, file_ext = splitext(file_with_ext) if not file_ext: file_with_ext = extsep.join( (file_name, extension.replace(extsep, ''))) # Rebuild the relative path relative_path = join(directory, file_with_ext) return abspath(relative_path)
Given a template name, a directory, and an extension, return the absolute path to the template.
Below is the the instruction that describes the task: ### Input: Given a template name, a directory, and an extension, return the absolute path to the template. ### Response: def get_abs_template_path(template_name, directory, extension): """ Given a template name, a directory, and an extension, return the absolute path to the template. """ # Get the relative path relative_path = join(directory, template_name) file_with_ext = template_name if extension: # If there is a default extension, but no file extension, then add it file_name, file_ext = splitext(file_with_ext) if not file_ext: file_with_ext = extsep.join( (file_name, extension.replace(extsep, ''))) # Rebuild the relative path relative_path = join(directory, file_with_ext) return abspath(relative_path)
def file_key_regenerate( blockchain_id, hostname, config_path=CONFIG_PATH, wallet_keys=None ): """ Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error """ config_dir = os.path.dirname(config_path) current_key = file_key_lookup( blockchain_id, 0, hostname, config_path=config_path ) if 'status' in current_key and current_key['status']: # retire # NOTE: implicitly depends on this method failing only because the key doesn't exist res = file_key_retire( blockchain_id, current_key, config_path=config_path, wallet_keys=wallet_keys ) if 'error' in res: log.error("Failed to retire key %s: %s" % (current_key['key_id'], res['error'])) return {'error': 'Failed to retire key'} # make a new key res = blockstack_gpg.gpg_app_create_key( blockchain_id, "files", hostname, wallet_keys=wallet_keys, config_dir=config_dir ) if 'error' in res: log.error("Failed to generate new key: %s" % res['error']) return {'error': 'Failed to generate new key'} return {'status': True}
Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error
Below is the the instruction that describes the task: ### Input: Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error ### Response: def file_key_regenerate( blockchain_id, hostname, config_path=CONFIG_PATH, wallet_keys=None ): """ Generate a new encryption key. Retire the existing key, if it exists. Return {'status': True} on success Return {'error': ...} on error """ config_dir = os.path.dirname(config_path) current_key = file_key_lookup( blockchain_id, 0, hostname, config_path=config_path ) if 'status' in current_key and current_key['status']: # retire # NOTE: implicitly depends on this method failing only because the key doesn't exist res = file_key_retire( blockchain_id, current_key, config_path=config_path, wallet_keys=wallet_keys ) if 'error' in res: log.error("Failed to retire key %s: %s" % (current_key['key_id'], res['error'])) return {'error': 'Failed to retire key'} # make a new key res = blockstack_gpg.gpg_app_create_key( blockchain_id, "files", hostname, wallet_keys=wallet_keys, config_dir=config_dir ) if 'error' in res: log.error("Failed to generate new key: %s" % res['error']) return {'error': 'Failed to generate new key'} return {'status': True}
def tmpdir(self): """ Temporary directory holding all the runtime data. """ if self._tmpdir is None: self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp") return self._tmpdir
Temporary directory holding all the runtime data.
Below is the the instruction that describes the task: ### Input: Temporary directory holding all the runtime data. ### Response: def tmpdir(self): """ Temporary directory holding all the runtime data. """ if self._tmpdir is None: self._tmpdir = mkdtemp(prefix="colin-", dir="/var/tmp") return self._tmpdir
def creatauth(name, homedir): """ Function create user in linux for group and set homedir. Function return gid and uid.""" uid, gid = [None, None] # get information about user command = "id %s" % (name) data = commands.getstatusoutput(command) if data[0] > 0: # create new system user command = "useradd -g %s %s" % (sett.APACHEIIS_GROUP, name) #command = "useradd -g %s %s" % ("www-data",name) data = commands.getstatusoutput(command) if data[0] != 0: msg = "Error: Can't create user." sys.stderr.write(msg) # set homedir for user command = "usermod -d %s %s" % (homedir, name) data = commands.getstatusoutput(command) command = "chown %s:%s %s -R" % (name, sett.APACHEIIS_GROUP, homedir) data = commands.getstatusoutput(command) # get information about user command = "id %s" % (name) data = commands.getstatusoutput(command) # check new user and get uid, gid if data[0] > 0: msg = "Error: User not create." sys.stderr.write(msg) else: for it in data[1].split(" "): m = re.search('uid=([0-9]*)', it) try: uid = m.group(1) except: pass m = re.search('gid=([0-9]*)', it) try: gid = m.group(1) except: pass return {"uid": uid, "gid": gid} return {}
Function create user in linux for group and set homedir. Function return gid and uid.
Below is the the instruction that describes the task: ### Input: Function create user in linux for group and set homedir. Function return gid and uid. ### Response: def creatauth(name, homedir): """ Function create user in linux for group and set homedir. Function return gid and uid.""" uid, gid = [None, None] # get information about user command = "id %s" % (name) data = commands.getstatusoutput(command) if data[0] > 0: # create new system user command = "useradd -g %s %s" % (sett.APACHEIIS_GROUP, name) #command = "useradd -g %s %s" % ("www-data",name) data = commands.getstatusoutput(command) if data[0] != 0: msg = "Error: Can't create user." sys.stderr.write(msg) # set homedir for user command = "usermod -d %s %s" % (homedir, name) data = commands.getstatusoutput(command) command = "chown %s:%s %s -R" % (name, sett.APACHEIIS_GROUP, homedir) data = commands.getstatusoutput(command) # get information about user command = "id %s" % (name) data = commands.getstatusoutput(command) # check new user and get uid, gid if data[0] > 0: msg = "Error: User not create." sys.stderr.write(msg) else: for it in data[1].split(" "): m = re.search('uid=([0-9]*)', it) try: uid = m.group(1) except: pass m = re.search('gid=([0-9]*)', it) try: gid = m.group(1) except: pass return {"uid": uid, "gid": gid} return {}
def shepherd(x, y, n_boot=200): """ Shepherd's Pi correlation, equivalent to Spearman's rho after outliers removal. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. n_boot : int Number of bootstrap samples to calculate. Returns ------- r : float Pi correlation coefficient pval : float Two-tailed adjusted p-value. outliers : array of bool Indicate if value is an outlier or not Notes ----- It first bootstraps the Mahalanobis distances, removes all observations with m >= 6 and finally calculates the correlation of the remaining data. Pi is Spearman's Rho after outlier removal. """ from scipy.stats import spearmanr X = np.column_stack((x, y)) # Bootstrapping on Mahalanobis distance m = bsmahal(X, X, n_boot) # Determine outliers outliers = (m >= 6) # Compute correlation r, pval = spearmanr(x[~outliers], y[~outliers]) # (optional) double the p-value to achieve a nominal false alarm rate # pval *= 2 # pval = 1 if pval > 1 else pval return r, pval, outliers
Shepherd's Pi correlation, equivalent to Spearman's rho after outliers removal. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. n_boot : int Number of bootstrap samples to calculate. Returns ------- r : float Pi correlation coefficient pval : float Two-tailed adjusted p-value. outliers : array of bool Indicate if value is an outlier or not Notes ----- It first bootstraps the Mahalanobis distances, removes all observations with m >= 6 and finally calculates the correlation of the remaining data. Pi is Spearman's Rho after outlier removal.
Below is the the instruction that describes the task: ### Input: Shepherd's Pi correlation, equivalent to Spearman's rho after outliers removal. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. n_boot : int Number of bootstrap samples to calculate. Returns ------- r : float Pi correlation coefficient pval : float Two-tailed adjusted p-value. outliers : array of bool Indicate if value is an outlier or not Notes ----- It first bootstraps the Mahalanobis distances, removes all observations with m >= 6 and finally calculates the correlation of the remaining data. Pi is Spearman's Rho after outlier removal. ### Response: def shepherd(x, y, n_boot=200): """ Shepherd's Pi correlation, equivalent to Spearman's rho after outliers removal. Parameters ---------- x, y : array_like First and second set of observations. x and y must be independent. n_boot : int Number of bootstrap samples to calculate. Returns ------- r : float Pi correlation coefficient pval : float Two-tailed adjusted p-value. outliers : array of bool Indicate if value is an outlier or not Notes ----- It first bootstraps the Mahalanobis distances, removes all observations with m >= 6 and finally calculates the correlation of the remaining data. Pi is Spearman's Rho after outlier removal. """ from scipy.stats import spearmanr X = np.column_stack((x, y)) # Bootstrapping on Mahalanobis distance m = bsmahal(X, X, n_boot) # Determine outliers outliers = (m >= 6) # Compute correlation r, pval = spearmanr(x[~outliers], y[~outliers]) # (optional) double the p-value to achieve a nominal false alarm rate # pval *= 2 # pval = 1 if pval > 1 else pval return r, pval, outliers
def deserialize(cls, key, network="bitcoin_testnet"): """Load the ExtendedBip32Key from a hex key. The key consists of * 4 byte version bytes (network key) * 1 byte depth: - 0x00 for master nodes, - 0x01 for level-1 descendants, .... * 4 byte fingerprint of the parent's key (0x00000000 if master key) * 4 byte child number. This is the number i in x_i = x_{par}/i, with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key) * 32 bytes: the chain code * 33 bytes: the public key or private key data (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won't even generate such data.) """ network = Wallet.get_network(network) if len(key) in [78, (78 + 32)]: # we have a byte array, so pass pass else: key = ensure_bytes(key) if len(key) in [78 * 2, (78 + 32) * 2]: # we have a hexlified non-base58 key, continue! key = unhexlify(key) elif len(key) == 111: # We have a base58 encoded string key = base58.b58decode_check(key) # Now that we double checkd the values, convert back to bytes because # they're easier to slice version, depth, parent_fingerprint, child, chain_code, key_data = ( key[:4], key[4], key[5:9], key[9:13], key[13:45], key[45:]) version_long = long_or_int(hexlify(version), 16) exponent = None pubkey = None point_type = key_data[0] if not isinstance(point_type, six.integer_types): point_type = ord(point_type) if point_type == 0: # Private key if version_long != network.EXT_SECRET_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_SECRET_KEY, version) exponent = key_data[1:] elif point_type in [2, 3, 4]: # Compressed public coordinates if version_long != network.EXT_PUBLIC_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_PUBLIC_KEY, version) pubkey = PublicKey.from_hex_key(key_data, network=network) # Even though this was generated from a compressed pubkey, we # want to store it as an uncompressed pubkey pubkey.compressed = False else: raise ValueError("Invalid key_data prefix, got %s" % point_type) def l(byte_seq): if byte_seq is None: return byte_seq elif isinstance(byte_seq, six.integer_types): return byte_seq return long_or_int(hexlify(byte_seq), 16) return cls(depth=l(depth), parent_fingerprint=l(parent_fingerprint), child_number=l(child), chain_code=l(chain_code), private_exponent=l(exponent), public_key=pubkey, network=network)
Load the ExtendedBip32Key from a hex key. The key consists of * 4 byte version bytes (network key) * 1 byte depth: - 0x00 for master nodes, - 0x01 for level-1 descendants, .... * 4 byte fingerprint of the parent's key (0x00000000 if master key) * 4 byte child number. This is the number i in x_i = x_{par}/i, with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key) * 32 bytes: the chain code * 33 bytes: the public key or private key data (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won't even generate such data.)
Below is the the instruction that describes the task: ### Input: Load the ExtendedBip32Key from a hex key. The key consists of * 4 byte version bytes (network key) * 1 byte depth: - 0x00 for master nodes, - 0x01 for level-1 descendants, .... * 4 byte fingerprint of the parent's key (0x00000000 if master key) * 4 byte child number. This is the number i in x_i = x_{par}/i, with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key) * 32 bytes: the chain code * 33 bytes: the public key or private key data (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won't even generate such data.) ### Response: def deserialize(cls, key, network="bitcoin_testnet"): """Load the ExtendedBip32Key from a hex key. The key consists of * 4 byte version bytes (network key) * 1 byte depth: - 0x00 for master nodes, - 0x01 for level-1 descendants, .... * 4 byte fingerprint of the parent's key (0x00000000 if master key) * 4 byte child number. This is the number i in x_i = x_{par}/i, with x_i the key being serialized. This is encoded in MSB order. (0x00000000 if master key) * 32 bytes: the chain code * 33 bytes: the public key or private key data (0x02 + X or 0x03 + X for public keys, 0x00 + k for private keys) (Note that this also supports 0x04 + X + Y uncompressed points, but this is totally non-standard and this library won't even generate such data.) """ network = Wallet.get_network(network) if len(key) in [78, (78 + 32)]: # we have a byte array, so pass pass else: key = ensure_bytes(key) if len(key) in [78 * 2, (78 + 32) * 2]: # we have a hexlified non-base58 key, continue! key = unhexlify(key) elif len(key) == 111: # We have a base58 encoded string key = base58.b58decode_check(key) # Now that we double checkd the values, convert back to bytes because # they're easier to slice version, depth, parent_fingerprint, child, chain_code, key_data = ( key[:4], key[4], key[5:9], key[9:13], key[13:45], key[45:]) version_long = long_or_int(hexlify(version), 16) exponent = None pubkey = None point_type = key_data[0] if not isinstance(point_type, six.integer_types): point_type = ord(point_type) if point_type == 0: # Private key if version_long != network.EXT_SECRET_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_SECRET_KEY, version) exponent = key_data[1:] elif point_type in [2, 3, 4]: # Compressed public coordinates if version_long != network.EXT_PUBLIC_KEY: raise incompatible_network_exception_factory( network.NAME, network.EXT_PUBLIC_KEY, version) pubkey = PublicKey.from_hex_key(key_data, network=network) # Even though this was generated from a compressed pubkey, we # want to store it as an uncompressed pubkey pubkey.compressed = False else: raise ValueError("Invalid key_data prefix, got %s" % point_type) def l(byte_seq): if byte_seq is None: return byte_seq elif isinstance(byte_seq, six.integer_types): return byte_seq return long_or_int(hexlify(byte_seq), 16) return cls(depth=l(depth), parent_fingerprint=l(parent_fingerprint), child_number=l(child), chain_code=l(chain_code), private_exponent=l(exponent), public_key=pubkey, network=network)
def get_command_response_from_cache(self, device_id, command, command2): """Gets response""" key = self.create_key_from_command(command, command2) command_cache = self.get_cache_from_file(device_id) if device_id not in command_cache: command_cache[device_id] = {} return False elif key not in command_cache[device_id]: return False response = command_cache[device_id][key] expired = False if response['ttl'] < int(time()): self.logger.info("cache expired for device %s", device_id) expired = True if os.path.exists(LOCK_FILE): self.logger.info("cache locked - will wait to rebuild %s", device_id) else: self.logger.info("cache unlocked - will rebuild %s", device_id) newpid = os.fork() if newpid == 0: self.rebuild_cache(device_id, command, command2) if expired: self.logger.info("returning expired cached device status %s", device_id) else: self.logger.info("returning unexpired cached device status %s", device_id) return response['response']
Gets response
Below is the the instruction that describes the task: ### Input: Gets response ### Response: def get_command_response_from_cache(self, device_id, command, command2): """Gets response""" key = self.create_key_from_command(command, command2) command_cache = self.get_cache_from_file(device_id) if device_id not in command_cache: command_cache[device_id] = {} return False elif key not in command_cache[device_id]: return False response = command_cache[device_id][key] expired = False if response['ttl'] < int(time()): self.logger.info("cache expired for device %s", device_id) expired = True if os.path.exists(LOCK_FILE): self.logger.info("cache locked - will wait to rebuild %s", device_id) else: self.logger.info("cache unlocked - will rebuild %s", device_id) newpid = os.fork() if newpid == 0: self.rebuild_cache(device_id, command, command2) if expired: self.logger.info("returning expired cached device status %s", device_id) else: self.logger.info("returning unexpired cached device status %s", device_id) return response['response']
def actualize_source_type (self, sources, prop_set): """ Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets. """ assert is_iterable_typed(sources, VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) result = [] for i in sources: scanner = None # FIXME: what's this? # if isinstance (i, str): # i = self.manager_.get_object (i) if i.type (): scanner = b2.build.type.get_scanner (i.type (), prop_set) r = i.actualize (scanner) result.append (r) return result
Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets.
Below is the the instruction that describes the task: ### Input: Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets. ### Response: def actualize_source_type (self, sources, prop_set): """ Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Returns the actualized virtual targets. """ assert is_iterable_typed(sources, VirtualTarget) assert isinstance(prop_set, property_set.PropertySet) result = [] for i in sources: scanner = None # FIXME: what's this? # if isinstance (i, str): # i = self.manager_.get_object (i) if i.type (): scanner = b2.build.type.get_scanner (i.type (), prop_set) r = i.actualize (scanner) result.append (r) return result
def remove_dcm2nii_underprocessed(filepaths): """ Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion. Parameters ---------- filepaths: iterable of str Returns ------- cleaned_paths: iterable of str """ cln_flist = [] # sort them by size len_sorted = sorted(filepaths, key=len) for idx, fpath in enumerate(len_sorted): remove = False # get the basename and the rest of the files fname = op.basename(fpath) rest = len_sorted[idx+1:] # check if the basename is in the basename of the rest of the files for rest_fpath in rest: rest_file = op.basename(rest_fpath) if rest_file.endswith(fname): remove = True break if not remove: cln_flist.append(fpath) return cln_flist
Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion. Parameters ---------- filepaths: iterable of str Returns ------- cleaned_paths: iterable of str
Below is the the instruction that describes the task: ### Input: Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion. Parameters ---------- filepaths: iterable of str Returns ------- cleaned_paths: iterable of str ### Response: def remove_dcm2nii_underprocessed(filepaths): """ Return a subset of `filepaths`. Keep only the files that have a basename longer than the others with same suffix. This works based on that dcm2nii appends a preffix character for each processing step it does automatically in the DICOM to NifTI conversion. Parameters ---------- filepaths: iterable of str Returns ------- cleaned_paths: iterable of str """ cln_flist = [] # sort them by size len_sorted = sorted(filepaths, key=len) for idx, fpath in enumerate(len_sorted): remove = False # get the basename and the rest of the files fname = op.basename(fpath) rest = len_sorted[idx+1:] # check if the basename is in the basename of the rest of the files for rest_fpath in rest: rest_file = op.basename(rest_fpath) if rest_file.endswith(fname): remove = True break if not remove: cln_flist.append(fpath) return cln_flist
def get_forward_star(self, node): """Given a node, get a copy of that node's forward star. :param node: node to retrieve the forward-star of. :returns: set -- set of hyperedge_ids for the hyperedges in the node's forward star. :raises: ValueError -- No such node exists. """ if node not in self._node_attributes: raise ValueError("No such node exists.") return self._forward_star[node].copy()
Given a node, get a copy of that node's forward star. :param node: node to retrieve the forward-star of. :returns: set -- set of hyperedge_ids for the hyperedges in the node's forward star. :raises: ValueError -- No such node exists.
Below is the the instruction that describes the task: ### Input: Given a node, get a copy of that node's forward star. :param node: node to retrieve the forward-star of. :returns: set -- set of hyperedge_ids for the hyperedges in the node's forward star. :raises: ValueError -- No such node exists. ### Response: def get_forward_star(self, node): """Given a node, get a copy of that node's forward star. :param node: node to retrieve the forward-star of. :returns: set -- set of hyperedge_ids for the hyperedges in the node's forward star. :raises: ValueError -- No such node exists. """ if node not in self._node_attributes: raise ValueError("No such node exists.") return self._forward_star[node].copy()
def isRef(self, doc, attr): """Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase). """ if doc is None: doc__o = None else: doc__o = doc._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlIsRef(doc__o, self._o, attr__o) return ret
Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase).
Below is the the instruction that describes the task: ### Input: Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase). ### Response: def isRef(self, doc, attr): """Determine whether an attribute is of type Ref. In case we have DTD(s) then this is simple, otherwise we use an heuristic: name Ref (upper or lowercase). """ if doc is None: doc__o = None else: doc__o = doc._o if attr is None: attr__o = None else: attr__o = attr._o ret = libxml2mod.xmlIsRef(doc__o, self._o, attr__o) return ret
def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: result = result_dict.ToDict() # InstalledOn comes back in a godawful format such as '7/10/2013'. installed_on = self.AmericanDateToEpoch(result.get("InstalledOn", "")) packages.append( rdf_client.SoftwarePackage( name=result.get("HotFixID"), description=result.get("Caption"), installed_by=result.get("InstalledBy"), install_state=status, installed_on=installed_on)) if packages: yield rdf_client.SoftwarePackages(packages=packages)
Parse the WMI packages output.
Below is the the instruction that describes the task: ### Input: Parse the WMI packages output. ### Response: def ParseMultiple(self, result_dicts): """Parse the WMI packages output.""" status = rdf_client.SoftwarePackage.InstallState.INSTALLED packages = [] for result_dict in result_dicts: result = result_dict.ToDict() # InstalledOn comes back in a godawful format such as '7/10/2013'. installed_on = self.AmericanDateToEpoch(result.get("InstalledOn", "")) packages.append( rdf_client.SoftwarePackage( name=result.get("HotFixID"), description=result.get("Caption"), installed_by=result.get("InstalledBy"), install_state=status, installed_on=installed_on)) if packages: yield rdf_client.SoftwarePackages(packages=packages)
def show(self): """ Plot the graph layout of the scene. """ import matplotlib.pyplot as plt nx.draw(self.transforms, with_labels=True) plt.show()
Plot the graph layout of the scene.
Below is the the instruction that describes the task: ### Input: Plot the graph layout of the scene. ### Response: def show(self): """ Plot the graph layout of the scene. """ import matplotlib.pyplot as plt nx.draw(self.transforms, with_labels=True) plt.show()
def ldSet(self, what, key, value): """List/dictionary-aware set.""" if isListKey(key): # Make sure we keep the indexes consistent, insert missing_values # as necessary. We do remember the lists, so that we can remove # missing values after inserting all values from all selectors. self.lists[id(what)] = what ix = listKeyIndex(key) while len(what) <= ix: what.append(missing_value) what[ix] = value else: what[key] = value return value
List/dictionary-aware set.
Below is the the instruction that describes the task: ### Input: List/dictionary-aware set. ### Response: def ldSet(self, what, key, value): """List/dictionary-aware set.""" if isListKey(key): # Make sure we keep the indexes consistent, insert missing_values # as necessary. We do remember the lists, so that we can remove # missing values after inserting all values from all selectors. self.lists[id(what)] = what ix = listKeyIndex(key) while len(what) <= ix: what.append(missing_value) what[ix] = value else: what[key] = value return value
def visit_Attribute(self, node): """Flatten one level of attribute access.""" new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) return ast.copy_location(new_node, node)
Flatten one level of attribute access.
Below is the the instruction that describes the task: ### Input: Flatten one level of attribute access. ### Response: def visit_Attribute(self, node): """Flatten one level of attribute access.""" new_node = ast.Name("%s.%s" % (node.value.id, node.attr), node.ctx) return ast.copy_location(new_node, node)
def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples """ print_stats(criteria['correctness'], criteria['confidence'], 'bundled') print("Saving to " + report_path) serial.save(report_path, report) assert report_path.endswith(".joblib") adv_x_path = report_path[:-len(".joblib")] + "_adv.npy" np.save(adv_x_path, adv_x_val)
Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples
Below is the the instruction that describes the task: ### Input: Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples ### Response: def save(criteria, report, report_path, adv_x_val): """ Saves the report and adversarial examples. :param criteria: dict, of the form returned by AttackGoal.get_criteria :param report: dict containing a confidence report :param report_path: string, filepath :param adv_x_val: numpy array containing dataset of adversarial examples """ print_stats(criteria['correctness'], criteria['confidence'], 'bundled') print("Saving to " + report_path) serial.save(report_path, report) assert report_path.endswith(".joblib") adv_x_path = report_path[:-len(".joblib")] + "_adv.npy" np.save(adv_x_path, adv_x_val)
def geom_transform(geom, t_srs): """Transform a geometry in place """ s_srs = geom.GetSpatialReference() if not s_srs.IsSame(t_srs): ct = osr.CoordinateTransformation(s_srs, t_srs) geom.Transform(ct) geom.AssignSpatialReference(t_srs)
Transform a geometry in place
Below is the the instruction that describes the task: ### Input: Transform a geometry in place ### Response: def geom_transform(geom, t_srs): """Transform a geometry in place """ s_srs = geom.GetSpatialReference() if not s_srs.IsSame(t_srs): ct = osr.CoordinateTransformation(s_srs, t_srs) geom.Transform(ct) geom.AssignSpatialReference(t_srs)
def _get_mro(cls): """Get an mro for a type or classic class""" if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__
Get an mro for a type or classic class
Below is the the instruction that describes the task: ### Input: Get an mro for a type or classic class ### Response: def _get_mro(cls): """Get an mro for a type or classic class""" if not isinstance(cls, type): class cls(cls, object): pass return cls.__mro__[1:] return cls.__mro__
def mul(self): r'''Viscosity of the mixture in the liquid phase at its current temperature, pressure, and composition in units of [Pa*s]. For calculation of this property at other temperatures and pressures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.viscosity.ViscosityLiquidMixture`; each Mixture instance creates one to actually perform the calculations. Examples -------- >>> Mixture(['water'], ws=[1], T=320).mul 0.0005767262693751547 ''' return self.ViscosityLiquidMixture(self.T, self.P, self.zs, self.ws)
r'''Viscosity of the mixture in the liquid phase at its current temperature, pressure, and composition in units of [Pa*s]. For calculation of this property at other temperatures and pressures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.viscosity.ViscosityLiquidMixture`; each Mixture instance creates one to actually perform the calculations. Examples -------- >>> Mixture(['water'], ws=[1], T=320).mul 0.0005767262693751547
Below is the the instruction that describes the task: ### Input: r'''Viscosity of the mixture in the liquid phase at its current temperature, pressure, and composition in units of [Pa*s]. For calculation of this property at other temperatures and pressures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.viscosity.ViscosityLiquidMixture`; each Mixture instance creates one to actually perform the calculations. Examples -------- >>> Mixture(['water'], ws=[1], T=320).mul 0.0005767262693751547 ### Response: def mul(self): r'''Viscosity of the mixture in the liquid phase at its current temperature, pressure, and composition in units of [Pa*s]. For calculation of this property at other temperatures and pressures, or specifying manually the method used to calculate it, and more - see the object oriented interface :obj:`thermo.viscosity.ViscosityLiquidMixture`; each Mixture instance creates one to actually perform the calculations. Examples -------- >>> Mixture(['water'], ws=[1], T=320).mul 0.0005767262693751547 ''' return self.ViscosityLiquidMixture(self.T, self.P, self.zs, self.ws)
def is_running(self) -> bool: """Specifies whether or not the thread is running""" return ( self._has_started and self.is_alive() or self.completed_at is None or (datetime.utcnow() - self.completed_at).total_seconds() < 0.5 )
Specifies whether or not the thread is running
Below is the the instruction that describes the task: ### Input: Specifies whether or not the thread is running ### Response: def is_running(self) -> bool: """Specifies whether or not the thread is running""" return ( self._has_started and self.is_alive() or self.completed_at is None or (datetime.utcnow() - self.completed_at).total_seconds() < 0.5 )
def name(self): """ Get the string representation of the image (registry, namespace, repository and digest together). :return: str """ name_parts = [] if self.registry: name_parts.append(self.registry) if self.namespace: name_parts.append(self.namespace) if self.repository: name_parts.append(self.repository) name = "/".join(name_parts) if self.digest: name += "@{}".format(self.digest) elif self.tag: name += ":{}".format(self.tag) return name
Get the string representation of the image (registry, namespace, repository and digest together). :return: str
Below is the the instruction that describes the task: ### Input: Get the string representation of the image (registry, namespace, repository and digest together). :return: str ### Response: def name(self): """ Get the string representation of the image (registry, namespace, repository and digest together). :return: str """ name_parts = [] if self.registry: name_parts.append(self.registry) if self.namespace: name_parts.append(self.namespace) if self.repository: name_parts.append(self.repository) name = "/".join(name_parts) if self.digest: name += "@{}".format(self.digest) elif self.tag: name += ":{}".format(self.tag) return name
def get_deadline_metadata(self): """Gets the metadata for the assessment deadline. return: (osid.Metadata) - metadata for the end time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['deadline']) metadata.update({'existing_date_time_values': self._my_map['deadline']}) return Metadata(**metadata)
Gets the metadata for the assessment deadline. return: (osid.Metadata) - metadata for the end time *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Gets the metadata for the assessment deadline. return: (osid.Metadata) - metadata for the end time *compliance: mandatory -- This method must be implemented.* ### Response: def get_deadline_metadata(self): """Gets the metadata for the assessment deadline. return: (osid.Metadata) - metadata for the end time *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resource.ResourceForm.get_group_metadata_template metadata = dict(self._mdata['deadline']) metadata.update({'existing_date_time_values': self._my_map['deadline']}) return Metadata(**metadata)
def module(self, name): """return a module by its name, raise KeyError if not found """ for mod in self.modules(): if mod.node.name == name: return mod raise KeyError(name)
return a module by its name, raise KeyError if not found
Below is the the instruction that describes the task: ### Input: return a module by its name, raise KeyError if not found ### Response: def module(self, name): """return a module by its name, raise KeyError if not found """ for mod in self.modules(): if mod.node.name == name: return mod raise KeyError(name)
def read(*filenames, **kwargs): """ Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string """ encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: if path.splitext(filename)[1] == ".md": try: import pypandoc buf.append(pypandoc.convert_file(filename, 'rst')) continue except: with io.open(filename, encoding=encoding) as f: buf.append(f.read()) with io.open(filename, encoding=encoding) as f: buf.append(f.read()) return sep.join(buf)
Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string
Below is the the instruction that describes the task: ### Input: Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string ### Response: def read(*filenames, **kwargs): """ Read file contents into string. Used by setup.py to concatenate long_description. :param string filenames: Files to be read and concatenated. :rtype: string """ encoding = kwargs.get('encoding', 'utf-8') sep = kwargs.get('sep', '\n') buf = [] for filename in filenames: if path.splitext(filename)[1] == ".md": try: import pypandoc buf.append(pypandoc.convert_file(filename, 'rst')) continue except: with io.open(filename, encoding=encoding) as f: buf.append(f.read()) with io.open(filename, encoding=encoding) as f: buf.append(f.read()) return sep.join(buf)
def detach(self, ids=None, touch=True): """ Detach models from the relationship. """ if isinstance(ids, orator.orm.model.Model): ids = ids.get_key() if ids is None: ids = [] query = self._new_pivot_query() if not isinstance(ids, list): ids = [ids] if len(ids) > 0: query.where_in(self._other_key, ids) if touch: self.touch_if_touching() results = query.delete() return results
Detach models from the relationship.
Below is the the instruction that describes the task: ### Input: Detach models from the relationship. ### Response: def detach(self, ids=None, touch=True): """ Detach models from the relationship. """ if isinstance(ids, orator.orm.model.Model): ids = ids.get_key() if ids is None: ids = [] query = self._new_pivot_query() if not isinstance(ids, list): ids = [ids] if len(ids) > 0: query.where_in(self._other_key, ids) if touch: self.touch_if_touching() results = query.delete() return results
def gradient_summaries(grad_vars, groups=None, scope='gradients'): """Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor. """ groups = groups or {r'all': r'.*'} grouped = collections.defaultdict(list) for grad, var in grad_vars: if grad is None: continue for name, pattern in groups.items(): if re.match(pattern, var.name): name = re.sub(pattern, name, var.name) grouped[name].append(grad) for name in groups: if name not in grouped: tf.logging.warn("No variables matching '{}' group.".format(name)) summaries = [] for name, grads in grouped.items(): grads = [tf.reshape(grad, [-1]) for grad in grads] grads = tf.concat(grads, 0) summaries.append(tf.summary.histogram(scope + '/' + name, grads)) return tf.summary.merge(summaries)
Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor.
Below is the the instruction that describes the task: ### Input: Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor. ### Response: def gradient_summaries(grad_vars, groups=None, scope='gradients'): """Create histogram summaries of the gradient. Summaries can be grouped via regexes matching variables names. Args: grad_vars: List of (gradient, variable) tuples as returned by optimizers. groups: Mapping of name to regex for grouping summaries. scope: Name scope for this operation. Returns: Summary tensor. """ groups = groups or {r'all': r'.*'} grouped = collections.defaultdict(list) for grad, var in grad_vars: if grad is None: continue for name, pattern in groups.items(): if re.match(pattern, var.name): name = re.sub(pattern, name, var.name) grouped[name].append(grad) for name in groups: if name not in grouped: tf.logging.warn("No variables matching '{}' group.".format(name)) summaries = [] for name, grads in grouped.items(): grads = [tf.reshape(grad, [-1]) for grad in grads] grads = tf.concat(grads, 0) summaries.append(tf.summary.histogram(scope + '/' + name, grads)) return tf.summary.merge(summaries)
def iter_project(projects, key_file=None): """ Call decorated function for each item in project list. Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions. If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively. If item in list is of type string_types, we assume it is the project string. Default credentials will be used by the underlying client library. :param projects: list of project strings or list of dictionaries Example: {'project':..., 'keyfile':...}. Required. :type projects: ``list`` of ``str`` or ``list`` of ``dict`` :param key_file: path on disk to keyfile, for use with all projects :type key_file: ``str`` :returns: tuple containing a list of function output and an exceptions map :rtype: ``tuple of ``list``, ``dict`` """ def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): item_list = [] exception_map = {} for project in projects: if isinstance(project, string_types): kwargs['project'] = project if key_file: kwargs['key_file'] = key_file elif isinstance(project, dict): kwargs['project'] = project['project'] kwargs['key_file'] = project['key_file'] itm, exc = func(*args, **kwargs) item_list.extend(itm) exception_map.update(exc) return (item_list, exception_map) return decorated_function return decorator
Call decorated function for each item in project list. Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions. If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively. If item in list is of type string_types, we assume it is the project string. Default credentials will be used by the underlying client library. :param projects: list of project strings or list of dictionaries Example: {'project':..., 'keyfile':...}. Required. :type projects: ``list`` of ``str`` or ``list`` of ``dict`` :param key_file: path on disk to keyfile, for use with all projects :type key_file: ``str`` :returns: tuple containing a list of function output and an exceptions map :rtype: ``tuple of ``list``, ``dict``
Below is the the instruction that describes the task: ### Input: Call decorated function for each item in project list. Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions. If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively. If item in list is of type string_types, we assume it is the project string. Default credentials will be used by the underlying client library. :param projects: list of project strings or list of dictionaries Example: {'project':..., 'keyfile':...}. Required. :type projects: ``list`` of ``str`` or ``list`` of ``dict`` :param key_file: path on disk to keyfile, for use with all projects :type key_file: ``str`` :returns: tuple containing a list of function output and an exceptions map :rtype: ``tuple of ``list``, ``dict`` ### Response: def iter_project(projects, key_file=None): """ Call decorated function for each item in project list. Note: the function 'decorated' is expected to return a value plus a dictionary of exceptions. If item in list is a dictionary, we look for a 'project' and 'key_file' entry, respectively. If item in list is of type string_types, we assume it is the project string. Default credentials will be used by the underlying client library. :param projects: list of project strings or list of dictionaries Example: {'project':..., 'keyfile':...}. Required. :type projects: ``list`` of ``str`` or ``list`` of ``dict`` :param key_file: path on disk to keyfile, for use with all projects :type key_file: ``str`` :returns: tuple containing a list of function output and an exceptions map :rtype: ``tuple of ``list``, ``dict`` """ def decorator(func): @wraps(func) def decorated_function(*args, **kwargs): item_list = [] exception_map = {} for project in projects: if isinstance(project, string_types): kwargs['project'] = project if key_file: kwargs['key_file'] = key_file elif isinstance(project, dict): kwargs['project'] = project['project'] kwargs['key_file'] = project['key_file'] itm, exc = func(*args, **kwargs) item_list.extend(itm) exception_map.update(exc) return (item_list, exception_map) return decorated_function return decorator
def save(self, fname: str): """ Saves this training state to fname. """ with open(fname, "wb") as fp: pickle.dump(self, fp)
Saves this training state to fname.
Below is the the instruction that describes the task: ### Input: Saves this training state to fname. ### Response: def save(self, fname: str): """ Saves this training state to fname. """ with open(fname, "wb") as fp: pickle.dump(self, fp)
def setup_pins(self, pins): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT). """ # General implementation that can be optimized by derived classes. for pin, value in iter(pins.items()): self.setup(pin, value)
Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT).
Below is the the instruction that describes the task: ### Input: Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT). ### Response: def setup_pins(self, pins): """Setup multiple pins as inputs or outputs at once. Pins should be a dict of pin name to pin type (IN or OUT). """ # General implementation that can be optimized by derived classes. for pin, value in iter(pins.items()): self.setup(pin, value)
def selectMap(name=None, excludeName=False, closestMatch=True, **tags): """select a map by name and/or critiera""" matches = filterMapAttrs(**tags) if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags) if name: # if name is specified, consider only the best-matching names only matches = filterMapNames(name, excludeRegex=excludeName, closestMatch=closestMatch, records=matches) try: if closestMatch: return random.choice(matches) # pick any map at random that matches all criteria elif matches: return matches except IndexError: pass # matches is empty still raise c.InvalidMapSelection("requested map '%s', but could not locate "\ "it within %s or its subdirectories. Submit the map to https://"\ "github.com/ttinies/sc2gameMapRepo/tree/master/sc2maptool/maps"%( name, c.PATH_MAP_INSTALL))
select a map by name and/or critiera
Below is the the instruction that describes the task: ### Input: select a map by name and/or critiera ### Response: def selectMap(name=None, excludeName=False, closestMatch=True, **tags): """select a map by name and/or critiera""" matches = filterMapAttrs(**tags) if not matches: raise c.InvalidMapSelection("could not find any matching maps given criteria: %s"%tags) if name: # if name is specified, consider only the best-matching names only matches = filterMapNames(name, excludeRegex=excludeName, closestMatch=closestMatch, records=matches) try: if closestMatch: return random.choice(matches) # pick any map at random that matches all criteria elif matches: return matches except IndexError: pass # matches is empty still raise c.InvalidMapSelection("requested map '%s', but could not locate "\ "it within %s or its subdirectories. Submit the map to https://"\ "github.com/ttinies/sc2gameMapRepo/tree/master/sc2maptool/maps"%( name, c.PATH_MAP_INSTALL))
def add_abbreviation(self, new_abbreviation): """ Adds a new name variant to an author. :param new_abbreviation: the abbreviation to be added :return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate) """ try: assert new_abbreviation not in self.get_abbreviations() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate abbreviation detected while adding \"%s\""%new_abbreviation) return False try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviation = [abbreviation for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation][0] abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.update() return True except IndexError as e: # means there is no abbreviation instance yet type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) Appellation = self.session.get_class(surf.ns.ECRM['E41_Appellation']) abbreviation_uri = "%s/abbr" % str(self.subject) abbreviation = Appellation(abbreviation_uri) abbreviation.ecrm_P2_has_type = type_abbreviation abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.save() name = (name for name in self.ecrm_P1_is_identified_by if name.uri == surf.ns.EFRBROO['F12_Name']).next() name.ecrm_P139_has_alternative_form = abbreviation name.update() return True except Exception as e: raise e
Adds a new name variant to an author. :param new_abbreviation: the abbreviation to be added :return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate)
Below is the the instruction that describes the task: ### Input: Adds a new name variant to an author. :param new_abbreviation: the abbreviation to be added :return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate) ### Response: def add_abbreviation(self, new_abbreviation): """ Adds a new name variant to an author. :param new_abbreviation: the abbreviation to be added :return: `True` if the abbreviation is added, `False` otherwise (the abbreviation is a duplicate) """ try: assert new_abbreviation not in self.get_abbreviations() except Exception as e: # TODO: raise a custom exception logger.warning("Duplicate abbreviation detected while adding \"%s\""%new_abbreviation) return False try: type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) abbreviation = [abbreviation for name in self.ecrm_P1_is_identified_by for abbreviation in name.ecrm_P139_has_alternative_form if name.uri == surf.ns.EFRBROO['F12_Name'] and abbreviation.ecrm_P2_has_type.first == type_abbreviation][0] abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.update() return True except IndexError as e: # means there is no abbreviation instance yet type_abbreviation = self.session.get_resource(BASE_URI_TYPES % "abbreviation" , self.session.get_class(surf.ns.ECRM['E55_Type'])) Appellation = self.session.get_class(surf.ns.ECRM['E41_Appellation']) abbreviation_uri = "%s/abbr" % str(self.subject) abbreviation = Appellation(abbreviation_uri) abbreviation.ecrm_P2_has_type = type_abbreviation abbreviation.rdfs_label.append(Literal(new_abbreviation)) abbreviation.save() name = (name for name in self.ecrm_P1_is_identified_by if name.uri == surf.ns.EFRBROO['F12_Name']).next() name.ecrm_P139_has_alternative_form = abbreviation name.update() return True except Exception as e: raise e
def get_time_string(time, unit): """ Create a properly formatted string given a time and unit :param time: Time to format :type time: float :param unit: Unit to apply format of. Only supports hours ('h') and minutes ('m'). :type unit: str :return: A string in format '{whole}:{part}' :rtype: str """ supported_units = ["h", "m"] if unit not in supported_units: return "{}".format(round(time, 2)) hours, minutes = str(time).split(".") hours = int(hours) minutes = int(round(float("0.{}".format(minutes)) * 60)) return "{:02d}:{:02d}".format(hours, minutes)
Create a properly formatted string given a time and unit :param time: Time to format :type time: float :param unit: Unit to apply format of. Only supports hours ('h') and minutes ('m'). :type unit: str :return: A string in format '{whole}:{part}' :rtype: str
Below is the the instruction that describes the task: ### Input: Create a properly formatted string given a time and unit :param time: Time to format :type time: float :param unit: Unit to apply format of. Only supports hours ('h') and minutes ('m'). :type unit: str :return: A string in format '{whole}:{part}' :rtype: str ### Response: def get_time_string(time, unit): """ Create a properly formatted string given a time and unit :param time: Time to format :type time: float :param unit: Unit to apply format of. Only supports hours ('h') and minutes ('m'). :type unit: str :return: A string in format '{whole}:{part}' :rtype: str """ supported_units = ["h", "m"] if unit not in supported_units: return "{}".format(round(time, 2)) hours, minutes = str(time).split(".") hours = int(hours) minutes = int(round(float("0.{}".format(minutes)) * 60)) return "{:02d}:{:02d}".format(hours, minutes)
def set_power_supplies(self, power_supplies): """ Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off. """ power_supply_id = 0 for power_supply in power_supplies: yield from self._hypervisor.send('c7200 set_power_supply "{name}" {power_supply_id} {powered_on}'.format(name=self._name, power_supply_id=power_supply_id, powered_on=power_supply)) log.info('Router "{name}" [{id}]: power supply {power_supply_id} state updated to {powered_on}'.format(name=self._name, id=self._id, power_supply_id=power_supply_id, powered_on=power_supply)) power_supply_id += 1 self._power_supplies = power_supplies
Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off.
Below is the the instruction that describes the task: ### Input: Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off. ### Response: def set_power_supplies(self, power_supplies): """ Sets the 2 power supplies with 0 = off, 1 = on. :param power_supplies: list of 2 power supplies. Example: [1, 0] = first power supply is on, second is off. """ power_supply_id = 0 for power_supply in power_supplies: yield from self._hypervisor.send('c7200 set_power_supply "{name}" {power_supply_id} {powered_on}'.format(name=self._name, power_supply_id=power_supply_id, powered_on=power_supply)) log.info('Router "{name}" [{id}]: power supply {power_supply_id} state updated to {powered_on}'.format(name=self._name, id=self._id, power_supply_id=power_supply_id, powered_on=power_supply)) power_supply_id += 1 self._power_supplies = power_supplies
def store_json(obj, destination): """store_json Takes in a json-portable object and a filesystem-based destination and stores the json-portable object as JSON into the filesystem-based destination. This is blind, dumb, and stupid; thus, it can fail if the object is more complex than simple dict, list, int, str, etc. type object structures. """ with open(destination, 'r+') as FH: fcntl.lockf(FH, fcntl.LOCK_EX) json_in = json.loads(FH.read()) json_in.update(obj) # obj overwrites items in json_in... FH.seek(0) FH.write(json.dumps(json_in, sort_keys=True, indent=4, separators=(',', ': ')))
store_json Takes in a json-portable object and a filesystem-based destination and stores the json-portable object as JSON into the filesystem-based destination. This is blind, dumb, and stupid; thus, it can fail if the object is more complex than simple dict, list, int, str, etc. type object structures.
Below is the the instruction that describes the task: ### Input: store_json Takes in a json-portable object and a filesystem-based destination and stores the json-portable object as JSON into the filesystem-based destination. This is blind, dumb, and stupid; thus, it can fail if the object is more complex than simple dict, list, int, str, etc. type object structures. ### Response: def store_json(obj, destination): """store_json Takes in a json-portable object and a filesystem-based destination and stores the json-portable object as JSON into the filesystem-based destination. This is blind, dumb, and stupid; thus, it can fail if the object is more complex than simple dict, list, int, str, etc. type object structures. """ with open(destination, 'r+') as FH: fcntl.lockf(FH, fcntl.LOCK_EX) json_in = json.loads(FH.read()) json_in.update(obj) # obj overwrites items in json_in... FH.seek(0) FH.write(json.dumps(json_in, sort_keys=True, indent=4, separators=(',', ': ')))
def set_next_week_day(val, week_day, iso=False): """ Set week day. New date will be greater or equal than input date. :param val: datetime or date :type val: datetime.datetime | datetime.date :param week_day: Week day to set :type week_day: int :param iso: week_day in ISO format, or not :type iso: bool :return: datetime.datetime | datetime.date """ return _set_week_day(val, week_day, val.isoweekday() if iso else val.weekday(), sign=1)
Set week day. New date will be greater or equal than input date. :param val: datetime or date :type val: datetime.datetime | datetime.date :param week_day: Week day to set :type week_day: int :param iso: week_day in ISO format, or not :type iso: bool :return: datetime.datetime | datetime.date
Below is the the instruction that describes the task: ### Input: Set week day. New date will be greater or equal than input date. :param val: datetime or date :type val: datetime.datetime | datetime.date :param week_day: Week day to set :type week_day: int :param iso: week_day in ISO format, or not :type iso: bool :return: datetime.datetime | datetime.date ### Response: def set_next_week_day(val, week_day, iso=False): """ Set week day. New date will be greater or equal than input date. :param val: datetime or date :type val: datetime.datetime | datetime.date :param week_day: Week day to set :type week_day: int :param iso: week_day in ISO format, or not :type iso: bool :return: datetime.datetime | datetime.date """ return _set_week_day(val, week_day, val.isoweekday() if iso else val.weekday(), sign=1)
def _get_results(self, identity_provider, param_name, param_value, result_field_name): """ Calls the third party auth api endpoint to get the mapping between usernames and remote ids. """ try: kwargs = {param_name: param_value} returned = self.client.providers(identity_provider).users.get(**kwargs) results = returned.get('results', []) except HttpNotFoundError: LOGGER.error( 'username not found for third party provider={provider}, {querystring_param}={id}'.format( provider=identity_provider, querystring_param=param_name, id=param_value ) ) results = [] for row in results: if row.get(param_name) == param_value: return row.get(result_field_name) return None
Calls the third party auth api endpoint to get the mapping between usernames and remote ids.
Below is the the instruction that describes the task: ### Input: Calls the third party auth api endpoint to get the mapping between usernames and remote ids. ### Response: def _get_results(self, identity_provider, param_name, param_value, result_field_name): """ Calls the third party auth api endpoint to get the mapping between usernames and remote ids. """ try: kwargs = {param_name: param_value} returned = self.client.providers(identity_provider).users.get(**kwargs) results = returned.get('results', []) except HttpNotFoundError: LOGGER.error( 'username not found for third party provider={provider}, {querystring_param}={id}'.format( provider=identity_provider, querystring_param=param_name, id=param_value ) ) results = [] for row in results: if row.get(param_name) == param_value: return row.get(result_field_name) return None
def set_data_location(self, current_extent, tag_location): # pylint: disable=unused-argument # type: (int, int) -> None ''' A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. Returns: Nothing. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('Directory Record not yet initialized') self.new_extent_loc = current_extent if self.ptr is not None: self.ptr.update_extent_location(current_extent)
A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. Returns: Nothing.
Below is the the instruction that describes the task: ### Input: A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. Returns: Nothing. ### Response: def set_data_location(self, current_extent, tag_location): # pylint: disable=unused-argument # type: (int, int) -> None ''' A method to set the new extent location that the data for this Directory Record should live at. Parameters: current_extent - The new extent. Returns: Nothing. ''' if not self._initialized: raise pycdlibexception.PyCdlibInternalError('Directory Record not yet initialized') self.new_extent_loc = current_extent if self.ptr is not None: self.ptr.update_extent_location(current_extent)
def get_file_size(self, fid): """ Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None """ url = self.get_file_url(fid) res = self.conn.head(url) if res is not None: size = res.headers.get("content-length", None) if size is not None: return int(size) return None
Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None
Below is the the instruction that describes the task: ### Input: Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None ### Response: def get_file_size(self, fid): """ Gets size of uploaded file Or None if file doesn't exist. Args: **fid**: File identifier <volume_id>,<file_name_hash> Returns: Int or None """ url = self.get_file_url(fid) res = self.conn.head(url) if res is not None: size = res.headers.get("content-length", None) if size is not None: return int(size) return None
def _walk(self, path_to_root, record_dict): ''' a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments item_pattern = re.compile('\d+\\]') dot_pattern = re.compile('\\.|\\[') path_segments = dot_pattern.split(path_to_root) # construct empty fields record_endpoints = [] # determine starting position if not path_segments[0]: path_segments.pop(0) # define internal recursive function def _walk_int(path_segments, record_dict): record_endpoint = record_dict for i in range(0, len(path_segments)): if item_pattern.match(path_segments[i]): for j in range(0, len(record_endpoint)): if len(path_segments) == 2: record_endpoints.append(record_endpoint[j]) else: stop_chain = False for x in range(0, i): if item_pattern.match(path_segments[x]): stop_chain = True if not stop_chain: shortened_segments = [] for z in range(i + 1, len(path_segments)): shortened_segments.append(path_segments[z]) _walk_int(shortened_segments, record_endpoint[j]) else: stop_chain = False for y in range(0, i): if item_pattern.match(path_segments[y]): stop_chain = True if not stop_chain: if len(path_segments) == i + 1: record_endpoints.append(record_endpoint[path_segments[i]]) else: record_endpoint = record_endpoint[path_segments[i]] # conduct recursive walk _walk_int(path_segments, record_dict) return record_endpoints
a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root
Below is the the instruction that describes the task: ### Input: a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root ### Response: def _walk(self, path_to_root, record_dict): ''' a helper method for finding the record endpoint from a path to root :param path_to_root: string with dot path to root from :param record_dict: :return: list, dict, string, number, or boolean at path to root ''' # split path to root into segments item_pattern = re.compile('\d+\\]') dot_pattern = re.compile('\\.|\\[') path_segments = dot_pattern.split(path_to_root) # construct empty fields record_endpoints = [] # determine starting position if not path_segments[0]: path_segments.pop(0) # define internal recursive function def _walk_int(path_segments, record_dict): record_endpoint = record_dict for i in range(0, len(path_segments)): if item_pattern.match(path_segments[i]): for j in range(0, len(record_endpoint)): if len(path_segments) == 2: record_endpoints.append(record_endpoint[j]) else: stop_chain = False for x in range(0, i): if item_pattern.match(path_segments[x]): stop_chain = True if not stop_chain: shortened_segments = [] for z in range(i + 1, len(path_segments)): shortened_segments.append(path_segments[z]) _walk_int(shortened_segments, record_endpoint[j]) else: stop_chain = False for y in range(0, i): if item_pattern.match(path_segments[y]): stop_chain = True if not stop_chain: if len(path_segments) == i + 1: record_endpoints.append(record_endpoint[path_segments[i]]) else: record_endpoint = record_endpoint[path_segments[i]] # conduct recursive walk _walk_int(path_segments, record_dict) return record_endpoints
def get_http_json(self, url=None, retry_count=3, rate_limit_timeout=120, headers=None): """ The function for retrieving a json result via HTTP. Args: url (:obj:`str`): The URL to retrieve (required). retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3. rate_limit_timeout (:obj:`int`): The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json or HTTP error 429. Defaults to 60. headers (:obj:`dict`): The HTTP headers. The Accept header defaults to 'application/rdap+json'. Returns: dict: The data in json format. Raises: HTTPLookupError: The HTTP lookup failed. HTTPRateLimitError: The HTTP request rate limited and retries were exhausted. """ if headers is None: headers = {'Accept': 'application/rdap+json'} try: # Create the connection for the whois query. log.debug('HTTP query for {0} at {1}'.format( self.address_str, url)) conn = Request(url, headers=headers) data = self.opener.open(conn, timeout=self.timeout) try: d = json.loads(data.readall().decode('utf-8', 'ignore')) except AttributeError: # pragma: no cover d = json.loads(data.read().decode('utf-8', 'ignore')) try: # Tests written but commented out. I do not want to send a # flood of requests on every test. for tmp in d['notices']: # pragma: no cover if tmp['title'] == 'Rate Limit Notice': log.debug('RDAP query rate limit exceeded.') if retry_count > 0: log.debug('Waiting {0} seconds...'.format( str(rate_limit_timeout))) sleep(rate_limit_timeout) return self.get_http_json( url=url, retry_count=retry_count-1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPRateLimitError( 'HTTP lookup failed for {0}. Rate limit ' 'exceeded, wait and try again (possibly a ' 'temporary block).'.format(url)) except (KeyError, IndexError): # pragma: no cover pass return d except HTTPError as e: # pragma: no cover # RIPE is producing this HTTP error rather than a JSON error. if e.code == 429: log.debug('HTTP query rate limit exceeded.') if retry_count > 0: log.debug('Waiting {0} seconds...'.format( str(rate_limit_timeout))) sleep(rate_limit_timeout) return self.get_http_json( url=url, retry_count=retry_count - 1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPRateLimitError( 'HTTP lookup failed for {0}. Rate limit ' 'exceeded, wait and try again (possibly a ' 'temporary block).'.format(url)) else: raise HTTPLookupError('HTTP lookup failed for {0} with error ' 'code {1}.'.format(url, str(e.code))) except (URLError, socket.timeout, socket.error) as e: log.debug('HTTP query socket error: {0}'.format(e)) if retry_count > 0: log.debug('HTTP query retrying (count: {0})'.format( str(retry_count))) return self.get_http_json( url=url, retry_count=retry_count-1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPLookupError('HTTP lookup failed for {0}.'.format( url)) except (HTTPLookupError, HTTPRateLimitError) as e: # pragma: no cover raise e except: # pragma: no cover raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url))
The function for retrieving a json result via HTTP. Args: url (:obj:`str`): The URL to retrieve (required). retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3. rate_limit_timeout (:obj:`int`): The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json or HTTP error 429. Defaults to 60. headers (:obj:`dict`): The HTTP headers. The Accept header defaults to 'application/rdap+json'. Returns: dict: The data in json format. Raises: HTTPLookupError: The HTTP lookup failed. HTTPRateLimitError: The HTTP request rate limited and retries were exhausted.
Below is the the instruction that describes the task: ### Input: The function for retrieving a json result via HTTP. Args: url (:obj:`str`): The URL to retrieve (required). retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3. rate_limit_timeout (:obj:`int`): The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json or HTTP error 429. Defaults to 60. headers (:obj:`dict`): The HTTP headers. The Accept header defaults to 'application/rdap+json'. Returns: dict: The data in json format. Raises: HTTPLookupError: The HTTP lookup failed. HTTPRateLimitError: The HTTP request rate limited and retries were exhausted. ### Response: def get_http_json(self, url=None, retry_count=3, rate_limit_timeout=120, headers=None): """ The function for retrieving a json result via HTTP. Args: url (:obj:`str`): The URL to retrieve (required). retry_count (:obj:`int`): The number of times to retry in case socket errors, timeouts, connection resets, etc. are encountered. Defaults to 3. rate_limit_timeout (:obj:`int`): The number of seconds to wait before retrying when a rate limit notice is returned via rdap+json or HTTP error 429. Defaults to 60. headers (:obj:`dict`): The HTTP headers. The Accept header defaults to 'application/rdap+json'. Returns: dict: The data in json format. Raises: HTTPLookupError: The HTTP lookup failed. HTTPRateLimitError: The HTTP request rate limited and retries were exhausted. """ if headers is None: headers = {'Accept': 'application/rdap+json'} try: # Create the connection for the whois query. log.debug('HTTP query for {0} at {1}'.format( self.address_str, url)) conn = Request(url, headers=headers) data = self.opener.open(conn, timeout=self.timeout) try: d = json.loads(data.readall().decode('utf-8', 'ignore')) except AttributeError: # pragma: no cover d = json.loads(data.read().decode('utf-8', 'ignore')) try: # Tests written but commented out. I do not want to send a # flood of requests on every test. for tmp in d['notices']: # pragma: no cover if tmp['title'] == 'Rate Limit Notice': log.debug('RDAP query rate limit exceeded.') if retry_count > 0: log.debug('Waiting {0} seconds...'.format( str(rate_limit_timeout))) sleep(rate_limit_timeout) return self.get_http_json( url=url, retry_count=retry_count-1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPRateLimitError( 'HTTP lookup failed for {0}. Rate limit ' 'exceeded, wait and try again (possibly a ' 'temporary block).'.format(url)) except (KeyError, IndexError): # pragma: no cover pass return d except HTTPError as e: # pragma: no cover # RIPE is producing this HTTP error rather than a JSON error. if e.code == 429: log.debug('HTTP query rate limit exceeded.') if retry_count > 0: log.debug('Waiting {0} seconds...'.format( str(rate_limit_timeout))) sleep(rate_limit_timeout) return self.get_http_json( url=url, retry_count=retry_count - 1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPRateLimitError( 'HTTP lookup failed for {0}. Rate limit ' 'exceeded, wait and try again (possibly a ' 'temporary block).'.format(url)) else: raise HTTPLookupError('HTTP lookup failed for {0} with error ' 'code {1}.'.format(url, str(e.code))) except (URLError, socket.timeout, socket.error) as e: log.debug('HTTP query socket error: {0}'.format(e)) if retry_count > 0: log.debug('HTTP query retrying (count: {0})'.format( str(retry_count))) return self.get_http_json( url=url, retry_count=retry_count-1, rate_limit_timeout=rate_limit_timeout, headers=headers ) else: raise HTTPLookupError('HTTP lookup failed for {0}.'.format( url)) except (HTTPLookupError, HTTPRateLimitError) as e: # pragma: no cover raise e except: # pragma: no cover raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url))