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` ...
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.re...
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 ...
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...
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` ins...
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) ...
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,...
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 ...
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 ...
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 a...
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 ...
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 ...
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 ...
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'): """DE...
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: ...
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.PER...
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, res...
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...
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...
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(...
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 outp...
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 a...
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 o...
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 ...
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 ex...
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...
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: ...
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,fre...
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.f...
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( ...
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. """...
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'...
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=...
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/py...
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, "timezon...
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-c...
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): ...
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): """ Funct...
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:...
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 ...
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 ...
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 t...
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.c...
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'])...
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 zipcod...
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_t...
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 ...
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_pipel...
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(sou...
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 ...
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(StaticN...
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 = engi...
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 { ...
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' i...
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) ...
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: ...
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: ...
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). R...
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 ...
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`. ...
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 strippe...
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...
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 -> alterna...
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 Un...
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 =...
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: ...
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=...
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): Yea...
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....
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(...
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 ...
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" measu...
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. ...
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=ab...
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(swee...
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 isinsta...
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 ...
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 datetim...
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_y...
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: ...
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...
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 :p...
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 cr...
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...
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 t...
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)....
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 stri...
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``, ...
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 ``co...
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``,...
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. ...
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.returncod...
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.P...
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. ...
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: Tens...
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...
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...
def p_scope(p): """scope : ',' SCOPE '(' metaElementList ')'""" slist = p[4] scopes = OrderedDict() for i in ('CLASS', 'ASSOCIATION', 'INDICATION', 'PROPERTY', 'REFERENCE', 'METHOD', 'PARAMETER', 'ANY'): ...
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', ...
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_i...
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 """ ...
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...
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.aw...
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: ...
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 += ...
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.timed...
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 = sel...
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, ...
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 '{...
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: ...
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 s...
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...
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 ``Tru...
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_l...
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. ...
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...
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...
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 me...
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 cont...
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). ...
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 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...
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...
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) cu...
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=N...
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") ...
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 ...
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, ...
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 calculat...
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 ...
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 boot...
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, .... ...
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 ke...
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, .... ...
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] = {} ...
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)...
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 isinsta...
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 ...
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...
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: iterab...
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 N...
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 ...
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: Val...
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 = ...
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 at...
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'. insta...
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: ...
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.li...
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 l...
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(ne...
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 o...
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 ...
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) ...
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 ...
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 int...
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...
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...
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_part...
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,...
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_t...
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 metadat...
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: ...
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 = [] ...
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 in...
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): ...
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() ...
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 s...
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: Summ...
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 summ...
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 i...
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 pro...
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....
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, va...
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 dic...
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 b...
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.InvalidMapSelec...
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...
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, ne...
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 s...
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 ...
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_suppli...
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): """ ...
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, e...
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 si...
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 ...
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...
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,...
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(ide...
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 endpo...
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. ...
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, curren...
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...
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): """ ...
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 ''' # ...
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 ...
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 ...
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. ...
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, connec...