code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def hub_scores(msm, waypoints=None): """ Calculate the hub score for one or more waypoints The "hub score" is a measure of how well traveled a certain state or set of states is in a network. Specifically, it is the fraction of times that a walker visits a state en route from some state A to another...
Calculate the hub score for one or more waypoints The "hub score" is a measure of how well traveled a certain state or set of states is in a network. Specifically, it is the fraction of times that a walker visits a state en route from some state A to another state B, averaged over all combinations of A...
Below is the the instruction that describes the task: ### Input: Calculate the hub score for one or more waypoints The "hub score" is a measure of how well traveled a certain state or set of states is in a network. Specifically, it is the fraction of times that a walker visits a state en route from som...
def init_return(self, ret_type): """Specify the return type. Note that this will also construct the '~fermipy.castro.Interpolator' object for the requested return type. """ if self._ret_type == ret_type: return if ret_type == "straight": ...
Specify the return type. Note that this will also construct the '~fermipy.castro.Interpolator' object for the requested return type.
Below is the the instruction that describes the task: ### Input: Specify the return type. Note that this will also construct the '~fermipy.castro.Interpolator' object for the requested return type. ### Response: def init_return(self, ret_type): """Specify the return type. ...
def compute_node_positions(self): """ Computes nodes positions. Arranges nodes in a line starting at (x,y) = (0,0). Node radius is assumed to be equal to 0.5 units. Nodes are placed at integer locations. """ xs = [0] * len(self.nodes) ys = [0] * len(self....
Computes nodes positions. Arranges nodes in a line starting at (x,y) = (0,0). Node radius is assumed to be equal to 0.5 units. Nodes are placed at integer locations.
Below is the the instruction that describes the task: ### Input: Computes nodes positions. Arranges nodes in a line starting at (x,y) = (0,0). Node radius is assumed to be equal to 0.5 units. Nodes are placed at integer locations. ### Response: def compute_node_positions(self): """...
def countdown( seconds=None, block=True, interval=1, daemon=True, tick_callback=None, finish_callback=None, ): """Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdo...
Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdown countdown(3) # 3 2 1 # countdown finished [3 seconds]: 2018-06-13 00:12:55 => 2018-06-13 00:12:58. countd...
Below is the the instruction that describes the task: ### Input: Run a countdown function to wait something, similar to threading.Timer, but will show the detail tick by tick_callback. :: from torequests.utils import countdown countdown(3) # 3 2 1 # countdown finished [3...
def parse(self, stream): """Parses the keys + values from a config file.""" items = OrderedDict() for i, line in enumerate(stream): line = line.strip() if not line or line[0] in ["#", ";", "["] or line.startswith("---"): continue white_space =...
Parses the keys + values from a config file.
Below is the the instruction that describes the task: ### Input: Parses the keys + values from a config file. ### Response: def parse(self, stream): """Parses the keys + values from a config file.""" items = OrderedDict() for i, line in enumerate(stream): line = line.strip() ...
def update(self): """Update RAID stats using the input method.""" # Init new stats stats = self.get_init_value() if import_error_tag: return self.stats if self.input_method == 'local': # Update stats using the PyMDstat lib (https://github.com/nicolargo/p...
Update RAID stats using the input method.
Below is the the instruction that describes the task: ### Input: Update RAID stats using the input method. ### Response: def update(self): """Update RAID stats using the input method.""" # Init new stats stats = self.get_init_value() if import_error_tag: return self.sta...
def add(self, *args, **kwargs): """ Add objects to the directory. """ for key in kwargs: if isinstance(kwargs[key], str): self._children[key] = File(kwargs[key]) else: self._children[key] = kwargs[key] self._children[key...
Add objects to the directory.
Below is the the instruction that describes the task: ### Input: Add objects to the directory. ### Response: def add(self, *args, **kwargs): """ Add objects to the directory. """ for key in kwargs: if isinstance(kwargs[key], str): self._children[key] = Fi...
def disconnect(service_instance): ''' Function that disconnects from the vCenter server or ESXi host service_instance The Service Instance from which to obtain managed object references. ''' log.trace('Disconnecting') try: Disconnect(service_instance) except vim.fault.NoPerm...
Function that disconnects from the vCenter server or ESXi host service_instance The Service Instance from which to obtain managed object references.
Below is the the instruction that describes the task: ### Input: Function that disconnects from the vCenter server or ESXi host service_instance The Service Instance from which to obtain managed object references. ### Response: def disconnect(service_instance): ''' Function that disconnects fr...
def _unmangle_attribute_name(name): """Unmangles attribute names so that correct Python variable names are used for mapping attribute names.""" # Python keywords cannot be used as variable names, an underscore should # be appended at the end of each of them when defining attribute names. name = _PY...
Unmangles attribute names so that correct Python variable names are used for mapping attribute names.
Below is the the instruction that describes the task: ### Input: Unmangles attribute names so that correct Python variable names are used for mapping attribute names. ### Response: def _unmangle_attribute_name(name): """Unmangles attribute names so that correct Python variable names are used for mappin...
def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ''' try: pkgs.setdefault(name, []).append(pkgver) except AttributeError as exc: log.exception(exc)
Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9
Below is the the instruction that describes the task: ### Input: Add a package to a dict of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.add_pkg '{}' bind 9 ### Response: def add_pkg(pkgs, name, pkgver): ''' Add a package to a dict of installed packages. ...
def clone(self, d): """ Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence """ return Desinence(d.grq(), d.morphoNum(), d.numRad(), self)
Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence
Below is the the instruction that describes the task: ### Input: Crée une Désinence copiée sur la désinence d. :param d: Desinence à copier :type d: Desinence :return: Désinence copiée sur la désinence d. :rtype: Desinence ### Response: def clone(self, d): """ Crée une Dés...
def grad_and_loss(func, argnum=None): """Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ...
Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gradient for. Returns ------- grad_and_loss_func: a python ...
Below is the the instruction that describes the task: ### Input: Return function that computes both gradient of arguments and loss value. Parameters ---------- func: a python function The forward (loss) function. argnum: an int or a list of int The index of argument to calculate gra...
def _pandas_interp(self, data, indices): """The actual transformation based on the following stackoverflow entry: http://stackoverflow.com/a/10465162 """ new_index = np.arange(indices[-1] + 1) data_frame = DataFrame(data, index=indices) data_frame_reindexed = data_frame...
The actual transformation based on the following stackoverflow entry: http://stackoverflow.com/a/10465162
Below is the the instruction that describes the task: ### Input: The actual transformation based on the following stackoverflow entry: http://stackoverflow.com/a/10465162 ### Response: def _pandas_interp(self, data, indices): """The actual transformation based on the following stackoverflow ...
def linkChunk(key, chunk): """ Parse LINK Chunk Method """ # Extract link type card linkType = chunk[1].strip().split()[0] # Cases if linkType == 'DX': # Cross section link type handler result = xSectionLink(chunk) elif linkType == 'STRUCTURE': # Structure link ...
Parse LINK Chunk Method
Below is the the instruction that describes the task: ### Input: Parse LINK Chunk Method ### Response: def linkChunk(key, chunk): """ Parse LINK Chunk Method """ # Extract link type card linkType = chunk[1].strip().split()[0] # Cases if linkType == 'DX': # Cross section link ty...
def next_population(self, population, fitnesses): """Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: lis...
Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: list; a list of solutions.
Below is the the instruction that describes the task: ### Input: Make a new population after each optimization iteration. Args: population: The population current population of solutions. fitnesses: The fitness associated with each solution in the population Returns: ...
async def get_tree(self, prefix, *, dc=None, separator=None, watch=None, consistency=None): """Gets all keys with a prefix of Key during the transaction. Parameters: prefix (str): Prefix to fetch separator (str): List only up to a given separator ...
Gets all keys with a prefix of Key during the transaction. Parameters: prefix (str): Prefix to fetch separator (str): List only up to a given separator dc (str): Specify datacenter that will be used. Defaults to the agent's local datacenter. ...
Below is the the instruction that describes the task: ### Input: Gets all keys with a prefix of Key during the transaction. Parameters: prefix (str): Prefix to fetch separator (str): List only up to a given separator dc (str): Specify datacenter that will be used. ...
def categories(self): """Returns the categories of `Ligands` in `LigandGroup`.""" category_dict = {} for ligand in self: if ligand.category in category_dict: category_dict[ligand.category].append(ligand) else: category_dict[ligand.category]...
Returns the categories of `Ligands` in `LigandGroup`.
Below is the the instruction that describes the task: ### Input: Returns the categories of `Ligands` in `LigandGroup`. ### Response: def categories(self): """Returns the categories of `Ligands` in `LigandGroup`.""" category_dict = {} for ligand in self: if ligand.category in cat...
def offer(self, p, e: Event): """ Offer a new event ``s`` at point ``p`` in this queue. """ existing = self.events_scan.setdefault( p, ([], [], [], []) if USE_VERTICAL else ([], [], [])) # Can use double linked-list for easy insertion at beginni...
Offer a new event ``s`` at point ``p`` in this queue.
Below is the the instruction that describes the task: ### Input: Offer a new event ``s`` at point ``p`` in this queue. ### Response: def offer(self, p, e: Event): """ Offer a new event ``s`` at point ``p`` in this queue. """ existing = self.events_scan.setdefault( p,...
def forecast_until(self, timestamp, tsformat=None): """Sets the forecasting goal (timestamp wise). This function enables the automatic determination of valuesToForecast. :param timestamp: timestamp containing the end date of the forecast. :param string tsformat: Format of the tim...
Sets the forecasting goal (timestamp wise). This function enables the automatic determination of valuesToForecast. :param timestamp: timestamp containing the end date of the forecast. :param string tsformat: Format of the timestamp. This is used to convert the timestamp from ...
Below is the the instruction that describes the task: ### Input: Sets the forecasting goal (timestamp wise). This function enables the automatic determination of valuesToForecast. :param timestamp: timestamp containing the end date of the forecast. :param string tsformat: Format of t...
def read_nc(self,filename,**kwargs): ''' data reader based on :class:`altimetry.tools.nctools.nc` object. .. note:: THIS can be VERY powerful! ''' #Set filename self._filename = filename remove_existing = kwargs.get('remove_exi...
data reader based on :class:`altimetry.tools.nctools.nc` object. .. note:: THIS can be VERY powerful!
Below is the the instruction that describes the task: ### Input: data reader based on :class:`altimetry.tools.nctools.nc` object. .. note:: THIS can be VERY powerful! ### Response: def read_nc(self,filename,**kwargs): ''' data reader based on :class:`altimetry.tools.nctools.nc`...
def init(*, threshold_lvl=1, quiet_stdout=False, log_file): """ Initiate the log module :param threshold_lvl: messages under this level won't be issued/logged :param to_stdout: activate stdout log stream """ global _logger, _log_lvl # translate lvl to those used by 'logging' module _lo...
Initiate the log module :param threshold_lvl: messages under this level won't be issued/logged :param to_stdout: activate stdout log stream
Below is the the instruction that describes the task: ### Input: Initiate the log module :param threshold_lvl: messages under this level won't be issued/logged :param to_stdout: activate stdout log stream ### Response: def init(*, threshold_lvl=1, quiet_stdout=False, log_file): """ Initiate the lo...
def notch_fir(self, f1, f2, order, beta=5.0, remove_corrupted=True): """ notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and ...
notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the number of samples in the filter length. For a few Hz bandwidth, a ...
Below is the the instruction that describes the task: ### Input: notch filter the time series using an FIR filtered generated from the ideal response passed through a time-domain kaiser window (beta = 5.0) The suppression of the notch filter is related to the bandwidth and the numbe...
def get_instance(self, payload): """ Build an instance of SyncMapPermissionInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_map.sync_...
Build an instance of SyncMapPermissionInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance :rtype: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance
Below is the the instruction that describes the task: ### Input: Build an instance of SyncMapPermissionInstance :param dict payload: Payload response from the API :returns: twilio.rest.sync.v1.service.sync_map.sync_map_permission.SyncMapPermissionInstance :rtype: twilio.rest.sync.v1.servic...
def impulse_deltav_plummer(v,y,b,w,GM,rs): """ NAME: impulse_deltav_plummer PURPOSE: calculate the delta velocity to due an encounter with a Plummer sphere in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the position along the stream INPUT: ...
NAME: impulse_deltav_plummer PURPOSE: calculate the delta velocity to due an encounter with a Plummer sphere in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the position along the stream INPUT: v - velocity of the stream (nstar,3) y - posi...
Below is the the instruction that describes the task: ### Input: NAME: impulse_deltav_plummer PURPOSE: calculate the delta velocity to due an encounter with a Plummer sphere in the impulse approximation; allows for arbitrary velocity vectors, but y is input as the position along the stream ...
def fprop(self, x): """ Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ logits = tf.py_func(self.fprop_np, [x], tf.float32) return {self.O_LOGITS: logits}
Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method.
Below is the the instruction that describes the task: ### Input: Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. ### Response: def fprop(self, x): """ Performs a forward pass through the DkNN on a TF tensor by wrapping the fprop_np method. """ logits...
def removeblanklines(astr): """remove the blank lines in astr""" lines = astr.splitlines() lines = [line for line in lines if line.strip() != ""] return "\n".join(lines)
remove the blank lines in astr
Below is the the instruction that describes the task: ### Input: remove the blank lines in astr ### Response: def removeblanklines(astr): """remove the blank lines in astr""" lines = astr.splitlines() lines = [line for line in lines if line.strip() != ""] return "\n".join(lines)
def fit(self, data): """ Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_tr...
Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also -------- transform, fit_transform
Below is the the instruction that describes the task: ### Input: Fits a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted object) See Also ------...
def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t if 'default' in kwargs: return kwargs['default'] else: raise LookupError("Token {} is not tagg...
Get the first tag with a type in this token
Below is the the instruction that describes the task: ### Input: Get the first tag with a type in this token ### Response: def find(self, tagtype, **kwargs): '''Get the first tag with a type in this token ''' for t in self.__tags: if t.tagtype == tagtype: return t ...
def _get_c_string(data, position): """Decode a BSON 'C' string to python unicode string.""" end = data.index(b"\x00", position) return _utf_8_decode(data[position:end], None, True)[0], end + 1
Decode a BSON 'C' string to python unicode string.
Below is the the instruction that describes the task: ### Input: Decode a BSON 'C' string to python unicode string. ### Response: def _get_c_string(data, position): """Decode a BSON 'C' string to python unicode string.""" end = data.index(b"\x00", position) return _utf_8_decode(data[position:end], None...
def disable_dataset(self, dataset=None, **kwargs): """ Disable a 'dataset'. Datasets that are enabled will be computed during :meth:`run_compute` and included in the cost function during :meth:`run_fitting`. If compute is not provided, the dataset will be disabled across all ...
Disable a 'dataset'. Datasets that are enabled will be computed during :meth:`run_compute` and included in the cost function during :meth:`run_fitting`. If compute is not provided, the dataset will be disabled across all compute options. :parameter str dataset: name of the dat...
Below is the the instruction that describes the task: ### Input: Disable a 'dataset'. Datasets that are enabled will be computed during :meth:`run_compute` and included in the cost function during :meth:`run_fitting`. If compute is not provided, the dataset will be disabled across all ...
def read_little_endian32(self): """Interprets the next 4 bytes of the stream as a little-endian encoded, unsiged 32-bit integer, and returns that integer. """ try: i = struct.unpack(wire_format.FORMAT_UINT32_LITTLE_ENDIAN, self._input.read(4)) ...
Interprets the next 4 bytes of the stream as a little-endian encoded, unsiged 32-bit integer, and returns that integer.
Below is the the instruction that describes the task: ### Input: Interprets the next 4 bytes of the stream as a little-endian encoded, unsiged 32-bit integer, and returns that integer. ### Response: def read_little_endian32(self): """Interprets the next 4 bytes of the stream as a little-endian ...
def canonicalize_origin(origin): """\ """ origin = origin.replace(u'USMISSION', u'') \ .replace(u'AMEMBASSY', u'') \ .replace(u'EMBASSY', u'').strip() return _STATION_C14N.get(origin, origin)
\
Below is the the instruction that describes the task: ### Input: \ ### Response: def canonicalize_origin(origin): """\ """ origin = origin.replace(u'USMISSION', u'') \ .replace(u'AMEMBASSY', u'') \ .replace(u'EMBASSY', u'').strip() return _STATION_C14N.get...
def results(self, key): """Serves a key off of the results backend""" if not results_backend: return json_error_response("Results backend isn't configured") read_from_results_backend_start = now_as_float() blob = results_backend.get(key) stats_logger.timing( ...
Serves a key off of the results backend
Below is the the instruction that describes the task: ### Input: Serves a key off of the results backend ### Response: def results(self, key): """Serves a key off of the results backend""" if not results_backend: return json_error_response("Results backend isn't configured") re...
def get_independencies(self, condition=None): """ Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition=None. Returns conditionally independent variables if condition!=None Parameter --------- ...
Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition=None. Returns conditionally independent variables if condition!=None Parameter --------- condition: array_like Random Variable on which ...
Below is the the instruction that describes the task: ### Input: Returns the independent variables in the joint probability distribution. Returns marginally independent variables if condition=None. Returns conditionally independent variables if condition!=None Parameter --------- ...
def RegisterCustomFieldCodec(encoder, decoder): """Register a custom encoder/decoder for this field.""" def Register(field): _CUSTOM_FIELD_CODECS[field] = _Codec(encoder=encoder, decoder=decoder) return field return Register
Register a custom encoder/decoder for this field.
Below is the the instruction that describes the task: ### Input: Register a custom encoder/decoder for this field. ### Response: def RegisterCustomFieldCodec(encoder, decoder): """Register a custom encoder/decoder for this field.""" def Register(field): _CUSTOM_FIELD_CODECS[field] = _Codec(encoder=...
def cut( self, start=None, stop=None, whence=0, version=None, include_ends=True, time_from_zero=False, ): """cut *MDF* file. *start* and *stop* limits are absolute values or values relative to the first timestamp depending on the *whence* ...
cut *MDF* file. *start* and *stop* limits are absolute values or values relative to the first timestamp depending on the *whence* argument. Parameters ---------- start : float start time, default *None*. If *None* then the start of measurement is used ...
Below is the the instruction that describes the task: ### Input: cut *MDF* file. *start* and *stop* limits are absolute values or values relative to the first timestamp depending on the *whence* argument. Parameters ---------- start : float start time, default *N...
def properties(self): ''' This is a lazily loaded dictionary containing the launchd runtime information of the job in question. Internally, this is retrieved using ServiceManagement.SMJobCopyDictionary(). Keep in mind that some dictionary keys are not always present (for example ...
This is a lazily loaded dictionary containing the launchd runtime information of the job in question. Internally, this is retrieved using ServiceManagement.SMJobCopyDictionary(). Keep in mind that some dictionary keys are not always present (for example 'PID'). If the job specified by th...
Below is the the instruction that describes the task: ### Input: This is a lazily loaded dictionary containing the launchd runtime information of the job in question. Internally, this is retrieved using ServiceManagement.SMJobCopyDictionary(). Keep in mind that some dictionary keys are not a...
def barrel_shifter(bits_to_shift, bit_in, direction, shift_dist, wrap_around=0): """ Create a barrel shifter that operates on data based on the wire width. :param bits_to_shift: the input wire :param bit_in: the 1-bit wire giving the value to shift in :param direction: a one bit WireVector representing...
Create a barrel shifter that operates on data based on the wire width. :param bits_to_shift: the input wire :param bit_in: the 1-bit wire giving the value to shift in :param direction: a one bit WireVector representing shift direction (0 = shift down, 1 = shift up) :param shift_dist: WireVector...
Below is the the instruction that describes the task: ### Input: Create a barrel shifter that operates on data based on the wire width. :param bits_to_shift: the input wire :param bit_in: the 1-bit wire giving the value to shift in :param direction: a one bit WireVector representing shift direction ...
def beam_search(symbols_to_logits_fn, initial_ids, beam_size, decode_length, vocab_size, alpha, states=None, eos_id=EOS_ID, stop_early=True, use_tpu=False, use_...
Beam search with length penalties. Requires a function that can take the currently decoded symbols and return the logits for the next symbol. The implementation is inspired by https://arxiv.org/abs/1609.08144. When running, the beam search steps can be visualized by using tfdbg to watch the operations gener...
Below is the the instruction that describes the task: ### Input: Beam search with length penalties. Requires a function that can take the currently decoded symbols and return the logits for the next symbol. The implementation is inspired by https://arxiv.org/abs/1609.08144. When running, the beam search s...
def _publish_metrics(self, name, prev_keys, key, data): """Recursively publish keys""" value = data[key] keys = prev_keys + [key] if isinstance(value, dict): for new_key in value: self._publish_metrics(name, keys, new_key, value) elif isinstance(value,...
Recursively publish keys
Below is the the instruction that describes the task: ### Input: Recursively publish keys ### Response: def _publish_metrics(self, name, prev_keys, key, data): """Recursively publish keys""" value = data[key] keys = prev_keys + [key] if isinstance(value, dict): for new_k...
def get_statement_model(self): """ Return the class for the statement model. """ from chatterbot.conversation import Statement # Create a storage-aware statement statement = Statement statement.storage = self return statement
Return the class for the statement model.
Below is the the instruction that describes the task: ### Input: Return the class for the statement model. ### Response: def get_statement_model(self): """ Return the class for the statement model. """ from chatterbot.conversation import Statement # Create a storage-aware s...
def fetch_seq(ac, start_i=None, end_i=None): """Fetches sequences and subsequences from NCBI eutils and Ensembl REST interfaces. :param string ac: accession of sequence to fetch :param int start_i: start position of *interbase* interval :param int end_i: end position of *interbase* interval *...
Fetches sequences and subsequences from NCBI eutils and Ensembl REST interfaces. :param string ac: accession of sequence to fetch :param int start_i: start position of *interbase* interval :param int end_i: end position of *interbase* interval **IMPORTANT** start_i and end_i specify 0-based inter...
Below is the the instruction that describes the task: ### Input: Fetches sequences and subsequences from NCBI eutils and Ensembl REST interfaces. :param string ac: accession of sequence to fetch :param int start_i: start position of *interbase* interval :param int end_i: end position of *interbase*...
def get_disabled(self): """Sorted list of (username, napp_name) of disabled napps. The difference of installed and enabled. """ installed = set(self.get_installed()) enabled = set(self.get_enabled()) return sorted(installed - enabled)
Sorted list of (username, napp_name) of disabled napps. The difference of installed and enabled.
Below is the the instruction that describes the task: ### Input: Sorted list of (username, napp_name) of disabled napps. The difference of installed and enabled. ### Response: def get_disabled(self): """Sorted list of (username, napp_name) of disabled napps. The difference of installed an...
def get_management_certificate(self, thumbprint): ''' The Get Management Certificate operation retrieves information about the management certificate with the specified thumbprint. Management certificates, which are also known as subscription certificates, authenticate clients at...
The Get Management Certificate operation retrieves information about the management certificate with the specified thumbprint. Management certificates, which are also known as subscription certificates, authenticate clients attempting to connect to resources associated with your Windows ...
Below is the the instruction that describes the task: ### Input: The Get Management Certificate operation retrieves information about the management certificate with the specified thumbprint. Management certificates, which are also known as subscription certificates, authenticate clients att...
def unset_config_value(self, name, quiet=False): """unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False) """ config_data = self._rea...
unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False)
Below is the the instruction that describes the task: ### Input: unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False) ### Response: def unset_config_val...
def __get_stat_display(self, stats, layer): """Return a dict of dict with all the stats display. stats: Global stats dict layer: ~ cs_status "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is connected to a...
Return a dict of dict with all the stats display. stats: Global stats dict layer: ~ cs_status "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is connected to a SNMP server "Disconnected": Client is disc...
Below is the the instruction that describes the task: ### Input: Return a dict of dict with all the stats display. stats: Global stats dict layer: ~ cs_status "None": standalone or server mode "Connected": Client is connected to a Glances server "SNMP": Client is ...
def proxy(self): """Return a Deferred that will result in a proxy object in the future.""" d = Deferred(self.loop) self._proxy_deferreds.append(d) if self._proxy: d.callback(self._proxy) return d
Return a Deferred that will result in a proxy object in the future.
Below is the the instruction that describes the task: ### Input: Return a Deferred that will result in a proxy object in the future. ### Response: def proxy(self): """Return a Deferred that will result in a proxy object in the future.""" d = Deferred(self.loop) self._proxy_deferreds.append(...
def get_all_permissions_views(self): """ Returns a set of tuples with the perm name and view menu name """ perms_views = set() for role in self.get_user_roles(): perms_views.update({(perm_view.permission.name, perm_view.view_menu.name) ...
Returns a set of tuples with the perm name and view menu name
Below is the the instruction that describes the task: ### Input: Returns a set of tuples with the perm name and view menu name ### Response: def get_all_permissions_views(self): """ Returns a set of tuples with the perm name and view menu name """ perms_views = set() for rol...
def UpdateShowDirInTVLibrary(self, showID, showDir): """ Update show directory entry for given show id in TVLibrary table. Parameters ---------- showID : int Show id value. showDir : string Show directory name. """ goodlogging.Log.Info("DB", "Updating TV library for...
Update show directory entry for given show id in TVLibrary table. Parameters ---------- showID : int Show id value. showDir : string Show directory name.
Below is the the instruction that describes the task: ### Input: Update show directory entry for given show id in TVLibrary table. Parameters ---------- showID : int Show id value. showDir : string Show directory name. ### Response: def UpdateShowDirInTVLibrary(self, showID, s...
def _build_dictionary(self, results): """ Build model dictionary keyed by the relation's foreign key. :param results: The results :type results: Collection :rtype: dict """ foreign = self._first_key dictionary = {} for result in results: ...
Build model dictionary keyed by the relation's foreign key. :param results: The results :type results: Collection :rtype: dict
Below is the the instruction that describes the task: ### Input: Build model dictionary keyed by the relation's foreign key. :param results: The results :type results: Collection :rtype: dict ### Response: def _build_dictionary(self, results): """ Build model dictionary ke...
def get_ISBNs(self): """ Get list of VALID ISBN. Returns: list: List with *valid* ISBN strings. """ invalid_isbns = set(self.get_invalid_ISBNs()) valid_isbns = [ self._clean_isbn(isbn) for isbn in self["020a"] if self._cle...
Get list of VALID ISBN. Returns: list: List with *valid* ISBN strings.
Below is the the instruction that describes the task: ### Input: Get list of VALID ISBN. Returns: list: List with *valid* ISBN strings. ### Response: def get_ISBNs(self): """ Get list of VALID ISBN. Returns: list: List with *valid* ISBN strings. """...
def scaled_imu_encode(self, time_boot_ms, xacc, yacc, zacc, xgyro, ygyro, zgyro, xmag, ymag, zmag): ''' The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms...
The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_t) xacc : X acceleration (mg) (i...
Below is the the instruction that describes the task: ### Input: The RAW IMU readings for the usual 9DOF sensor setup. This message should contain the scaled values to the described units time_boot_ms : Timestamp (milliseconds since system boot) (uint32_...
def get_bond_order(self, tol=0.2, default_bl=None): """ The bond order according the distance between the two sites Args: tol (float): Relative tolerance to test. (1 + tol) * the longest bond distance is considered to be the threshold length for a bond...
The bond order according the distance between the two sites Args: tol (float): Relative tolerance to test. (1 + tol) * the longest bond distance is considered to be the threshold length for a bond to exist. (1 - tol) * the shortest bond distance is con...
Below is the the instruction that describes the task: ### Input: The bond order according the distance between the two sites Args: tol (float): Relative tolerance to test. (1 + tol) * the longest bond distance is considered to be the threshold length for a bond to...
def _get_location_list(interval_bed): """Retrieve list of locations to analyze from input BED file. """ import pybedtools regions = collections.OrderedDict() for region in pybedtools.BedTool(interval_bed): regions[str(region.chrom)] = None return regions.keys()
Retrieve list of locations to analyze from input BED file.
Below is the the instruction that describes the task: ### Input: Retrieve list of locations to analyze from input BED file. ### Response: def _get_location_list(interval_bed): """Retrieve list of locations to analyze from input BED file. """ import pybedtools regions = collections.OrderedDict() ...
def build_chain(self, source, chain): """ Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source """ ...
Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source
Below is the the instruction that describes the task: ### Input: Build markov chain from source on top of existin chain Args: source: iterable which will be used to build chain chain: MarkovChain in currently loaded shelve file that will be extended by source ### ...
def filter_by(self, values, column_name, exclude=False): """ Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values``...
Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we atte...
Below is the the instruction that describes the task: ### Input: Filter an SFrame by values inside an iterable object. Result is an SFrame that only includes (or excludes) the rows that have a column with the given ``column_name`` which holds one of the values in the given ``values`` :class:...
def wrap(f_df, xref, size=1): """ Memoizes an objective + gradient function, and splits it into two functions that return just the objective and gradient, respectively. Parameters ---------- f_df : function Must be unary (takes a single argument) xref : list, dict, or array_like ...
Memoizes an objective + gradient function, and splits it into two functions that return just the objective and gradient, respectively. Parameters ---------- f_df : function Must be unary (takes a single argument) xref : list, dict, or array_like The form of the parameters size...
Below is the the instruction that describes the task: ### Input: Memoizes an objective + gradient function, and splits it into two functions that return just the objective and gradient, respectively. Parameters ---------- f_df : function Must be unary (takes a single argument) xref : l...
def unhandle(self, handler): """ unregister handler (removing callback function) """ with self._hlock: try: self._handler_list.remove(handler) except ValueError: raise ValueError("Handler is not handling this event, so cannot unhandle it.") ...
unregister handler (removing callback function)
Below is the the instruction that describes the task: ### Input: unregister handler (removing callback function) ### Response: def unhandle(self, handler): """ unregister handler (removing callback function) """ with self._hlock: try: self._handler_list.remove(handler) ...
def _render_objects(self, items, attributes=None, datatype='object'): """Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'obje...
Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'object' for Python objects, 'dict' for a list of dictionaries, or 'char...
Below is the the instruction that describes the task: ### Input: Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'object' for ...
def all_domain_events(self): """ Yields all domain events in the event store. """ for originator_id in self.record_manager.all_sequence_ids(): for domain_event in self.get_domain_events(originator_id=originator_id, page_size=100): yield domain_event
Yields all domain events in the event store.
Below is the the instruction that describes the task: ### Input: Yields all domain events in the event store. ### Response: def all_domain_events(self): """ Yields all domain events in the event store. """ for originator_id in self.record_manager.all_sequence_ids(): for ...
def summarize(self, sentences=0, chars=0): """ Summarize page either by number of sentences, chars, or first section (**default**) Args: sentences (int): Number of sentences to use in summary \ (first `x` sentences) chars ...
Summarize page either by number of sentences, chars, or first section (**default**) Args: sentences (int): Number of sentences to use in summary \ (first `x` sentences) chars (int): Number of characters to use in summary \ ...
Below is the the instruction that describes the task: ### Input: Summarize page either by number of sentences, chars, or first section (**default**) Args: sentences (int): Number of sentences to use in summary \ (first `x` sentences) ...
def _check_data(self): """Ensure that the data in the cache is valid. If it's invalid, the cache is wiped. """ if not self.cache_available(): return parsed = self._parse_data() _LOGGER.debug('Received new data from sensor: Temp=%.1f, Humidity=%.1f', ...
Ensure that the data in the cache is valid. If it's invalid, the cache is wiped.
Below is the the instruction that describes the task: ### Input: Ensure that the data in the cache is valid. If it's invalid, the cache is wiped. ### Response: def _check_data(self): """Ensure that the data in the cache is valid. If it's invalid, the cache is wiped. """ if...
def determine_newline(data): """ Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data (bytes): The data to...
Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data (bytes): The data to be searched Returns: None: ...
Below is the the instruction that describes the task: ### Input: Looks for a newline character in bytestring parameter 'data'. Currently only looks for strings '\r\n', '\n'. If '\n' is found at the first position of the string, this raises an exception. Parameters: data ...
def remove_all_timers(self): """Remove all waiting timers and terminate any blocking threads.""" with self.lock: if self.rtimer is not None: self.rtimer.cancel() self.timers = {} self.heap = [] self.rtimer = None self.expiring ...
Remove all waiting timers and terminate any blocking threads.
Below is the the instruction that describes the task: ### Input: Remove all waiting timers and terminate any blocking threads. ### Response: def remove_all_timers(self): """Remove all waiting timers and terminate any blocking threads.""" with self.lock: if self.rtimer is not None: ...
def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = None) -> bool: """ Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded """ return obj._is_valid(log)
Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded
Below is the the instruction that describes the task: ### Input: Determine whether obj is valid :param obj: Object to validate :param log: Logger to record validation failures. If absent, no information is recorded ### Response: def is_valid(obj: JSGValidateable, log: Optional[Union[TextIO, Logger]] = No...
def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFormat() items = list(style.style_for_token(token).items()) for key, value in items: if value is None and key == 'color': ...
Returns a QTextCharFormat for token by reading a Pygments style.
Below is the the instruction that describes the task: ### Input: Returns a QTextCharFormat for token by reading a Pygments style. ### Response: def _get_format_from_style(self, token, style): """ Returns a QTextCharFormat for token by reading a Pygments style. """ result = QtGui.QTextCharFo...
def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). """ if not dist_is_editable(dist): return (None, False, []) location = os.path.normcase(os.path.abspath(dist.lo...
Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist().
Below is the the instruction that describes the task: ### Input: Compute and return values (req, editable, comments) for use in FrozenRequirement.from_dist(). ### Response: def get_requirement_info(dist): # type: (Distribution) -> RequirementInfo """ Compute and return values (req, editable, commen...
def validate_deployments_tx_receipt( deployments: Dict[str, Any], w3: Web3, allow_missing_data: bool = False ) -> None: """ Validate that address and block hash found in deployment data match what is found on-chain. :allow_missing_data: by default, enforces validation of address and blockHash. """ ...
Validate that address and block hash found in deployment data match what is found on-chain. :allow_missing_data: by default, enforces validation of address and blockHash.
Below is the the instruction that describes the task: ### Input: Validate that address and block hash found in deployment data match what is found on-chain. :allow_missing_data: by default, enforces validation of address and blockHash. ### Response: def validate_deployments_tx_receipt( deployments: Dict[st...
def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', name='org.bluez.Error.NoSuchDevice') device = mockobject.objects[device_path] dev...
Connect a device
Below is the the instruction that describes the task: ### Input: Connect a device ### Response: def Connect(self): '''Connect a device ''' device_path = self.path if device_path not in mockobject.objects: raise dbus.exceptions.DBusException('No such device.', ...
def load_meta_data(self, path=None): """Load meta data of state model from the file system The meta data of the state model is loaded from the file system and stored in the meta property of the model. Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes,...
Load meta data of state model from the file system The meta data of the state model is loaded from the file system and stored in the meta property of the model. Existing meta data is removed. Also the meta data of all state elements (data ports, outcomes, etc) are loaded, as those stored in the...
Below is the the instruction that describes the task: ### Input: Load meta data of state model from the file system The meta data of the state model is loaded from the file system and stored in the meta property of the model. Existing meta data is removed. Also the meta data of all state elements (...
def format_json(json_object, indent): """ Pretty-format json data """ indent_str = "\n" + " " * indent json_str = json.dumps(json_object, indent=2, default=serialize_json_var) return indent_str.join(json_str.split("\n"))
Pretty-format json data
Below is the the instruction that describes the task: ### Input: Pretty-format json data ### Response: def format_json(json_object, indent): """ Pretty-format json data """ indent_str = "\n" + " " * indent json_str = json.dumps(json_object, indent=2, default=serialize_json_var) return indent_str.jo...
def generate_sentence(self, chain): """ !DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence """ def weighted_choice(cho...
!DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence
Below is the the instruction that describes the task: ### Input: !DEMO! Demo function that shows how to generate a simple sentence starting with uppercase letter without lenght limit. Args: chain: MarkovChain that will be used to generate sentence ### Response: def generate_sen...
def file_set_details(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /file-xxxx/setDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FsetDetails """ return DXHTTPRequest('/%s/setDetails...
Invokes the /file-xxxx/setDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FsetDetails
Below is the the instruction that describes the task: ### Input: Invokes the /file-xxxx/setDetails API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Details-and-Links#API-method%3A-%2Fclass-xxxx%2FsetDetails ### Response: def file_set_details(object_id, input_params={}, always...
def main(): """Command line interface of mpu.""" parser = get_parser() args = parser.parse_args() if hasattr(args, 'func') and args.func: args.func(args) else: parser.print_help()
Command line interface of mpu.
Below is the the instruction that describes the task: ### Input: Command line interface of mpu. ### Response: def main(): """Command line interface of mpu.""" parser = get_parser() args = parser.parse_args() if hasattr(args, 'func') and args.func: args.func(args) else: parser.pr...
def addDatastream(self, pid, dsID, dsLabel=None, mimeType=None, logMessage=None, controlGroup=None, dsLocation=None, altIDs=None, versionable=None, dsState=None, formatURI=None, checksumType=None, checksum=None, content=None): '''Add a new datastream to an existing object. On success, t...
Add a new datastream to an existing object. On success, the return response should have a status of 201 Created; if there is an error, the response body includes the error message. :param pid: object pid :param dsID: id for the new datastream :param dslabel: label for the new d...
Below is the the instruction that describes the task: ### Input: Add a new datastream to an existing object. On success, the return response should have a status of 201 Created; if there is an error, the response body includes the error message. :param pid: object pid :param dsID: ...
def fill_buffer(heap_data, i_chan): """Blocking function to populate data in the heap. This is run in an executor. """ # Calculate the time count and fraction. now = datetime.datetime.utcnow() time_full = now.timestamp() time_count = int(time_full) time_fr...
Blocking function to populate data in the heap. This is run in an executor.
Below is the the instruction that describes the task: ### Input: Blocking function to populate data in the heap. This is run in an executor. ### Response: def fill_buffer(heap_data, i_chan): """Blocking function to populate data in the heap. This is run in an executor. """ #...
def login(self, year, firstname, lastname, passwd, with_year=True): """ Authenticate an user """ firstname = firstname.upper() lastname = lastname.upper() if with_year and not self.set_year(year): return False url = URLS['login'] params = { ...
Authenticate an user
Below is the the instruction that describes the task: ### Input: Authenticate an user ### Response: def login(self, year, firstname, lastname, passwd, with_year=True): """ Authenticate an user """ firstname = firstname.upper() lastname = lastname.upper() if with_yea...
def create_cas_login_url(cas_url, cas_route, service, renew=None, gateway=None): """ Create a CAS login URL . Keyword arguments: cas_url -- The url to the CAS (ex. http://sso.pdx.edu) cas_route -- The route where the CAS lives on server (ex. /cas) service -- (ex. http://localhost:5000/login) r...
Create a CAS login URL . Keyword arguments: cas_url -- The url to the CAS (ex. http://sso.pdx.edu) cas_route -- The route where the CAS lives on server (ex. /cas) service -- (ex. http://localhost:5000/login) renew -- "true" or "false" gateway -- "true" or "false" Example usage: >>> cr...
Below is the the instruction that describes the task: ### Input: Create a CAS login URL . Keyword arguments: cas_url -- The url to the CAS (ex. http://sso.pdx.edu) cas_route -- The route where the CAS lives on server (ex. /cas) service -- (ex. http://localhost:5000/login) renew -- "true" or "f...
def history_view(self, request, object_id, extra_context=None): from django.template.response import TemplateResponse from django.contrib.admin.options import get_content_type_for_model from django.contrib.admin.utils import unquote from django.core.exceptions import PermissionDenied ...
The 'history' admin view for this model.
Below is the the instruction that describes the task: ### Input: The 'history' admin view for this model. ### Response: def history_view(self, request, object_id, extra_context=None): from django.template.response import TemplateResponse from django.contrib.admin.options import get_content_type_for...
def nullify(v): """Convert empty strings and strings with only spaces to None values. """ if isinstance(v, six.string_types): v = v.strip() if v is None or v == '': return None else: return v
Convert empty strings and strings with only spaces to None values.
Below is the the instruction that describes the task: ### Input: Convert empty strings and strings with only spaces to None values. ### Response: def nullify(v): """Convert empty strings and strings with only spaces to None values. """ if isinstance(v, six.string_types): v = v.strip() if v is...
def delete_resource(self, resource_name, name): """Delete a specific resource by name""" try: logger.info("Trying to get %s: '%s'", resource_name, name) if name is None: # No name is defined, delete all the resources... if not self.dry_run: ...
Delete a specific resource by name
Below is the the instruction that describes the task: ### Input: Delete a specific resource by name ### Response: def delete_resource(self, resource_name, name): """Delete a specific resource by name""" try: logger.info("Trying to get %s: '%s'", resource_name, name) if name...
def sink_get(self, project, sink_name): """API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The sink object returned...
API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The sink object returned from the API (converted from a p...
Below is the the instruction that describes the task: ### Input: API call: retrieve a sink resource. :type project: str :param project: ID of the project containing the sink. :type sink_name: str :param sink_name: the name of the sink :rtype: dict :returns: The si...
def axes(self): """A mapping from axes to data objects with the plotter in this axes """ ret = utils.DefaultOrderedDict(lambda: self[1:0]) for arr in self: if arr.psy.plotter is not None: ret[arr.psy.plotter.ax].append(arr) return OrderedDict(ret)
A mapping from axes to data objects with the plotter in this axes
Below is the the instruction that describes the task: ### Input: A mapping from axes to data objects with the plotter in this axes ### Response: def axes(self): """A mapping from axes to data objects with the plotter in this axes """ ret = utils.DefaultOrderedDict(lambda: self[1:0]) ...
def param_list_to_dict(list,param_struct,skeys): """convert from param dictionary to list param_struct: structure of parameter array """ RV = [] i0= 0 for key in skeys: val = param_struct[key] shape = SP.array(val) np = shape.prod() i1 = i0+np params = lis...
convert from param dictionary to list param_struct: structure of parameter array
Below is the the instruction that describes the task: ### Input: convert from param dictionary to list param_struct: structure of parameter array ### Response: def param_list_to_dict(list,param_struct,skeys): """convert from param dictionary to list param_struct: structure of parameter array """ ...
def send_report(report, config): """ Sends the report to IOpipe's collector. :param report: The report to be sent. :param config: The IOpipe agent configuration. """ headers = {"Authorization": "Bearer {}".format(config["token"])} url = "https://{host}{path}".format(**config) try: ...
Sends the report to IOpipe's collector. :param report: The report to be sent. :param config: The IOpipe agent configuration.
Below is the the instruction that describes the task: ### Input: Sends the report to IOpipe's collector. :param report: The report to be sent. :param config: The IOpipe agent configuration. ### Response: def send_report(report, config): """ Sends the report to IOpipe's collector. :param repor...
def attr_matches(self, text): """Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible com...
Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are used as possible completions. (For class instances, class me...
Below is the the instruction that describes the task: ### Input: Compute matches when text contains a dot. Assuming the text is of the form NAME.NAME....[NAME], and is evaluatable in self.namespace or self.global_namespace, it will be evaluated and its attributes (as revealed by dir()) are ...
def get_wan_ip(n=0): """ That IP module sucks. Occasionally it returns an IP address behind cloudflare which probably happens when cloudflare tries to proxy your web request because it thinks you're trying to DoS. It's better if we just run our own infrastructure. """ if n == 2: try...
That IP module sucks. Occasionally it returns an IP address behind cloudflare which probably happens when cloudflare tries to proxy your web request because it thinks you're trying to DoS. It's better if we just run our own infrastructure.
Below is the the instruction that describes the task: ### Input: That IP module sucks. Occasionally it returns an IP address behind cloudflare which probably happens when cloudflare tries to proxy your web request because it thinks you're trying to DoS. It's better if we just run our own infrastructure....
def get_measurements_from_kal_scan(kal_out): """Return a list of all measurements from kalibrate channel scan.""" result = [] for line in kal_out.splitlines(): if "offset " in line: p_line = line.split(' ') result.append(p_line[-1]) return result
Return a list of all measurements from kalibrate channel scan.
Below is the the instruction that describes the task: ### Input: Return a list of all measurements from kalibrate channel scan. ### Response: def get_measurements_from_kal_scan(kal_out): """Return a list of all measurements from kalibrate channel scan.""" result = [] for line in kal_out.splitlines(): ...
def timeframe(self, start, end): r""" When you want to search bugs for a certain time frame. :param start: :param end: :returns: :class:`Search` """ if start: self._time_frame['chfieldfrom'] = start if end: self._ti...
r""" When you want to search bugs for a certain time frame. :param start: :param end: :returns: :class:`Search`
Below is the the instruction that describes the task: ### Input: r""" When you want to search bugs for a certain time frame. :param start: :param end: :returns: :class:`Search` ### Response: def timeframe(self, start, end): r""" When you want to ...
def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: """ Returns True if you have vision on a grid point. """ # more info: https://github.com/Blizzard/s2client-proto/blob/9906df71d6909511907d8419b33acc1a3bd51ec0/s2clientprotocol/spatial.proto#L19 assert isinstance(pos, (Point2, Point3...
Returns True if you have vision on a grid point.
Below is the the instruction that describes the task: ### Input: Returns True if you have vision on a grid point. ### Response: def is_visible(self, pos: Union[Point2, Point3, Unit]) -> bool: """ Returns True if you have vision on a grid point. """ # more info: https://github.com/Blizzard/s2client-...
def _merge_with_defaults(params): """ Performs a 2-level deep merge of params with _default_params with corrent merging of params for each mark. This is a bit complicated since params['marks'] is a list and we need to make sure each mark gets the default params. """ marks_params = [ ...
Performs a 2-level deep merge of params with _default_params with corrent merging of params for each mark. This is a bit complicated since params['marks'] is a list and we need to make sure each mark gets the default params.
Below is the the instruction that describes the task: ### Input: Performs a 2-level deep merge of params with _default_params with corrent merging of params for each mark. This is a bit complicated since params['marks'] is a list and we need to make sure each mark gets the default params. ### Response:...
def do_action(self, target, dry_run=False): """ :param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes """ original_path =...
:param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes
Below is the the instruction that describes the task: ### Input: :param target: Full path and filename :param dry_run: True - don't actually perform action. False: perform action. No effect for this rule. :return: filename: Full path and filename after action completes ### Response: def do_action(s...
def get_schema_for_game(self, appID, language=None, format=None): """Request the available achievements and stats for a game. appID: The app id language: The language to return the results in. None uses default. format: Return format. None defaults to json. (json, xml, vdf) """...
Request the available achievements and stats for a game. appID: The app id language: The language to return the results in. None uses default. format: Return format. None defaults to json. (json, xml, vdf)
Below is the the instruction that describes the task: ### Input: Request the available achievements and stats for a game. appID: The app id language: The language to return the results in. None uses default. format: Return format. None defaults to json. (json, xml, vdf) ### Response: def g...
def create(self, enable_turn=values.unset, type=values.unset, unique_name=values.unset, status_callback=values.unset, status_callback_method=values.unset, max_participants=values.unset, record_participants_on_connect=values.unset, video_codecs=values.unset, me...
Create a new RoomInstance :param bool enable_turn: Use Twilio Network Traversal for TURN service. :param RoomInstance.RoomType type: Type of room, either peer-to-peer, group-small or group. :param unicode unique_name: Name of the Room. :param unicode status_callback: A URL that Twilio s...
Below is the the instruction that describes the task: ### Input: Create a new RoomInstance :param bool enable_turn: Use Twilio Network Traversal for TURN service. :param RoomInstance.RoomType type: Type of room, either peer-to-peer, group-small or group. :param unicode unique_name: Name of ...
def xpnsl(h1, h2, use_threads=True): """Cross-population version of the NSL statistic. Parameters ---------- h1 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the first population. h2 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for th...
Cross-population version of the NSL statistic. Parameters ---------- h1 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the first population. h2 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the second population. use_threads : bool,...
Below is the the instruction that describes the task: ### Input: Cross-population version of the NSL statistic. Parameters ---------- h1 : array_like, int, shape (n_variants, n_haplotypes) Haplotype array for the first population. h2 : array_like, int, shape (n_variants, n_haplotypes) ...
def report(location, document): """ Run reporter on document and return list of ReporterError instances. (Depending on the location it will or won't run anything.) Returns a list of `ReporterError`. """ assert isinstance(location, six.string_types) if location.endswith('.py'): retu...
Run reporter on document and return list of ReporterError instances. (Depending on the location it will or won't run anything.) Returns a list of `ReporterError`.
Below is the the instruction that describes the task: ### Input: Run reporter on document and return list of ReporterError instances. (Depending on the location it will or won't run anything.) Returns a list of `ReporterError`. ### Response: def report(location, document): """ Run reporter on docu...
def systemInformationType2ter(): """SYSTEM INFORMATION TYPE 2ter Section 9.1.34""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x3) # 00000011 d = NeighbourCellsDescription2() e = Si2terRestOctets() packet = a / b / c / d / e return packet
SYSTEM INFORMATION TYPE 2ter Section 9.1.34
Below is the the instruction that describes the task: ### Input: SYSTEM INFORMATION TYPE 2ter Section 9.1.34 ### Response: def systemInformationType2ter(): """SYSTEM INFORMATION TYPE 2ter Section 9.1.34""" a = L2PseudoLength(l2pLength=0x12) b = TpPd(pd=0x6) c = MessageType(mesType=0x3) # 00000011 ...
def from_path(path: str, encoding: str = 'utf-8', **kwargs) -> BELGraph: """Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`. :param path: A file path :param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the pytho...
Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`. :param path: A file path :param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the python `docs <https://docs.python.org/3/library/codecs.html#standard-encodings>`...
Below is the the instruction that describes the task: ### Input: Load a BEL graph from a file resource. This function is a thin wrapper around :func:`from_lines`. :param path: A file path :param encoding: the encoding to use when reading this file. Is passed to :code:`codecs.open`. See the python `doc...
def list_databases(self, page_size=None, page_token=None): """List databases for the instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases :type page_size: int :param page_size:...
List databases for the instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases :type page_size: int :param page_size: Optional. The maximum number of databases in each page of...
Below is the the instruction that describes the task: ### Input: List databases for the instance. See https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1#google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases :type page_size: int :param page_size: ...
def convert_runsummary_to_json( df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_' ): """Convert a Pandas DataFrame with runsummary to JSON for DB upload""" data_field = [] comment += ", by {}".format(getpass.getuser()) for det_id, det_data in df.groupby('det_id'): runs_field = ...
Convert a Pandas DataFrame with runsummary to JSON for DB upload
Below is the the instruction that describes the task: ### Input: Convert a Pandas DataFrame with runsummary to JSON for DB upload ### Response: def convert_runsummary_to_json( df, comment='Uploaded via km3pipe.StreamDS', prefix='TEST_' ): """Convert a Pandas DataFrame with runsummary to JSON for DB upl...