code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def GetAllPluginInformation(cls, show_all=True): """Retrieves a list of the registered analysis plugins. Args: show_all (Optional[bool]): True if all analysis plugin names should be listed. Returns: list[tuple[str, str, str]]: the name, docstring and type string of each ana...
Retrieves a list of the registered analysis plugins. Args: show_all (Optional[bool]): True if all analysis plugin names should be listed. Returns: list[tuple[str, str, str]]: the name, docstring and type string of each analysis plugin in alphabetical order.
Below is the the instruction that describes the task: ### Input: Retrieves a list of the registered analysis plugins. Args: show_all (Optional[bool]): True if all analysis plugin names should be listed. Returns: list[tuple[str, str, str]]: the name, docstring and type string of each ...
def send(self, response): """ Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent. """ self._connection.connection.set('{}:{}'.format(SIGNAL_REDIS_PREFIX, response.uid), ...
Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent.
Below is the the instruction that describes the task: ### Input: Send a response back to the client that issued a request. Args: response (Response): Reference to the response object that should be sent. ### Response: def send(self, response): """ Send a response back to the client tha...
def generate(self): """Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the architecture. generated_graph: Graph An instance of Graph. """ generated_grap...
Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the architecture. generated_graph: Graph An instance of Graph.
Below is the the instruction that describes the task: ### Input: Generate the next neural architecture. Returns ------- other_info: any object Anything to be saved in the training queue together with the architecture. generated_graph: Graph An instance of Gra...
def combine_tensors_and_multiply(combination: str, tensors: List[torch.Tensor], weights: torch.nn.Parameter) -> torch.Tensor: """ Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate fu...
Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate function from ``combine_tensors`` because we try to avoid instantiating large intermediate tensors during the combination, which is possible because we know that we're going to be multiplying by a w...
Below is the the instruction that describes the task: ### Input: Like :func:`combine_tensors`, but does a weighted (linear) multiplication while combining. This is a separate function from ``combine_tensors`` because we try to avoid instantiating large intermediate tensors during the combination, which is p...
def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]: """Get several graphs by their identifiers.""" return [ self.networks[network_id] for network_id in network_ids ]
Get several graphs by their identifiers.
Below is the the instruction that describes the task: ### Input: Get several graphs by their identifiers. ### Response: def get_graphs_by_ids(self, network_ids: Iterable[int]) -> List[BELGraph]: """Get several graphs by their identifiers.""" return [ self.networks[network_id] ...
def _parse_users(self, match): '''Parse usernames.''' # Don't parse lists here if match.group(2) is not None: return match.group(0) mat = match.group(0) if self._include_spans: self._users.append((mat[1:], match.span(0))) else: self._...
Parse usernames.
Below is the the instruction that describes the task: ### Input: Parse usernames. ### Response: def _parse_users(self, match): '''Parse usernames.''' # Don't parse lists here if match.group(2) is not None: return match.group(0) mat = match.group(0) if self._inc...
def basic_retinotopy_data(hemi, retino_type): ''' basic_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi and retinotopy type t; it does this by looking at the properties in hemi and picking out any combination that is commonly used to denote empirical retinotopy dat...
basic_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi and retinotopy type t; it does this by looking at the properties in hemi and picking out any combination that is commonly used to denote empirical retinotopy data. These common names are stored in _predicted_retinto...
Below is the the instruction that describes the task: ### Input: basic_retinotopy_data(hemi, t) yields a numpy array of data for the given cortex object hemi and retinotopy type t; it does this by looking at the properties in hemi and picking out any combination that is commonly used to denote empirical ret...
def _get_conditions(pk_conds, and_conds=None): """If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of pri...
If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list of list of primary key constraints returned by _get_conditions_list ...
Below is the the instruction that describes the task: ### Input: If and_conds = [a1, a2, ..., an] and pk_conds = [[b11, b12, ..., b1m], ... [bk1, ..., bkm]], this function will return the mysql condition clause: a1 & a2 & ... an & ((b11 and ... b1m) or ... (b11 and ... b1m)) :param pk_conds: a list...
def txn2data(self, txn: dict) -> str: """ Given ledger transaction, return its data json. :param txn: transaction as dict :return: transaction data json """ rv_json = json.dumps({}) if self == Protocol.V_13: rv_json = json.dumps(txn['result'].get('da...
Given ledger transaction, return its data json. :param txn: transaction as dict :return: transaction data json
Below is the the instruction that describes the task: ### Input: Given ledger transaction, return its data json. :param txn: transaction as dict :return: transaction data json ### Response: def txn2data(self, txn: dict) -> str: """ Given ledger transaction, return its data json. ...
def read_excel_file(inputfile, sheet_name): """ Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return """ workbook = xlrd.open_workbook(inputfile) ...
Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return
Below is the the instruction that describes the task: ### Input: Return a matrix containing all the information present in the excel sheet of the specified excel document. :arg inputfile: excel document to read :arg sheetname: the name of the excel sheet to return ### Response: def read_excel_file(inp...
def _validate_positional_arguments(args): """ To validate the positional argument feature - https://github.com/Azure/azure-cli/pull/6055. Assuming that unknown commands are positional arguments immediately led by words that only appear at the end of the commands Slight modification of https://g...
To validate the positional argument feature - https://github.com/Azure/azure-cli/pull/6055. Assuming that unknown commands are positional arguments immediately led by words that only appear at the end of the commands Slight modification of https://github.com/Azure/azure-cli/blob/dev/src/azure-cli-core/...
Below is the the instruction that describes the task: ### Input: To validate the positional argument feature - https://github.com/Azure/azure-cli/pull/6055. Assuming that unknown commands are positional arguments immediately led by words that only appear at the end of the commands Slight modification o...
def create_entry_tag(sender, instance, created, **kwargs): """ Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sending ItemBase class. :param instance: the ItemBase instance. """ from ..models import ( Entry, EntryTag ) en...
Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sending ItemBase class. :param instance: the ItemBase instance.
Below is the the instruction that describes the task: ### Input: Creates EntryTag for Entry corresponding to specified ItemBase instance. :param sender: the sending ItemBase class. :param instance: the ItemBase instance. ### Response: def create_entry_tag(sender, instance, created, **kwargs): """ ...
def format_result(result): """Serialise Result""" instance = None error = None if result["instance"] is not None: instance = format_instance(result["instance"]) if result["error"] is not None: error = format_error(result["error"]) result = { "success": result["success"...
Serialise Result
Below is the the instruction that describes the task: ### Input: Serialise Result ### Response: def format_result(result): """Serialise Result""" instance = None error = None if result["instance"] is not None: instance = format_instance(result["instance"]) if result["error"] is not No...
def csv(self): """Parse raw response as csv and return row object list. """ lines = self._parsecsv(self.raw) # set keys from header line (first line) keys = next(lines) for line in lines: yield dict(zip(keys, line))
Parse raw response as csv and return row object list.
Below is the the instruction that describes the task: ### Input: Parse raw response as csv and return row object list. ### Response: def csv(self): """Parse raw response as csv and return row object list. """ lines = self._parsecsv(self.raw) # set keys from header line (first line)...
def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. """ if not g.cpars['hcam_server_on']: raise DriverError('getRunNumber error: servers are not active') url = g.cpars['hipercam_server'] + 'status/DET.FRAM2.NO...
Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it.
Below is the the instruction that describes the task: ### Input: Polls the data server to find the current frame number. Throws an exceotion if it cannot determine it. ### Response: def getFrameNumber(g): """ Polls the data server to find the current frame number. Throws an exceotion if it cannot...
def cast_conditionally(data: mx.sym.Symbol, dtype: str) -> mx.sym.Symbol: """ Workaround until no-op cast will be fixed in MXNet codebase. Creates cast symbol only if dtype is different from default one, i.e. float32. :param data: Input symbol. :param dtype: Target dtype. :return: Cast symbol o...
Workaround until no-op cast will be fixed in MXNet codebase. Creates cast symbol only if dtype is different from default one, i.e. float32. :param data: Input symbol. :param dtype: Target dtype. :return: Cast symbol or just data symbol.
Below is the the instruction that describes the task: ### Input: Workaround until no-op cast will be fixed in MXNet codebase. Creates cast symbol only if dtype is different from default one, i.e. float32. :param data: Input symbol. :param dtype: Target dtype. :return: Cast symbol or just data symbo...
def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """ # Regression if mode == 'regressor': return scikit_value[0] * scaling # Binary classification if n_classes == 2: # Decision tree ...
Get the right value from the scikit-tree
Below is the the instruction that describes the task: ### Input: Get the right value from the scikit-tree ### Response: def _get_value(scikit_value, mode = 'regressor', scaling = 1.0, n_classes = 2, tree_index = 0): """ Get the right value from the scikit-tree """ # Regression if mode == 'regressor...
def icmpv6(self): """ - An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise. """ ipproto, proto_start = self.protocol if ipproto == Protocol.ICMPV6: return ICMPv6Header(self, proto_start)
- An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise.
Below is the the instruction that describes the task: ### Input: - An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise. ### Response: def icmpv6(self): """ - An ICMPv6Header instance, if the packet is valid ICMPv6. - None, otherwise. """ ipprot...
def reorder_mod(A, ci): ''' This function reorders the connectivity matrix by modular structure and may hence be useful in visualization of modular structure. Parameters ---------- A : NxN np.ndarray binary/weighted connectivity matrix ci : Nx1 np.ndarray module affiliation ...
This function reorders the connectivity matrix by modular structure and may hence be useful in visualization of modular structure. Parameters ---------- A : NxN np.ndarray binary/weighted connectivity matrix ci : Nx1 np.ndarray module affiliation vector Returns ------- ...
Below is the the instruction that describes the task: ### Input: This function reorders the connectivity matrix by modular structure and may hence be useful in visualization of modular structure. Parameters ---------- A : NxN np.ndarray binary/weighted connectivity matrix ci : Nx1 np.nd...
def short_label(self): """str: A short description of the group. >>> device.group.short_label 'Kitchen + 1' """ group_names = sorted([m.player_name for m in self.members]) group_label = group_names[0] if len(group_names) > 1: group_label += " + {}".fo...
str: A short description of the group. >>> device.group.short_label 'Kitchen + 1'
Below is the the instruction that describes the task: ### Input: str: A short description of the group. >>> device.group.short_label 'Kitchen + 1' ### Response: def short_label(self): """str: A short description of the group. >>> device.group.short_label 'Kitchen + 1' ...
def holidays_set(self, year=None): "Return a quick date index (set)" return set([day for day, label in self.holidays(year)])
Return a quick date index (set)
Below is the the instruction that describes the task: ### Input: Return a quick date index (set) ### Response: def holidays_set(self, year=None): "Return a quick date index (set)" return set([day for day, label in self.holidays(year)])
def forwards(self, orm): "Write your forwards methods here." orm.Project.objects.update(label=F('name')) orm.Cohort.objects.update(label=F('name')) orm.Sample.objects.update(name=F('label'))
Write your forwards methods here.
Below is the the instruction that describes the task: ### Input: Write your forwards methods here. ### Response: def forwards(self, orm): "Write your forwards methods here." orm.Project.objects.update(label=F('name')) orm.Cohort.objects.update(label=F('name')) orm.Sample.objects.upd...
def serialize(self, data): """Return the data as serialized string. :param dict data: The data to serialize :rtype: str """ return json.dumps(self._serialize_datetime(data), ensure_ascii=False)
Return the data as serialized string. :param dict data: The data to serialize :rtype: str
Below is the the instruction that describes the task: ### Input: Return the data as serialized string. :param dict data: The data to serialize :rtype: str ### Response: def serialize(self, data): """Return the data as serialized string. :param dict data: The data to serialize ...
def setVisible(self, state): """ Sets the visibility for this record box. :param state | <bool> """ super(XOrbRecordBox, self).setVisible(state) if state and not self._loaded: if self.autoInitialize(): table = s...
Sets the visibility for this record box. :param state | <bool>
Below is the the instruction that describes the task: ### Input: Sets the visibility for this record box. :param state | <bool> ### Response: def setVisible(self, state): """ Sets the visibility for this record box. :param state | <bool> ""...
def get_niggli_reduced_lattice(self, tol: float = 1e-5) -> "Lattice": """ Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams, Acta Crystallographica Section A Foundations of Crystallography, 2003, 60(1)...
Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams, Acta Crystallographica Section A Foundations of Crystallography, 2003, 60(1), 1-6. doi:10.1107/S010876730302186X Args: tol (float): The numerical...
Below is the the instruction that describes the task: ### Input: Get the Niggli reduced lattice using the numerically stable algo proposed by R. W. Grosse-Kunstleve, N. K. Sauter, & P. D. Adams, Acta Crystallographica Section A Foundations of Crystallography, 2003, 60(1), 1-6. doi:10.1107/S0...
def _soap_client_call(method_name, *args): """Wrapper to call SoapClient method""" # a new client instance is built for threading issues soap_client = _build_soap_client() soap_args = _convert_soap_method_args(*args) # if pysimplesoap version requires it, apply a workaround for # https://github....
Wrapper to call SoapClient method
Below is the the instruction that describes the task: ### Input: Wrapper to call SoapClient method ### Response: def _soap_client_call(method_name, *args): """Wrapper to call SoapClient method""" # a new client instance is built for threading issues soap_client = _build_soap_client() soap_args = _c...
def row_cells(self, row_idx): """ Sequence of cells in the row at *row_idx* in this table. """ column_count = self._column_count start = row_idx * column_count end = start + column_count return self._cells[start:end]
Sequence of cells in the row at *row_idx* in this table.
Below is the the instruction that describes the task: ### Input: Sequence of cells in the row at *row_idx* in this table. ### Response: def row_cells(self, row_idx): """ Sequence of cells in the row at *row_idx* in this table. """ column_count = self._column_count start = ro...
def make_result_response(self): """Create result response for the a "get" or "set" iq stanza. :return: new `Iq` object with the same "id" as self, "from" and "to" attributes replaced and type="result". :returntype: `Iq`""" if self.stanza_type not in ("set", "get"): ...
Create result response for the a "get" or "set" iq stanza. :return: new `Iq` object with the same "id" as self, "from" and "to" attributes replaced and type="result". :returntype: `Iq`
Below is the the instruction that describes the task: ### Input: Create result response for the a "get" or "set" iq stanza. :return: new `Iq` object with the same "id" as self, "from" and "to" attributes replaced and type="result". :returntype: `Iq` ### Response: def make_result_respon...
def infos(cls, fqdn): """ Display information about hosted certificates for a fqdn. """ if isinstance(fqdn, (list, tuple)): ids = [] for fqd_ in fqdn: ids.extend(cls.infos(fqd_)) return ids ids = cls.usable_id(fqdn) if not ids: ...
Display information about hosted certificates for a fqdn.
Below is the the instruction that describes the task: ### Input: Display information about hosted certificates for a fqdn. ### Response: def infos(cls, fqdn): """ Display information about hosted certificates for a fqdn. """ if isinstance(fqdn, (list, tuple)): ids = [] for f...
def cache(ignore=None): """Decorator for memoizing a function using either the filesystem or a database. """ def decorator(func): # Initialize both cached versions joblib_cached = constants.joblib_memory.cache(func, ignore=ignore) db_cached = DbMemoizedFunc(func, ignore) ...
Decorator for memoizing a function using either the filesystem or a database.
Below is the the instruction that describes the task: ### Input: Decorator for memoizing a function using either the filesystem or a database. ### Response: def cache(ignore=None): """Decorator for memoizing a function using either the filesystem or a database. """ def decorator(func): ...
def point_displ(pt1, pt2): """ Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring """ #Imports import numpy as np # Make iterable if not np.iterable(pt1): pt1 = np.float64(np.array([pt1])) else: pt1 = np.fl...
Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring
Below is the the instruction that describes the task: ### Input: Calculate the displacement vector between two n-D points. pt1 - pt2 .. todo:: Complete point_disp docstring ### Response: def point_displ(pt1, pt2): """ Calculate the displacement vector between two n-D points. pt1 - pt2 .. to...
async def asgi_send(self, message: dict) -> None: """Called by the ASGI instance to send a message.""" if message["type"] == "http.response.start" and self.state == ASGIHTTPState.REQUEST: self.response = message elif message["type"] == "http.response.body" and self.state in { ...
Called by the ASGI instance to send a message.
Below is the the instruction that describes the task: ### Input: Called by the ASGI instance to send a message. ### Response: async def asgi_send(self, message: dict) -> None: """Called by the ASGI instance to send a message.""" if message["type"] == "http.response.start" and self.state == ASGIHTTP...
def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]: """Returns the nth digit of each number in m.""" return (m // (10 ** n)) % 10
Returns the nth digit of each number in m.
Below is the the instruction that describes the task: ### Input: Returns the nth digit of each number in m. ### Response: def digit(m: Union[int, pd.Series], n: int) -> Union[int, pd.Series]: """Returns the nth digit of each number in m.""" return (m // (10 ** n)) % 10
def process_item(self, item, spider): """ Process single item. Add item to items and then upload to S3 if size of items >= max_chunk_size. """ self.items.append(item) if len(self.items) >= self.max_chunk_size: self._upload_chunk(spider) return item
Process single item. Add item to items and then upload to S3 if size of items >= max_chunk_size.
Below is the the instruction that describes the task: ### Input: Process single item. Add item to items and then upload to S3 if size of items >= max_chunk_size. ### Response: def process_item(self, item, spider): """ Process single item. Add item to items and then upload to S3 if size of i...
def _get_handling_triplet(self, node_id): """_get_handling_triplet(node_id) -> (handler, value, attrs)""" handler = self._get_handler(node_id) value = self[node_id] attrs = self._get_attrs(node_id) return handler, value, attrs
_get_handling_triplet(node_id) -> (handler, value, attrs)
Below is the the instruction that describes the task: ### Input: _get_handling_triplet(node_id) -> (handler, value, attrs) ### Response: def _get_handling_triplet(self, node_id): """_get_handling_triplet(node_id) -> (handler, value, attrs)""" handler = self._get_handler(node_id) value = sel...
def get_now_utc(): ''' date in UTC, ISO format''' # Helper class for UTC time # Source: http://stackoverflow.com/questions/2331592/datetime-datetime-utcnow-why-no-tzinfo ZERO = datetime.timedelta(0) class UTC(datetime.tzinfo): """UTC""" def utcoffset(self, dt): return ZE...
date in UTC, ISO format
Below is the the instruction that describes the task: ### Input: date in UTC, ISO format ### Response: def get_now_utc(): ''' date in UTC, ISO format''' # Helper class for UTC time # Source: http://stackoverflow.com/questions/2331592/datetime-datetime-utcnow-why-no-tzinfo ZERO = datetime.timedelta...
def count(self): """ If result is True, then the count will process result set , if result if False, then only use condition to count """ if self._group_by or self._join or self.distinct_field: return self.do_(self.get_query().limit(None).order_by(None).offset(None).a...
If result is True, then the count will process result set , if result if False, then only use condition to count
Below is the the instruction that describes the task: ### Input: If result is True, then the count will process result set , if result if False, then only use condition to count ### Response: def count(self): """ If result is True, then the count will process result set , if result ...
def slice(filename, number_tiles=None, col=None, row=None, save=True): """ Split an image into a specified number of tiles. Args: filename (str): The filename of the image to split. number_tiles (int): The number of tiles required. Kwargs: save (bool): Whether or not to save til...
Split an image into a specified number of tiles. Args: filename (str): The filename of the image to split. number_tiles (int): The number of tiles required. Kwargs: save (bool): Whether or not to save tiles to disk. Returns: Tuple of :class:`Tile` instances.
Below is the the instruction that describes the task: ### Input: Split an image into a specified number of tiles. Args: filename (str): The filename of the image to split. number_tiles (int): The number of tiles required. Kwargs: save (bool): Whether or not to save tiles to disk. ...
def _feed_to_kafka(self, json_item): """Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not """ @MethodTimer.timeout(self.settings['KAFKA_FEED_TIMEOUT'], False) def _feed(json_item):...
Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not
Below is the the instruction that describes the task: ### Input: Sends a request to Kafka :param json_item: The json item to send :returns: A boolean indicating whther the data was sent successfully or not ### Response: def _feed_to_kafka(self, json_item): """Sends a request to Kafka ...
def update_function(self, param_vals): """Takes an array param_vals, updates function, returns the new error""" self.model = self.func(param_vals, *self.func_args, **self.func_kwargs) d = self.calc_residuals() return np.dot(d.flat, d.flat)
Takes an array param_vals, updates function, returns the new error
Below is the the instruction that describes the task: ### Input: Takes an array param_vals, updates function, returns the new error ### Response: def update_function(self, param_vals): """Takes an array param_vals, updates function, returns the new error""" self.model = self.func(param_vals, *self....
def iter_entry_points(self, group, name=None): """Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution ord...
Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distribution order).
Below is the the instruction that describes the task: ### Input: Yield entry point objects from `group` matching `name` If `name` is None, yields all entry points in `group` from all distributions in the working set, otherwise only ones matching both `group` and `name` are yielded (in distr...
def stellingwerf_pdm_theta(times, mags, errs, frequency, binsize=0.05, minbin=9): ''' This calculates the Stellingwerf PDM theta value at a test frequency. Parameters ---------- times,mags,errs : np.array The input time-series and associated errors. frequenc...
This calculates the Stellingwerf PDM theta value at a test frequency. Parameters ---------- times,mags,errs : np.array The input time-series and associated errors. frequency : float The test frequency to calculate the theta statistic at. binsize : float The phase bin size...
Below is the the instruction that describes the task: ### Input: This calculates the Stellingwerf PDM theta value at a test frequency. Parameters ---------- times,mags,errs : np.array The input time-series and associated errors. frequency : float The test frequency to calculate th...
def _compute_output_layer_expected(self): """Compute output layers expected that the IF will produce. Be careful when you call this function. It's a private function, better to use the public function `output_layers_expected()`. :return: List of expected layer keys. :rtype: lis...
Compute output layers expected that the IF will produce. Be careful when you call this function. It's a private function, better to use the public function `output_layers_expected()`. :return: List of expected layer keys. :rtype: list
Below is the the instruction that describes the task: ### Input: Compute output layers expected that the IF will produce. Be careful when you call this function. It's a private function, better to use the public function `output_layers_expected()`. :return: List of expected layer keys. ...
def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades. .. versionadded:: 2018.3.0 refresh Whether or not to refresh the package database before installing. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ''' pkgs = {} for...
List all available package upgrades. .. versionadded:: 2018.3.0 refresh Whether or not to refresh the package database before installing. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades
Below is the the instruction that describes the task: ### Input: List all available package upgrades. .. versionadded:: 2018.3.0 refresh Whether or not to refresh the package database before installing. CLI Example: .. code-block:: bash salt '*' pkg.list_upgrades ### Response: ...
def get_pathext(default_pathext=None): """Returns the path extensions from environment or a default""" if default_pathext is None: default_pathext = os.pathsep.join([ '.COM', '.EXE', '.BAT', '.CMD' ]) pathext = os.environ.get('PATHEXT', default_pathext) return pathext
Returns the path extensions from environment or a default
Below is the the instruction that describes the task: ### Input: Returns the path extensions from environment or a default ### Response: def get_pathext(default_pathext=None): """Returns the path extensions from environment or a default""" if default_pathext is None: default_pathext = os.pathsep.jo...
def targeted_conjugate_about(tensor: np.ndarray, target: np.ndarray, indices: Sequence[int], conj_indices: Sequence[int] = None, buffer: Optional[np.ndarray] = None, out: Opti...
r"""Conjugates the given tensor about the target tensor. This method computes a target tensor conjugated by another tensor. Here conjugate is used in the sense of conjugating by a matrix, i.a. A conjugated about B is $A B A^\dagger$ where $\dagger$ represents the conjugate transpose. Abstractly th...
Below is the the instruction that describes the task: ### Input: r"""Conjugates the given tensor about the target tensor. This method computes a target tensor conjugated by another tensor. Here conjugate is used in the sense of conjugating by a matrix, i.a. A conjugated about B is $A B A^\dagger$ where...
def _updateNumbers(self, linenumers): """ add/remove line numbers """ b = self.blockCount() c = b - linenumers if c > 0: # remove lines numbers for _ in range(c): # remove last line: self.setFocus() s...
add/remove line numbers
Below is the the instruction that describes the task: ### Input: add/remove line numbers ### Response: def _updateNumbers(self, linenumers): """ add/remove line numbers """ b = self.blockCount() c = b - linenumers if c > 0: # remove lines numbers ...
def find_object(self, username, secret, domain=None, host_ip=None, service_id=None): """ Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id. """ # Not sure yet if this is advisable... Older passwords can be overwritten... ...
Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id.
Below is the the instruction that describes the task: ### Input: Searches elasticsearch for objects with the same username, password, optional domain, host_ip and service_id. ### Response: def find_object(self, username, secret, domain=None, host_ip=None, service_id=None): """ Searches elastics...
def get_instance(self, payload): """ Build an instance of StyleSheetInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance ...
Build an instance of StyleSheetInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance
Below is the the instruction that describes the task: ### Input: Build an instance of StyleSheetInstance :param dict payload: Payload response from the API :returns: twilio.rest.autopilot.v1.assistant.style_sheet.StyleSheetInstance :rtype: twilio.rest.autopilot.v1.assistant.style_sheet.Sty...
def mag_discrepancy(RAW_IMU, ATTITUDE, inclination, declination=None): '''give the magnitude of the discrepancy between observed and expected magnetic field''' if declination is None: import mavutil declination = degrees(mavutil.mavfile_global.param('COMPASS_DEC', 0)) expected = expected_mag...
give the magnitude of the discrepancy between observed and expected magnetic field
Below is the the instruction that describes the task: ### Input: give the magnitude of the discrepancy between observed and expected magnetic field ### Response: def mag_discrepancy(RAW_IMU, ATTITUDE, inclination, declination=None): '''give the magnitude of the discrepancy between observed and expected magneti...
def metaseries_description_metadata(description): """Return metatata from MetaSeries image description as dict.""" if not description.startswith('<MetaData>'): raise ValueError('invalid MetaSeries image description') from xml.etree import cElementTree as etree # delayed import root = etree.fro...
Return metatata from MetaSeries image description as dict.
Below is the the instruction that describes the task: ### Input: Return metatata from MetaSeries image description as dict. ### Response: def metaseries_description_metadata(description): """Return metatata from MetaSeries image description as dict.""" if not description.startswith('<MetaData>'): r...
def get_assessments(self): """Gets all ``Assessments``. In plenary mode, the returned list contains all known assessments or an error results. Otherwise, the returned list may contain only those assessments that are accessible through this session. return: (osid.assessm...
Gets all ``Assessments``. In plenary mode, the returned list contains all known assessments or an error results. Otherwise, the returned list may contain only those assessments that are accessible through this session. return: (osid.assessment.AssessmentList) - a list of ...
Below is the the instruction that describes the task: ### Input: Gets all ``Assessments``. In plenary mode, the returned list contains all known assessments or an error results. Otherwise, the returned list may contain only those assessments that are accessible through this session....
def simulate_system(self, parameters, initial_conditions, timepoints, max_moment_order=1, number_of_processes=1): """ Perform Gillespie SSA simulations and returns trajectories for of each species. Each trajectory is interpolated at the given time points. By defau...
Perform Gillespie SSA simulations and returns trajectories for of each species. Each trajectory is interpolated at the given time points. By default, the average amounts of species for all simulations is returned. :param parameters: list of the initial values for the constants in the model. ...
Below is the the instruction that describes the task: ### Input: Perform Gillespie SSA simulations and returns trajectories for of each species. Each trajectory is interpolated at the given time points. By default, the average amounts of species for all simulations is returned. :param param...
def _login(session): """Login to UPS.""" resp = session.get(LOGIN_URL, params=_get_params(session.auth.locale)) parsed = BeautifulSoup(resp.text, HTML_PARSER) csrf = parsed.find(CSRF_FIND_TAG, CSRF_FIND_ATTR).get(VALUE_ATTR) resp = session.post(LOGIN_URL, { 'userID': session.auth.username, ...
Login to UPS.
Below is the the instruction that describes the task: ### Input: Login to UPS. ### Response: def _login(session): """Login to UPS.""" resp = session.get(LOGIN_URL, params=_get_params(session.auth.locale)) parsed = BeautifulSoup(resp.text, HTML_PARSER) csrf = parsed.find(CSRF_FIND_TAG, CSRF_FIND_ATT...
def add_prefix(self, ncname: str) -> None: """ Look up ncname and add it to the prefix map if necessary @param ncname: name to add """ if ncname not in self.prefixmap: uri = cu.expand_uri(ncname + ':', self.curi_maps) if uri and '://' in uri: self...
Look up ncname and add it to the prefix map if necessary @param ncname: name to add
Below is the the instruction that describes the task: ### Input: Look up ncname and add it to the prefix map if necessary @param ncname: name to add ### Response: def add_prefix(self, ncname: str) -> None: """ Look up ncname and add it to the prefix map if necessary @param ncname: name to...
def get(self, sid): """ Constructs a FeedbackSummaryContext :param sid: A string that uniquely identifies this feedback summary resource :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext :rtype: twilio.rest.api.v2010.account.call.feedback_summ...
Constructs a FeedbackSummaryContext :param sid: A string that uniquely identifies this feedback summary resource :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext :rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext
Below is the the instruction that describes the task: ### Input: Constructs a FeedbackSummaryContext :param sid: A string that uniquely identifies this feedback summary resource :returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext :rtype: twilio.rest.api.v20...
def end_workunit(self, workunit): """Implementation of Reporter callback.""" duration = workunit.duration() timing = '{:.3f}'.format(duration) unaccounted_time = '' # Background work may be idle a lot, no point in reporting that as unaccounted. if self.is_under_main_root(workunit): unaccou...
Implementation of Reporter callback.
Below is the the instruction that describes the task: ### Input: Implementation of Reporter callback. ### Response: def end_workunit(self, workunit): """Implementation of Reporter callback.""" duration = workunit.duration() timing = '{:.3f}'.format(duration) unaccounted_time = '' # Background w...
def get_iso_time(date_part, time_part): r"""Combign date and time into an iso datetime.""" str_date = datetime.datetime.strptime( date_part, '%m/%d/%Y').strftime('%Y-%m-%d') str_time = datetime.datetime.strptime( time_part, '%I:%M %p').strftime('%H:%M:%S') return str_date + "T" +...
r"""Combign date and time into an iso datetime.
Below is the the instruction that describes the task: ### Input: r"""Combign date and time into an iso datetime. ### Response: def get_iso_time(date_part, time_part): r"""Combign date and time into an iso datetime.""" str_date = datetime.datetime.strptime( date_part, '%m/%d/%Y').strftime('%Y-%m-...
def parse_request_body_response(self, body, scope=None, **kwargs): """Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the reque...
Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the request failed client authentication or is invalid, the authorization serve...
Below is the the instruction that describes the task: ### Input: Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the request ...
def setup_axes(rows=1, cols=1, figsize=(8, 6), expand=True, tight_layout=None, **kwargs): """ Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters --------...
Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number of rows to create. cols : int Number of columns to creat...
Below is the the instruction that describes the task: ### Input: Sets up a figure of size *figsize* with a number of rows (*rows*) and columns (*cols*). \*\*kwargs passed through to :meth:`matplotlib.figure.Figure.add_subplot`. .. versionadded:: 1.2 Parameters ---------- rows : int Number...
def check_dihedral(self, construction_table): """Checks, if the dihedral defining atom is colinear. Checks for each index starting from the third row of the ``construction_table``, if the reference atoms are colinear. Args: construction_table (pd.DataFrame): Return...
Checks, if the dihedral defining atom is colinear. Checks for each index starting from the third row of the ``construction_table``, if the reference atoms are colinear. Args: construction_table (pd.DataFrame): Returns: list: A list of problematic indices.
Below is the the instruction that describes the task: ### Input: Checks, if the dihedral defining atom is colinear. Checks for each index starting from the third row of the ``construction_table``, if the reference atoms are colinear. Args: construction_table (pd.DataFrame): ...
def add_personalization(self, personalization, index=0): """Add a Personaliztion object :param personalizations: Add a Personalization object :type personalizations: Personalization :param index: The index where to add the Personalization :type index: int """ sel...
Add a Personaliztion object :param personalizations: Add a Personalization object :type personalizations: Personalization :param index: The index where to add the Personalization :type index: int
Below is the the instruction that describes the task: ### Input: Add a Personaliztion object :param personalizations: Add a Personalization object :type personalizations: Personalization :param index: The index where to add the Personalization :type index: int ### Response: def add...
def normalizeURL(url): """Normalize a URL, converting normalization failures to DiscoveryFailure""" try: normalized = urinorm.urinorm(url) except ValueError as why: raise DiscoveryFailure('Normalizing identifier: %s' % (why, ), None) else: return urllib.parse.urldefrag(normal...
Normalize a URL, converting normalization failures to DiscoveryFailure
Below is the the instruction that describes the task: ### Input: Normalize a URL, converting normalization failures to DiscoveryFailure ### Response: def normalizeURL(url): """Normalize a URL, converting normalization failures to DiscoveryFailure""" try: normalized = urinorm.urinorm(url) ...
def symmetric_difference(self, other): """Constructs an unminimized DFA recognizing the symmetric difference of the languages of two given DFAs. Args: other (DFA): The other DFA that will be used for the symmetric difference operation Returns: ...
Constructs an unminimized DFA recognizing the symmetric difference of the languages of two given DFAs. Args: other (DFA): The other DFA that will be used for the symmetric difference operation Returns: DFA: The resulting DFA
Below is the the instruction that describes the task: ### Input: Constructs an unminimized DFA recognizing the symmetric difference of the languages of two given DFAs. Args: other (DFA): The other DFA that will be used for the symmetric difference operation ...
def get_create_batch_env_fun(batch_env_fn, time_limit): """Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing envi...
Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializing environment.
Below is the the instruction that describes the task: ### Input: Factory for dopamine environment initialization function. Args: batch_env_fn: function(in_graph: bool) -> batch environment. time_limit: time steps limit for environment. Returns: function (with optional, unused parameters) initializ...
def remove_event_subscriber(self, name, ws): """ Remove a websocket subscriber from an event. name -- name of the event ws -- the websocket """ if name in self.available_events and \ ws in self.available_events[name]['subscribers']: self.avail...
Remove a websocket subscriber from an event. name -- name of the event ws -- the websocket
Below is the the instruction that describes the task: ### Input: Remove a websocket subscriber from an event. name -- name of the event ws -- the websocket ### Response: def remove_event_subscriber(self, name, ws): """ Remove a websocket subscriber from an event. name -- n...
def chunks(self, size=32, alignment=1): """Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data. """ if (size % alignment) !...
Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data.
Below is the the instruction that describes the task: ### Input: Iterate over all segments and return chunks of the data aligned as given by `alignment`. `size` must be a multiple of `alignment`. Each chunk is returned as a named two-tuple of its address and data. ### Response: def chunks(s...
def setRecords(self, records): """ Manually sets the list of records that will be displayed in this tree. This is a shortcut method to creating a RecordSet with a list of records and assigning it to the tree. :param records | [<orb.Table>, ..] ...
Manually sets the list of records that will be displayed in this tree. This is a shortcut method to creating a RecordSet with a list of records and assigning it to the tree. :param records | [<orb.Table>, ..]
Below is the the instruction that describes the task: ### Input: Manually sets the list of records that will be displayed in this tree. This is a shortcut method to creating a RecordSet with a list of records and assigning it to the tree. :param records | [<orb.Ta...
def restoreXml(self, xml): """ Saves the logging settings for this widget to XML format. :param xml | <xml.etree.ElementTree.Element> """ self.uiFilterTXT.setText(xml.get('filter', '')) xlevels = xml.find('levels') xloggerlevels = x...
Saves the logging settings for this widget to XML format. :param xml | <xml.etree.ElementTree.Element>
Below is the the instruction that describes the task: ### Input: Saves the logging settings for this widget to XML format. :param xml | <xml.etree.ElementTree.Element> ### Response: def restoreXml(self, xml): """ Saves the logging settings for this widget to XML format. ...
def scan(host, port=80, url=None, https=False, timeout=1, max_size=65535): """ Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the hos...
Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the host and port specified https : bool, optional Perform ssl connection on the ...
Below is the the instruction that describes the task: ### Input: Scan a network port Parameters ---------- host : str Host or ip address to scan port : int, optional Port to scan, default=80 url : str, optional URL to perform get request to on the host and port specifi...
def psf_class(self): """ creates instance of PSF() class based on knowledge of the observations For the full possibility of how to create such an instance, see the PSF() class documentation :return: instance of PSF() class """ if self._psf_type == 'GAUSSIAN': ...
creates instance of PSF() class based on knowledge of the observations For the full possibility of how to create such an instance, see the PSF() class documentation :return: instance of PSF() class
Below is the the instruction that describes the task: ### Input: creates instance of PSF() class based on knowledge of the observations For the full possibility of how to create such an instance, see the PSF() class documentation :return: instance of PSF() class ### Response: def psf_class(self): ...
def expect(self, expect, searchwindowsize=None, maxread=None, timeout=None, iteration_n=1): """Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) t...
Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run)
Below is the the instruction that describes the task: ### Input: Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run) ### ...
def play_Bar(self, bar): """Convert a Bar object to MIDI events and write them to the track_data.""" self.set_deltatime(self.delay) self.delay = 0 self.set_meter(bar.meter) self.set_deltatime(0) self.set_key(bar.key) for x in bar: tick = int(ro...
Convert a Bar object to MIDI events and write them to the track_data.
Below is the the instruction that describes the task: ### Input: Convert a Bar object to MIDI events and write them to the track_data. ### Response: def play_Bar(self, bar): """Convert a Bar object to MIDI events and write them to the track_data.""" self.set_deltatime(self.delay) ...
def success(item): '''Successful finish''' try: # mv to done trg_queue = item.queue os.rename(fsq_path.item(trg_queue, item.id, host=item.host), os.path.join(fsq_path.done(trg_queue, host=item.host), item.id)) except AttributeError, e:...
Successful finish
Below is the the instruction that describes the task: ### Input: Successful finish ### Response: def success(item): '''Successful finish''' try: # mv to done trg_queue = item.queue os.rename(fsq_path.item(trg_queue, item.id, host=item.host), os.path.join(fsq_path.d...
def get_export_configuration(self, config_id): """ Retrieve the ExportConfiguration with the given ID :param string config_id: ID for which to search :return: a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found. """ sql = ...
Retrieve the ExportConfiguration with the given ID :param string config_id: ID for which to search :return: a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found.
Below is the the instruction that describes the task: ### Input: Retrieve the ExportConfiguration with the given ID :param string config_id: ID for which to search :return: a :class:`meteorpi_model.ExportConfiguration` or None, or no match was found. ### Response: def get_e...
def start(self): """ Launch the process and start processing the DAG. """ self._process = DagFileProcessor._launch_process( self._result_queue, self.file_path, self._pickle_dags, self._dag_id_white_list, "DagFileProcessor{}".for...
Launch the process and start processing the DAG.
Below is the the instruction that describes the task: ### Input: Launch the process and start processing the DAG. ### Response: def start(self): """ Launch the process and start processing the DAG. """ self._process = DagFileProcessor._launch_process( self._result_queue,...
def load_sst(path=None, url='http://nlp.stanford.edu/sentiment/trainDevTestTrees_PTB.zip'): """ Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ----...
Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ---------- path : str, (optional defaults to ~/stanford_sentiment_treebank), directory where the corp...
Below is the the instruction that describes the task: ### Input: Download and read in the Stanford Sentiment Treebank dataset into a dictionary with a 'train', 'dev', and 'test' keys. The dictionary keys point to lists of LabeledTrees. Arguments: ---------- path : str, (optional defaults to...
def _render_short_instance(self, instance): """ For those very short versions of resources, we have this. :param instance: The instance to render """ check_permission(instance, None, Permissions.VIEW) return {'type': instance.__jsonapi_type__, 'id': instance.id}
For those very short versions of resources, we have this. :param instance: The instance to render
Below is the the instruction that describes the task: ### Input: For those very short versions of resources, we have this. :param instance: The instance to render ### Response: def _render_short_instance(self, instance): """ For those very short versions of resources, we have this. ...
def from_config(config): """Return a Recruiter instance based on the configuration. Default is HotAirRecruiter in debug mode (unless we're using the bot recruiter, which can be used in debug mode) and the MTurkRecruiter in other modes. """ debug_mode = config.get("mode") == "debug" name = c...
Return a Recruiter instance based on the configuration. Default is HotAirRecruiter in debug mode (unless we're using the bot recruiter, which can be used in debug mode) and the MTurkRecruiter in other modes.
Below is the the instruction that describes the task: ### Input: Return a Recruiter instance based on the configuration. Default is HotAirRecruiter in debug mode (unless we're using the bot recruiter, which can be used in debug mode) and the MTurkRecruiter in other modes. ### Response: def from_config...
def _probe_positions(probe, group): """Return the positions of a probe channel group.""" positions = probe['channel_groups'][group]['geometry'] channels = _probe_channels(probe, group) return np.array([positions[channel] for channel in channels])
Return the positions of a probe channel group.
Below is the the instruction that describes the task: ### Input: Return the positions of a probe channel group. ### Response: def _probe_positions(probe, group): """Return the positions of a probe channel group.""" positions = probe['channel_groups'][group]['geometry'] channels = _probe_channels(probe,...
def charge( self, amount, currency=None, application_fee=None, capture=None, description=None, destination=None, metadata=None, shipping=None, source=None, statement_descriptor=None, idempotency_key=None, ): """ Creates a charge for this customer. Parameters not implemented: * **recei...
Creates a charge for this customer. Parameters not implemented: * **receipt_email** - Since this is a charge on a customer, the customer's email address is used. :param amount: The amount to charge. :type amount: Decimal. Precision is 2; anything more will be ignored. :param currency: 3-letter ISO code fo...
Below is the the instruction that describes the task: ### Input: Creates a charge for this customer. Parameters not implemented: * **receipt_email** - Since this is a charge on a customer, the customer's email address is used. :param amount: The amount to charge. :type amount: Decimal. Precision is 2; a...
def attr(self, *args): '''Add the specific attribute to the attribute dictionary with key ``name`` and value ``value`` and return ``self``.''' attr = self._attr if not args: return attr or {} result, adding = self._attrdata('attr', *args) if adding: ...
Add the specific attribute to the attribute dictionary with key ``name`` and value ``value`` and return ``self``.
Below is the the instruction that describes the task: ### Input: Add the specific attribute to the attribute dictionary with key ``name`` and value ``value`` and return ``self``. ### Response: def attr(self, *args): '''Add the specific attribute to the attribute dictionary with key ``name``...
def has_param(self, param): """ .. todo:: has_param docstring """ # Imports from ..error import RepoError # Try to get the param; pass along all errors, except 'data' error # from RepoError retval = True try: self.get_param(param) ex...
.. todo:: has_param docstring
Below is the the instruction that describes the task: ### Input: .. todo:: has_param docstring ### Response: def has_param(self, param): """ .. todo:: has_param docstring """ # Imports from ..error import RepoError # Try to get the param; pass along all errors, except 'dat...
def process_data(self, new_data): """ handles incoming data from the `IrcProtocol` connection. Main data processing/routing is handled by the _process_line method, inherited from `ServerConnection` """ self.buffer.feed(new_data) # process each non-empty line afte...
handles incoming data from the `IrcProtocol` connection. Main data processing/routing is handled by the _process_line method, inherited from `ServerConnection`
Below is the the instruction that describes the task: ### Input: handles incoming data from the `IrcProtocol` connection. Main data processing/routing is handled by the _process_line method, inherited from `ServerConnection` ### Response: def process_data(self, new_data): """ handle...
def _compare_blocks(block_a, block_b): """Compare two blocks of characters Compares two blocks of characters of the form returned by either the :any:`_pop_digits` or :any:`_pop_letters` function. Blocks should be character lists containing only digits or only letters. Both blocks should contain the...
Compare two blocks of characters Compares two blocks of characters of the form returned by either the :any:`_pop_digits` or :any:`_pop_letters` function. Blocks should be character lists containing only digits or only letters. Both blocks should contain the same character type (digits or letters). ...
Below is the the instruction that describes the task: ### Input: Compare two blocks of characters Compares two blocks of characters of the form returned by either the :any:`_pop_digits` or :any:`_pop_letters` function. Blocks should be character lists containing only digits or only letters. Both bl...
def convert_coords(self): """ Process list of coordinates This mainly searches for tuple of coordinates in the coordinate list and creates a SkyCoord or PixCoord object from them if appropriate for a given region type. This involves again some coordinate transformation, ...
Process list of coordinates This mainly searches for tuple of coordinates in the coordinate list and creates a SkyCoord or PixCoord object from them if appropriate for a given region type. This involves again some coordinate transformation, so this step could be moved to the parsing pro...
Below is the the instruction that describes the task: ### Input: Process list of coordinates This mainly searches for tuple of coordinates in the coordinate list and creates a SkyCoord or PixCoord object from them if appropriate for a given region type. This involves again some coordinate t...
def release(self): """ Release the database connection and cursor The receiver of the Connection instance MUST call this method in order to reclaim resources """ self._logger.debug("Releasing: %r", self) # Discard self from set of outstanding instances if self._addedToInstanceSet: t...
Release the database connection and cursor The receiver of the Connection instance MUST call this method in order to reclaim resources
Below is the the instruction that describes the task: ### Input: Release the database connection and cursor The receiver of the Connection instance MUST call this method in order to reclaim resources ### Response: def release(self): """ Release the database connection and cursor The receiver of t...
def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] """ Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None """ if value: if isinstance(value, str): return [...
Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None
Below is the the instruction that describes the task: ### Input: Converts a string or list of string into a list of strings :param value: A string or a list of strings :return: A list of strings or None ### Response: def get_string_plus_property_value(value): # type: (Any) -> Optional[List[str]] "...
def api_routes(self, callsign: str) -> Tuple[Airport, ...]: """Returns the route associated to a callsign.""" from .. import airports c = requests.get( f"https://opensky-network.org/api/routes?callsign={callsign}" ) if c.status_code == 404: raise ValueErr...
Returns the route associated to a callsign.
Below is the the instruction that describes the task: ### Input: Returns the route associated to a callsign. ### Response: def api_routes(self, callsign: str) -> Tuple[Airport, ...]: """Returns the route associated to a callsign.""" from .. import airports c = requests.get( f"h...
def execute(*args, **kwargs): """Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution """ # Inspect the call stack for the originating call args = CoyoteDb.__add_query_comment(args[0]) db =...
Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution
Below is the the instruction that describes the task: ### Input: Executes the sql statement, but does not commit. Returns the cursor to commit @return: DB and cursor instance following sql execution ### Response: def execute(*args, **kwargs): """Executes the sql statement, but does not commit. Ret...
def run(self): """Runs a single experiment task""" self.__logger.debug("run(): Starting task <%s>", self.__task['taskLabel']) # Set up the task # Create our main loop-control iterator if self.__cmdOptions.privateOptions['testMode']: numIters = 10 else: numIters = self.__task['itera...
Runs a single experiment task
Below is the the instruction that describes the task: ### Input: Runs a single experiment task ### Response: def run(self): """Runs a single experiment task""" self.__logger.debug("run(): Starting task <%s>", self.__task['taskLabel']) # Set up the task # Create our main loop-control iterator ...
def parameter_count(funcsig): """Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters """ return sum( p...
Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters
Below is the the instruction that describes the task: ### Input: Get the number of positional-or-keyword or position-only parameters in a function signature. Parameters ---------- funcsig : inspect.Signature A UDF signature Returns ------- int The number of parameters #...
def get_full_lonlats(self): """Get the interpolated lons/lats. """ if self.lons is not None and self.lats is not None: return self.lons, self.lats self.lons, self.lats = self._get_full_lonlats() self.lons = da.from_delayed(self.lons, dtype=self["EARTH_LOCATIONS"].dty...
Get the interpolated lons/lats.
Below is the the instruction that describes the task: ### Input: Get the interpolated lons/lats. ### Response: def get_full_lonlats(self): """Get the interpolated lons/lats. """ if self.lons is not None and self.lats is not None: return self.lons, self.lats self.lons, s...
def encode(self): """Encode this record into binary, suitable for embedded into an update script. This function will create multiple records that correspond to the actual underlying rpcs that SetConfigRecord turns into. Returns: bytearary: The binary version of the record t...
Encode this record into binary, suitable for embedded into an update script. This function will create multiple records that correspond to the actual underlying rpcs that SetConfigRecord turns into. Returns: bytearary: The binary version of the record that could be parsed via ...
Below is the the instruction that describes the task: ### Input: Encode this record into binary, suitable for embedded into an update script. This function will create multiple records that correspond to the actual underlying rpcs that SetConfigRecord turns into. Returns: bytea...
def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False return True
True if all filters are matching.
Below is the the instruction that describes the task: ### Input: True if all filters are matching. ### Response: def matches(self, client, event_data): """True if all filters are matching.""" for f in self.filters: if not f(client, event_data): return False ret...
def aside_for(cls, view_name): """ A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... ...
A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ... return Fragment(...)
Below is the the instruction that describes the task: ### Input: A decorator to indicate a function is the aside view for the given view_name. Aside views should have a signature like: @XBlockAside.aside_for('student_view') def student_aside(self, block, context=None): ...
def reset_point_source_cache(self, bool=True): """ deletes all the cache in the point source class and saves it from then on :return: """ for imageModel in self._imageModel_list: imageModel.reset_point_source_cache(bool=bool)
deletes all the cache in the point source class and saves it from then on :return:
Below is the the instruction that describes the task: ### Input: deletes all the cache in the point source class and saves it from then on :return: ### Response: def reset_point_source_cache(self, bool=True): """ deletes all the cache in the point source class and saves it from then on ...
def initializerepo(self): """ Fill empty directory with products and make first commit """ try: os.mkdir(self.repopath) except OSError: pass cmd = self.repo.init(bare=self.bare, shared=self.shared) if not self.bare: self.write_testing_data([...
Fill empty directory with products and make first commit
Below is the the instruction that describes the task: ### Input: Fill empty directory with products and make first commit ### Response: def initializerepo(self): """ Fill empty directory with products and make first commit """ try: os.mkdir(self.repopath) except OSError: ...
def getsource(obj,is_binary=False): """Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to co...
Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether the object is known to come from a binary source. This implement...
Below is the the instruction that describes the task: ### Input: Wrapper around inspect.getsource. This can be modified by other projects to provide customized source extraction. Inputs: - obj: an object whose source code we will attempt to extract. Optional inputs: - is_binary: whether...
def client_path_to_os_path(self, client_path): """ Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'. """ ...
Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'.
Below is the the instruction that describes the task: ### Input: Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'. ### Response: def...