code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def default_listener(col_attr, default): """Establish a default-setting listener.""" @event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, value, dict_): if default.is_callable: # the callable of ColumnDefault always accepts a context argument...
Establish a default-setting listener.
Below is the the instruction that describes the task: ### Input: Establish a default-setting listener. ### Response: def default_listener(col_attr, default): """Establish a default-setting listener.""" @event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, val...
def movies_opening(self, **kwargs): """Gets the current opening movies from the API. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of t...
Gets the current opening movies from the API. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dict respresentation of the JSON returned from the API.
Below is the the instruction that describes the task: ### Input: Gets the current opening movies from the API. Args: limit (optional): limits the number of movies returned, default=10 country (optional): localized data for selected country, default="us" Returns: A dic...
def safe_dir(obj, predicate = None): ''' "Safely" obtain a list of attributes for an # object. Python's dynamic properties are incredibly useful but there's a serious lack of good introspection tools. Python provides an inspect module which does introspection, but at its heart it re...
"Safely" obtain a list of attributes for an # object. Python's dynamic properties are incredibly useful but there's a serious lack of good introspection tools. Python provides an inspect module which does introspection, but at its heart it relies on dir() and getattr(), both of which can...
Below is the the instruction that describes the task: ### Input: "Safely" obtain a list of attributes for an # object. Python's dynamic properties are incredibly useful but there's a serious lack of good introspection tools. Python provides an inspect module which does introspection, but ...
def remove(self, value): """ Remove element *value* from the set. Raises :exc:`KeyError` if it is not contained in the set. """ # Raise TypeError if value is not hashable hash(value) result = self.redis.srem(self.key, self._pickle(value)) if not result: ...
Remove element *value* from the set. Raises :exc:`KeyError` if it is not contained in the set.
Below is the the instruction that describes the task: ### Input: Remove element *value* from the set. Raises :exc:`KeyError` if it is not contained in the set. ### Response: def remove(self, value): """ Remove element *value* from the set. Raises :exc:`KeyError` if it is not contain...
def cbday_roll(self): """ Define default roll function to be called in apply method. """ cbday = CustomBusinessDay(n=self.n, normalize=False, **self.kwds) if self._prefix.endswith('S'): # MonthBegin roll_func = cbday.rollforward else: ...
Define default roll function to be called in apply method.
Below is the the instruction that describes the task: ### Input: Define default roll function to be called in apply method. ### Response: def cbday_roll(self): """ Define default roll function to be called in apply method. """ cbday = CustomBusinessDay(n=self.n, normalize=False, **s...
def coerce_to_pendulum_date(x: PotentialDatetimeType, assume_local: bool = False) -> Optional[Date]: """ Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``Fals...
Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Date`, or ``None``. Raises: pendulum.parsing.exceptions.Par...
Below is the the instruction that describes the task: ### Input: Converts something to a :class:`pendulum.Date`. Args: x: something that may be coercible to a date assume_local: if ``True``, assume local timezone; if ``False``, assume UTC Returns: a :class:`pendulum.Dat...
def is_subtype_of(self, type_name, context=None): """Whether this class is a subtype of the given type. :param type_name: The name of the type of check against. :type type_name: str :returns: True if this class is a subtype of the given type, False otherwise. :rtype...
Whether this class is a subtype of the given type. :param type_name: The name of the type of check against. :type type_name: str :returns: True if this class is a subtype of the given type, False otherwise. :rtype: bool
Below is the the instruction that describes the task: ### Input: Whether this class is a subtype of the given type. :param type_name: The name of the type of check against. :type type_name: str :returns: True if this class is a subtype of the given type, False otherwise. ...
def command_exists(command, noop_invocation, exc_msg): """ Verify that the provided command exists. Raise CommandDoesNotExistException in case of an error or if the command does not exist. :param command: str, command to check (python 3 only) :param noop_invocation: list of str, command to check (p...
Verify that the provided command exists. Raise CommandDoesNotExistException in case of an error or if the command does not exist. :param command: str, command to check (python 3 only) :param noop_invocation: list of str, command to check (python 2 only) :param exc_msg: str, message of exception when co...
Below is the the instruction that describes the task: ### Input: Verify that the provided command exists. Raise CommandDoesNotExistException in case of an error or if the command does not exist. :param command: str, command to check (python 3 only) :param noop_invocation: list of str, command to check ...
def refresh_db(force=False, **kwargs): ''' Use pkg update to get latest pkg_summary force Pass -f so that the cache is always refreshed. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ''' # Remove rtag file to keep multiple ...
Use pkg update to get latest pkg_summary force Pass -f so that the cache is always refreshed. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db
Below is the the instruction that describes the task: ### Input: Use pkg update to get latest pkg_summary force Pass -f so that the cache is always refreshed. .. versionadded:: 2018.3.0 CLI Example: .. code-block:: bash salt '*' pkg.refresh_db ### Response: def refresh_db(...
def get_changes(self, dest_attr, new_name=None, resources=None, task_handle=taskhandle.NullTaskHandle()): """Return the changes needed for this refactoring Parameters: - `dest_attr`: the name of the destination attribute - `new_name`: the name of the new method; if ...
Return the changes needed for this refactoring Parameters: - `dest_attr`: the name of the destination attribute - `new_name`: the name of the new method; if `None` uses the old name - `resources` can be a list of `rope.base.resources.File`\s to apply this refactorin...
Below is the the instruction that describes the task: ### Input: Return the changes needed for this refactoring Parameters: - `dest_attr`: the name of the destination attribute - `new_name`: the name of the new method; if `None` uses the old name - `resources` can be a li...
def set_broad_fig_style(self): '''4 times width, 1.5 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*4, self.frontierswidth/self.inchpercm*1.5], })
4 times width, 1.5 times height
Below is the the instruction that describes the task: ### Input: 4 times width, 1.5 times height ### Response: def set_broad_fig_style(self): '''4 times width, 1.5 times height''' plt.rcParams.update({ 'figure.figsize' : [self.frontierswidth/self.inchpercm*4, self.frontierswidth/self.in...
def html_table_color(row, item, color=(0, 0, 0)): """ Return background color of each cell of table. :param row: row dictionary :type row : dict :param item: cell number :type item : int :param color : input color :type color : tuple :return: background color as list [R,G,B] """...
Return background color of each cell of table. :param row: row dictionary :type row : dict :param item: cell number :type item : int :param color : input color :type color : tuple :return: background color as list [R,G,B]
Below is the the instruction that describes the task: ### Input: Return background color of each cell of table. :param row: row dictionary :type row : dict :param item: cell number :type item : int :param color : input color :type color : tuple :return: background color as list [R,G,B] ...
def _divide_bundles(bundles): """Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata.""" divided = [] for bund in bundles: for t in bund['times']: new_bund = bund.copy() new_bund['times'] = [t] divided.append(new_bun...
Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata.
Below is the the instruction that describes the task: ### Input: Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata. ### Response: def _divide_bundles(bundles): """Take each subsegment inside a bundle and put it in its own bundle, copying the bundle metadata....
def register_upload_callback(self, *args, **kwargs): """Registers an Upload function (see :ref:`upload-plugin`) to handle a certain form. Refer to :func:`sijax.plugin.upload.register_upload_callback` for more details. This method passes some additional arguments to your handler...
Registers an Upload function (see :ref:`upload-plugin`) to handle a certain form. Refer to :func:`sijax.plugin.upload.register_upload_callback` for more details. This method passes some additional arguments to your handler functions - the ``flask.request.files`` object. ...
Below is the the instruction that describes the task: ### Input: Registers an Upload function (see :ref:`upload-plugin`) to handle a certain form. Refer to :func:`sijax.plugin.upload.register_upload_callback` for more details. This method passes some additional arguments to your ha...
def _updateType(self): """Make sure that the class behaves like the data structure that it is, so that we don't get a ListFile trying to represent a dict.""" data = self._data() # Change type if needed if isinstance(data, dict) and isinstance(self, ListFile): self.__c...
Make sure that the class behaves like the data structure that it is, so that we don't get a ListFile trying to represent a dict.
Below is the the instruction that describes the task: ### Input: Make sure that the class behaves like the data structure that it is, so that we don't get a ListFile trying to represent a dict. ### Response: def _updateType(self): """Make sure that the class behaves like the data structure that it ...
def compute_hr(sig_len, qrs_inds, fs): """ Compute instantaneous heart rate from peak indices. Parameters ---------- sig_len : int The length of the corresponding signal qrs_inds : numpy array The qrs index locations fs : int, or float The corresponding signal's samp...
Compute instantaneous heart rate from peak indices. Parameters ---------- sig_len : int The length of the corresponding signal qrs_inds : numpy array The qrs index locations fs : int, or float The corresponding signal's sampling frequency. Returns ------- heart_...
Below is the the instruction that describes the task: ### Input: Compute instantaneous heart rate from peak indices. Parameters ---------- sig_len : int The length of the corresponding signal qrs_inds : numpy array The qrs index locations fs : int, or float The correspon...
def get1(self, name, **kwargs): """ Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. """ if 'retheader' in kwargs: raise GenderizeException( "get1() doesn't support the retheader option.") return s...
Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option.
Below is the the instruction that describes the task: ### Input: Look up gender for a single name. See :py:meth:`get`. Doesn't support retheader option. ### Response: def get1(self, name, **kwargs): """ Look up gender for a single name. See :py:meth:`get`. Doesn't su...
def add_transitions_to_closest_sibling_state_from_selected_state(): """ Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return: """ task_string = "create transition" sub_task_string = "to closest sibling state" selected_state_m, msg = get_sele...
Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return:
Below is the the instruction that describes the task: ### Input: Generates the outcome transitions from outcomes with positive outcome_id to the closest next state :return: ### Response: def add_transitions_to_closest_sibling_state_from_selected_state(): """ Generates the outcome transitions from outcomes...
def create(cls, name, negotiation_expiration=200000, negotiation_retry_timer=500, negotiation_retry_max_number=32, negotiation_retry_timer_max=7000, certificate_cache_crl_validity=90000, mobike_after_sa_update=False, mobike_before...
Create a new gateway setting profile. :param str name: name of profile :param int negotiation_expiration: expire after (ms) :param int negotiation_retry_timer: retry time length (ms) :param int negotiation_retry_max_num: max number of retries allowed :param int negotiation_retry...
Below is the the instruction that describes the task: ### Input: Create a new gateway setting profile. :param str name: name of profile :param int negotiation_expiration: expire after (ms) :param int negotiation_retry_timer: retry time length (ms) :param int negotiation_retry_max_nu...
def update_offset(self, new_offset): """Updates how many data points to skip in caculations. Always use this function to update offset instead of directly setting self.offset. Args: new_offset: The new offset. """ self.offset = new_offset self.data_p...
Updates how many data points to skip in caculations. Always use this function to update offset instead of directly setting self.offset. Args: new_offset: The new offset.
Below is the the instruction that describes the task: ### Input: Updates how many data points to skip in caculations. Always use this function to update offset instead of directly setting self.offset. Args: new_offset: The new offset. ### Response: def update_offset(self, new_...
def update(self, tag_id, name): """ 编辑标签 :param tag_id: 标签id,由微信分配 :param name: 标签名字(30个字符以内) :return: 返回的 JSON 数据包 """ name = to_text(name) return self._post( 'tags/update', data={ 'tag': { 'id...
编辑标签 :param tag_id: 标签id,由微信分配 :param name: 标签名字(30个字符以内) :return: 返回的 JSON 数据包
Below is the the instruction that describes the task: ### Input: 编辑标签 :param tag_id: 标签id,由微信分配 :param name: 标签名字(30个字符以内) :return: 返回的 JSON 数据包 ### Response: def update(self, tag_id, name): """ 编辑标签 :param tag_id: 标签id,由微信分配 :param name: 标签名字(30个字符以内) ...
def srepr(expr, indented=False, cache=None): """Render the given expression into a string that can be evaluated in an appropriate context to re-instantiate an identical expression. If `indented` is False (default), the resulting string is a single line. Otherwise, the result is a multiline string, and e...
Render the given expression into a string that can be evaluated in an appropriate context to re-instantiate an identical expression. If `indented` is False (default), the resulting string is a single line. Otherwise, the result is a multiline string, and each positional and keyword argument of each `Exp...
Below is the the instruction that describes the task: ### Input: Render the given expression into a string that can be evaluated in an appropriate context to re-instantiate an identical expression. If `indented` is False (default), the resulting string is a single line. Otherwise, the result is a multil...
def setup(self, **kwargs): """ Setting up Grab instance configuration. """ for key in kwargs: if key not in self.config.keys(): raise error.GrabMisuseError('Unknown option: %s' % key) if 'url' in kwargs: if self.config.get('url'): ...
Setting up Grab instance configuration.
Below is the the instruction that describes the task: ### Input: Setting up Grab instance configuration. ### Response: def setup(self, **kwargs): """ Setting up Grab instance configuration. """ for key in kwargs: if key not in self.config.keys(): raise e...
def performance_diagram(roc_objs, obj_labels, colors, markers, filename, figsize=(8, 8), xlabel="Success Ratio (1-FAR)", ylabel="Probability of Detection", ticks=np.arange(0, 1.1, 0.1), dpi=300, csi_cmap="Blues", csi_label="...
Draws a performance diagram from a set of DistributedROC objects. A performance diagram is a variation on the ROC curve in which the Probability of False Detection on the x-axis has been replaced with the Success Ratio (1-False Alarm Ratio or Precision). The diagram also shows the Critical Success Index (C...
Below is the the instruction that describes the task: ### Input: Draws a performance diagram from a set of DistributedROC objects. A performance diagram is a variation on the ROC curve in which the Probability of False Detection on the x-axis has been replaced with the Success Ratio (1-False Alarm Ratio or...
def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x): """ Goes through each root possible branch making it the root. Returns tree that requires the minimum number of duplications. """ #get all rooted trees #run dup calc on each tree #return tree with fewest num...
Goes through each root possible branch making it the root. Returns tree that requires the minimum number of duplications.
Below is the the instruction that describes the task: ### Input: Goes through each root possible branch making it the root. Returns tree that requires the minimum number of duplications. ### Response: def calculateProbableRootOfGeneTree(speciesTree, geneTree, processID=lambda x : x): """ Goes through ...
def start( self, phone=lambda: input('Please enter your phone (or bot token): '), password=lambda: getpass.getpass('Please enter your password: '), *, bot_token=None, force_sms=False, code_callback=None, first_name='New User', last_name='', max_att...
Convenience method to interactively connect and sign in if required, also taking into consideration that 2FA may be enabled in the account. If the phone doesn't belong to an existing account (and will hence `sign_up` for a new one), **you are agreeing to Telegram's Terms of Service. Th...
Below is the the instruction that describes the task: ### Input: Convenience method to interactively connect and sign in if required, also taking into consideration that 2FA may be enabled in the account. If the phone doesn't belong to an existing account (and will hence `sign_up` for a new...
def render_homepage(config, env): """Render the homepage.jinja template.""" template = env.get_template('homepage.jinja') rendered_page = template.render( config=config) return rendered_page
Render the homepage.jinja template.
Below is the the instruction that describes the task: ### Input: Render the homepage.jinja template. ### Response: def render_homepage(config, env): """Render the homepage.jinja template.""" template = env.get_template('homepage.jinja') rendered_page = template.render( config=config) return...
def dynamic_part_name(raml_resource, route_name, pk_field): """ Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' ...
Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id' is used as the 2nd part. E.g. if your dynamic part on route ...
Below is the the instruction that describes the task: ### Input: Generate a dynamic part for a resource :raml_resource:. A dynamic part is generated using 2 parts: :route_name: of the resource and the dynamic part of first dynamic child resources. If :raml_resource: has no dynamic child resources, 'id'...
def correct(tokens, term_freq): """ Correct a list of tokens, according to the term_freq """ log = [] output = [] for token in tokens: corrected = _correct(token, term_freq) if corrected != token: log.append((token, corrected)) output.append(corrected) ret...
Correct a list of tokens, according to the term_freq
Below is the the instruction that describes the task: ### Input: Correct a list of tokens, according to the term_freq ### Response: def correct(tokens, term_freq): """ Correct a list of tokens, according to the term_freq """ log = [] output = [] for token in tokens: corrected = _cor...
def create_equipamento_roteiro(self): """Get an instance of equipamento_roteiro services facade.""" return EquipamentoRoteiro( self.networkapi_url, self.user, self.password, self.user_ldap)
Get an instance of equipamento_roteiro services facade.
Below is the the instruction that describes the task: ### Input: Get an instance of equipamento_roteiro services facade. ### Response: def create_equipamento_roteiro(self): """Get an instance of equipamento_roteiro services facade.""" return EquipamentoRoteiro( self.networkapi_url, ...
def _serialize(self, include_run_logs=False, strict_json=False): """ Serialize a representation of this Job to a Python dict object. """ # return tasks in sorted order if graph is in a valid state try: topo_sorted = self.topological_sort() t = [self.tasks[task]._serializ...
Serialize a representation of this Job to a Python dict object.
Below is the the instruction that describes the task: ### Input: Serialize a representation of this Job to a Python dict object. ### Response: def _serialize(self, include_run_logs=False, strict_json=False): """ Serialize a representation of this Job to a Python dict object. """ # return tasks in ...
def __setWildcardSymbol(self, value): """self.__wildcardSymbol variable setter""" errors = [] if not value is str and not value.split(): errors.append('wildcardSymbol_ERROR : Symbol : must be char or string!') else: self.__wildcardSymbol = value if errors: view.Tli.showErrors('SymbolError', errors)
self.__wildcardSymbol variable setter
Below is the the instruction that describes the task: ### Input: self.__wildcardSymbol variable setter ### Response: def __setWildcardSymbol(self, value): """self.__wildcardSymbol variable setter""" errors = [] if not value is str and not value.split(): errors.append('wildcardSymbol_ERROR : Symbol : must...
def clone(self, opts): ''' Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance. ''' topt = self.opts.copy() topt.update(opts) return self.__class__(self.modl, self.name, self...
Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance.
Below is the the instruction that describes the task: ### Input: Create a new instance of this type with the specified options. Args: opts (dict): The type specific options for the new instance. ### Response: def clone(self, opts): ''' Create a new instance of this type with th...
def send_to_graphite(self, metric, value, timestamp=None): """ Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: ...
Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str :param value: :type value: float :param timestamp: ...
Below is the the instruction that describes the task: ### Input: Inner store a new metric and flush to Graphite if the flush threshold is reached. If no timestamp is provided, get the current time for the metric timestam. :param metric: metric name in dotted format :type metric: str ...
def latmio_dir(R, itr, D=None, seed=None): ''' This function "latticizes" a directed network, while preserving the in- and out-degree distributions. In weighted networks, the function preserves the out-strength but not the in-strength distributions. Parameters ---------- R : NxN np.ndarray ...
This function "latticizes" a directed network, while preserving the in- and out-degree distributions. In weighted networks, the function preserves the out-strength but not the in-strength distributions. Parameters ---------- R : NxN np.ndarray directed binary/weighted connection matrix ...
Below is the the instruction that describes the task: ### Input: This function "latticizes" a directed network, while preserving the in- and out-degree distributions. In weighted networks, the function preserves the out-strength but not the in-strength distributions. Parameters ---------- R : N...
def _set_mirror(self, v, load=False): """ Setter method for mirror, mapped from YANG variable /openflow_global/openflow/mirror (container) If this variable is read-only (config: false) in the source YANG file, then _set_mirror is considered as a private method. Backends looking to populate this vari...
Setter method for mirror, mapped from YANG variable /openflow_global/openflow/mirror (container) If this variable is read-only (config: false) in the source YANG file, then _set_mirror is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mir...
Below is the the instruction that describes the task: ### Input: Setter method for mirror, mapped from YANG variable /openflow_global/openflow/mirror (container) If this variable is read-only (config: false) in the source YANG file, then _set_mirror is considered as a private method. Backends looking to...
def init_app(self, app, datastore=None, register_blueprint=None, **kwargs): """Initializes the Flask-Security extension for the specified application and datastore implementation. :param app: The application. :param datastore: An instance of a user datastore. :param register_blu...
Initializes the Flask-Security extension for the specified application and datastore implementation. :param app: The application. :param datastore: An instance of a user datastore. :param register_blueprint: to register the Security blueprint or not.
Below is the the instruction that describes the task: ### Input: Initializes the Flask-Security extension for the specified application and datastore implementation. :param app: The application. :param datastore: An instance of a user datastore. :param register_blueprint: to registe...
def parse_datetime(s: str) -> datetime.date: """Try to parse a datetime object from a standard datetime format or date format.""" for fmt in (CREATION_DATE_FMT, PUBLISHED_DATE_FMT, PUBLISHED_DATE_FMT_2): try: dt = datetime.strptime(s, fmt) except ValueError: pass ...
Try to parse a datetime object from a standard datetime format or date format.
Below is the the instruction that describes the task: ### Input: Try to parse a datetime object from a standard datetime format or date format. ### Response: def parse_datetime(s: str) -> datetime.date: """Try to parse a datetime object from a standard datetime format or date format.""" for fmt in (CREATIO...
def first_or_create(self, _attributes=None, **attributes): """ Get the first related record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model """ if _attributes is not None: attributes.updat...
Get the first related record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model
Below is the the instruction that describes the task: ### Input: Get the first related record matching the attributes or create it. :param attributes: The attributes :type attributes: dict :rtype: Model ### Response: def first_or_create(self, _attributes=None, **attributes): """ ...
def tokenize(s, locale, update=None): """ Tokenize `s` according to corresponding locale dictionary. Don't use this for serious text processing. """ zhdict = getdict(locale) pfset = pfsdict[locale] if update: zhdict = zhdict.copy() zhdict.update(update) newset = set()...
Tokenize `s` according to corresponding locale dictionary. Don't use this for serious text processing.
Below is the the instruction that describes the task: ### Input: Tokenize `s` according to corresponding locale dictionary. Don't use this for serious text processing. ### Response: def tokenize(s, locale, update=None): """ Tokenize `s` according to corresponding locale dictionary. Don't use this f...
def fulfill_lock_reward_condition(event, agreement_id, price, consumer_account): """ Fulfill the lock reward condition. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param price: Asset price, int :param consumer_account: Account instance of ...
Fulfill the lock reward condition. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param price: Asset price, int :param consumer_account: Account instance of the consumer
Below is the the instruction that describes the task: ### Input: Fulfill the lock reward condition. :param event: AttributeDict with the event data. :param agreement_id: id of the agreement, hex str :param price: Asset price, int :param consumer_account: Account instance of the consumer ### Respons...
def from_data(data): """ Construct a Prettytable from list of rows. """ if len(data) == 0: # pragma: no cover return None else: ptable = PrettyTable() ptable.field_names = data[0].keys() for row in data: ptable.add_row(row) return ptable
Construct a Prettytable from list of rows.
Below is the the instruction that describes the task: ### Input: Construct a Prettytable from list of rows. ### Response: def from_data(data): """ Construct a Prettytable from list of rows. """ if len(data) == 0: # pragma: no cover return None else: ptable = PrettyTable() ...
def abort(self, exception=exc.ConnectError): """ Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``except...
Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``exception`` parameter is used (defaults to ``ConnectError``).
Below is the the instruction that describes the task: ### Input: Aborts a connection and puts all pending futures into an error state. If ``sys.exc_info()`` is set (i.e. this is being called in an exception handler) then pending futures will have that exc info set. Otherwise the given ``ex...
def connect(self, *, db=None): """ Attempt to connect to device. If unable, attempt to connect to a controller database (so the user can use previously saved data). """ if not self.properties.network: self.new_state(DeviceFromDB) else: t...
Attempt to connect to device. If unable, attempt to connect to a controller database (so the user can use previously saved data).
Below is the the instruction that describes the task: ### Input: Attempt to connect to device. If unable, attempt to connect to a controller database (so the user can use previously saved data). ### Response: def connect(self, *, db=None): """ Attempt to connect to device. If unable,...
def constraint(self): """Constraint string""" constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: constraint_arr.append("UNIQUE") return " ".join(constraint_arr)
Constraint string
Below is the the instruction that describes the task: ### Input: Constraint string ### Response: def constraint(self): """Constraint string""" constraint_arr = [] if self._not_null: constraint_arr.append("PRIMARY KEY" if self._pk else "NOT NULL") if self._unique: ...
def overlay_gateway_monitor_direction(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:brocade.com:mgmt:brocade-tunnels") name_key = ET.SubElement(overlay_gateway, "name") name_...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def overlay_gateway_monitor_direction(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") overlay_gateway = ET.SubElement(config, "overlay-gateway", xmlns="urn:br...
def as_dict(self, default=None): """ Returns a ``SettingDict`` object for this queryset. """ settings = SettingDict(queryset=self, default=default) return settings
Returns a ``SettingDict`` object for this queryset.
Below is the the instruction that describes the task: ### Input: Returns a ``SettingDict`` object for this queryset. ### Response: def as_dict(self, default=None): """ Returns a ``SettingDict`` object for this queryset. """ settings = SettingDict(queryset=self, default=default) ...
def patches_until(self, patch): """ Returns a list of patches before patch from the patches list including the provided patch """ return [line.get_patch() for line in self._patchlines_until(patch) if line.get_patch()]
Returns a list of patches before patch from the patches list including the provided patch
Below is the the instruction that describes the task: ### Input: Returns a list of patches before patch from the patches list including the provided patch ### Response: def patches_until(self, patch): """ Returns a list of patches before patch from the patches list including the provided pa...
def _validate_props(self): """Assert that all the properties are valid on validate()""" for key, prop in iteritems(self._props): try: value = self._get(key) err_msg = 'Invalid value for property {}: {}'.format(key, value) if value is not None: ...
Assert that all the properties are valid on validate()
Below is the the instruction that describes the task: ### Input: Assert that all the properties are valid on validate() ### Response: def _validate_props(self): """Assert that all the properties are valid on validate()""" for key, prop in iteritems(self._props): try: val...
def __recognize_union(self, node: yaml.Node, expected_type: Type) -> RecResult: """Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The ...
Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The specific type that was recognized, multiple, or none.
Below is the the instruction that describes the task: ### Input: Recognize a node that we expect to be one of a union of types. Args: node: The node to recognize. expected_type: Union[...something...] Returns: The specific type that was recognized, multiple, or ...
def step(self, input_token): """Performs a step to establish the context as an acceptor. This method should be called in a loop and fed input tokens from the initiator, and its output tokens should be sent to the initiator, until this context's :attr:`established` attribute is True. ...
Performs a step to establish the context as an acceptor. This method should be called in a loop and fed input tokens from the initiator, and its output tokens should be sent to the initiator, until this context's :attr:`established` attribute is True. :param input_token: The input toke...
Below is the the instruction that describes the task: ### Input: Performs a step to establish the context as an acceptor. This method should be called in a loop and fed input tokens from the initiator, and its output tokens should be sent to the initiator, until this context's :attr:`established` ...
def setup_console(output): """Console setup.""" global console # All console related operations is handled via the ConsoleOutput class console = ConsoleOutput(output, streamlink) console.json = args.json # Handle SIGTERM just like SIGINT signal.signal(signal.SIGTERM, signal.default_int_han...
Console setup.
Below is the the instruction that describes the task: ### Input: Console setup. ### Response: def setup_console(output): """Console setup.""" global console # All console related operations is handled via the ConsoleOutput class console = ConsoleOutput(output, streamlink) console.json = args.j...
def tar_runner(self): """ Returns a tar with the runner script. """ script_bytes = self.RUNNER.read_bytes() tarstream = BytesIO() tar = tarfile.TarFile(fileobj=tarstream, mode='w') tarinfo = tarfile.TarInfo(name="runner.py") tarinfo.size = len(script_bytes) ...
Returns a tar with the runner script.
Below is the the instruction that describes the task: ### Input: Returns a tar with the runner script. ### Response: def tar_runner(self): """ Returns a tar with the runner script. """ script_bytes = self.RUNNER.read_bytes() tarstream = BytesIO() tar = tarfile.TarFile(fileo...
def operation_effects(self, op_id, cursor=None, order='asc', limit=10): """This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-...
This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html>`_ :param int op_id: The operation ID to get effects on. ...
Below is the the instruction that describes the task: ### Input: This endpoint represents all effects that occurred as a result of a given operation. `GET /operations/{id}/effects{?cursor,limit,order} <https://www.stellar.org/developers/horizon/reference/endpoints/effects-for-operation.html...
def reset(self): ''' Initialize this type for a new simulated history of K/L ratio. Parameters ---------- None Returns ------- None ''' self.initializeSim() self.aLvlNow = self.kInit*np.ones(self.AgentCount) # Start simulation nea...
Initialize this type for a new simulated history of K/L ratio. Parameters ---------- None Returns ------- None
Below is the the instruction that describes the task: ### Input: Initialize this type for a new simulated history of K/L ratio. Parameters ---------- None Returns ------- None ### Response: def reset(self): ''' Initialize this type for a new simulat...
def create_nic(self, datacenter_id, server_id, nic): """ Creates a NIC on the specified server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``s...
Creates a NIC on the specified server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic: A NIC dict. :type nic: ``dic...
Below is the the instruction that describes the task: ### Input: Creates a NIC on the specified server. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str``...
def handle(self, t_input: inference.TranslatorInput, t_output: inference.TranslatorOutput, t_walltime: float = 0.): """ :param t_input: Translator input. :param t_output: Translator output. :param t_walltime: Total wall-clock time for translat...
:param t_input: Translator input. :param t_output: Translator output. :param t_walltime: Total wall-clock time for translation.
Below is the the instruction that describes the task: ### Input: :param t_input: Translator input. :param t_output: Translator output. :param t_walltime: Total wall-clock time for translation. ### Response: def handle(self, t_input: inference.TranslatorInput, t_output:...
def _disambiguate_sid_ksid( words_layer, text, scope=CLAUSES ): ''' Disambiguates verb forms based on existence of 2nd person pronoun ('sina') in given scope. The scope could be either CLAUSES or SENTENCES. ''' assert scope in [CLAUSES, SENTENCES], '(!) The scope should be either "clauses" or "sente...
Disambiguates verb forms based on existence of 2nd person pronoun ('sina') in given scope. The scope could be either CLAUSES or SENTENCES.
Below is the the instruction that describes the task: ### Input: Disambiguates verb forms based on existence of 2nd person pronoun ('sina') in given scope. The scope could be either CLAUSES or SENTENCES. ### Response: def _disambiguate_sid_ksid( words_layer, text, scope=CLAUSES ): ''' Disambiguates ver...
def _map_center(self, coord, val): ''' Identitify the center of the Image correspond to one coordinate. ''' if self.ppd in [4, 8, 16, 32, 64]: res = {'lat': 0, 'long': 360} return res[coord] / 2.0 elif self.ppd in [128]: res = {'lat': 90, 'long': 90} ...
Identitify the center of the Image correspond to one coordinate.
Below is the the instruction that describes the task: ### Input: Identitify the center of the Image correspond to one coordinate. ### Response: def _map_center(self, coord, val): ''' Identitify the center of the Image correspond to one coordinate. ''' if self.ppd in [4, 8, 16, 32, 64]: ...
def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_version = salt.utils.systemd.version(__context__) if sd_version is not None and sd_version >= 231: # systemd 231 changed the output of "systemctl...
Returns boolean telling whether or not the named service is available
Below is the the instruction that describes the task: ### Input: Returns boolean telling whether or not the named service is available ### Response: def _check_available(name): ''' Returns boolean telling whether or not the named service is available ''' _status = _systemctl_status(name) sd_ver...
def select(self, space, key=None, **kwargs) -> _MethodRet: """ Select request coroutine. Examples: .. code-block:: pycon >>> await conn.select('tester') <Response sync=3 rowcount=2 data=[ <TarantoolTuple id=1 name='one'>,...
Select request coroutine. Examples: .. code-block:: pycon >>> await conn.select('tester') <Response sync=3 rowcount=2 data=[ <TarantoolTuple id=1 name='one'>, <TarantoolTuple id=2 name='two'> ]> ...
Below is the the instruction that describes the task: ### Input: Select request coroutine. Examples: .. code-block:: pycon >>> await conn.select('tester') <Response sync=3 rowcount=2 data=[ <TarantoolTuple id=1 name='one'>, ...
def with_variants(self, variants: Union['Variant', List['Variant']]) -> 'CentralDogma': """Create a new entity with the given variants. :param variants: An optional variant or list of variants Example Usage: >>> app = Protein(name='APP', namespace='HGNC') >>> ab42 = app.with_v...
Create a new entity with the given variants. :param variants: An optional variant or list of variants Example Usage: >>> app = Protein(name='APP', namespace='HGNC') >>> ab42 = app.with_variants([Fragment(start=672, stop=713)]) >>> assert 'p(HGNC:APP, frag(672_713))' == ab42.as...
Below is the the instruction that describes the task: ### Input: Create a new entity with the given variants. :param variants: An optional variant or list of variants Example Usage: >>> app = Protein(name='APP', namespace='HGNC') >>> ab42 = app.with_variants([Fragment(start=672, s...
def get_course_video_ids_with_youtube_profile(course_ids=None, offset=None, limit=None): """ Returns a list that contains all the course ids and video ids with the youtube profile Args: course_ids (list): valid course ids limit (int): batch records limit offset (int): an offset f...
Returns a list that contains all the course ids and video ids with the youtube profile Args: course_ids (list): valid course ids limit (int): batch records limit offset (int): an offset for selecting a batch Returns: (list): Tuples of course_id, edx_video_id and youtube vide...
Below is the the instruction that describes the task: ### Input: Returns a list that contains all the course ids and video ids with the youtube profile Args: course_ids (list): valid course ids limit (int): batch records limit offset (int): an offset for selecting a batch Returns...
def is_whitelisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or given credentials are whitelisted for access. """ if is_client_ip_address_whitelisted(request): return True if is_cl...
Checks if the request or given credentials are whitelisted for access.
Below is the the instruction that describes the task: ### Input: Checks if the request or given credentials are whitelisted for access. ### Response: def is_whitelisted(self, request: AxesHttpRequest, credentials: dict = None) -> bool: # pylint: disable=unused-argument """ Checks if the request or...
def handle_write(self): """get a PDU from the queue and send it.""" if _debug: UDPDirector._debug("handle_write") try: pdu = self.request.get() sent = self.socket.sendto(pdu.pduData, pdu.pduDestination) if _debug: UDPDirector._debug(" - sent %d octets to ...
get a PDU from the queue and send it.
Below is the the instruction that describes the task: ### Input: get a PDU from the queue and send it. ### Response: def handle_write(self): """get a PDU from the queue and send it.""" if _debug: UDPDirector._debug("handle_write") try: pdu = self.request.get() sent...
def process_trun(trun): """Goes through the trun and processes "run.log" """ trun["log_content"] = runlogs_to_html(trun["res_root"]) trun["aux_list"] = aux_listing(trun["aux_root"]) trun["hnames"] = extract_hook_names(trun) return True
Goes through the trun and processes "run.log"
Below is the the instruction that describes the task: ### Input: Goes through the trun and processes "run.log" ### Response: def process_trun(trun): """Goes through the trun and processes "run.log" """ trun["log_content"] = runlogs_to_html(trun["res_root"]) trun["aux_list"] = aux_listing(trun["aux_roo...
def save_account(self, account: Account) -> None: """ Account was saved. """ person = account.person if self._primary_group == 'institute': lgroup = self._get_group(person.institute.group.name) elif self._primary_group == 'default_project': if account.default_proj...
Account was saved.
Below is the the instruction that describes the task: ### Input: Account was saved. ### Response: def save_account(self, account: Account) -> None: """ Account was saved. """ person = account.person if self._primary_group == 'institute': lgroup = self._get_group(person.institute...
def tables(auth=None, eager=True): """Returns a list of tables for the given user.""" auth = auth or [] dynamodb = boto.connect_dynamodb(*auth) return [table(t, auth, eager=eager) for t in dynamodb.list_tables()]
Returns a list of tables for the given user.
Below is the the instruction that describes the task: ### Input: Returns a list of tables for the given user. ### Response: def tables(auth=None, eager=True): """Returns a list of tables for the given user.""" auth = auth or [] dynamodb = boto.connect_dynamodb(*auth) return [table(t, auth, eager=e...
def pickle_data(data, picklefile): """Helper function to pickle `data` in `picklefile`.""" with open(picklefile, 'wb') as f: pickle.dump(data, f, protocol=2)
Helper function to pickle `data` in `picklefile`.
Below is the the instruction that describes the task: ### Input: Helper function to pickle `data` in `picklefile`. ### Response: def pickle_data(data, picklefile): """Helper function to pickle `data` in `picklefile`.""" with open(picklefile, 'wb') as f: pickle.dump(data, f, protocol=2)
def heading(headingtext, headinglevel, lang='en'): '''Make a new heading, return the heading element''' lmap = {'en': 'Heading', 'it': 'Titolo'} # Make our elements paragraph = makeelement('p') pr = makeelement('pPr') pStyle = makeelement( 'pStyle', attributes={'val': lmap[lang]+str(head...
Make a new heading, return the heading element
Below is the the instruction that describes the task: ### Input: Make a new heading, return the heading element ### Response: def heading(headingtext, headinglevel, lang='en'): '''Make a new heading, return the heading element''' lmap = {'en': 'Heading', 'it': 'Titolo'} # Make our elements paragrap...
def get_conflicting_tools(self, request_only=False): """Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {too...
Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of {tool-name: set([Variant])}.
Below is the the instruction that describes the task: ### Input: Returns tools of the same name provided by more than one package. Args: request_only: If True, only return the key from resolved packages that were also present in the request. Returns: Dict of...
def course_key_is_valid(course_key): """ Course key object validation """ if course_key is None: return False try: CourseKey.from_string(text_type(course_key)) except (InvalidKeyError, UnicodeDecodeError): return False return True
Course key object validation
Below is the the instruction that describes the task: ### Input: Course key object validation ### Response: def course_key_is_valid(course_key): """ Course key object validation """ if course_key is None: return False try: CourseKey.from_string(text_type(course_key)) except ...
def show(context, id): """show(context, id) Show a file. >>> dcictl file-show [OPTIONS] :param string id: ID of the file to show [required] """ content = file.content(context, id=id) click.echo(content.text)
show(context, id) Show a file. >>> dcictl file-show [OPTIONS] :param string id: ID of the file to show [required]
Below is the the instruction that describes the task: ### Input: show(context, id) Show a file. >>> dcictl file-show [OPTIONS] :param string id: ID of the file to show [required] ### Response: def show(context, id): """show(context, id) Show a file. >>> dcictl file-show [OPTIONS] ...
def unpack_from(cls, payload, expected_parts): """Unpack parts from payload""" for num_part in iter_range(expected_parts): hdr = payload.read(cls.header_size) try: part_header = PartHeader(*cls.header_struct.unpack(hdr)) except struct.error: ...
Unpack parts from payload
Below is the the instruction that describes the task: ### Input: Unpack parts from payload ### Response: def unpack_from(cls, payload, expected_parts): """Unpack parts from payload""" for num_part in iter_range(expected_parts): hdr = payload.read(cls.header_size) try: ...
def _reload_version(self): """ Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not ...
Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These distributions will not be parsed properly downstream b...
Below is the the instruction that describes the task: ### Input: Packages installed by distutils (e.g. numpy or scipy), which uses an old safe_version, and so their version numbers can get mangled when converted to filenames (e.g., 1.11.0.dev0+2329eae to 1.11.0.dev0_2329eae). These d...
def get_login_redirect(self, provider, account): """Return url to redirect authenticated users.""" info = self.model._meta.app_label, self.model._meta.model_name # inline import to prevent circular imports. from .admin import PRESERVED_FILTERS_SESSION_KEY preserved_filters = self...
Return url to redirect authenticated users.
Below is the the instruction that describes the task: ### Input: Return url to redirect authenticated users. ### Response: def get_login_redirect(self, provider, account): """Return url to redirect authenticated users.""" info = self.model._meta.app_label, self.model._meta.model_name # inli...
def get_default_plot_params(plot_type=''): """ Return the default parameters used for figure generation. Parameter --------- plot_type : string-optional Defines some plot-specific parameters to use by default Returns ------- default_plot_params :...
Return the default parameters used for figure generation. Parameter --------- plot_type : string-optional Defines some plot-specific parameters to use by default Returns ------- default_plot_params : dictionary Dictionary key-value ...
Below is the the instruction that describes the task: ### Input: Return the default parameters used for figure generation. Parameter --------- plot_type : string-optional Defines some plot-specific parameters to use by default Returns ------- default_plo...
def reverse(cls, value, prop, visitor): """Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply. """ return ( None if isinstance(value, (Attribute...
Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply.
Below is the the instruction that describes the task: ### Input: Like :py:meth:`normalize.visitor.VisitorPattern.apply` but called for ``cast`` operations. The default implementation passes through but squashes exceptions, just like apply. ### Response: def reverse(cls, value, prop, visitor): ...
def validate_protected_resource_request(self, uri, http_method='GET', body=None, headers=None, realms=None): """Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A va...
Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a string. :param headers: The request headers as a dict. :pa...
Below is the the instruction that describes the task: ### Input: Create a request token response, with a new request token if valid. :param uri: The full URI of the token request. :param http_method: A valid HTTP verb, i.e. GET, POST, PUT, HEAD, etc. :param body: The request body as a strin...
def people(self): """ Retrieve all people of the company :return: list of people objects :rtype: list """ return fields.ListField(name=HightonConstants.PEOPLE, init_class=Person).decode( self.element_from_string( self._get_request( ...
Retrieve all people of the company :return: list of people objects :rtype: list
Below is the the instruction that describes the task: ### Input: Retrieve all people of the company :return: list of people objects :rtype: list ### Response: def people(self): """ Retrieve all people of the company :return: list of people objects :rtype: list ...
def truncate_to(value: Decimal, currency: str) -> Decimal: """Truncates a value to the number of decimals corresponding to the currency""" decimal_places = DECIMALS.get(currency.upper(), 2) return truncate(value, decimal_places)
Truncates a value to the number of decimals corresponding to the currency
Below is the the instruction that describes the task: ### Input: Truncates a value to the number of decimals corresponding to the currency ### Response: def truncate_to(value: Decimal, currency: str) -> Decimal: """Truncates a value to the number of decimals corresponding to the currency""" decimal_places ...
def find_column(t): """Get cursor position, based on previous newline""" pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: last_cr = -1 column = pos - last_cr return column
Get cursor position, based on previous newline
Below is the the instruction that describes the task: ### Input: Get cursor position, based on previous newline ### Response: def find_column(t): """Get cursor position, based on previous newline""" pos = t.lexer.lexpos data = t.lexer.lexdata last_cr = data.rfind('\n', 0, pos) if last_cr < 0: ...
def get_all_api_keys(self, **kwargs): # noqa: E501 """Get all API keys # noqa: E501 An endpoint for retrieving API keys in an array, optionally filtered by the owner. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/api-keys -H 'Authorization: Bearer API_KEY'` # noqa: E501 T...
Get all API keys # noqa: E501 An endpoint for retrieving API keys in an array, optionally filtered by the owner. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/api-keys -H 'Authorization: Bearer API_KEY'` # noqa: E501 This method makes a synchronous HTTP request by default. To make...
Below is the the instruction that describes the task: ### Input: Get all API keys # noqa: E501 An endpoint for retrieving API keys in an array, optionally filtered by the owner. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/api-keys -H 'Authorization: Bearer API_KEY'` # noqa: E501 ...
def _create_factor_rule(tok): """ Simple helper method for creating factor node objects based on node name. """ if tok[0] == 'IPV4': return IPV4Rule(tok[1]) if tok[0] == 'IPV6': return IPV6Rule(tok[1]) if tok[0] == 'DATETIME': return Da...
Simple helper method for creating factor node objects based on node name.
Below is the the instruction that describes the task: ### Input: Simple helper method for creating factor node objects based on node name. ### Response: def _create_factor_rule(tok): """ Simple helper method for creating factor node objects based on node name. """ if tok[0] == 'IPV4...
def create_processing_context(feedback): """ Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext """ context = QgsProcessingContext() context.setFeedba...
Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext
Below is the the instruction that describes the task: ### Input: Creates a default processing context :param feedback: Linked processing feedback object :type feedback: QgsProcessingFeedback :return: Processing context :rtype: QgsProcessingContext ### Response: def create_processing_context(feedb...
async def execute_method(self, method, **params): """Execute a specified Slack Web API method. Arguments: method (:py:class:`str`): The name of the method. **params (:py:class:`dict`): Any additional parameters required. Returns: :py:class:`dict`: The ...
Execute a specified Slack Web API method. Arguments: method (:py:class:`str`): The name of the method. **params (:py:class:`dict`): Any additional parameters required. Returns: :py:class:`dict`: The JSON data from the response. Raises: :py:c...
Below is the the instruction that describes the task: ### Input: Execute a specified Slack Web API method. Arguments: method (:py:class:`str`): The name of the method. **params (:py:class:`dict`): Any additional parameters required. Returns: :py:class:`dic...
def get_report_column_builders(self, request, model): """ Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the col...
Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the column. :param model: model to analyze and fetch. :param requ...
Below is the the instruction that describes the task: ### Input: Returns builders for column names and column values for the elements, being each element like this: 1. A header fetcher: will retrieve the title for the column. 2. A value fetcher: will retrieve the value for the column. ...
def prox_xline(x, step): """Projection onto line in x""" if not np.isscalar(x): x= x[0] if x > 0.5: return np.array([0.5]) else: return np.array([x])
Projection onto line in x
Below is the the instruction that describes the task: ### Input: Projection onto line in x ### Response: def prox_xline(x, step): """Projection onto line in x""" if not np.isscalar(x): x= x[0] if x > 0.5: return np.array([0.5]) else: return np.array([x])
def distance_covariance_sqr(x, y, **kwargs): """ distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with t...
distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are...
Below is the the instruction that describes the task: ### Input: distance_covariance_sqr(x, y, *, exponent=1) Computes the usual (biased) estimator for the squared distance covariance between two random vectors. Parameters ---------- x: array_like First random vector. The columns corre...
def init(self, conn): """ Create the version table and run the base script on an empty database. :param conn: a DB API 2 connection """ base = self.read_scripts()[0]['fname'] logging.info('Creating the initial schema from %s', base) apply_sql_script(conn, os.pat...
Create the version table and run the base script on an empty database. :param conn: a DB API 2 connection
Below is the the instruction that describes the task: ### Input: Create the version table and run the base script on an empty database. :param conn: a DB API 2 connection ### Response: def init(self, conn): """ Create the version table and run the base script on an empty database. ...
def ensure_new_style_deprecation(cli_ctx, kwargs, object_type): """ Helper method to make the previous string-based deprecate_info kwarg work with the new style. """ deprecate_info = kwargs.get('deprecate_info', None) if isinstance(deprecate_info, Deprecated): deprecate_i...
Helper method to make the previous string-based deprecate_info kwarg work with the new style.
Below is the the instruction that describes the task: ### Input: Helper method to make the previous string-based deprecate_info kwarg work with the new style. ### Response: def ensure_new_style_deprecation(cli_ctx, kwargs, object_type): """ Helper method to make the previous string-based deprec...
def disable_signing(self): '''disable MAVLink2 signing''' self.mav.signing.secret_key = None self.mav.signing.sign_outgoing = False self.mav.signing.allow_unsigned_callback = None self.mav.signing.link_id = 0 self.mav.signing.timestamp = 0
disable MAVLink2 signing
Below is the the instruction that describes the task: ### Input: disable MAVLink2 signing ### Response: def disable_signing(self): '''disable MAVLink2 signing''' self.mav.signing.secret_key = None self.mav.signing.sign_outgoing = False self.mav.signing.allow_unsigned_callback = None...
def get_beam(secret_uuid): """ Get a beam from the session with `secret_uuid`. Parameters ---------- secret_uuid : str Returns ------- The beam object if it exists, otherwise `None`. """ beam_dir = get_beam_cache_directory() beam_filename = os.path.join(beam_dir, secret_uui...
Get a beam from the session with `secret_uuid`. Parameters ---------- secret_uuid : str Returns ------- The beam object if it exists, otherwise `None`.
Below is the the instruction that describes the task: ### Input: Get a beam from the session with `secret_uuid`. Parameters ---------- secret_uuid : str Returns ------- The beam object if it exists, otherwise `None`. ### Response: def get_beam(secret_uuid): """ Get a beam from the...
def _parse_auth_message(self, auth_message): """ Parse a message to see if we have ip addresses or users that we care about :param auth_message: The auth message to parse :return: Result """ result = {} has_matched = False for regex in REGEXES_INVALID_U...
Parse a message to see if we have ip addresses or users that we care about :param auth_message: The auth message to parse :return: Result
Below is the the instruction that describes the task: ### Input: Parse a message to see if we have ip addresses or users that we care about :param auth_message: The auth message to parse :return: Result ### Response: def _parse_auth_message(self, auth_message): """ Parse a message ...
def _subscribe_resp(self, data): """ Handle a subscribe response. :param data: Payload. :returns: State (ON/OFF) """ if _is_subscribe_response(data): status = bytes([data[23]]) _LOGGER.debug("Successfully subscribed to %s, state: %s", ...
Handle a subscribe response. :param data: Payload. :returns: State (ON/OFF)
Below is the the instruction that describes the task: ### Input: Handle a subscribe response. :param data: Payload. :returns: State (ON/OFF) ### Response: def _subscribe_resp(self, data): """ Handle a subscribe response. :param data: Payload. :returns: State (ON/OFF) ...
def data_to_df(self, sysbase=False): """ Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base """ p_dict_comp = self.data_to_dict(sysbase=sysbase) self._check_pd() self.param_df = pd.DataFrame(data=p_dict_comp).set_...
Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base
Below is the the instruction that describes the task: ### Input: Return a pandas.DataFrame of device parameters. :param sysbase: save per unit values in system base ### Response: def data_to_df(self, sysbase=False): """ Return a pandas.DataFrame of device parameters. :param sysbase:...
def imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True): """ Save image by pypng module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This...
Save image by pypng module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This argument specifies the shape of img is whether (height, width, channel) or (channel, heig...
Below is the the instruction that describes the task: ### Input: Save image by pypng module. Args: path (str): output filename img (numpy.ndarray): Image array to save. Image shape is considered as (height, width, channel) by default. channel_first: This argument specifies t...
def api(self, name, url, **kwargs): """Generic API method.""" if name not in self._apis: raise ValueError('API name must be one of {0}, not {1!r}.'.format( tuple(self._apis), name)) fields = kwargs.get('fields') timeout = kwargs.get('timeout') text = k...
Generic API method.
Below is the the instruction that describes the task: ### Input: Generic API method. ### Response: def api(self, name, url, **kwargs): """Generic API method.""" if name not in self._apis: raise ValueError('API name must be one of {0}, not {1!r}.'.format( tuple(self._apis...
def sort_variants(vcf_handle): """Sort the variants of a vcf file Args: vcf_handle mode (str): position or rank score Returns: sorted_variants (Iterable): An iterable with sorted variants """ logger.debug("Creating temp file") temp_file =...
Sort the variants of a vcf file Args: vcf_handle mode (str): position or rank score Returns: sorted_variants (Iterable): An iterable with sorted variants
Below is the the instruction that describes the task: ### Input: Sort the variants of a vcf file Args: vcf_handle mode (str): position or rank score Returns: sorted_variants (Iterable): An iterable with sorted variants ### Response: def sort_variant...
def match(self, regex, flags=0): """ Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): The flags to use when comp...
Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): The flags to use when compiling the pattern.
Below is the the instruction that describes the task: ### Input: Matches the specified *regex* from the current character of the *scanner* and returns the result. The Scanners column and line numbers are updated respectively. # Arguments regex (str, Pattern): The regex to match. flags (int): Th...