code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_default_config(self): """ Returns the default collector settings """ config = super(NfsdCollector, self).get_default_config() config.update({ 'path': 'nfsd' }) return config
Returns the default collector settings
Below is the the instruction that describes the task: ### Input: Returns the default collector settings ### Response: def get_default_config(self): """ Returns the default collector settings """ config = super(NfsdCollector, self).get_default_config() config.update({ ...
def with_name(self, name): """Return a new path with the file name changed.""" if not self.name: raise ValueError("%r has an empty name" % (self,)) drv, root, parts = self._flavour.parse_parts((name,)) if (not name or name[-1] in [self._flavour.sep, self._flavour.altsep] ...
Return a new path with the file name changed.
Below is the the instruction that describes the task: ### Input: Return a new path with the file name changed. ### Response: def with_name(self, name): """Return a new path with the file name changed.""" if not self.name: raise ValueError("%r has an empty name" % (self,)) drv, r...
def _wait_until(obj, att, desired, callback, interval, attempts, verbose, verbose_atts): """ Loops until either the desired value of the attribute is reached, or the number of attempts is exceeded. """ if not isinstance(desired, (list, tuple)): desired = [desired] if verbose_atts...
Loops until either the desired value of the attribute is reached, or the number of attempts is exceeded.
Below is the the instruction that describes the task: ### Input: Loops until either the desired value of the attribute is reached, or the number of attempts is exceeded. ### Response: def _wait_until(obj, att, desired, callback, interval, attempts, verbose, verbose_atts): """ Loops until either...
def save_to_file(destination_filename, append=False): """ Save the output value to file. """ def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res = f(*args, **kwargs) makedirs(os.path.dirname(destination_filename)) mode = "a" if append...
Save the output value to file.
Below is the the instruction that describes the task: ### Input: Save the output value to file. ### Response: def save_to_file(destination_filename, append=False): """ Save the output value to file. """ def decorator_fn(f): @wraps(f) def wrapper_fn(*args, **kwargs): res...
def use_gl(target='gl2'): """ Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL * gl+ - Use the ...
Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL * gl+ - Use the desktop ES 2.0 subset plus all non...
Below is the the instruction that describes the task: ### Input: Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. Parameters ---------- target : str The target GL backend to use. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. ...
def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result. """ res = fw_const.DCNM_IN_PART_UPDDEL_SUCCESS tenant_name = fw_dict.get(...
Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result.
Below is the the instruction that describes the task: ### Input: Clear the DCNM in partition service information. Clear the In partition service node IP address in DCNM and update the result. ### Response: def clear_dcnm_in_part(self, tenant_id, fw_dict, is_fw_virt=False): """Clear the DCN...
def convert_convolution(node, **kwargs): """Map MXNet's convolution operator attributes to onnx's Conv operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) kernel_dims = list(parse_helper(attrs, "kernel")) stride_dims = list(parse_helper(attrs, "stride",...
Map MXNet's convolution operator attributes to onnx's Conv operator and return the created node.
Below is the the instruction that describes the task: ### Input: Map MXNet's convolution operator attributes to onnx's Conv operator and return the created node. ### Response: def convert_convolution(node, **kwargs): """Map MXNet's convolution operator attributes to onnx's Conv operator and return the ...
def dimension_values(self, dimension, expanded=True, flat=True): """Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values flat (bool, optional): Whether to flatten arra...
Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values flat (bool, optional): Whether to flatten array Returns: NumPy array of values along the requested di...
Below is the the instruction that describes the task: ### Input: Return the values along the requested dimension. Args: dimension: The dimension to return values for expanded (bool, optional): Whether to expand values flat (bool, optional): Whether to flatten array ...
def apply_grad(fun, grad): """ Apply a function that takes a gradient matrix to a sequence of 2 or 3 dimensional gradients. This is partucularly useful when the gradient of a basis concatenation object is quite complex, eg. >>> X = np.random.randn(100, 3) >>> y = np.random.randn(100) >...
Apply a function that takes a gradient matrix to a sequence of 2 or 3 dimensional gradients. This is partucularly useful when the gradient of a basis concatenation object is quite complex, eg. >>> X = np.random.randn(100, 3) >>> y = np.random.randn(100) >>> N, d = X.shape >>> base = Random...
Below is the the instruction that describes the task: ### Input: Apply a function that takes a gradient matrix to a sequence of 2 or 3 dimensional gradients. This is partucularly useful when the gradient of a basis concatenation object is quite complex, eg. >>> X = np.random.randn(100, 3) >>> ...
def ensure(self, func, *args, **kwargs): r""" Wraps around a function. A cfgstr must be stored in the base cacher. Args: func (callable): function that will compute data on cache miss *args: passed to func **kwargs: passed to func Example: ...
r""" Wraps around a function. A cfgstr must be stored in the base cacher. Args: func (callable): function that will compute data on cache miss *args: passed to func **kwargs: passed to func Example: >>> from ubelt.util_cache import * # NOQA ...
Below is the the instruction that describes the task: ### Input: r""" Wraps around a function. A cfgstr must be stored in the base cacher. Args: func (callable): function that will compute data on cache miss *args: passed to func **kwargs: passed to func ...
def flexifunction_buffer_function_encode(self, target_system, target_component, func_index, func_count, data_address, data_size, data): ''' Flexifunction type and parameters for component at function index from buffer target_system : System ID...
Flexifunction type and parameters for component at function index from buffer target_system : System ID (uint8_t) target_component : Component ID (uint8_t) func_index : Function index (uint16_t) func_cou...
Below is the the instruction that describes the task: ### Input: Flexifunction type and parameters for component at function index from buffer target_system : System ID (uint8_t) target_component : Component ID (uint8_t) func_inde...
def admin(self): """points to the adminstrative side of ArcGIS Server""" if self._securityHandler is None: raise Exception("Cannot connect to adminstrative server without authentication") from ..manageags import AGSAdministration return AGSAdministration(url=self._adminUrl, ...
points to the adminstrative side of ArcGIS Server
Below is the the instruction that describes the task: ### Input: points to the adminstrative side of ArcGIS Server ### Response: def admin(self): """points to the adminstrative side of ArcGIS Server""" if self._securityHandler is None: raise Exception("Cannot connect to adminstrative se...
def check(self): """ Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for whether the windows are synchron...
Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for whether the windows are synchronised.
Below is the the instruction that describes the task: ### Input: Checks the values of the window pairs. If any problems are found, it flags them by changing the background colour. Returns (status, synced) status : flag for whether parameters are viable at all synced : flag for ...
def unit(self, unit): """Sets the unit of this Dimensions. :param unit: The unit of this Dimensions. :type: str """ allowed_values = ["cm", "inch", "foot"] # noqa: E501 if unit is not None and unit not in allowed_values: raise ValueError( "I...
Sets the unit of this Dimensions. :param unit: The unit of this Dimensions. :type: str
Below is the the instruction that describes the task: ### Input: Sets the unit of this Dimensions. :param unit: The unit of this Dimensions. :type: str ### Response: def unit(self, unit): """Sets the unit of this Dimensions. :param unit: The unit of this Dimensions. :typ...
def _cdf(self, xloc, left, right, cache): """ Cumulative distribution function. Example: >>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.5 1. 1. ] >>> print(Mul(chaospy.Uniform(), 2).fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.25 0.75 1. ...
Cumulative distribution function. Example: >>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.5 1. 1. ] >>> print(Mul(chaospy.Uniform(), 2).fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.25 0.75 1. ] >>> print(Mul(2, chaospy.Uniform()).fwd([-0.5, 0...
Below is the the instruction that describes the task: ### Input: Cumulative distribution function. Example: >>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.5 1. 1. ] >>> print(Mul(chaospy.Uniform(), 2).fwd([-0.5, 0.5, 1.5, 2.5])) [0. 0.25 0....
async def discover_nupnp(websession): """Discover bridges via NUPNP.""" async with websession.get(URL_NUPNP) as res: return [Bridge(item['internalipaddress'], websession=websession) for item in (await res.json())]
Discover bridges via NUPNP.
Below is the the instruction that describes the task: ### Input: Discover bridges via NUPNP. ### Response: async def discover_nupnp(websession): """Discover bridges via NUPNP.""" async with websession.get(URL_NUPNP) as res: return [Bridge(item['internalipaddress'], websession=websession) ...
def _make_hostport(conn, default_host, default_port, default_user='', default_password=None): """Convert a '[user[:pass]@]host:port' string to a Connection tuple. If the given connection is empty, use defaults. If no port is given, use the default. Args: conn (str): the string describing the t...
Convert a '[user[:pass]@]host:port' string to a Connection tuple. If the given connection is empty, use defaults. If no port is given, use the default. Args: conn (str): the string describing the target hsot/port default_host (str): the host to use if ``conn`` is empty default_port...
Below is the the instruction that describes the task: ### Input: Convert a '[user[:pass]@]host:port' string to a Connection tuple. If the given connection is empty, use defaults. If no port is given, use the default. Args: conn (str): the string describing the target hsot/port default_...
def desired_destination(self, network, edge): """Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in the :class:...
Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in the :class:`QueueNetwork's<.QueueNetwork>` transition matrix...
Below is the the instruction that describes the task: ### Input: Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in...
def prob_flat(m1, m2, s1z, s2z, **kwargs): ''' Return probability density for uniform in component mass Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1 (not in use currently) ...
Return probability density for uniform in component mass Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1 (not in use currently) s2z: Aligned spin 2 (not in use curren...
Below is the the instruction that describes the task: ### Input: Return probability density for uniform in component mass Parameters ---------- m1: array Component masses 1 m2: array Component masses 2 s1z: array Aligned spin 1 (not in use ...
def _vars_match(self): """Regular expression to match playbook variable.""" return re.compile( r'#([A-Za-z]+)' # match literal (#App) at beginning of String r':([\d]+)' # app id (:7979) r':([A-Za-z0-9_\.\-\[\]]+)' # variable name (:variable_name) r'!(St...
Regular expression to match playbook variable.
Below is the the instruction that describes the task: ### Input: Regular expression to match playbook variable. ### Response: def _vars_match(self): """Regular expression to match playbook variable.""" return re.compile( r'#([A-Za-z]+)' # match literal (#App) at beginning of String ...
def _stamp_and_update_hook(method, # suppress(too-many-arguments) dependencies, stampfile, func, *args, **kwargs): """Write stamp and call update_stampfile_hook on method.""" r...
Write stamp and call update_stampfile_hook on method.
Below is the the instruction that describes the task: ### Input: Write stamp and call update_stampfile_hook on method. ### Response: def _stamp_and_update_hook(method, # suppress(too-many-arguments) dependencies, stampfile, func, ...
def parseModuleNameAndSpec(module_name_and_spec): ''' Parse modulename[@versionspec] and return a tuple (module_name_string, version_spec_string). Also accepts raw github version specs (Owner/reponame#whatever), as the name can be deduced from these. Note that the specification spl...
Parse modulename[@versionspec] and return a tuple (module_name_string, version_spec_string). Also accepts raw github version specs (Owner/reponame#whatever), as the name can be deduced from these. Note that the specification split from the name is not validated. If there is no ...
Below is the the instruction that describes the task: ### Input: Parse modulename[@versionspec] and return a tuple (module_name_string, version_spec_string). Also accepts raw github version specs (Owner/reponame#whatever), as the name can be deduced from these. Note that the specif...
def tobinarray(self, start=None, end=None, size=None): '''Convert this object to binary form as array (of 2-bytes word data). If start and end unspecified, they will be inferred from the data. @param start start address of output data. @param end end address of output data (inclu...
Convert this object to binary form as array (of 2-bytes word data). If start and end unspecified, they will be inferred from the data. @param start start address of output data. @param end end address of output data (inclusive). @param size size of the block (number of words)...
Below is the the instruction that describes the task: ### Input: Convert this object to binary form as array (of 2-bytes word data). If start and end unspecified, they will be inferred from the data. @param start start address of output data. @param end end address of output data (in...
def titletable(html_doc, tofloat=True): """return a list of [(title, table), .....] title = previous item with a <b> tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]""" soup = BeautifulSoup(html_doc, "html.parser") btables = soup.find_all(['b', 'table']) # find all the <b> and <tabl...
return a list of [(title, table), .....] title = previous item with a <b> tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..]
Below is the the instruction that describes the task: ### Input: return a list of [(title, table), .....] title = previous item with a <b> tag table = rows -> [[cell1, cell2, ..], [cell1, cell2, ..], ..] ### Response: def titletable(html_doc, tofloat=True): """return a list of [(title, table), .....] ...
def tree(self, expand=False, level=None): """Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional Maximum depth ...
Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional Maximum depth to descend into hierarchy. Examples ...
Below is the the instruction that describes the task: ### Input: Provide a ``print``-able display of the hierarchy. Parameters ---------- expand : bool, optional Only relevant for HTML representation. If True, tree will be fully expanded. level : int, optional ...
def from_date(self, value: date) -> datetime: """ Initializes from the given date value """ assert isinstance(value, date) #self.value = datetime.combine(value, time.min) self.value = datetime(value.year, value.month, value.day) return self.value
Initializes from the given date value
Below is the the instruction that describes the task: ### Input: Initializes from the given date value ### Response: def from_date(self, value: date) -> datetime: """ Initializes from the given date value """ assert isinstance(value, date) #self.value = datetime.combine(value, time.min) ...
def _failure_raiser(validation_callable, # type: Callable failure_type=None, # type: Type[WrappingFailure] help_msg=None, # type: str **kw_context_args): # type: (...) -> Callable """ Wraps the provided validation function so that in ...
Wraps the provided validation function so that in case of failure it raises the given failure_type or a WrappingFailure with the given help message. :param validation_callable: :param failure_type: an optional subclass of `WrappingFailure` that should be raised in case of failure, instead of `WrappingF...
Below is the the instruction that describes the task: ### Input: Wraps the provided validation function so that in case of failure it raises the given failure_type or a WrappingFailure with the given help message. :param validation_callable: :param failure_type: an optional subclass of `WrappingFailure...
def switch_to_frame_with_class(self, frame): """Swap Selenium's context to the given frame or iframe.""" elem = world.browser.find_element_by_class_name(frame) world.browser.switch_to.frame(elem)
Swap Selenium's context to the given frame or iframe.
Below is the the instruction that describes the task: ### Input: Swap Selenium's context to the given frame or iframe. ### Response: def switch_to_frame_with_class(self, frame): """Swap Selenium's context to the given frame or iframe.""" elem = world.browser.find_element_by_class_name(frame) world.brow...
def _do_ned_namesearch_queries_and_add_resulting_metadata_to_database( self, batchCount): """*Query NED via name searcha and add result metadata to database* **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED (only needed for printing to ...
*Query NED via name searcha and add result metadata to database* **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED (only needed for printing to STDOUT to give user idea of progress) *Usage:* .. code-block:: python numberSources = ...
Below is the the instruction that describes the task: ### Input: *Query NED via name searcha and add result metadata to database* **Key Arguments:** - ``batchCount`` - the index number of the batch sent to NED (only needed for printing to STDOUT to give user idea of progress) *Usage:* ...
def apply_T2(word): '''There is a syllable boundary within a sequence VV of two nonidentical that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].''' WORD = _split_consonants_and_vowels(word) for k, v in WORD.iteritems(): if is_diphthong(v): continue if len(v) == 2 ...
There is a syllable boundary within a sequence VV of two nonidentical that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa].
Below is the the instruction that describes the task: ### Input: There is a syllable boundary within a sequence VV of two nonidentical that are not a genuine diphthong, e.g., [ta.e], [ko.et.taa]. ### Response: def apply_T2(word): '''There is a syllable boundary within a sequence VV of two nonidentical ...
def predict_proba(self, X): """Returns the value of the nearest neighbor from the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and i...
Returns the value of the nearest neighbor from the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ``dtype=np.float32`` and if a sparse matrix is provided ...
Below is the the instruction that describes the task: ### Input: Returns the value of the nearest neighbor from the training set. Parameters ---------- X : array-like or sparse matrix, shape (n_samples, n_features) The input samples. Internally, it will be converted to ...
def voucher_code(request): ''' A view *just* for entering a voucher form. ''' VOUCHERS_FORM_PREFIX = "vouchers" # Handle the voucher form *before* listing products. # Products can change as vouchers are entered. v = _handle_voucher(request, VOUCHERS_FORM_PREFIX) voucher_form, voucher_handled =...
A view *just* for entering a voucher form.
Below is the the instruction that describes the task: ### Input: A view *just* for entering a voucher form. ### Response: def voucher_code(request): ''' A view *just* for entering a voucher form. ''' VOUCHERS_FORM_PREFIX = "vouchers" # Handle the voucher form *before* listing products. # Products...
def excite(self, currentActivation, inputs): """ Increases current activation by amount. @param currentActivation (numpy array) Current activation levels for each cell @param inputs (numpy array) inputs for each cell """ currentActivation += self._minValue + (self._maxValue - self._m...
Increases current activation by amount. @param currentActivation (numpy array) Current activation levels for each cell @param inputs (numpy array) inputs for each cell
Below is the the instruction that describes the task: ### Input: Increases current activation by amount. @param currentActivation (numpy array) Current activation levels for each cell @param inputs (numpy array) inputs for each cell ### Response: def excite(self, currentActivation, inputs): ...
def parse_xdot_drawing_directive(self, new): """ Parses the drawing directive, updating the node components. """ components = XdotAttrParser().parse_xdot_data(new) max_x = max( [c.bounds[0] for c in components] + [1] ) max_y = max( [c.bounds[1] for c in components] + [1] ) ...
Parses the drawing directive, updating the node components.
Below is the the instruction that describes the task: ### Input: Parses the drawing directive, updating the node components. ### Response: def parse_xdot_drawing_directive(self, new): """ Parses the drawing directive, updating the node components. """ components = XdotAttrParser().parse_xdo...
def read(self, size=-1): """ Read and return up to size bytes, with at most one call to the underlying raw stream’s. Use at most one call to the underlying raw stream’s read method. Args: size (int): Number of bytes to read. -1 to read the stream unt...
Read and return up to size bytes, with at most one call to the underlying raw stream’s. Use at most one call to the underlying raw stream’s read method. Args: size (int): Number of bytes to read. -1 to read the stream until end. Returns: bytes: ...
Below is the the instruction that describes the task: ### Input: Read and return up to size bytes, with at most one call to the underlying raw stream’s. Use at most one call to the underlying raw stream’s read method. Args: size (int): Number of bytes to read. -1 to read the ...
def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ if from_symbol == to_symbol: return value factor = conversion_factor(from_symbol, to_symbol, date) if type(value) == float: output = ...
Converts an amount of money from one currency to another on a specified date.
Below is the the instruction that describes the task: ### Input: Converts an amount of money from one currency to another on a specified date. ### Response: def convert_currency(from_symbol, to_symbol, value, date): """ Converts an amount of money from one currency to another on a specified date. """ ...
def variable_relative(self, r: float) -> mm.ModelMapper: """ Parameters ---------- r The relative width of gaussian priors Returns ------- A model mapper created by taking results from this phase and creating priors with the defined relative width. ...
Parameters ---------- r The relative width of gaussian priors Returns ------- A model mapper created by taking results from this phase and creating priors with the defined relative width.
Below is the the instruction that describes the task: ### Input: Parameters ---------- r The relative width of gaussian priors Returns ------- A model mapper created by taking results from this phase and creating priors with the defined relative width. ### Respon...
def _can_change_or_view(model, user): """ Return True iff `user` has either change or view permission for `model`. """ model_name = model._meta.model_name app_label = model._meta.app_label can_change = user.has_perm(app_label + '.change_' + model_name) can_view = user.has_perm(app_label + '....
Return True iff `user` has either change or view permission for `model`.
Below is the the instruction that describes the task: ### Input: Return True iff `user` has either change or view permission for `model`. ### Response: def _can_change_or_view(model, user): """ Return True iff `user` has either change or view permission for `model`. """ model_name = model._meta...
def _parse_device_path(self, device_path, char_path_override=None): """Parse each device and add to the approriate list.""" # 1. Make sure that we can parse the device path. try: device_type = device_path.rsplit('-', 1)[1] except IndexError: warn("The following d...
Parse each device and add to the approriate list.
Below is the the instruction that describes the task: ### Input: Parse each device and add to the approriate list. ### Response: def _parse_device_path(self, device_path, char_path_override=None): """Parse each device and add to the approriate list.""" # 1. Make sure that we can parse the device p...
def ilookup(self, name): """Lookup the inferred values of the given variable. :param name: The variable name to find values for. :type name: str :returns: The inferred values of the statements returned from :meth:`lookup`. :rtype: iterable """ frame,...
Lookup the inferred values of the given variable. :param name: The variable name to find values for. :type name: str :returns: The inferred values of the statements returned from :meth:`lookup`. :rtype: iterable
Below is the the instruction that describes the task: ### Input: Lookup the inferred values of the given variable. :param name: The variable name to find values for. :type name: str :returns: The inferred values of the statements returned from :meth:`lookup`. :rtype: it...
def save(coll, to_save): """ Pymongo has deprecated the save logic, even though MongoDB still advertizes that logic in the core API: https://docs.mongodb.com/manual/reference/method/db.collection.save/ This function provides a compatible interface. """ filter = Projection(['_id'], to_save) upsert_replace = fun...
Pymongo has deprecated the save logic, even though MongoDB still advertizes that logic in the core API: https://docs.mongodb.com/manual/reference/method/db.collection.save/ This function provides a compatible interface.
Below is the the instruction that describes the task: ### Input: Pymongo has deprecated the save logic, even though MongoDB still advertizes that logic in the core API: https://docs.mongodb.com/manual/reference/method/db.collection.save/ This function provides a compatible interface. ### Response: def save(col...
def verify_password(self, password): """ Verify a given string for being valid password """ if self.password is None: return False from boiler.user.util.passlib import passlib_context return passlib_context.verify(str(password), self.password)
Verify a given string for being valid password
Below is the the instruction that describes the task: ### Input: Verify a given string for being valid password ### Response: def verify_password(self, password): """ Verify a given string for being valid password """ if self.password is None: return False from boiler.user.util...
def encode(self, s): """Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, then these temporary OOV numbers will be...
Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, then these temporary OOV numbers will be 50000, 50001, 50002. A...
Below is the the instruction that describes the task: ### Input: Converts a space-separated string of tokens to lists of ids. Also store temporary vocabulary IDs for source OOV tokens. OOVs are represented by their temporary OOV number. E.g., if the vocabulary size is 50k and the source has 3 OOVs, the...
def print_docs(self): ''' Print out the documentation! ''' arg = self.opts.get('fun', None) docs = super(Runner, self).get_docs(arg) for fun in sorted(docs): display_output('{0}:'.format(fun), 'text', self.opts) print(docs[fun])
Print out the documentation!
Below is the the instruction that describes the task: ### Input: Print out the documentation! ### Response: def print_docs(self): ''' Print out the documentation! ''' arg = self.opts.get('fun', None) docs = super(Runner, self).get_docs(arg) for fun in sorted(docs): ...
def get_operation_ast( document_ast: DocumentNode, operation_name: Optional[str] = None ) -> Optional[OperationDefinitionNode]: """Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one...
Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document.
Below is the the instruction that describes the task: ### Input: Get operation AST node. Returns an operation AST given a document AST and optionally an operation name. If a name is not provided, an operation is only returned if only one is provided in the document. ### Response: def get_operation_ast...
def update(self, **kwargs): """ Main entrypoint to kick off an update run. :param kwargs: :return: RequirementsBundle """ self.configure(**kwargs) self.get_all_requirements() self.apply_updates( initial=kwargs.get("initial", False), ...
Main entrypoint to kick off an update run. :param kwargs: :return: RequirementsBundle
Below is the the instruction that describes the task: ### Input: Main entrypoint to kick off an update run. :param kwargs: :return: RequirementsBundle ### Response: def update(self, **kwargs): """ Main entrypoint to kick off an update run. :param kwargs: :return: Req...
def setFilter(self, search): """ Apply a filter and hide rows. The filter must be a `DataSearch` object, which evaluates a python expression. If there was an error while parsing the expression, the data will remain unfiltered. Args: search(qtpandas.D...
Apply a filter and hide rows. The filter must be a `DataSearch` object, which evaluates a python expression. If there was an error while parsing the expression, the data will remain unfiltered. Args: search(qtpandas.DataSearch): data search object to use. R...
Below is the the instruction that describes the task: ### Input: Apply a filter and hide rows. The filter must be a `DataSearch` object, which evaluates a python expression. If there was an error while parsing the expression, the data will remain unfiltered. Args: ...
def ikev2scan(ip, **kwargs): """Send a IKEv2 SA to an IP and wait for answers.""" return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8), exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs)
Send a IKEv2 SA to an IP and wait for answers.
Below is the the instruction that describes the task: ### Input: Send a IKEv2 SA to an IP and wait for answers. ### Response: def ikev2scan(ip, **kwargs): """Send a IKEv2 SA to an IP and wait for answers.""" return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8), ...
def plot_roc_curve(y_true, y_probas, title='ROC Curves', curves=('micro', 'macro', 'each_class'), ax=None, figsize=None, cmap='nipy_spectral', title_fontsize="large", text_fontsize="medium"): """Generates the ROC curves from labels and predicted scores/probab...
Generates the ROC curves from labels and predicted scores/probabilities Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probas (array-like, shape (n_samples, n_classes)): Prediction probabilities for each class returned by a classifier....
Below is the the instruction that describes the task: ### Input: Generates the ROC curves from labels and predicted scores/probabilities Args: y_true (array-like, shape (n_samples)): Ground truth (correct) target values. y_probas (array-like, shape (n_samples, n_classes)): ...
def expand_labels(labels, subtopic=False): '''Expand a set of labels that define a connected component. ``labels`` must define a *positive* connected component: it is all of the edges that make up the *single* connected component in the :class:`LabelStore`. expand will ignore subtopic assignments, and ...
Expand a set of labels that define a connected component. ``labels`` must define a *positive* connected component: it is all of the edges that make up the *single* connected component in the :class:`LabelStore`. expand will ignore subtopic assignments, and annotator_id will be an arbitrary one selected...
Below is the the instruction that describes the task: ### Input: Expand a set of labels that define a connected component. ``labels`` must define a *positive* connected component: it is all of the edges that make up the *single* connected component in the :class:`LabelStore`. expand will ignore subtopi...
def fetch_access_token(self): """ 获取 access token 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档 :return: 返回的 JSON 数据包 """ return self._fetch_access_token( url='https://api.weixin.qq.com/cgi-bin/token', params={ 'grant_t...
获取 access token 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档 :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 获取 access token 详情请参考 http://mp.weixin.qq.com/wiki/index.php?title=通用接口文档 :return: 返回的 JSON 数据包 ### Response: def fetch_access_token(self): """ 获取 access token 详情请参考 http://mp.weixin.qq.com/wiki/index.php?titl...
def _bowtie_major_version(stdout): """ bowtie --version returns strings like this: bowtie version 0.12.7 32-bit Built on Franklin.local Tue Sep 7 14:25:02 PDT 2010 """ version_line = stdout.split("\n")[0] version_string = version_line.strip().split()[2] major_version = int(versi...
bowtie --version returns strings like this: bowtie version 0.12.7 32-bit Built on Franklin.local Tue Sep 7 14:25:02 PDT 2010
Below is the the instruction that describes the task: ### Input: bowtie --version returns strings like this: bowtie version 0.12.7 32-bit Built on Franklin.local Tue Sep 7 14:25:02 PDT 2010 ### Response: def _bowtie_major_version(stdout): """ bowtie --version returns strings like this: ...
def aspirate(self, volume: float = None, location: Union[types.Location, Well] = None, rate: float = 1.0) -> 'InstrumentContext': """ Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only...
Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only a volume is passed, the pipette will aspirate from its current position. If only a location is passed, :py:meth:`aspirate` will default to its :py:attr:`max_volume`. :param vo...
Below is the the instruction that describes the task: ### Input: Aspirate a volume of liquid (in microliters/uL) using this pipette from the specified location If only a volume is passed, the pipette will aspirate from its current position. If only a location is passed, :py:meth:`as...
def _input_arg(self, a): """ Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action """ # if action of an argument that suppresses any other, just return if a.dest == SUPPRES...
Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action
Below is the the instruction that describes the task: ### Input: Ask the user for input of a single argument. :param a: argparse.Action instance :return: the user input, asked according to the action ### Response: def _input_arg(self, a): """ Ask the user for input of a si...
def update(self, *pkgs, **kwargs): """Update package(s) (in an environment) by name.""" cmd_list = ['update', '--json', '--yes'] if not pkgs and not kwargs.get('all'): raise TypeError("Must specify at least one package to update, or " "all=True.") ...
Update package(s) (in an environment) by name.
Below is the the instruction that describes the task: ### Input: Update package(s) (in an environment) by name. ### Response: def update(self, *pkgs, **kwargs): """Update package(s) (in an environment) by name.""" cmd_list = ['update', '--json', '--yes'] if not pkgs and not kwargs.get('all...
def dateAndDepthFromOoid(ooid): """ Extract the encoded date and expected storage depth from an ooid. ooid: The ooid from which to extract the info returns (datetime(yyyy,mm,dd),depth) if the ooid is in expected format else (None,None) """ year = month = day = None try: day = int(ooid[-2:]) except: ...
Extract the encoded date and expected storage depth from an ooid. ooid: The ooid from which to extract the info returns (datetime(yyyy,mm,dd),depth) if the ooid is in expected format else (None,None)
Below is the the instruction that describes the task: ### Input: Extract the encoded date and expected storage depth from an ooid. ooid: The ooid from which to extract the info returns (datetime(yyyy,mm,dd),depth) if the ooid is in expected format else (None,None) ### Response: def dateAndDepthFromOoid(ooid): ...
def validate(wire, keyname, secret, now, request_mac, tsig_start, tsig_rdata, tsig_rdlen, ctx=None, multi=False, first=True): """Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew betwe...
Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew between the client and the server. @raises BadSignature: The TSIG signature did not validate @rtype: hmac.HMAC object
Below is the the instruction that describes the task: ### Input: Validate the specified TSIG rdata against the other input parameters. @raises FormError: The TSIG is badly formed. @raises BadTime: There is too much time skew between the client and the server. @raises BadSignature: The TSIG signatur...
def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt=_DEFAULT_FLOATFMT, numalign="decimal", stralign="left", missingval=_DEFAULT_MISSINGVAL, showindex="default", disable_numparse=False): """Format a fixed width table for pretty printing. """ if tabular_da...
Format a fixed width table for pretty printing.
Below is the the instruction that describes the task: ### Input: Format a fixed width table for pretty printing. ### Response: def tabulate(tabular_data, headers=(), tablefmt="simple", floatfmt=_DEFAULT_FLOATFMT, numalign="decimal", stralign="left", missingval=_DEFAULT_MISSINGVAL, showind...
def templates(self): """ Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager """ if self._template_manager is None: self._template_manager = TemplateManager(session=self._sessi...
Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager
Below is the the instruction that describes the task: ### Input: Property for accessing :class:`TemplateManager` instance, which is used to manage templates. :rtype: yagocd.resources.template.TemplateManager ### Response: def templates(self): """ Property for accessing :class:`TemplateMana...
def eval(self, expression, use_compilation_plan=False): """evaluates expression in current context and returns its value""" code = 'PyJsEvalResult = eval(%s)' % json.dumps(expression) self.execute(code, use_compilation_plan=use_compilation_plan) return self['PyJsEvalResult']
evaluates expression in current context and returns its value
Below is the the instruction that describes the task: ### Input: evaluates expression in current context and returns its value ### Response: def eval(self, expression, use_compilation_plan=False): """evaluates expression in current context and returns its value""" code = 'PyJsEvalResult = eval(%s)'...
def needs_values(func): """Returns method assuring we read values (on demand) before we try to access them""" @wraps(func) def assure_data_present(self, *args, **kwargs): self.read() return func(self, *args, **kwargs) # END wrapper method return assure_data_present
Returns method assuring we read values (on demand) before we try to access them
Below is the the instruction that describes the task: ### Input: Returns method assuring we read values (on demand) before we try to access them ### Response: def needs_values(func): """Returns method assuring we read values (on demand) before we try to access them""" @wraps(func) def assure_data_pres...
def master(self, name): """Returns a dictionary containing the specified masters state.""" fut = self.execute(b'MASTER', name, encoding='utf-8') return wait_convert(fut, parse_sentinel_master)
Returns a dictionary containing the specified masters state.
Below is the the instruction that describes the task: ### Input: Returns a dictionary containing the specified masters state. ### Response: def master(self, name): """Returns a dictionary containing the specified masters state.""" fut = self.execute(b'MASTER', name, encoding='utf-8') return...
def _finalize_run(self): """Called by the environment after storing to perform some rollback operations. All results and derived parameters created in the current run are removed. Important for single processing to not blow up the parent trajectory with the results of all runs. ...
Called by the environment after storing to perform some rollback operations. All results and derived parameters created in the current run are removed. Important for single processing to not blow up the parent trajectory with the results of all runs.
Below is the the instruction that describes the task: ### Input: Called by the environment after storing to perform some rollback operations. All results and derived parameters created in the current run are removed. Important for single processing to not blow up the parent trajectory with the res...
def WriteMessagesFile(file_descriptor, package, version, printer): """Write the given extended file descriptor to out as a message file.""" _WriteFile(file_descriptor, package, version, _Proto2Printer(printer))
Write the given extended file descriptor to out as a message file.
Below is the the instruction that describes the task: ### Input: Write the given extended file descriptor to out as a message file. ### Response: def WriteMessagesFile(file_descriptor, package, version, printer): """Write the given extended file descriptor to out as a message file.""" _WriteFile(file_descr...
def Gram_matrix(self, F, F1, F2, F3, lower, upper): """ Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1. :param F: vector of functions :type F: np.array :param F1: vector of derivatives of F ...
Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1. :param F: vector of functions :type F: np.array :param F1: vector of derivatives of F :type F1: np.array :param F2: vector of second derivatives...
Below is the the instruction that describes the task: ### Input: Return the Gram matrix of the vector of functions F with respect to the RKHS norm. The use of this function is limited to input_dim=1. :param F: vector of functions :type F: np.array :param F1: vector of derivatives of F ...
def validate_options(options): """Validate Google Cloud Storage options. Args: options: a str->basestring dict of options to pass to Google Cloud Storage. Raises: ValueError: if option is not supported. TypeError: if option is not of type str or value of an option is not of type basestring. ...
Validate Google Cloud Storage options. Args: options: a str->basestring dict of options to pass to Google Cloud Storage. Raises: ValueError: if option is not supported. TypeError: if option is not of type str or value of an option is not of type basestring.
Below is the the instruction that describes the task: ### Input: Validate Google Cloud Storage options. Args: options: a str->basestring dict of options to pass to Google Cloud Storage. Raises: ValueError: if option is not supported. TypeError: if option is not of type str or value of an option ...
def clone(self): """todo: Docstring for clone :return: :rtype: """ logger.debug("") if not self.url: estr = "Cannot install this repos without a URL. %s" % self.info() logger.warning(estr) raise ValueError(estr) # check if...
todo: Docstring for clone :return: :rtype:
Below is the the instruction that describes the task: ### Input: todo: Docstring for clone :return: :rtype: ### Response: def clone(self): """todo: Docstring for clone :return: :rtype: """ logger.debug("") if not self.url: estr = "Can...
def syntax(self): """ Executes ``ansible-playbook`` against the converge playbook with the ``-syntax-check`` flag and returns None. :return: None """ pb = self._get_ansible_playbook(self.playbooks.converge) pb.add_cli_arg('syntax-check', True) pb.execute(...
Executes ``ansible-playbook`` against the converge playbook with the ``-syntax-check`` flag and returns None. :return: None
Below is the the instruction that describes the task: ### Input: Executes ``ansible-playbook`` against the converge playbook with the ``-syntax-check`` flag and returns None. :return: None ### Response: def syntax(self): """ Executes ``ansible-playbook`` against the converge playbo...
def parse(self, declarations_str): """Generates (prop, value) pairs from declarations In a future version may generate parsed tokens from tinycss/tinycss2 """ for decl in declarations_str.split(';'): if not decl.strip(): continue prop, sep, val = ...
Generates (prop, value) pairs from declarations In a future version may generate parsed tokens from tinycss/tinycss2
Below is the the instruction that describes the task: ### Input: Generates (prop, value) pairs from declarations In a future version may generate parsed tokens from tinycss/tinycss2 ### Response: def parse(self, declarations_str): """Generates (prop, value) pairs from declarations In a fu...
def get_all_results(starting_page): """ Given starting API query for Open Humans, iterate to get all results. :param starting page: This field is the first page, starting from which results will be obtained. """ logging.info('Retrieving all results for {}'.format(starting_page)) page = ...
Given starting API query for Open Humans, iterate to get all results. :param starting page: This field is the first page, starting from which results will be obtained.
Below is the the instruction that describes the task: ### Input: Given starting API query for Open Humans, iterate to get all results. :param starting page: This field is the first page, starting from which results will be obtained. ### Response: def get_all_results(starting_page): """ Given s...
def _find_usages_vpn_gateways(self): """find usage of vpn gateways""" # do not include deleting and deleted in the results vpngws = self.conn.describe_vpn_gateways(Filters=[ { 'Name': 'state', 'Values': [ 'available', ...
find usage of vpn gateways
Below is the the instruction that describes the task: ### Input: find usage of vpn gateways ### Response: def _find_usages_vpn_gateways(self): """find usage of vpn gateways""" # do not include deleting and deleted in the results vpngws = self.conn.describe_vpn_gateways(Filters=[ ...
def _as_dict(self) -> Dict[str, JsonTypes]: """ Convert a JsonObj into a straight dictionary :return: dictionary that cooresponds to the json object """ return {k: v._as_dict if isinstance(v, JsonObj) else self.__as_list(v) if isinstance(v, list) else ...
Convert a JsonObj into a straight dictionary :return: dictionary that cooresponds to the json object
Below is the the instruction that describes the task: ### Input: Convert a JsonObj into a straight dictionary :return: dictionary that cooresponds to the json object ### Response: def _as_dict(self) -> Dict[str, JsonTypes]: """ Convert a JsonObj into a straight dictionary :return: diction...
def remove_child_repository(self, repository_id, child_id): """Removes a child from a repository. arg: repository_id (osid.id.Id): the ``Id`` of a repository arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``repository_id`` not a parent of ...
Removes a child from a repository. arg: repository_id (osid.id.Id): the ``Id`` of a repository arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``repository_id`` not a parent of ``child_id`` raise: NullArgument - ``repository_id`` or ``ch...
Below is the the instruction that describes the task: ### Input: Removes a child from a repository. arg: repository_id (osid.id.Id): the ``Id`` of a repository arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``repository_id`` not a parent of ...
def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, six.integer_types) return str(value).encode("utf_8")
Returns field's single value prepared for saving into a database.
Below is the the instruction that describes the task: ### Input: Returns field's single value prepared for saving into a database. ### Response: def value_to_db(self, value): """ Returns field's single value prepared for saving into a database. """ assert isinstance(value, six.integer_types) ...
def rebin_spec(spec, wavnew, oversamp=100, plot=False): """ Rebin a spectrum to a new wavelength array while preserving the total flux Parameters ---------- spec: array-like The wavelength and flux to be binned wavenew: array-like The new wavelength array Returns --...
Rebin a spectrum to a new wavelength array while preserving the total flux Parameters ---------- spec: array-like The wavelength and flux to be binned wavenew: array-like The new wavelength array Returns ------- np.ndarray The rebinned flux
Below is the the instruction that describes the task: ### Input: Rebin a spectrum to a new wavelength array while preserving the total flux Parameters ---------- spec: array-like The wavelength and flux to be binned wavenew: array-like The new wavelength array Returns -...
def expiry_time(ns, cavs): ''' Returns the minimum time of any time-before caveats found in the given list or None if no such caveats were found. The ns parameter is :param ns: used to determine the standard namespace prefix - if the standard namespace is not found, the empty prefix is assumed. ...
Returns the minimum time of any time-before caveats found in the given list or None if no such caveats were found. The ns parameter is :param ns: used to determine the standard namespace prefix - if the standard namespace is not found, the empty prefix is assumed. :param cavs: a list of pymacaroons...
Below is the the instruction that describes the task: ### Input: Returns the minimum time of any time-before caveats found in the given list or None if no such caveats were found. The ns parameter is :param ns: used to determine the standard namespace prefix - if the standard namespace is not found...
def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dict The quote for this instruments """ if self in self.parent.quotes.keys(): return self.parent.quotes[self] return None
Get last quote for this instrument :Retruns: quote : dict The quote for this instruments
Below is the the instruction that describes the task: ### Input: Get last quote for this instrument :Retruns: quote : dict The quote for this instruments ### Response: def get_quote(self): """ Get last quote for this instrument :Retruns: quote : dic...
def to_dict(jfile, key_path=None, in_memory=True, ignore_prefix=('.', '_'), parse_decimal=False): """ input json to dict Parameters ---------- jfile : str, file_like or path_like if str, must be existing file or folder, if file_like, must have 'read' method if path_l...
input json to dict Parameters ---------- jfile : str, file_like or path_like if str, must be existing file or folder, if file_like, must have 'read' method if path_like, must have 'iterdir' method (see pathlib.Path) key_path : list[str] a list of keys to index into the j...
Below is the the instruction that describes the task: ### Input: input json to dict Parameters ---------- jfile : str, file_like or path_like if str, must be existing file or folder, if file_like, must have 'read' method if path_like, must have 'iterdir' method (see pathlib.Path...
def get_pv(self, device): """ Returns the physical volume associated with the given device:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.get_pv("/dev/sdb1") *Args:* * device (str): An existing device. ...
Returns the physical volume associated with the given device:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.get_pv("/dev/sdb1") *Args:* * device (str): An existing device. *Raises:* * ValueError, Hand...
Below is the the instruction that describes the task: ### Input: Returns the physical volume associated with the given device:: from lvm2py import * lvm = LVM() vg = lvm.get_vg("myvg", "w") vg.get_pv("/dev/sdb1") *Args:* * device (str): An ...
def get_fieldsets(self, fieldsets=None): """ This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to generate fieldsets for. If no fieldsets argument is passed, the class property ``fieldsets`` is used. When generating...
This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to generate fieldsets for. If no fieldsets argument is passed, the class property ``fieldsets`` is used. When generating the fieldsets, the method ensures that at least one fielset ...
Below is the the instruction that describes the task: ### Input: This method returns a generator which yields fieldset instances. The method uses the optional fieldsets argument to generate fieldsets for. If no fieldsets argument is passed, the class property ``fieldsets`` is used. When ge...
def modified_environ(*remove: str, **update: str) -> Iterator[None]: """ Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state when finished. (https://stackoverflow.com/questions/2059482/ python-temporarily-modify-the-current-processs-environment/34333710...
Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state when finished. (https://stackoverflow.com/questions/2059482/ python-temporarily-modify-the-current-processs-environment/34333710#34333710) The ``os.environ`` dictionary is updated in-place so that the mod...
Below is the the instruction that describes the task: ### Input: Temporarily updates the ``os.environ`` dictionary in-place and resets it to the original state when finished. (https://stackoverflow.com/questions/2059482/ python-temporarily-modify-the-current-processs-environment/34333710#34333710) ...
def EWFGlobPathSpec(file_system, path_spec): """Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: PathSpecError: if ...
Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: PathSpecError: if the path specification is invalid. RuntimeErro...
Below is the the instruction that describes the task: ### Input: Globs for path specifications according to the EWF naming schema. Args: file_system (FileSystem): file system. path_spec (PathSpec): path specification. Returns: list[PathSpec]: path specifications that match the glob. Raises: ...
def updateCameraTree(self): self.treelist.reset_() self.server = ServerListItem( name = "Localhost", ip = "127.0.0.1", parent = self.root) """ self.server1 = ServerListItem( name="First Server", ip="192.168.1.20", parent=self.root) """ """ ...
self.server1 = ServerListItem( name="First Server", ip="192.168.1.20", parent=self.root)
Below is the the instruction that describes the task: ### Input: self.server1 = ServerListItem( name="First Server", ip="192.168.1.20", parent=self.root) ### Response: def updateCameraTree(self): self.treelist.reset_() self.server = ServerListItem( name = "Localhost", ip = ...
def _create_jobs(self, target, jumpkind, current_function_addr, irsb, addr, cfg_node, ins_addr, stmt_idx): """ Given a node and details of a successor, makes a list of CFGJobs and if it is a call or exit marks it appropriately so in the CFG :param int target: Destination of the...
Given a node and details of a successor, makes a list of CFGJobs and if it is a call or exit marks it appropriately so in the CFG :param int target: Destination of the resultant job :param str jumpkind: The jumpkind of the edge going to this node :param int current_funct...
Below is the the instruction that describes the task: ### Input: Given a node and details of a successor, makes a list of CFGJobs and if it is a call or exit marks it appropriately so in the CFG :param int target: Destination of the resultant job :param str jumpkind: The jum...
def _groupname(): ''' Grain for the minion groupname ''' if grp: try: groupname = grp.getgrgid(os.getgid()).gr_name except KeyError: groupname = '' else: groupname = '' return groupname
Grain for the minion groupname
Below is the the instruction that describes the task: ### Input: Grain for the minion groupname ### Response: def _groupname(): ''' Grain for the minion groupname ''' if grp: try: groupname = grp.getgrgid(os.getgid()).gr_name except KeyError: groupname = '' ...
def longcount_generator(baktun, katun, tun, uinal, kin): '''Generate long counts, starting with input''' j = to_jd(baktun, katun, tun, uinal, kin) while True: yield from_jd(j) j = j + 1
Generate long counts, starting with input
Below is the the instruction that describes the task: ### Input: Generate long counts, starting with input ### Response: def longcount_generator(baktun, katun, tun, uinal, kin): '''Generate long counts, starting with input''' j = to_jd(baktun, katun, tun, uinal, kin) while True: yield from_jd(...
def ensure_params(kty, provided, required): """Ensure all required parameters are present in dictionary""" if not required <= provided: missing = required - provided raise MissingValue('Missing properties for kty={}, {}'.format(kty, str(list(missing))))
Ensure all required parameters are present in dictionary
Below is the the instruction that describes the task: ### Input: Ensure all required parameters are present in dictionary ### Response: def ensure_params(kty, provided, required): """Ensure all required parameters are present in dictionary""" if not required <= provided: missing = required - provid...
def contiguous(self): """Object-based iterator over contiguous range sets.""" pad = self.padding or 0 for sli in self._contiguous_slices(): yield RangeSet.fromone(slice(sli.start, sli.stop, sli.step), pad)
Object-based iterator over contiguous range sets.
Below is the the instruction that describes the task: ### Input: Object-based iterator over contiguous range sets. ### Response: def contiguous(self): """Object-based iterator over contiguous range sets.""" pad = self.padding or 0 for sli in self._contiguous_slices(): yield Rang...
def extract_params(): """Extract request params.""" uri = _get_uri_from_request(request) http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del headers['wsgi.input'] if 'wsgi.errors' in headers: del headers['wsgi.errors'] # Werkzeug, and...
Extract request params.
Below is the the instruction that describes the task: ### Input: Extract request params. ### Response: def extract_params(): """Extract request params.""" uri = _get_uri_from_request(request) http_method = request.method headers = dict(request.headers) if 'wsgi.input' in headers: del h...
def combinations(n, k, strength=1, vartype=BINARY): r"""Generate a bqm that is minimized when k of n variables are selected. More fully, we wish to generate a binary quadratic model which is minimized for each of the k-combinations of its variables. The energy for the binary quadratic model is given b...
r"""Generate a bqm that is minimized when k of n variables are selected. More fully, we wish to generate a binary quadratic model which is minimized for each of the k-combinations of its variables. The energy for the binary quadratic model is given by :math:`(\sum_{i} x_i - k)^2`. Args: n...
Below is the the instruction that describes the task: ### Input: r"""Generate a bqm that is minimized when k of n variables are selected. More fully, we wish to generate a binary quadratic model which is minimized for each of the k-combinations of its variables. The energy for the binary quadratic mod...
def get_stops_for_route_type(self, route_type): """ Parameters ---------- route_type: int Returns ------- stops: pandas.DataFrame """ if route_type is WALK: return self.stops() else: return pd.read_sql_query("SELEC...
Parameters ---------- route_type: int Returns ------- stops: pandas.DataFrame
Below is the the instruction that describes the task: ### Input: Parameters ---------- route_type: int Returns ------- stops: pandas.DataFrame ### Response: def get_stops_for_route_type(self, route_type): """ Parameters ---------- route_type:...
def maxEntropy(n,k): """ The maximum enropy we could get with n units and k winners """ s = float(k)/n if s > 0.0 and s < 1.0: entropy = - s * math.log(s,2) - (1 - s) * math.log(1 - s,2) else: entropy = 0 return n*entropy
The maximum enropy we could get with n units and k winners
Below is the the instruction that describes the task: ### Input: The maximum enropy we could get with n units and k winners ### Response: def maxEntropy(n,k): """ The maximum enropy we could get with n units and k winners """ s = float(k)/n if s > 0.0 and s < 1.0: entropy = - s * math.log(s,2) - (1 ...
def _ping(self, uid, addr, port): """ Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the ...
Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Unique id of the controller :param addr: Address of the control...
Below is the the instruction that describes the task: ### Input: Just say hello so that pymlgame knows that your controller is still alive. Unused controllers will be deleted after a while. This function is also used to update the address and port of the controller if it has changed. :param uid: Un...
def split(self, nbr): """ Split the rangeset into nbr sub-rangesets (at most). Each sub-rangeset will have the same number of elements more or less 1. Current rangeset remains unmodified. Returns an iterator. >>> RangeSet("1-5").split(3) RangeSet("1-2") ...
Split the rangeset into nbr sub-rangesets (at most). Each sub-rangeset will have the same number of elements more or less 1. Current rangeset remains unmodified. Returns an iterator. >>> RangeSet("1-5").split(3) RangeSet("1-2") RangeSet("3-4") RangeSet("foo5")
Below is the the instruction that describes the task: ### Input: Split the rangeset into nbr sub-rangesets (at most). Each sub-rangeset will have the same number of elements more or less 1. Current rangeset remains unmodified. Returns an iterator. >>> RangeSet("1-5").split(3) ...
def _print_summary(case, summary): """ Show some statistics from the run """ for dof, data in summary.items(): b4b = data["Bit for Bit"] conf = data["Configurations"] stdout = data["Std. Out Files"] print(" " + case + " " + str(dof)) print(" --------------------") ...
Show some statistics from the run
Below is the the instruction that describes the task: ### Input: Show some statistics from the run ### Response: def _print_summary(case, summary): """ Show some statistics from the run """ for dof, data in summary.items(): b4b = data["Bit for Bit"] conf = data["Configurations"] std...
def send_game(self, *args, **kwargs): """See :func:`send_game`""" return send_game(*args, **self._merge_overrides(**kwargs)).run()
See :func:`send_game`
Below is the the instruction that describes the task: ### Input: See :func:`send_game` ### Response: def send_game(self, *args, **kwargs): """See :func:`send_game`""" return send_game(*args, **self._merge_overrides(**kwargs)).run()
def VORPS(cpu, dest, src, src2): """ Performs a bitwise logical OR operation on the source operand (second operand) and second source operand (third operand) and stores the result in the destination operand (first operand). """ res = dest.write(src.read() | src2.read())
Performs a bitwise logical OR operation on the source operand (second operand) and second source operand (third operand) and stores the result in the destination operand (first operand).
Below is the the instruction that describes the task: ### Input: Performs a bitwise logical OR operation on the source operand (second operand) and second source operand (third operand) and stores the result in the destination operand (first operand). ### Response: def VORPS(cpu, dest, src, src2): ...
def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ pkg_resources.py31compat.makedirs(replacement, exist_ok=True) saved = tempfile.tempdir tempfile.tempdir = replacement try: yield finally: tempfile.tempdir = saved
Monkey-patch tempfile.tempdir with replacement, ensuring it exists
Below is the the instruction that describes the task: ### Input: Monkey-patch tempfile.tempdir with replacement, ensuring it exists ### Response: def override_temp(replacement): """ Monkey-patch tempfile.tempdir with replacement, ensuring it exists """ pkg_resources.py31compat.makedirs(replacement,...
def _getKeyForUrl(url, existing=None): """ Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True, key is e...
Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True, key is expected to exist. If False, key is expected not to ...
Below is the the instruction that describes the task: ### Input: Extracts a key from a given s3:// URL. On return, but not on exceptions, this method leaks an S3Connection object. The caller is responsible to close that by calling key.bucket.connection.close(). :param bool existing: If True...
def check_is_dataarray(comp): r"""Decorator to check that a computation has an instance of xarray.DataArray as first argument.""" @wraps(comp) def func(data_array, *args, **kwds): assert isinstance(data_array, xr.DataArray) return comp(data_array, *args, **kwds) return func
r"""Decorator to check that a computation has an instance of xarray.DataArray as first argument.
Below is the the instruction that describes the task: ### Input: r"""Decorator to check that a computation has an instance of xarray.DataArray as first argument. ### Response: def check_is_dataarray(comp): r"""Decorator to check that a computation has an instance of xarray.DataArray as first argument...