code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def encode(self, payload): """ Encode payload """ try: return self.encoder.encode(payload) except Exception as exception: raise EncodeError(str(exception))
Encode payload
Below is the the instruction that describes the task: ### Input: Encode payload ### Response: def encode(self, payload): """ Encode payload """ try: return self.encoder.encode(payload) except Exception as exception: raise EncodeError(str(exception))
def _rewrite_function(f): """ Rewrite a function so that any if/else branches are intercepted and their behavior can be overridden. This is accomplished using 3 steps: 1. Get the source of the function and then rewrite the AST using _IfTransformer 2. Do some small fixups to the tree to make sure ...
Rewrite a function so that any if/else branches are intercepted and their behavior can be overridden. This is accomplished using 3 steps: 1. Get the source of the function and then rewrite the AST using _IfTransformer 2. Do some small fixups to the tree to make sure a) the function doesn't have the...
Below is the the instruction that describes the task: ### Input: Rewrite a function so that any if/else branches are intercepted and their behavior can be overridden. This is accomplished using 3 steps: 1. Get the source of the function and then rewrite the AST using _IfTransformer 2. Do some small fix...
def get_inventory_str(self, keys=None): """ Convert a dict generated by ansible.LagoAnsible.get_inventory to an INI-like file. Args: keys (list of str): Path to the keys that will be used to create groups. Returns: str: INI-like Ansible i...
Convert a dict generated by ansible.LagoAnsible.get_inventory to an INI-like file. Args: keys (list of str): Path to the keys that will be used to create groups. Returns: str: INI-like Ansible inventory
Below is the the instruction that describes the task: ### Input: Convert a dict generated by ansible.LagoAnsible.get_inventory to an INI-like file. Args: keys (list of str): Path to the keys that will be used to create groups. Returns: str: INI-like ...
def clear_sonos_playlist(self, sonos_playlist, update_id=0): """Clear all tracks from a Sonos playlist. This is a convenience method for :py:meth:`reorder_sonos_playlist`. Example:: device.clear_sonos_playlist(sonos_playlist) Args: sonos_playlist ...
Clear all tracks from a Sonos playlist. This is a convenience method for :py:meth:`reorder_sonos_playlist`. Example:: device.clear_sonos_playlist(sonos_playlist) Args: sonos_playlist (:py:class:`~.soco.data_structures.DidlPlaylistContainer`): ...
Below is the the instruction that describes the task: ### Input: Clear all tracks from a Sonos playlist. This is a convenience method for :py:meth:`reorder_sonos_playlist`. Example:: device.clear_sonos_playlist(sonos_playlist) Args: sonos_playlist (...
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSess...
Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession or None, optional) : This is used to prevent "boomeran...
Below is the the instruction that describes the task: ### Input: Sets the value of this property from a JSON value. This method first Args: obj (HasProps) : json (JSON-dict) : models(seq[Model], optional) : setter (ClientSession or ServerSession o...
def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') """ gk = get_api_client() site = get_cluster_site(cluster) return gk.sites[site].clusters[cluster].nodes.list()
Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes')
Below is the the instruction that describes the task: ### Input: Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g 'rennes') ### Response: def get_nodes(cluster): """Get all the nodes of a given cluster. Args: cluster(string): uid of the cluster (e.g...
def _flatten_dict(self, dict_): """Modifies the given dict into a flat dict consisting of only key/value pairs. """ flattened_dict = {} for (key, value) in dict_.iteritems(): if isinstance(value, dict): flattened_dict.update(self._flatten_dict(value)) ...
Modifies the given dict into a flat dict consisting of only key/value pairs.
Below is the the instruction that describes the task: ### Input: Modifies the given dict into a flat dict consisting of only key/value pairs. ### Response: def _flatten_dict(self, dict_): """Modifies the given dict into a flat dict consisting of only key/value pairs. """ fla...
def cancel(self, client=None): """API call: cancel job via a POST request See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel :type client: :class:`~google.cloud.bigquery.client.Client` or ``NoneType`` :param client: the client to use...
API call: cancel job via a POST request See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel :type client: :class:`~google.cloud.bigquery.client.Client` or ``NoneType`` :param client: the client to use. If not passed, falls back to the ...
Below is the the instruction that describes the task: ### Input: API call: cancel job via a POST request See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs/cancel :type client: :class:`~google.cloud.bigquery.client.Client` or ``NoneType`` :para...
def parse_options(self, option_values): """ Set the options (with parsing) and returns a dict of all options values """ self.set_options_values(option_values, parse=True) return self.get_options_values(hidden=False)
Set the options (with parsing) and returns a dict of all options values
Below is the the instruction that describes the task: ### Input: Set the options (with parsing) and returns a dict of all options values ### Response: def parse_options(self, option_values): """ Set the options (with parsing) and returns a dict of all options values """ self.set_options_val...
def persistent_load(self, pid): """ Reconstruct a GLC object using the persistent ID. This method should not be used externally. It is required by the unpickler super class. Parameters ---------- pid : The persistent ID used in pickle file to save the GLC object. ...
Reconstruct a GLC object using the persistent ID. This method should not be used externally. It is required by the unpickler super class. Parameters ---------- pid : The persistent ID used in pickle file to save the GLC object. Returns ---------- The GLC o...
Below is the the instruction that describes the task: ### Input: Reconstruct a GLC object using the persistent ID. This method should not be used externally. It is required by the unpickler super class. Parameters ---------- pid : The persistent ID used in pickle file to save ...
def _return_fieldset(self, fieldset): """ This function became a bit messy, since it needs to deal with two cases. 1) No fieldset, which is represented as an integer 2) A fieldset """ collapsible = None description = None try: # Make s...
This function became a bit messy, since it needs to deal with two cases. 1) No fieldset, which is represented as an integer 2) A fieldset
Below is the the instruction that describes the task: ### Input: This function became a bit messy, since it needs to deal with two cases. 1) No fieldset, which is represented as an integer 2) A fieldset ### Response: def _return_fieldset(self, fieldset): """ This function b...
def contains_element(self, element): """Determines if an element is contained in the priority queue." :returns: bool -- true iff element is in the priority queue. """ return (element in self.element_finder) and \ (self.element_finder[element][1] != self.INVALID)
Determines if an element is contained in the priority queue." :returns: bool -- true iff element is in the priority queue.
Below is the the instruction that describes the task: ### Input: Determines if an element is contained in the priority queue." :returns: bool -- true iff element is in the priority queue. ### Response: def contains_element(self, element): """Determines if an element is contained in the priority qu...
def GetFirstWrittenEventSource(self): """Retrieves the first event source that was written after open. Using GetFirstWrittenEventSource and GetNextWrittenEventSource newly added event sources can be retrieved in order of addition. Returns: EventSource: event source or None if there are no newly ...
Retrieves the first event source that was written after open. Using GetFirstWrittenEventSource and GetNextWrittenEventSource newly added event sources can be retrieved in order of addition. Returns: EventSource: event source or None if there are no newly written ones. Raises: IOError: whe...
Below is the the instruction that describes the task: ### Input: Retrieves the first event source that was written after open. Using GetFirstWrittenEventSource and GetNextWrittenEventSource newly added event sources can be retrieved in order of addition. Returns: EventSource: event source or Non...
def resolve_DID(did, hostport=None, proxy=None): """ Resolve a DID to a public key. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4. fetch and authenticate the JWT at each URL (abort if t...
Resolve a DID to a public key. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4. fetch and authenticate the JWT at each URL (abort if there are none) 5. extract the public key from the JWT and...
Below is the the instruction that describes the task: ### Input: Resolve a DID to a public key. This is a multi-step process: 1. get the name record 2. get the zone file 3. parse the zone file to get its URLs (if it's not well-formed, then abort) 4. fetch and authenticate the JWT at each URL (ab...
def predict_topk(self, dataset, output_type='probability', k=3, output_frequency='per_row'): """ Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `prediction_id`, `class`, and `probability`, or `rank`, depen...
Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `prediction_id`, `class`, and `probability`, or `rank`, depending on the ``output_type`` parameter. Parameters ---------- dataset : SFrame ...
Below is the the instruction that describes the task: ### Input: Return top-k predictions for the ``dataset``, using the trained model. Predictions are returned as an SFrame with three columns: `prediction_id`, `class`, and `probability`, or `rank`, depending on the ``output_type`` paramete...
def full_path(self): """ Return the full path of the local object If not local, it will return self.path :return: str """ if "local" in self.driver.name.lower(): return "%s/%s" % self.container.key, self.path return self.path
Return the full path of the local object If not local, it will return self.path :return: str
Below is the the instruction that describes the task: ### Input: Return the full path of the local object If not local, it will return self.path :return: str ### Response: def full_path(self): """ Return the full path of the local object If not local, it will return self.pat...
def deserialize(self, value, **kwargs): """Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value """ kwargs.update({'trusted': kwargs.get('trusted', False)}) if self.deserializer is not None: ...
Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value
Below is the the instruction that describes the task: ### Input: Return a deserialized value If no deserializer is provided, it uses the deserialize method of the prop corresponding to the value ### Response: def deserialize(self, value, **kwargs): """Return a deserialized value I...
def get_explicit_resnorms(self, indices=None): '''Explicitly computes the Ritz residual norms.''' res = self.get_explicit_residual(indices) # apply preconditioner linear_system = self._deflated_solver.linear_system Mres = linear_system.M * res # compute norms re...
Explicitly computes the Ritz residual norms.
Below is the the instruction that describes the task: ### Input: Explicitly computes the Ritz residual norms. ### Response: def get_explicit_resnorms(self, indices=None): '''Explicitly computes the Ritz residual norms.''' res = self.get_explicit_residual(indices) # apply preconditioner ...
def many(p): """Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values. """ @Parser def _many(tokens, s): """Iterative implementati...
Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values.
Below is the the instruction that describes the task: ### Input: Parser(a, b) -> Parser(a, [b]) Returns a parser that infinitely applies the parser p to the input sequence of tokens while it successfully parsers them. The resulting parser returns a list of parsed values. ### Response: def many(p): ...
def access_token(self): """Get access_token.""" if self.cache_token: return self.access_token_ or \ self._resolve_credential('access_token') return self.access_token_
Get access_token.
Below is the the instruction that describes the task: ### Input: Get access_token. ### Response: def access_token(self): """Get access_token.""" if self.cache_token: return self.access_token_ or \ self._resolve_credential('access_token') return self.access_tok...
def default_route(family=None): ''' Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.d...
Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash salt '*' network.default_route
Below is the the instruction that describes the task: ### Input: Return default route(s) from routing table .. versionchanged:: 2015.8.0 Added support for SunOS (Solaris 10, Illumos, SmartOS) .. versionchanged:: 2016.11.4 Added support for AIX CLI Example: .. code-block:: bash ...
def batch_gen(data, batch_size): ''' Usage:: for batch in batch_gen(iter, 100): do_something(batch) ''' data = data or [] for i in range(0, len(data), batch_size): yield data[i:i + batch_size]
Usage:: for batch in batch_gen(iter, 100): do_something(batch)
Below is the the instruction that describes the task: ### Input: Usage:: for batch in batch_gen(iter, 100): do_something(batch) ### Response: def batch_gen(data, batch_size): ''' Usage:: for batch in batch_gen(iter, 100): do_something(batch) ''' data = data o...
def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string version of extension name. """ # Parse out any extension specified in filename _indx = filename.find('[') if _indx > 0: # Read extension name provided _fname = fil...
Parse out filename from any specified extensions. Returns rootname and string version of extension name.
Below is the the instruction that describes the task: ### Input: Parse out filename from any specified extensions. Returns rootname and string version of extension name. ### Response: def parseFilename(filename): """ Parse out filename from any specified extensions. Returns rootname and string ve...
def create_multiple_bar_chart(self, x_labels, mul_y_values, mul_y_labels, normalize=False): """Creates bar chart with multiple lines :param x_labels: Names for each variable :param mul_y_values: list of values of x labels :param mul_y_labels: list of la...
Creates bar chart with multiple lines :param x_labels: Names for each variable :param mul_y_values: list of values of x labels :param mul_y_labels: list of labels for each y value :param normalize: True iff you want to normalize each y series :return: Bar chart
Below is the the instruction that describes the task: ### Input: Creates bar chart with multiple lines :param x_labels: Names for each variable :param mul_y_values: list of values of x labels :param mul_y_labels: list of labels for each y value :param normalize: True iff you want to...
def relookup(self, pattern): """ Dictionary lookup with a regular expression. Return pairs whose key matches pattern. """ key = re.compile(pattern) return filter(lambda x : key.match(x[0]), self.data.items())
Dictionary lookup with a regular expression. Return pairs whose key matches pattern.
Below is the the instruction that describes the task: ### Input: Dictionary lookup with a regular expression. Return pairs whose key matches pattern. ### Response: def relookup(self, pattern): """ Dictionary lookup with a regular expression. Return pairs whose key matches pattern. ...
def set_target(self, target: EventDispatcherBase) -> None: """ This method should be called by the event dispatcher that dispatches this event to set its target property. Args: target (EventDispatcherBase): The event dispatcher that will dispatch this event. ...
This method should be called by the event dispatcher that dispatches this event to set its target property. Args: target (EventDispatcherBase): The event dispatcher that will dispatch this event. Raises: PermissionError: If the target property of the event has al...
Below is the the instruction that describes the task: ### Input: This method should be called by the event dispatcher that dispatches this event to set its target property. Args: target (EventDispatcherBase): The event dispatcher that will dispatch this event. Raises: ...
def cast_to_a1_notation(method): """ Decorator function casts wrapped arguments to A1 notation in range method calls. """ @wraps(method) def wrapper(self, *args, **kwargs): try: if len(args): int(args[0]) # Convert to A1 notation range...
Decorator function casts wrapped arguments to A1 notation in range method calls.
Below is the the instruction that describes the task: ### Input: Decorator function casts wrapped arguments to A1 notation in range method calls. ### Response: def cast_to_a1_notation(method): """ Decorator function casts wrapped arguments to A1 notation in range method calls. """ @wraps(me...
def linear_cmap(field_name, palette, low, high, low_color=None, high_color=None, nan_color="gray"): ''' Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with ...
Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list of colors to use for colormapping low (float) : a minimum va...
Below is the the instruction that describes the task: ### Input: Create a ``DataSpec`` dict that applyies a client-side ``LinearColorMapper`` transformation to a ``ColumnDataSource`` column. Args: field_name (str) : a field name to configure ``DataSpec`` with palette (seq[color]) : a list ...
def connect_all(state): ''' Connect to all the configured servers in parallel. Reads/writes state.inventory. Args: state (``pyinfra.api.State`` obj): the state containing an inventory to connect to ''' hosts = [ host for host in state.inventory if state.is_host_in_limit(hos...
Connect to all the configured servers in parallel. Reads/writes state.inventory. Args: state (``pyinfra.api.State`` obj): the state containing an inventory to connect to
Below is the the instruction that describes the task: ### Input: Connect to all the configured servers in parallel. Reads/writes state.inventory. Args: state (``pyinfra.api.State`` obj): the state containing an inventory to connect to ### Response: def connect_all(state): ''' Connect to all th...
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html file...
Write to a single output file and/or subdirectory.
Below is the the instruction that describes the task: ### Input: Write to a single output file and/or subdirectory. ### Response: def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save P...
def read_all(filename): """ Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list """ array = javabridge.static_call( ...
Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list
Below is the the instruction that describes the task: ### Input: Reads the serialized objects from disk. Caller must wrap objects in appropriate Python wrapper classes. :param filename: the file with the serialized objects :type filename: str :return: the list of JB_OBjects :rtype: list ### Respons...
def abort(self): """Terminate audio processing immediately. This does not wait for pending audio buffers. If successful, the stream is considered inactive. """ err = _pa.Pa_AbortStream(self._stream) if err == _pa.paStreamIsStopped: return self._handl...
Terminate audio processing immediately. This does not wait for pending audio buffers. If successful, the stream is considered inactive.
Below is the the instruction that describes the task: ### Input: Terminate audio processing immediately. This does not wait for pending audio buffers. If successful, the stream is considered inactive. ### Response: def abort(self): """Terminate audio processing immediately. This d...
def move_asset_behind(self, asset_id, composition_id, reference_id): """Reorders assets in a composition by moving the specified asset behind of a reference asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composi...
Reorders assets in a composition by moving the specified asset behind of a reference asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` arg: reference_id (osid.id.Id): ``Id`` of the reference ...
Below is the the instruction that describes the task: ### Input: Reorders assets in a composition by moving the specified asset behind of a reference asset. arg: asset_id (osid.id.Id): ``Id`` of the ``Asset`` arg: composition_id (osid.id.Id): ``Id`` of the ``Composition`` ...
def get_gdal_options(opts, is_remote=False): """ Return a merged set of custom and default GDAL/rasterio Env options. If is_remote is set to True, the default GDAL_HTTP_OPTS are appended. Parameters ---------- opts : dict or None Explicit GDAL options. is_remote : bool Indi...
Return a merged set of custom and default GDAL/rasterio Env options. If is_remote is set to True, the default GDAL_HTTP_OPTS are appended. Parameters ---------- opts : dict or None Explicit GDAL options. is_remote : bool Indicate whether Env is for a remote file. Returns -...
Below is the the instruction that describes the task: ### Input: Return a merged set of custom and default GDAL/rasterio Env options. If is_remote is set to True, the default GDAL_HTTP_OPTS are appended. Parameters ---------- opts : dict or None Explicit GDAL options. is_remote : bool ...
def plot_zt_dop(self, temps='all', output='average', relaxation_time=1e-14): """ Plot the figure of merit zT in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list ...
Plot the figure of merit zT in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want to plot only some. output: with 'average' you get an aver...
Below is the the instruction that describes the task: ### Input: Plot the figure of merit zT in function of doping levels for different temperatures. Args: temps: the default 'all' plots all the temperatures in the analyzer. Specify a list of temperatures if you want ...
def storage(self): """Getter for various Storage variables""" if self._storage is None: api = "SYNO.Storage.CGI.Storage" url = "%s/entry.cgi?api=%s&version=1&method=load_info" % ( self.base_url, api) self._storage = SynoStorage(s...
Getter for various Storage variables
Below is the the instruction that describes the task: ### Input: Getter for various Storage variables ### Response: def storage(self): """Getter for various Storage variables""" if self._storage is None: api = "SYNO.Storage.CGI.Storage" url = "%s/entry.cgi?api=%s&version...
def get_statistic_by_name(stat_name): """ Fetches a statistics based on the given class name. Does a look-up in the gadgets' registered statistics to find the specified one. """ if stat_name == 'ALL': return get_statistic_models() for stat in get_statistic_models(): if stat.__n...
Fetches a statistics based on the given class name. Does a look-up in the gadgets' registered statistics to find the specified one.
Below is the the instruction that describes the task: ### Input: Fetches a statistics based on the given class name. Does a look-up in the gadgets' registered statistics to find the specified one. ### Response: def get_statistic_by_name(stat_name): """ Fetches a statistics based on the given class name...
def imf(m): ''' Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorization available via vimf() ''' m1 = 0.08; m2 = 0.50 a1 = 0.30; a2 = 1.30; a3 = 2.3 const2 = m1**-a1 -m1**-a2 const3 = m2**-a2 -m2**-a3 if m < 0.08: alpha = 0.3 ...
Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorization available via vimf()
Below is the the instruction that describes the task: ### Input: Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorization available via vimf() ### Response: def imf(m): ''' Returns ------- N(M)dM for given mass according to Kroupa IMF, vectorizat...
def is_contiguous(self): """Return offset and size of contiguous data, else None.""" if self._keyframe is None: raise RuntimeError('keyframe not set') if self._keyframe.is_contiguous: return self._offsetscounts[0][0], self._keyframe.is_contiguous[1] return None
Return offset and size of contiguous data, else None.
Below is the the instruction that describes the task: ### Input: Return offset and size of contiguous data, else None. ### Response: def is_contiguous(self): """Return offset and size of contiguous data, else None.""" if self._keyframe is None: raise RuntimeError('keyframe not set') ...
async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if parameters is None: parameters = [] return await self._execute(self._execute_insert, sql, parameters)
Helper to insert and get the last_insert_rowid.
Below is the the instruction that describes the task: ### Input: Helper to insert and get the last_insert_rowid. ### Response: async def execute_insert( self, sql: str, parameters: Iterable[Any] = None ) -> Optional[sqlite3.Row]: """Helper to insert and get the last_insert_rowid.""" if ...
def remove_nonancestors_of(self, node): """Remove all of the non-ancestors operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,' ' use a DAGNode instead', Deprec...
Remove all of the non-ancestors operation nodes of node.
Below is the the instruction that describes the task: ### Input: Remove all of the non-ancestors operation nodes of node. ### Response: def remove_nonancestors_of(self, node): """Remove all of the non-ancestors operation nodes of node.""" if isinstance(node, int): warnings.warn('Calling...
def get_game(self, name): """Get the game instance for a game name :param name: the name of the game :type name: :class:`str` :returns: the game instance :rtype: :class:`models.Game` | None :raises: None """ games = self.search_games(query=name, live=Fals...
Get the game instance for a game name :param name: the name of the game :type name: :class:`str` :returns: the game instance :rtype: :class:`models.Game` | None :raises: None
Below is the the instruction that describes the task: ### Input: Get the game instance for a game name :param name: the name of the game :type name: :class:`str` :returns: the game instance :rtype: :class:`models.Game` | None :raises: None ### Response: def get_game(self, n...
def true_positives(links_true, links_pred): """Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) l...
Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The true (or actual) links. links_pred: pandas.MultiIndex, pandas.Dat...
Below is the the instruction that describes the task: ### Input: Count the number of True Positives. Returns the number of correctly predicted links, also called the number of True Positives (TP). Parameters ---------- links_true: pandas.MultiIndex, pandas.DataFrame, pandas.Series The ...
def color_is_disabled(**envars): ''' Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_DISABLED='1'`` Re...
Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLOR_DISABLED='1'`` Returns: None, Bool: Disabled
Below is the the instruction that describes the task: ### Input: Look for clues in environment, e.g.: - https://bixense.com/clicolors/ - http://no-color.org/ Arguments: envars: Additional environment variables to check for equality, i.e. ``MYAPP_COLO...
def get_op_nodes(self, op=None, data=False): """Deprecated. Use op_nodes().""" warnings.warn('The method get_op_nodes() is being replaced by op_nodes().' 'Returning a list of node_ids/(node_id, data) tuples is ' 'also deprecated, op_nodes() returns a list of ...
Deprecated. Use op_nodes().
Below is the the instruction that describes the task: ### Input: Deprecated. Use op_nodes(). ### Response: def get_op_nodes(self, op=None, data=False): """Deprecated. Use op_nodes().""" warnings.warn('The method get_op_nodes() is being replaced by op_nodes().' 'Returning a li...
def _postprocess_hover(self, renderer, source): """ Attaches renderer to hover tool and processes tooltips to ensure datetime data is displayed correctly. """ hover = self.handles.get('hover') if hover is None: return if hover.renderers == 'auto': ...
Attaches renderer to hover tool and processes tooltips to ensure datetime data is displayed correctly.
Below is the the instruction that describes the task: ### Input: Attaches renderer to hover tool and processes tooltips to ensure datetime data is displayed correctly. ### Response: def _postprocess_hover(self, renderer, source): """ Attaches renderer to hover tool and processes tooltips to...
def send_line(self, data, nowait=False): """send a line to the server. replace CR by spaces""" data = data.replace('\n', ' ').replace('\r', ' ') f = asyncio.Future(loop=self.loop) if self.queue is not None and nowait is False: self.queue.put_nowait((f, data)) else: ...
send a line to the server. replace CR by spaces
Below is the the instruction that describes the task: ### Input: send a line to the server. replace CR by spaces ### Response: def send_line(self, data, nowait=False): """send a line to the server. replace CR by spaces""" data = data.replace('\n', ' ').replace('\r', ' ') f = asyncio.Future(...
def verify(self, data, signature): """ Verify signed data using the Montgomery public key stored by this XEdDSA instance. :param data: A bytes-like object containing the data that was signed. :param signature: A bytes-like object encoding the signature with length SIGNATURE_...
Verify signed data using the Montgomery public key stored by this XEdDSA instance. :param data: A bytes-like object containing the data that was signed. :param signature: A bytes-like object encoding the signature with length SIGNATURE_SIZE. :returns: A boolean indicating whether th...
Below is the the instruction that describes the task: ### Input: Verify signed data using the Montgomery public key stored by this XEdDSA instance. :param data: A bytes-like object containing the data that was signed. :param signature: A bytes-like object encoding the signature with length ...
def lock(self): """ This method sets a cache variable to mark current job as "already running". """ if self.cache.get(self.lock_name): return False else: self.cache.set(self.lock_name, timezone.now(), self.timeout) return True
This method sets a cache variable to mark current job as "already running".
Below is the the instruction that describes the task: ### Input: This method sets a cache variable to mark current job as "already running". ### Response: def lock(self): """ This method sets a cache variable to mark current job as "already running". """ if self.cache.get(self.lock_...
def verify_proxy_ticket(ticket, service): """ Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure. """ params = {'ticket': ticket, 'service': service} url = (urljoin(settings.CAS_SERVER_URL, 'proxyValidate') + '?' +...
Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure.
Below is the the instruction that describes the task: ### Input: Verifies CAS 2.0+ XML-based proxy ticket. :param: ticket :param: service Returns username on success and None on failure. ### Response: def verify_proxy_ticket(ticket, service): """ Verifies CAS 2.0+ XML-based proxy ticket. ...
def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): """ Lock packages. Downloader search packages """ if deps_file_path is None: deps_file_path = self._deps_path if depslock_file_path is None: depslock_file_path = self._de...
Lock packages. Downloader search packages
Below is the the instruction that describes the task: ### Input: Lock packages. Downloader search packages ### Response: def lock_packages(self, deps_file_path=None, depslock_file_path=None, packages=None): """ Lock packages. Downloader search packages """ if deps_file_path is None:...
def _integrate_cvode(self, *args, **kwargs): """ Do not use directly (use ``integrate(..., integrator='cvode')``). Uses CVode from CVodes in `SUNDIALS <https://computation.llnl.gov/casc/sundials/>`_ (via `pycvodes <https://pypi.python.org/pypi/pycvodes>`_) to integrate the ODE s...
Do not use directly (use ``integrate(..., integrator='cvode')``). Uses CVode from CVodes in `SUNDIALS <https://computation.llnl.gov/casc/sundials/>`_ (via `pycvodes <https://pypi.python.org/pypi/pycvodes>`_) to integrate the ODE system.
Below is the the instruction that describes the task: ### Input: Do not use directly (use ``integrate(..., integrator='cvode')``). Uses CVode from CVodes in `SUNDIALS <https://computation.llnl.gov/casc/sundials/>`_ (via `pycvodes <https://pypi.python.org/pypi/pycvodes>`_) to integra...
def invoke_function(self, function_name, **function_params): """ Invokes an Excel Function """ url = self.build_url(self._endpoints.get('function').format(function_name)) response = self.session.post(url, data=function_params) if not response: return None data = respo...
Invokes an Excel Function
Below is the the instruction that describes the task: ### Input: Invokes an Excel Function ### Response: def invoke_function(self, function_name, **function_params): """ Invokes an Excel Function """ url = self.build_url(self._endpoints.get('function').format(function_name)) response = self...
def create_config(sections, section_contents): """Create a config file from the provided sections and key value pairs. Args: sections (List[str]): A list of section keys. key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as the list of sections. That is to say...
Create a config file from the provided sections and key value pairs. Args: sections (List[str]): A list of section keys. key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as the list of sections. That is to say, if there are two sections, there should be two ...
Below is the the instruction that describes the task: ### Input: Create a config file from the provided sections and key value pairs. Args: sections (List[str]): A list of section keys. key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as the list of sections....
def siblingsId(self) -> Tuple[CtsReference, CtsReference]: """ Siblings Identifiers of the passage :rtype: (str, str) """ if not self._text: raise MissingAttribute("CapitainsCtsPassage was iniated without CtsTextMetadata object") if self._prev_next is not None: ...
Siblings Identifiers of the passage :rtype: (str, str)
Below is the the instruction that describes the task: ### Input: Siblings Identifiers of the passage :rtype: (str, str) ### Response: def siblingsId(self) -> Tuple[CtsReference, CtsReference]: """ Siblings Identifiers of the passage :rtype: (str, str) """ if not self._tex...
def simulateCatalog(config,roi=None,lon=None,lat=None): """ Simulate a catalog object. """ import ugali.simulation.simulator if roi is None: roi = createROI(config,lon,lat) sim = ugali.simulation.simulator.Simulator(config,roi) return sim.catalog()
Simulate a catalog object.
Below is the the instruction that describes the task: ### Input: Simulate a catalog object. ### Response: def simulateCatalog(config,roi=None,lon=None,lat=None): """ Simulate a catalog object. """ import ugali.simulation.simulator if roi is None: roi = createROI(config,lon,lat) sim = ugali....
def replace(self, **updates): """Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments. """ state = self.dump() state.update(updates) return self.__class__(**state)
Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments.
Below is the the instruction that describes the task: ### Input: Return a new profile with the given updates. Unspecified fields will be the same as this instance. See `__new__` for details on the arguments. ### Response: def replace(self, **updates): """Return a new profile with the given...
def preferred_width(self, cli, max_available_width): """ Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that com...
Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that completions are suddenly shown in more or fewer columns.)
Below is the the instruction that describes the task: ### Input: Report the width of the longest meta text as the preferred width of this control. It could be that we use less width, but this way, we're sure that the layout doesn't change when we select another completion (E.g. that complet...
def list_timeline(self, list_id, since_id=None, max_id=None, count=20): """ List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specifie...
List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specified ID (older than) :param count: number of results per page :return: list of ...
Below is the the instruction that describes the task: ### Input: List the tweets of specified list. :param list_id: list ID number :param since_id: results will have ID greater than specified ID (more recent than) :param max_id: results will have ID less than specified ID (older than) ...
def violation_lines(self, src_path): """ Return a list of lines in violation (integers) in `src_path` that were changed. If we have no coverage information for `src_path`, returns an empty list. """ diff_violations = self._diff_violations().get(src_path) ...
Return a list of lines in violation (integers) in `src_path` that were changed. If we have no coverage information for `src_path`, returns an empty list.
Below is the the instruction that describes the task: ### Input: Return a list of lines in violation (integers) in `src_path` that were changed. If we have no coverage information for `src_path`, returns an empty list. ### Response: def violation_lines(self, src_path): """ ...
def read_frames(self, n, channels=None): """Read ``n`` frames from the track, starting with the current frame :param integer n: Number of frames to read :param integer channels: Number of channels to return (default is number of channels in track) :returns: Next ``n`...
Read ``n`` frames from the track, starting with the current frame :param integer n: Number of frames to read :param integer channels: Number of channels to return (default is number of channels in track) :returns: Next ``n`` frames from the track, starting with ``current_fra...
Below is the the instruction that describes the task: ### Input: Read ``n`` frames from the track, starting with the current frame :param integer n: Number of frames to read :param integer channels: Number of channels to return (default is number of channels in track) :r...
def users_set_preferences(self, user_id, data, **kwargs): """Set user’s preferences.""" return self.__call_api_post('users.setPreferences', userId=user_id, data=data, kwargs=kwargs)
Set user’s preferences.
Below is the the instruction that describes the task: ### Input: Set user’s preferences. ### Response: def users_set_preferences(self, user_id, data, **kwargs): """Set user’s preferences.""" return self.__call_api_post('users.setPreferences', userId=user_id, data=data, kwargs=kwargs)
def setup(self, analysis_project_name, remote_project_name, incident_id, zone, boot_disk_size, cpu_cores, remote_instance_name=None, disk_names=None, all_disks=False, image_project="ubuntu-os-cloud", ...
Sets up a Google cloud collector. This method creates and starts an analysis VM in the analysis project and selects disks to copy from the remote project. If disk_names is specified, it will copy the corresponding disks from the project, ignoring disks belonging to any specific instances. If remo...
Below is the the instruction that describes the task: ### Input: Sets up a Google cloud collector. This method creates and starts an analysis VM in the analysis project and selects disks to copy from the remote project. If disk_names is specified, it will copy the corresponding disks from the proj...
def create_summary_metadata(display_name, description, num_thresholds): """Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: display_name: The display name used in TensorBoard. description: The description to show in TensorBoard. num_thresholds: The number of thresholds...
Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: display_name: The display name used in TensorBoard. description: The description to show in TensorBoard. num_thresholds: The number of thresholds to use for PR curves. Returns: A `summary_pb2.SummaryMetadata` protob...
Below is the the instruction that describes the task: ### Input: Create a `summary_pb2.SummaryMetadata` proto for pr_curves plugin data. Arguments: display_name: The display name used in TensorBoard. description: The description to show in TensorBoard. num_thresholds: The number of thresholds to use ...
def get_function_config(cfg): """Check whether a function exists or not and return its config""" function_name = cfg.get('function_name') profile_name = cfg.get('profile') aws_access_key_id = cfg.get('aws_access_key_id') aws_secret_access_key = cfg.get('aws_secret_access_key') client = get_clie...
Check whether a function exists or not and return its config
Below is the the instruction that describes the task: ### Input: Check whether a function exists or not and return its config ### Response: def get_function_config(cfg): """Check whether a function exists or not and return its config""" function_name = cfg.get('function_name') profile_name = cfg.get('...
def add(self, selected: 'SelectedMailbox', *, replace: 'SelectedMailbox' = None) -> None: """Add a new selected mailbox object to the set, which may then be returned by :meth:`.any_selected`. Args: selected: The new selected mailbox object. replace: An existi...
Add a new selected mailbox object to the set, which may then be returned by :meth:`.any_selected`. Args: selected: The new selected mailbox object. replace: An existing selected mailbox object that should be removed from the weak set.
Below is the the instruction that describes the task: ### Input: Add a new selected mailbox object to the set, which may then be returned by :meth:`.any_selected`. Args: selected: The new selected mailbox object. replace: An existing selected mailbox object that should be re...
def drop_keyspace(keyspace, contact_points=None, port=None, cql_user=None, cql_pass=None): ''' Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string ...
Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type contact_points: str | list[str] :param cql_user: The Cassandra u...
Below is the the instruction that describes the task: ### Input: Drop a keyspace if it exists in a Cassandra cluster. :param keyspace: The keyspace to drop. :type keyspace: str :param contact_points: The Cassandra cluster addresses, can either be a string or a list of IPs. :type conta...
def rigthgen(self, value=0): """Generate rows to fill right pixels in int mode""" while True: yield self.newarray(self.nplanes_right * self.width, value)
Generate rows to fill right pixels in int mode
Below is the the instruction that describes the task: ### Input: Generate rows to fill right pixels in int mode ### Response: def rigthgen(self, value=0): """Generate rows to fill right pixels in int mode""" while True: yield self.newarray(self.nplanes_right * self.width, value)
def generate_random(featureType, numberVertices=3, boundingBox=[-180.0, -90.0, 180.0, 90.0]): """ Generates random geojson features depending on the parameters passed through. The bounding box defaults to the world - [-180.0, -90.0, 180.0, 90.0]. The number of vertices defaults t...
Generates random geojson features depending on the parameters passed through. The bounding box defaults to the world - [-180.0, -90.0, 180.0, 90.0]. The number of vertices defaults to 3. :param featureType: A geometry type :type featureType: Point, LineString, Polygon :param numberVertices: The...
Below is the the instruction that describes the task: ### Input: Generates random geojson features depending on the parameters passed through. The bounding box defaults to the world - [-180.0, -90.0, 180.0, 90.0]. The number of vertices defaults to 3. :param featureType: A geometry type :type f...
def add(self, client): """Add a client to the penalty box.""" if client.pool_id in self._client_ids: log.info("%r is already in the penalty box. Ignoring.", client) return release = time.time() + self._min_wait heapq.heappush(self._clients, (release, (client, self...
Add a client to the penalty box.
Below is the the instruction that describes the task: ### Input: Add a client to the penalty box. ### Response: def add(self, client): """Add a client to the penalty box.""" if client.pool_id in self._client_ids: log.info("%r is already in the penalty box. Ignoring.", client) ...
def _eigsorted(cov, asc=True): """ Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted smallest to largest (asc=Tr...
Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted smallest to largest (asc=True), or largest to smallest (asc=Fa...
Below is the the instruction that describes the task: ### Input: Computes eigenvalues and eigenvectors of a covariance matrix and returns them sorted by eigenvalue. Parameters ---------- cov : ndarray covariance matrix asc : bool, default=True determines whether we are sorted s...
def search(self, value): """Find an element in the tree""" if self.payload == value: return self else: if value <= self.payload: if self.left: return self.left.search(value) else: if self.right: ...
Find an element in the tree
Below is the the instruction that describes the task: ### Input: Find an element in the tree ### Response: def search(self, value): """Find an element in the tree""" if self.payload == value: return self else: if value <= self.payload: if self.left: ...
def indexables(self): """ create/cache the indexables if they don't exist """ if self._indexables is None: self._indexables = [] # index columns self._indexables.extend([ IndexCol(name=name, axis=axis, pos=i) for i, (axis, name) in en...
create/cache the indexables if they don't exist
Below is the the instruction that describes the task: ### Input: create/cache the indexables if they don't exist ### Response: def indexables(self): """ create/cache the indexables if they don't exist """ if self._indexables is None: self._indexables = [] # index columns ...
def load(self, elem): """ Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict> """ self.testTag(elem, 'dict') out = {} for xitem in elem: key = xitem.get('key') t...
Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict>
Below is the the instruction that describes the task: ### Input: Converts the inputted dict tag to Python. :param elem | <xml.etree.ElementTree> :return <dict> ### Response: def load(self, elem): """ Converts the inputted dict tag to Python. ...
def correlation(df, cm=cm.PuOr_r, vmin=None, vmax=None, labels=None, show_scatter=False): """ Generate a column-wise correlation plot from the provided data. The columns of the supplied dataframes will be correlated (using `analysis.correlation`) to generate a Pearson correlation plot heatmap. Scatter ...
Generate a column-wise correlation plot from the provided data. The columns of the supplied dataframes will be correlated (using `analysis.correlation`) to generate a Pearson correlation plot heatmap. Scatter plots of correlated samples can also be generated over the redundant half of the plot to give a vi...
Below is the the instruction that describes the task: ### Input: Generate a column-wise correlation plot from the provided data. The columns of the supplied dataframes will be correlated (using `analysis.correlation`) to generate a Pearson correlation plot heatmap. Scatter plots of correlated samples can a...
def make_parser(defaults=None): """ :param defaults: Default option values """ if defaults is None: defaults = DEFAULTS ctypes = API.list_types() ctypes_s = ", ".join(ctypes) type_help = "Select type of %s config files from " + \ ctypes_s + " [Automatically detected by file ...
:param defaults: Default option values
Below is the the instruction that describes the task: ### Input: :param defaults: Default option values ### Response: def make_parser(defaults=None): """ :param defaults: Default option values """ if defaults is None: defaults = DEFAULTS ctypes = API.list_types() ctypes_s = ", ".jo...
def _validate_login(self): ''' a method to validate user can access heroku account ''' title = '%s.validate_login' % self.__class__.__name__ # verbosity windows_insert = ' On windows, run in cmd.exe' self.printer('Checking heroku credentials ......
a method to validate user can access heroku account
Below is the the instruction that describes the task: ### Input: a method to validate user can access heroku account ### Response: def _validate_login(self): ''' a method to validate user can access heroku account ''' title = '%s.validate_login' % self.__class__.__name__ ...
def restore_node(self, node): """ Restores a previously hidden node back into the graph and restores all of its incoming and outgoing edges. """ try: self.nodes[node], all_edges = self.hidden_nodes[node] for edge in all_edges: self.restore_...
Restores a previously hidden node back into the graph and restores all of its incoming and outgoing edges.
Below is the the instruction that describes the task: ### Input: Restores a previously hidden node back into the graph and restores all of its incoming and outgoing edges. ### Response: def restore_node(self, node): """ Restores a previously hidden node back into the graph and restores ...
def stateDict(self): """Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...} """ state = { 'duration' : self._duration, 'intensity' : self._intensity, 'risefall' : self._risefall, 'stim_t...
Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...}
Below is the the instruction that describes the task: ### Input: Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...} ### Response: def stateDict(self): """Saves internal values to be loaded later :returns: dict -- {'parametername': value, ...} ...
def create_blueprint(endpoints): """Create Invenio-Records-REST blueprint. :params endpoints: Dictionary representing the endpoints configuration. :returns: Configured blueprint. """ endpoints = endpoints or {} blueprint = Blueprint( 'invenio_records_rest', __name__, ur...
Create Invenio-Records-REST blueprint. :params endpoints: Dictionary representing the endpoints configuration. :returns: Configured blueprint.
Below is the the instruction that describes the task: ### Input: Create Invenio-Records-REST blueprint. :params endpoints: Dictionary representing the endpoints configuration. :returns: Configured blueprint. ### Response: def create_blueprint(endpoints): """Create Invenio-Records-REST blueprint. ...
def create_expanded_design_for_mixing(design, draw_list, mixing_pos, rows_to_mixers): """ Parameters ---------- design : 2D ndarray. All elements should be ints, floats, or longs. Ea...
Parameters ---------- design : 2D ndarray. All elements should be ints, floats, or longs. Each row corresponds to an available alternative for a given individual. There should be one column per index coefficient being estimated. draw_list : list of 2D ndarrays. All numpy arra...
Below is the the instruction that describes the task: ### Input: Parameters ---------- design : 2D ndarray. All elements should be ints, floats, or longs. Each row corresponds to an available alternative for a given individual. There should be one column per index coefficient being e...
def _prepare(self): """Builds a URL and return a PreparedRequest. Returns (requests.PreparedRequest) Raises UberIllegalState (APIError) """ if self.method not in http.ALLOWED_METHODS: raise UberIllegalState('Unsupported HTTP Method.') ...
Builds a URL and return a PreparedRequest. Returns (requests.PreparedRequest) Raises UberIllegalState (APIError)
Below is the the instruction that describes the task: ### Input: Builds a URL and return a PreparedRequest. Returns (requests.PreparedRequest) Raises UberIllegalState (APIError) ### Response: def _prepare(self): """Builds a URL and return a PreparedRequest. ...
def new_password_challenge(self, password, new_password): """ Respond to the new password challenge using the SRP protocol :param password: The user's current passsword :param password: The user's new passsword """ aws = AWSSRP(username=self.username, password=password, p...
Respond to the new password challenge using the SRP protocol :param password: The user's current passsword :param password: The user's new passsword
Below is the the instruction that describes the task: ### Input: Respond to the new password challenge using the SRP protocol :param password: The user's current passsword :param password: The user's new passsword ### Response: def new_password_challenge(self, password, new_password): """ ...
def save_chat_message(*args, **kwargs): """ kwargs will always include: 'data': # will always be exactly what your client sent on the socket # in this case... {u'message': u'hi', u'sender': u'anonymous', u'channel': u'homepage'}, 'dispatcher': # the dispatcher that ...
kwargs will always include: 'data': # will always be exactly what your client sent on the socket # in this case... {u'message': u'hi', u'sender': u'anonymous', u'channel': u'homepage'}, 'dispatcher': # the dispatcher that will allow for broadcasting a response <hendri...
Below is the the instruction that describes the task: ### Input: kwargs will always include: 'data': # will always be exactly what your client sent on the socket # in this case... {u'message': u'hi', u'sender': u'anonymous', u'channel': u'homepage'}, 'dispatcher': # the...
def local_assortativity_wu_sign(W): ''' Local assortativity measures the extent to which nodes are connected to nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014 formula to allowed weighted/signed networks. Parameters ---------- W : NxN np.ndarray undirected conne...
Local assortativity measures the extent to which nodes are connected to nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014 formula to allowed weighted/signed networks. Parameters ---------- W : NxN np.ndarray undirected connection matrix with positive and negative weights ...
Below is the the instruction that describes the task: ### Input: Local assortativity measures the extent to which nodes are connected to nodes of similar strength. Adapted from Thedchanamoorthy et al. 2014 formula to allowed weighted/signed networks. Parameters ---------- W : NxN np.ndarray ...
def _single_tree_paths(self, tree): """Get all traversal paths from a single tree.""" skel = tree.consolidate() tree = defaultdict(list) for edge in skel.edges: svert = edge[0] evert = edge[1] tree[svert].append(evert) tree[evert].append(svert) def dfs(path, visited): ...
Get all traversal paths from a single tree.
Below is the the instruction that describes the task: ### Input: Get all traversal paths from a single tree. ### Response: def _single_tree_paths(self, tree): """Get all traversal paths from a single tree.""" skel = tree.consolidate() tree = defaultdict(list) for edge in skel.edges: svert =...
def get_dependencies_from_decl(decl, recursive=True): """ Returns the list of all types and declarations the declaration depends on. """ result = [] if isinstance(decl, typedef.typedef_t) or \ isinstance(decl, variable.variable_t): return [dependency_info_t(decl, decl.decl_type)...
Returns the list of all types and declarations the declaration depends on.
Below is the the instruction that describes the task: ### Input: Returns the list of all types and declarations the declaration depends on. ### Response: def get_dependencies_from_decl(decl, recursive=True): """ Returns the list of all types and declarations the declaration depends on. """ result ...
def login(self): """ This method performs the login on TheTVDB given the api key, user name and account identifier. :return: None """ auth_data = dict() auth_data['apikey'] = self.api_key auth_data['username'] = self.username auth_data['userkey'] = self.a...
This method performs the login on TheTVDB given the api key, user name and account identifier. :return: None
Below is the the instruction that describes the task: ### Input: This method performs the login on TheTVDB given the api key, user name and account identifier. :return: None ### Response: def login(self): """ This method performs the login on TheTVDB given the api key, user name and accoun...
def iterator(self, *argv): """ Iterator returning any list of elements via attribute lookup in `self` This iterator retains the order of the arguments """ for arg in argv: if hasattr(self, arg): for item in getattr(self, arg): yield item
Iterator returning any list of elements via attribute lookup in `self` This iterator retains the order of the arguments
Below is the the instruction that describes the task: ### Input: Iterator returning any list of elements via attribute lookup in `self` This iterator retains the order of the arguments ### Response: def iterator(self, *argv): """ Iterator returning any list of elements via attribute lookup in `sel...
def permission_delete_link(context, perm): """ Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions. """ user = context['request'].user if user.is_authenticated(): if (user.has_perm('aut...
Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions.
Below is the the instruction that describes the task: ### Input: Renders a html link to the delete view of the given permission. Returns no content if the request-user has no permission to delete foreign permissions. ### Response: def permission_delete_link(context, perm): """ Renders a html link t...
async def _set_whitelist(self): """ Whitelist domains for the messenger extensions """ page = self.settings() if 'whitelist' in page: await self._send_to_messenger_profile(page, { 'whitelisted_domains': page['whitelist'], }) ...
Whitelist domains for the messenger extensions
Below is the the instruction that describes the task: ### Input: Whitelist domains for the messenger extensions ### Response: async def _set_whitelist(self): """ Whitelist domains for the messenger extensions """ page = self.settings() if 'whitelist' in page: a...
def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from wx_loader import wx state = self self.app = wx.App(False) self.app.frame = MPImageFrame(state=self) self.app.frame.Show() self.app.MainLoop()
child process - this holds all the GUI elements
Below is the the instruction that describes the task: ### Input: child process - this holds all the GUI elements ### Response: def child_task(self): '''child process - this holds all the GUI elements''' mp_util.child_close_fds() from wx_loader import wx state = self self.ap...
def send_string(self, string: str): """ Sends the given string for output. """ if not string: return string = string.replace('\n', "<enter>") string = string.replace('\t', "<tab>") _logger.debug("Send via event interface") self.__clea...
Sends the given string for output.
Below is the the instruction that describes the task: ### Input: Sends the given string for output. ### Response: def send_string(self, string: str): """ Sends the given string for output. """ if not string: return string = string.replace('\n', "<enter>") ...
def parse_network_data(data_packet=None, include_filter_key=None, filter_keys=[], record_tcp=True, record_udp=True, record_arp=True, record_icmp=True): """build_node :param ...
build_node :param data_packet: raw recvfrom data :param filter_keys: list of strings to filter and remove baby-birding packets to yourself :param record_tcp: want to record TCP frames? :param record_udp: want to record UDP frames? :param record_arp: w...
Below is the the instruction that describes the task: ### Input: build_node :param data_packet: raw recvfrom data :param filter_keys: list of strings to filter and remove baby-birding packets to yourself :param record_tcp: want to record TCP frames? :...
def selective_download(name, oldest, newest): """Note: RSS feeds are counted backwards, default newest is 0, the most recent.""" if six.PY3: name = name.encode("utf-8") feed = resolve_name(name) if six.PY3: feed = feed.decode() d = feedparser.parse(feed) logger.debug(d) try: ...
Note: RSS feeds are counted backwards, default newest is 0, the most recent.
Below is the the instruction that describes the task: ### Input: Note: RSS feeds are counted backwards, default newest is 0, the most recent. ### Response: def selective_download(name, oldest, newest): """Note: RSS feeds are counted backwards, default newest is 0, the most recent.""" if six.PY3: na...
def _computeWeights(self, logform=False, include_nonzero=False, recalc_denom=True, return_f_k=False): """Compute the normalized weights corresponding to samples for the given reduced potential. Compute the normalized weights corresponding to samples for the given reduced potential. Also stores ...
Compute the normalized weights corresponding to samples for the given reduced potential. Compute the normalized weights corresponding to samples for the given reduced potential. Also stores the all_log_denom array for reuse. Parameters ---------- logform : bool, optional ...
Below is the the instruction that describes the task: ### Input: Compute the normalized weights corresponding to samples for the given reduced potential. Compute the normalized weights corresponding to samples for the given reduced potential. Also stores the all_log_denom array for reuse. ...
def download_async(self, remote_path, local_path, callback=None): """Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param cal...
Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: the callback which will be invoked when downloading is complete.
Below is the the instruction that describes the task: ### Input: Downloads remote resources from WebDAV server asynchronously :param remote_path: the path to remote resource on WebDAV server. Can be file and directory. :param local_path: the path to save resource locally. :param callback: t...
def GetAvailableClaimTotal(self): """ Gets the total amount of Gas that this wallet is able to claim at a given moment. Returns: Fixed8: the amount of Gas available to claim as a Fixed8 number. """ coinrefs = [coin.Reference for coin in self.GetUnclaimedCoins()] ...
Gets the total amount of Gas that this wallet is able to claim at a given moment. Returns: Fixed8: the amount of Gas available to claim as a Fixed8 number.
Below is the the instruction that describes the task: ### Input: Gets the total amount of Gas that this wallet is able to claim at a given moment. Returns: Fixed8: the amount of Gas available to claim as a Fixed8 number. ### Response: def GetAvailableClaimTotal(self): """ Gets ...
def get_cn(n, mc, dl, F, e): """ Compute c_n from Eq. 22 of Taylor et al. (2015). :param n: Harmonic number :param mc: Chirp mass of binary [Solar Mass] :param dl: Luminosity distance [Mpc] :param F: Orbital frequency of binary [Hz] :param e: Orbital Eccentricity :returns: c_n ...
Compute c_n from Eq. 22 of Taylor et al. (2015). :param n: Harmonic number :param mc: Chirp mass of binary [Solar Mass] :param dl: Luminosity distance [Mpc] :param F: Orbital frequency of binary [Hz] :param e: Orbital Eccentricity :returns: c_n
Below is the the instruction that describes the task: ### Input: Compute c_n from Eq. 22 of Taylor et al. (2015). :param n: Harmonic number :param mc: Chirp mass of binary [Solar Mass] :param dl: Luminosity distance [Mpc] :param F: Orbital frequency of binary [Hz] :param e: Orbital Eccentri...
def plot_ppc(self, nsims=1000, T=np.mean, **kwargs): """ Plots histogram of the discrepancy from draws of the posterior Parameters ---------- nsims : int (default : 1000) How many draws for the PPC T : function A discrepancy measure - e.g. np.mean, np.st...
Plots histogram of the discrepancy from draws of the posterior Parameters ---------- nsims : int (default : 1000) How many draws for the PPC T : function A discrepancy measure - e.g. np.mean, np.std, np.max
Below is the the instruction that describes the task: ### Input: Plots histogram of the discrepancy from draws of the posterior Parameters ---------- nsims : int (default : 1000) How many draws for the PPC T : function A discrepancy measure - e.g. np.mean, n...