code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def interpolate_mrms_day(start_date, variable, interp_type, mrms_path, map_filename, out_path): """ For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datet...
For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datetime.datetime): Date of data being interpolated variable (str): MRMS variable interp_type (st...
Below is the the instruction that describes the task: ### Input: For a given day, this module interpolates hourly MRMS data to a specified latitude and longitude grid, and saves the interpolated grids to CF-compliant netCDF4 files. Args: start_date (datetime.datetime): Date of data being inter...
def finalize(self, params, rep): """ Save the full model once we are done. """ if params.get("saveNet", True): saveDir = os.path.join(params["path"], params["name"], "model_{}.pt".format(rep)) torch.save(self.model, saveDir)
Save the full model once we are done.
Below is the the instruction that describes the task: ### Input: Save the full model once we are done. ### Response: def finalize(self, params, rep): """ Save the full model once we are done. """ if params.get("saveNet", True): saveDir = os.path.join(params["path"], params["name"], ...
def send_approved_mail(request, user): """ Sends an email to a user once their ``is_active`` status goes from ``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. """ context = {"request": request, "user": user} subject = subject_template("email/account_approved...
Sends an email to a user once their ``is_active`` status goes from ``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``.
Below is the the instruction that describes the task: ### Input: Sends an email to a user once their ``is_active`` status goes from ``False`` to ``True`` when the ``ACCOUNTS_APPROVAL_REQUIRED`` setting is ``True``. ### Response: def send_approved_mail(request, user): """ Sends an email to a user on...
def spawn(self, command): """ Spawns a new process and adds it to the pool """ # process_name # output # time before starting (wait for port?) # start_new_session=True : avoid sending parent signals to child env = dict(os.environ) env["MRQ_IS_SUBPROCESS"] = "1" ...
Spawns a new process and adds it to the pool
Below is the the instruction that describes the task: ### Input: Spawns a new process and adds it to the pool ### Response: def spawn(self, command): """ Spawns a new process and adds it to the pool """ # process_name # output # time before starting (wait for port?) # start...
def register_fn(cls, f): """Registers a scope function on this builder.""" def inner(self, *args, **kwargs): try: query, projection, options = cls.unpack_scope(f(*args, **kwargs)) new_query = deepcopy(self.query) new_projection = deepcopy(self....
Registers a scope function on this builder.
Below is the the instruction that describes the task: ### Input: Registers a scope function on this builder. ### Response: def register_fn(cls, f): """Registers a scope function on this builder.""" def inner(self, *args, **kwargs): try: query, projection, options = cls.u...
def p_Catch(p): ''' Catch : | Catch CATCH LPARENT Varible COLON NsContentName RPARENT COLON Terminator Block ''' if len(p) <= 1: p[0] = Catch(None, None, None, None, None) else: p[0] = Catch(p[1], p[4], p[6], p[9], p[10])
Catch : | Catch CATCH LPARENT Varible COLON NsContentName RPARENT COLON Terminator Block
Below is the the instruction that describes the task: ### Input: Catch : | Catch CATCH LPARENT Varible COLON NsContentName RPARENT COLON Terminator Block ### Response: def p_Catch(p): ''' Catch : | Catch CATCH LPARENT Varible COLON NsContentName RPARENT COLON Terminator Block ''' ...
def _load_ssh(self, tag): """Loads the SSH configuration into the vardict.""" for child in tag: if child.tag == "server": self._vardict["server"] = child.attrib elif child.tag == "codes": self._load_codes(child, True) elif child.tag == ...
Loads the SSH configuration into the vardict.
Below is the the instruction that describes the task: ### Input: Loads the SSH configuration into the vardict. ### Response: def _load_ssh(self, tag): """Loads the SSH configuration into the vardict.""" for child in tag: if child.tag == "server": self._vardict["server"] ...
def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BA...
Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to...
Below is the the instruction that describes the task: ### Input: Output completion suggestions for BASH. The output of this function is passed to BASH's `COMREPLY` variable and treated as completion suggestions. `COMREPLY` expects a space separated string as the result. The `COMP_W...
def alias_bin(self, bin_id, alias_id): """Adds an ``Id`` to a ``Bin`` for the purpose of creating compatibility. The primary ``Id`` of the ``Bin`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another bin, it is re...
Adds an ``Id`` to a ``Bin`` for the purpose of creating compatibility. The primary ``Id`` of the ``Bin`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to another bin, it is reassigned to the given bin ``Id``. ...
Below is the the instruction that describes the task: ### Input: Adds an ``Id`` to a ``Bin`` for the purpose of creating compatibility. The primary ``Id`` of the ``Bin`` is determined by the provider. The new ``Id`` performs as an alias to the primary ``Id``. If the alias is a pointer to an...
def list(self, options=None, **kwds): """ Endpoint: /activities[/<options>]/list.json Returns a list of Activity objects. The options parameter can be used to narrow down the activities. Eg: options={"type": "photo-upload"} """ option_string = self._build_option_...
Endpoint: /activities[/<options>]/list.json Returns a list of Activity objects. The options parameter can be used to narrow down the activities. Eg: options={"type": "photo-upload"}
Below is the the instruction that describes the task: ### Input: Endpoint: /activities[/<options>]/list.json Returns a list of Activity objects. The options parameter can be used to narrow down the activities. Eg: options={"type": "photo-upload"} ### Response: def list(self, options=None, ...
def main(args=None): """Build and run parser :param args: cli args from tests """ parser = argument_parser() args = parser.parse_args(args) # If 'func' isn't present, something is misconfigured above or no (positional) arg was given. if not hasattr(args, 'func'): args = parser.pars...
Build and run parser :param args: cli args from tests
Below is the the instruction that describes the task: ### Input: Build and run parser :param args: cli args from tests ### Response: def main(args=None): """Build and run parser :param args: cli args from tests """ parser = argument_parser() args = parser.parse_args(args) # If 'func'...
def get_marshaller_for_type_string(self, type_string): """ Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used to read/write a Python object with the given type string. The modules it requires, if available, will be loaded. Para...
Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used to read/write a Python object with the given type string. The modules it requires, if available, will be loaded. Parameters ---------- type_string : str Typ...
Below is the the instruction that describes the task: ### Input: Gets the appropriate marshaller for a type string. Retrieves the marshaller, if any, that can be used to read/write a Python object with the given type string. The modules it requires, if available, will be loaded. Pa...
def getTaskTypes(self): """ Return the current list of task types """ types = [ ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')), ('Enhancement', safe_unicode(_('Enhancement')).encode('utf-8')), ('Preventive', safe_unicode(_('Preventive')).encod...
Return the current list of task types
Below is the the instruction that describes the task: ### Input: Return the current list of task types ### Response: def getTaskTypes(self): """ Return the current list of task types """ types = [ ('Calibration', safe_unicode(_('Calibration')).encode('utf-8')), ('Enh...
def parse(argv, rules=None, config=None, **kwargs): """Parse the given arg vector with the default Splunk command rules.""" parser_ = parser(rules, **kwargs) if config is not None: parser_.loadrc(config) return parser_.parse(argv).result
Parse the given arg vector with the default Splunk command rules.
Below is the the instruction that describes the task: ### Input: Parse the given arg vector with the default Splunk command rules. ### Response: def parse(argv, rules=None, config=None, **kwargs): """Parse the given arg vector with the default Splunk command rules.""" parser_ = parser(rules, **kwargs) ...
def set_text(self, x, y, text): """Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position """ col, row = get_pos(x, y) for i,c in enumerate(text): self.chars[row][col+i] = c
Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position
Below is the the instruction that describes the task: ### Input: Set text to the given coords. :param x: x coordinate of the text start position :param y: y coordinate of the text start position ### Response: def set_text(self, x, y, text): """Set text to the given coords. :param ...
def clear_lock(remote=None): ''' Clear update.lk ``remote`` can either be a dictionary containing repo configuration information, or a pattern. If the latter, then remotes for which the URL matches the pattern will be locked. ''' def _do_clear_lock(repo): def _add_error(errlist, rep...
Clear update.lk ``remote`` can either be a dictionary containing repo configuration information, or a pattern. If the latter, then remotes for which the URL matches the pattern will be locked.
Below is the the instruction that describes the task: ### Input: Clear update.lk ``remote`` can either be a dictionary containing repo configuration information, or a pattern. If the latter, then remotes for which the URL matches the pattern will be locked. ### Response: def clear_lock(remote=None): ...
def setCurrentInspectorRegItem(self, regItem): """ Sets the current inspector given an InspectorRegItem """ check_class(regItem, InspectorRegItem, allow_none=True) self.inspectorTab.setCurrentRegItem(regItem)
Sets the current inspector given an InspectorRegItem
Below is the the instruction that describes the task: ### Input: Sets the current inspector given an InspectorRegItem ### Response: def setCurrentInspectorRegItem(self, regItem): """ Sets the current inspector given an InspectorRegItem """ check_class(regItem, InspectorRegItem, allow_none=T...
def construct_datapipeline(env='', generated=None, previous_env=None, region='us-east-1', settings=None, pipeline_data=None): """Create the Pipeline JSON from template. This ha...
Create the Pipeline JSON from template. This handles the common repeatable patterns in a pipeline, such as judgement, infrastructure, tagger and qe. Args: env (str): Deploy environment name, e.g. dev, stage, prod. generated (gogoutils.Generator): Gogo Application name generator. pr...
Below is the the instruction that describes the task: ### Input: Create the Pipeline JSON from template. This handles the common repeatable patterns in a pipeline, such as judgement, infrastructure, tagger and qe. Args: env (str): Deploy environment name, e.g. dev, stage, prod. generat...
def server_side(func): """ Decorator to designate an API method applicable only to server-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. """ def inner(*args, **kwargs): if args and hasat...
Decorator to designate an API method applicable only to server-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion.
Below is the the instruction that describes the task: ### Input: Decorator to designate an API method applicable only to server-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. ### Response: def server_side(...
def resolve(self, piper, forgive=False): """ Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the ``Piper`` instance if it can be resolved else raises a ``DaggerError`` or returns ``False`` depending on the "forgive" argument. Arguments: ...
Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the ``Piper`` instance if it can be resolved else raises a ``DaggerError`` or returns ``False`` depending on the "forgive" argument. Arguments: - piper(``Piper`` or id(``Piper``)) a ``Piper`` instance or i...
Below is the the instruction that describes the task: ### Input: Given a ``Piper`` instance or the ``id`` of the ``Piper``. Returns the ``Piper`` instance if it can be resolved else raises a ``DaggerError`` or returns ``False`` depending on the "forgive" argument. Arguments: ...
def server(self): """ All in one endpoints. This property is created automaticly if you have implemented all the getters and setters. However, if you are not satisfied with the getter and setter, you can create a validator with :class:`OAuth2RequestValidator`:: clas...
All in one endpoints. This property is created automaticly if you have implemented all the getters and setters. However, if you are not satisfied with the getter and setter, you can create a validator with :class:`OAuth2RequestValidator`:: class MyValidator(OAuth2RequestValidator):...
Below is the the instruction that describes the task: ### Input: All in one endpoints. This property is created automaticly if you have implemented all the getters and setters. However, if you are not satisfied with the getter and setter, you can create a validator with :class:`OAuth2Reques...
def generate_boosted_machine(self): """generate_boosted_machine() -> strong Creates a single strong classifier from this cascade by concatenating all strong classifiers. **Returns:** ``strong`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier as a combination of all classif...
generate_boosted_machine() -> strong Creates a single strong classifier from this cascade by concatenating all strong classifiers. **Returns:** ``strong`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier as a combination of all classifiers in this cascade.
Below is the the instruction that describes the task: ### Input: generate_boosted_machine() -> strong Creates a single strong classifier from this cascade by concatenating all strong classifiers. **Returns:** ``strong`` : :py:class:`bob.learn.boosting.BoostedMachine` The strong classifier as a ...
def make( password_provider, *, pin_store=None, pin_type=PinType.PUBLIC_KEY, post_handshake_deferred_failure=None, anonymous=False, ssl_context_factory=default_ssl_context, no_verify=False): """ Construct a :class:`SecurityLayer`. Depending on the ...
Construct a :class:`SecurityLayer`. Depending on the arguments passed, different features are enabled or disabled. .. warning:: When using any argument except `password_provider`, be sure to read its documentation below the following overview **carefully**. Many arguments can be used t...
Below is the the instruction that describes the task: ### Input: Construct a :class:`SecurityLayer`. Depending on the arguments passed, different features are enabled or disabled. .. warning:: When using any argument except `password_provider`, be sure to read its documentation below the f...
def get_future_days(self): """Return only future Day objects.""" today = timezone.now().date() return Day.objects.filter(date__gte=today)
Return only future Day objects.
Below is the the instruction that describes the task: ### Input: Return only future Day objects. ### Response: def get_future_days(self): """Return only future Day objects.""" today = timezone.now().date() return Day.objects.filter(date__gte=today)
def ListJobs(self, token=None): """Returns a list of all currently running cron jobs.""" job_root = aff4.FACTORY.Open(self.CRON_JOBS_PATH, token=token) return [urn.Basename() for urn in job_root.ListChildren()]
Returns a list of all currently running cron jobs.
Below is the the instruction that describes the task: ### Input: Returns a list of all currently running cron jobs. ### Response: def ListJobs(self, token=None): """Returns a list of all currently running cron jobs.""" job_root = aff4.FACTORY.Open(self.CRON_JOBS_PATH, token=token) return [urn.Basename(...
def dict_to_cognito(attributes, attr_map=None): """ :param attributes: Dictionary of User Pool attribute names/values :return: list of User Pool attribute formatted dicts: {'Name': <attr_name>, 'Value': <attr_value>} """ if attr_map is None: attr_map = {} for k,v in attr_map.items(): ...
:param attributes: Dictionary of User Pool attribute names/values :return: list of User Pool attribute formatted dicts: {'Name': <attr_name>, 'Value': <attr_value>}
Below is the the instruction that describes the task: ### Input: :param attributes: Dictionary of User Pool attribute names/values :return: list of User Pool attribute formatted dicts: {'Name': <attr_name>, 'Value': <attr_value>} ### Response: def dict_to_cognito(attributes, attr_map=None): """ :param ...
def eval(self, text): """ Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception """ assert is_text_string(text) try: return eval(text, self.loc...
Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception
Below is the the instruction that describes the task: ### Input: Evaluate text and return (obj, valid) where *obj* is the object represented by *text* and *valid* is True if object evaluation did not raise any exception ### Response: def eval(self, text): """ Evaluate text and r...
def from_inet_ptoi(bgp_id): """Convert an IPv4 address string format to a four byte long. """ four_byte_id = None try: four_byte_id = ip.ipv4_to_int(bgp_id) except ValueError: LOG.debug('Invalid bgp id given for conversion to integer value %s', bgp_id) return f...
Convert an IPv4 address string format to a four byte long.
Below is the the instruction that describes the task: ### Input: Convert an IPv4 address string format to a four byte long. ### Response: def from_inet_ptoi(bgp_id): """Convert an IPv4 address string format to a four byte long. """ four_byte_id = None try: four_byte_id = ip.ipv4_to_int(bgp_...
def do_import(token, account_uuid, bank_account, since=None): """Import data from teller.io Returns the created StatementImport """ response = requests.get( url="https://api.teller.io/accounts/{}/transactions".format(account_uuid), headers={"Authorization": "Bearer {}".format(token)}, ...
Import data from teller.io Returns the created StatementImport
Below is the the instruction that describes the task: ### Input: Import data from teller.io Returns the created StatementImport ### Response: def do_import(token, account_uuid, bank_account, since=None): """Import data from teller.io Returns the created StatementImport """ response = requests...
def _find(self, spec): """ Find and return the path to the template associated to the instance. """ if spec.template_path is not None: return spec.template_path dir_path, file_name = self._find_relative(spec) locator = self.loader._make_locator() i...
Find and return the path to the template associated to the instance.
Below is the the instruction that describes the task: ### Input: Find and return the path to the template associated to the instance. ### Response: def _find(self, spec): """ Find and return the path to the template associated to the instance. """ if spec.template_path is not None:...
def update_rbac_policy(self, rbac_policy_id, body=None): """Update a RBAC policy.""" return self.put(self.rbac_policy_path % rbac_policy_id, body=body)
Update a RBAC policy.
Below is the the instruction that describes the task: ### Input: Update a RBAC policy. ### Response: def update_rbac_policy(self, rbac_policy_id, body=None): """Update a RBAC policy.""" return self.put(self.rbac_policy_path % rbac_policy_id, body=body)
def create_dataset(self, name=None, description=None, public=False): """ Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or ...
Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or not the dataset should be public. :type public: bool :return: The newly c...
Below is the the instruction that describes the task: ### Input: Create a new data set. :param name: name of the dataset :type name: str :param description: description for the dataset :type description: str :param public: A boolean indicating whether or not the dataset shou...
def show(config, username): """Display a specific user.""" client = Client() client.prepare_connection() user_api = API(client) CLI.show_user(user_api.show(username))
Display a specific user.
Below is the the instruction that describes the task: ### Input: Display a specific user. ### Response: def show(config, username): """Display a specific user.""" client = Client() client.prepare_connection() user_api = API(client) CLI.show_user(user_api.show(username))
def _setup_states(state_definitions, prev=()): """Create a StateList object from a 'states' Workflow attribute.""" states = list(prev) for state_def in state_definitions: if len(state_def) != 2: raise TypeError( "The 'state' attribute of a workflow should be " ...
Create a StateList object from a 'states' Workflow attribute.
Below is the the instruction that describes the task: ### Input: Create a StateList object from a 'states' Workflow attribute. ### Response: def _setup_states(state_definitions, prev=()): """Create a StateList object from a 'states' Workflow attribute.""" states = list(prev) for state_def in state_defi...
def parse_int(str_num): """ Given an integer number, return its value, or None if it could not be parsed. Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh) :param str_num: (string) the number to be parsed :return: an integer number or None if it could not be parsedd """ str_num = (str_n...
Given an integer number, return its value, or None if it could not be parsed. Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh) :param str_num: (string) the number to be parsed :return: an integer number or None if it could not be parsedd
Below is the the instruction that describes the task: ### Input: Given an integer number, return its value, or None if it could not be parsed. Allowed formats: DECIMAL, HEXA (0xnnn, $nnnn or nnnnh) :param str_num: (string) the number to be parsed :return: an integer number or None if it could not be...
def compute_control_digit(clabe: str) -> str: """ Compute CLABE control digit according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control """ clabe = [int(i) for i in clabe] weighted = [c * w % 10 for c, w in zip(clabe[:CLABE_LENGTH - 1], CLABE_WEIGHTS)] summed = sum...
Compute CLABE control digit according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control
Below is the the instruction that describes the task: ### Input: Compute CLABE control digit according to https://es.wikipedia.org/wiki/CLABE#D.C3.ADgito_control ### Response: def compute_control_digit(clabe: str) -> str: """ Compute CLABE control digit according to https://es.wikipedia.org/wiki/CL...
def _translators(attr, kwargs): """ Decorator which associates a set of translators (serializers or deserializers) with a given method. The `attr` parameter identifies which attribute is being updated. """ # Add translators to a function or class def decorator(func): # Make sure we...
Decorator which associates a set of translators (serializers or deserializers) with a given method. The `attr` parameter identifies which attribute is being updated.
Below is the the instruction that describes the task: ### Input: Decorator which associates a set of translators (serializers or deserializers) with a given method. The `attr` parameter identifies which attribute is being updated. ### Response: def _translators(attr, kwargs): """ Decorator which a...
def SA_ellipsoidal_head(D, a): r'''Calculates the surface area of an ellipsoidal head according to [1]_. Formula below is for the full shape, the result of which is halved. The formula also does not support `D` being larger than `a`; this is ensured by simply swapping the variables if necessary, as geom...
r'''Calculates the surface area of an ellipsoidal head according to [1]_. Formula below is for the full shape, the result of which is halved. The formula also does not support `D` being larger than `a`; this is ensured by simply swapping the variables if necessary, as geometrically the result is the sam...
Below is the the instruction that describes the task: ### Input: r'''Calculates the surface area of an ellipsoidal head according to [1]_. Formula below is for the full shape, the result of which is halved. The formula also does not support `D` being larger than `a`; this is ensured by simply swapping t...
def patch(self, url, headers=None, body=None, kwargs=None): """Make a PATCH request. To make a PATCH request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`` """ return self._request( ...
Make a PATCH request. To make a PATCH request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict``
Below is the the instruction that describes the task: ### Input: Make a PATCH request. To make a PATCH request pass, ``url`` :param url: ``str`` :param headers: ``dict`` :param body: ``object`` :param kwargs: ``dict`` ### Response: def patch(self, url, headers=None, body=N...
def format(self, version=None, wipe=None): """Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some integer th...
Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some integer then :meth:`format` will overwrite all user date that ...
Below is the the instruction that describes the task: ### Input: Erase the NDEF message on a Type 2 Tag. The :meth:`format` method will reset the length of the NDEF message on a type 2 tag to zero, thus the tag will appear to be empty. Additionally, if the *wipe* argument is set to some ...
def get(self, keys, default=None): """ To get a value by dot notation :param keys: dot notaion string :param default: :return: """ try: d = self for k in keys.split("."): if not k in d: d[k] = {} ...
To get a value by dot notation :param keys: dot notaion string :param default: :return:
Below is the the instruction that describes the task: ### Input: To get a value by dot notation :param keys: dot notaion string :param default: :return: ### Response: def get(self, keys, default=None): """ To get a value by dot notation :param keys: dot notaion strin...
def _close_rpc_interface(self, connection_id, callback): """Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, ad...
Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, adapter_id, success, failure_reason)
Below is the the instruction that describes the task: ### Input: Disable RPC interface for this IOTile device Args: connection_id (int): The unique identifier for the connection callback (callback): Callback to be called when this command finishes callback(conn_id, a...
def _generate_union(self, union_type): """ Emits a JSDoc @typedef for a union type. """ union_name = fmt_type_name(union_type) self._emit_jsdoc_header(union_type.doc) self.emit(' * @typedef {Object} %s' % union_name) variant_types = [] for variant in union...
Emits a JSDoc @typedef for a union type.
Below is the the instruction that describes the task: ### Input: Emits a JSDoc @typedef for a union type. ### Response: def _generate_union(self, union_type): """ Emits a JSDoc @typedef for a union type. """ union_name = fmt_type_name(union_type) self._emit_jsdoc_header(unio...
def _convert_pooling_param(param): """Convert the pooling layer parameter """ param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool=True, kernel=(1,1)" else: param_string += "pad=(%d,%d), kernel=(%d,%d), stride=(%d,%d)" % ( par...
Convert the pooling layer parameter
Below is the the instruction that describes the task: ### Input: Convert the pooling layer parameter ### Response: def _convert_pooling_param(param): """Convert the pooling layer parameter """ param_string = "pooling_convention='full', " if param.global_pooling: param_string += "global_pool...
def invalidate_authorization_code(self, client_id, code, request, *args, **kwargs): """Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself. """ log.debug('Destroy...
Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself.
Below is the the instruction that describes the task: ### Input: Invalidate an authorization code after use. We keep the temporary code in a grant, which has a `delete` function to destroy itself. ### Response: def invalidate_authorization_code(self, client_id, code, request, ...
def filterAcceptsRow(self, sourceRow, sourceParent): """ If onlyShowImported is True, regItems that were not (successfully) imported are filtered out. """ if not self.onlyShowImported: return True item = self.sourceModel().registry.items[sourceRow] return...
If onlyShowImported is True, regItems that were not (successfully) imported are filtered out.
Below is the the instruction that describes the task: ### Input: If onlyShowImported is True, regItems that were not (successfully) imported are filtered out. ### Response: def filterAcceptsRow(self, sourceRow, sourceParent): """ If onlyShowImported is True, regItems that were not (successfully...
def create_topics(self, new_topics, **kwargs): """ Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlli...
Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics to be created. :param float operation_timeout: Set broker's operation timeout in seconds, controlling how long the CreateTopics request will block o...
Below is the the instruction that describes the task: ### Input: Create new topics in cluster. The future result() value is None. :param list(NewTopic) new_topics: New topics to be created. :param float operation_timeout: Set broker's operation timeout in seconds, control...
def get_long(): """ Generates a random long. The length of said long varies by platform. """ # The C long type to populate. pbRandomData = c_ulong() # Determine the byte size of this machine's long type. size_of_long = wintypes.DWORD(sizeof(pbRandomData)) # Used to keep track of status. ...
Generates a random long. The length of said long varies by platform.
Below is the the instruction that describes the task: ### Input: Generates a random long. The length of said long varies by platform. ### Response: def get_long(): """ Generates a random long. The length of said long varies by platform. """ # The C long type to populate. pbRandomData = c_ulong(...
def _IncludeFields(encoded_message, message, include_fields): """Add the requested fields to the encoded message.""" if include_fields is None: return encoded_message result = json.loads(encoded_message) for field_name in include_fields: try: value = _GetField(message, field_...
Add the requested fields to the encoded message.
Below is the the instruction that describes the task: ### Input: Add the requested fields to the encoded message. ### Response: def _IncludeFields(encoded_message, message, include_fields): """Add the requested fields to the encoded message.""" if include_fields is None: return encoded_message ...
def discoverAllNodes(self): ''' .. todo:: node discovery has changed, breathe no longer used...update docs ''' doxygen_index_xml = os.path.join( configs._doxygen_xml_output_directory, "index.xml" ) try: with codecs.open(doxygen_index_xm...
.. todo:: node discovery has changed, breathe no longer used...update docs
Below is the the instruction that describes the task: ### Input: .. todo:: node discovery has changed, breathe no longer used...update docs ### Response: def discoverAllNodes(self): ''' .. todo:: node discovery has changed, breathe no longer used...update docs ''' doxygen_index_xml ...
def add_data(self, addr, data): """Callback when data is received from the Crazyflie""" data_len = len(data) if not addr == self._current_addr: logger.warning( 'Address did not match when adding data to read request!') return # Add the data and ca...
Callback when data is received from the Crazyflie
Below is the the instruction that describes the task: ### Input: Callback when data is received from the Crazyflie ### Response: def add_data(self, addr, data): """Callback when data is received from the Crazyflie""" data_len = len(data) if not addr == self._current_addr: logger...
def uni_to_beta(text): """ Convert unicode text to a betacode equivalent. This method can handle tónos or oxeîa characters in the input. Args: text: The text to convert to betacode. This text does not have to all be Greek polytonic text, and only Greek characters will be converted. Note ...
Convert unicode text to a betacode equivalent. This method can handle tónos or oxeîa characters in the input. Args: text: The text to convert to betacode. This text does not have to all be Greek polytonic text, and only Greek characters will be converted. Note that in this case, you cannot...
Below is the the instruction that describes the task: ### Input: Convert unicode text to a betacode equivalent. This method can handle tónos or oxeîa characters in the input. Args: text: The text to convert to betacode. This text does not have to all be Greek polytonic text, and only Greek cha...
def format_sensor_bar(self, sensor): """ Build and format a sensor bar. If pango is enabled bar color is per sensor.""" percentage = self.percentage(sensor.current, sensor.critical) bar = make_vertical_bar(int(percentage)) if self.pango_enabled: if self.dynamic_color: ...
Build and format a sensor bar. If pango is enabled bar color is per sensor.
Below is the the instruction that describes the task: ### Input: Build and format a sensor bar. If pango is enabled bar color is per sensor. ### Response: def format_sensor_bar(self, sensor): """ Build and format a sensor bar. If pango is enabled bar color is per sensor.""" percentage = self.percen...
def add_filter(ds, patterns): """ Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, list of strings, or set of ...
Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, list of strings, or set of strings to add to the datasour...
Below is the the instruction that describes the task: ### Input: Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, ...
def openTypeNameCompatibleFullNameFallback(info): """ Fallback to *styleMapFamilyName styleMapStyleName*. If *styleMapStyleName* is *regular* this will not add the style name. """ familyName = getAttrWithFallback(info, "styleMapFamilyName") styleMapStyleName = getAttrWithFallback(info, "styl...
Fallback to *styleMapFamilyName styleMapStyleName*. If *styleMapStyleName* is *regular* this will not add the style name.
Below is the the instruction that describes the task: ### Input: Fallback to *styleMapFamilyName styleMapStyleName*. If *styleMapStyleName* is *regular* this will not add the style name. ### Response: def openTypeNameCompatibleFullNameFallback(info): """ Fallback to *styleMapFamilyName styleMapStyl...
def ilist(self, in_list=[]): """Return a list that uses this server's IRC casemapping. All strings in this list are lowercased using the server's casemapping before inserting them into the list, and the ``in`` operator takes casemapping into account. """ new_list = IList(in_list...
Return a list that uses this server's IRC casemapping. All strings in this list are lowercased using the server's casemapping before inserting them into the list, and the ``in`` operator takes casemapping into account.
Below is the the instruction that describes the task: ### Input: Return a list that uses this server's IRC casemapping. All strings in this list are lowercased using the server's casemapping before inserting them into the list, and the ``in`` operator takes casemapping into account. ### Response: ...
def __init_from_list_np2d(self, mats, params_str, ref_dataset): """Initialize data from a list of 2-D numpy matrices.""" ncol = mats[0].shape[1] nrow = np.zeros((len(mats),), np.int32) if mats[0].dtype == np.float64: ptr_data = (ctypes.POINTER(ctypes.c_double) * len(mats))() ...
Initialize data from a list of 2-D numpy matrices.
Below is the the instruction that describes the task: ### Input: Initialize data from a list of 2-D numpy matrices. ### Response: def __init_from_list_np2d(self, mats, params_str, ref_dataset): """Initialize data from a list of 2-D numpy matrices.""" ncol = mats[0].shape[1] nrow = np.zeros(...
def report_collection_diff(from_collection, to_collection, from_id, to_id): """Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal. """ if from_collection == to_collection: retu...
Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal.
Below is the the instruction that describes the task: ### Input: Report the collected test difference between two nodes. :returns: detailed message describing the difference between the given collections, or None if they are equal. ### Response: def report_collection_diff(from_collection, to_collection, f...
def customer_stop(self, nick, session): '''taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。''' request = TOPRequest('taobao.increment.customer.stop') request['nick'] = nick self.create(self.execute(request, session), fields=['is_success',]) ...
taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。
Below is the the instruction that describes the task: ### Input: taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。 ### Response: def customer_stop(self, nick, session): '''taobao.increment.customer.stop 关闭用户的增量消息服务 供应用关闭其用户的增量消息服务功能,这样可以节省ISV的流量。''...
def xor(key, data): """ Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``data`` with. ...
Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``data`` with. data(bytes): The data to p...
Below is the the instruction that describes the task: ### Input: Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or byt...
def read_register(self, addr, numBytes): """Reads @numBytes bytes from the grizzly starting at @addr. Due to packet format, cannot read more than 127 packets at a time. Returns a byte array of the requested data in little endian. @addr should be from the Addr class e.g. Addr.Speed""" ...
Reads @numBytes bytes from the grizzly starting at @addr. Due to packet format, cannot read more than 127 packets at a time. Returns a byte array of the requested data in little endian. @addr should be from the Addr class e.g. Addr.Speed
Below is the the instruction that describes the task: ### Input: Reads @numBytes bytes from the grizzly starting at @addr. Due to packet format, cannot read more than 127 packets at a time. Returns a byte array of the requested data in little endian. @addr should be from the Addr class e.g. ...
def search(self, keyword, types=[], terr=KKBOXTerritory.TAIWAN): ''' Searches within KKBOX's database. :param keyword: the keyword. :type keyword: str :param types: the search types. :return: list :param terr: the current territory. :return: API response....
Searches within KKBOX's database. :param keyword: the keyword. :type keyword: str :param types: the search types. :return: list :param terr: the current territory. :return: API response. :rtype: dict See `https://docs-en.kkbox.codes/v1.1/reference#search...
Below is the the instruction that describes the task: ### Input: Searches within KKBOX's database. :param keyword: the keyword. :type keyword: str :param types: the search types. :return: list :param terr: the current territory. :return: API response. :rtype:...
def coerce_to_synchronous(func): ''' Given a function that might be async, wrap it in an explicit loop so it can be run in a synchronous context. ''' if inspect.iscoroutinefunction(func): @functools.wraps(func) def sync_wrapper(*args, **kwargs): loop = asyncio.get_event_l...
Given a function that might be async, wrap it in an explicit loop so it can be run in a synchronous context.
Below is the the instruction that describes the task: ### Input: Given a function that might be async, wrap it in an explicit loop so it can be run in a synchronous context. ### Response: def coerce_to_synchronous(func): ''' Given a function that might be async, wrap it in an explicit loop so it can ...
def get_video(self, node): """ Create a video object from a video embed """ video = Video() video.embed_code = self.get_embed_code(node) video.embed_type = self.get_embed_type(node) video.width = self.get_width(node) video.height = self.get_height(node) ...
Create a video object from a video embed
Below is the the instruction that describes the task: ### Input: Create a video object from a video embed ### Response: def get_video(self, node): """ Create a video object from a video embed """ video = Video() video.embed_code = self.get_embed_code(node) video.embe...
def Ceil(input_vertex: vertex_constructor_param_types, label: Optional[str]=None) -> Vertex: """ Applies the Ceiling operator to a vertex. This maps a vertex to the smallest integer greater than or equal to its value :param input_vertex: the vertex to be ceil'd """ return Double(context.jvm...
Applies the Ceiling operator to a vertex. This maps a vertex to the smallest integer greater than or equal to its value :param input_vertex: the vertex to be ceil'd
Below is the the instruction that describes the task: ### Input: Applies the Ceiling operator to a vertex. This maps a vertex to the smallest integer greater than or equal to its value :param input_vertex: the vertex to be ceil'd ### Response: def Ceil(input_vertex: vertex_constructor_param_types, lab...
def AgregarDatosAutorizacion(self, nro_remito=None, cod_autorizacion=None, fecha_emision=None, fecha_vencimiento=None, **kwargs): "Agrega la información referente a los datos de autorización del remito electrónico cárnico" self.remito['datosEmision'] = dict(nroRemito=nro_remito, codAutorizacion=cod_auto...
Agrega la información referente a los datos de autorización del remito electrónico cárnico
Below is the the instruction that describes the task: ### Input: Agrega la información referente a los datos de autorización del remito electrónico cárnico ### Response: def AgregarDatosAutorizacion(self, nro_remito=None, cod_autorizacion=None, fecha_emision=None, fecha_vencimiento=None, **kwargs): "Agrega...
def get_created_by(self): '''Returns created by''' created_by = parsers.get_created_by(self.__chebi_id) if created_by is None: created_by = parsers.get_created_by(self.get_parent_id()) if created_by is None: for parent_or_child_id in self.__get_all_ids(): ...
Returns created by
Below is the the instruction that describes the task: ### Input: Returns created by ### Response: def get_created_by(self): '''Returns created by''' created_by = parsers.get_created_by(self.__chebi_id) if created_by is None: created_by = parsers.get_created_by(self.get_parent_i...
def QA_SU_save_future_min_all(engine, client=DATABASE): """[summary] Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) """ engine = select_save_engine(engine) engine.QA_SU_save_future_min_all(client=client)
[summary] Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE})
Below is the the instruction that describes the task: ### Input: [summary] Arguments: engine {[type]} -- [description] Keyword Arguments: client {[type]} -- [description] (default: {DATABASE}) ### Response: def QA_SU_save_future_min_all(engine, client=DATABASE): """[summary] Argu...
def convert_fig_elements(self): """ Responsible for the correct conversion of JPTS 3.0 <fig> elements to EPUB xhtml. Aside from translating <fig> to <img>, the content model must be edited. """ for fig in self.main.getroot().findall('.//fig'): if fig.getparent...
Responsible for the correct conversion of JPTS 3.0 <fig> elements to EPUB xhtml. Aside from translating <fig> to <img>, the content model must be edited.
Below is the the instruction that describes the task: ### Input: Responsible for the correct conversion of JPTS 3.0 <fig> elements to EPUB xhtml. Aside from translating <fig> to <img>, the content model must be edited. ### Response: def convert_fig_elements(self): """ Responsible fo...
def herald_message(self, herald_svc, message): """ Handles a message received by Herald :param herald_svc: Herald service :param message: Received message """ subject = message.subject if subject == SUBJECT_DISCOVERY_STEP_1: # Step 1: Register the rem...
Handles a message received by Herald :param herald_svc: Herald service :param message: Received message
Below is the the instruction that describes the task: ### Input: Handles a message received by Herald :param herald_svc: Herald service :param message: Received message ### Response: def herald_message(self, herald_svc, message): """ Handles a message received by Herald :p...
def _build_job_meta(cls, job_dir): """Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info. """ meta_file = os.path.join(job_dir, JOB_META_FILE) meta = parse_json(meta_file) if not meta...
Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info.
Below is the the instruction that describes the task: ### Input: Build meta file for job. Args: job_dir (str): Directory path of the job. Return: A dict of job meta info. ### Response: def _build_job_meta(cls, job_dir): """Build meta file for job. Args: ...
def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value.success(index, res))
Return a value according to the parameter `res` when parse successfully.
Below is the the instruction that describes the task: ### Input: Return a value according to the parameter `res` when parse successfully. ### Response: def result(self, res): '''Return a value according to the parameter `res` when parse successfully.''' return self >> Parser(lambda _, index: Value....
def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True): """Add commas and equals as appropriate to function argument lists in the stack.""" kwarg_names = [] if nkw == -1: if sys.version_info[0] < 3: # Compute nkw and nargs from nargs for python 2.7 nargs, nkw = (nargs % 256, ...
Add commas and equals as appropriate to function argument lists in the stack.
Below is the the instruction that describes the task: ### Input: Add commas and equals as appropriate to function argument lists in the stack. ### Response: def _annotate_fn_args(stack, fn_opname, nargs, nkw=-1, consume_fn_name=True): """Add commas and equals as appropriate to function argument lists in the stac...
def purge_stream(self, stream_id, remove_definition=False, sandbox=None): """ Clears all the data in a given stream and the calculated intervals :param stream_id: The stream id :param remove_definition: Whether to remove the stream definition as well :param sandbox: The ...
Clears all the data in a given stream and the calculated intervals :param stream_id: The stream id :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox id :return: None
Below is the the instruction that describes the task: ### Input: Clears all the data in a given stream and the calculated intervals :param stream_id: The stream id :param remove_definition: Whether to remove the stream definition as well :param sandbox: The sandbox id :retur...
def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' for r in self.roots: refs = r.references() check_integrity(refs)
Perform integrity checks on the modes in this document. Returns: None
Below is the the instruction that describes the task: ### Input: Perform integrity checks on the modes in this document. Returns: None ### Response: def validate(self): ''' Perform integrity checks on the modes in this document. Returns: None ''' f...
def new_session( self, session_name=None, kill_session=False, attach=False, start_directory=None, window_name=None, window_command=None, *args, **kwargs ): """ Return :class:`Session` from ``$ tmux new-session``. Uses ...
Return :class:`Session` from ``$ tmux new-session``. Uses ``-P`` flag to print session info, ``-F`` for return formatting returns new Session object. ``$ tmux new-session -d`` will create the session in the background ``$ tmux new-session -Ad`` will move to the session name if it alre...
Below is the the instruction that describes the task: ### Input: Return :class:`Session` from ``$ tmux new-session``. Uses ``-P`` flag to print session info, ``-F`` for return formatting returns new Session object. ``$ tmux new-session -d`` will create the session in the background ...
def V_horiz_spherical(D, L, a, h, headonly=False): r'''Calculates volume of a tank with spherical heads, according to [1]_. .. math:: V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R .. math:: V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R .. math:: ...
r'''Calculates volume of a tank with spherical heads, according to [1]_. .. math:: V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R .. math:: V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R .. math:: V_f = A_fL + \pi a h^2\left(1 - \frac{h}{3R}\right),\;...
Below is the the instruction that describes the task: ### Input: r'''Calculates volume of a tank with spherical heads, according to [1]_. .. math:: V_f = A_fL + \frac{\pi a}{6}(3R^2 + a^2),\;\; h = R, |a|\le R .. math:: V_f = A_fL + \frac{\pi a}{3}(3R^2 + a^2),\;\; h = D, |a|\le R .. ...
def run(self, tasks=None, timeout=None): """Block, run loop until all tasks completed.""" timeout = self._timeout if timeout is None else timeout if self.async_running or self.loop.is_running(): return self.wait_all_tasks_done(timeout) else: tasks = tasks or self....
Block, run loop until all tasks completed.
Below is the the instruction that describes the task: ### Input: Block, run loop until all tasks completed. ### Response: def run(self, tasks=None, timeout=None): """Block, run loop until all tasks completed.""" timeout = self._timeout if timeout is None else timeout if self.async_running o...
def _draw_legend(self): """ Draw legend onto the figure """ legend_box = self.guides.build(self) if not legend_box: return figure = self.figure left = figure.subplotpars.left right = figure.subplotpars.right top = figure.subplotpars.to...
Draw legend onto the figure
Below is the the instruction that describes the task: ### Input: Draw legend onto the figure ### Response: def _draw_legend(self): """ Draw legend onto the figure """ legend_box = self.guides.build(self) if not legend_box: return figure = self.figure ...
def get_listeners(self): """Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.""" return [(name, getattr(self, method_name)) for name, method_name in self.__cog_listeners__]
Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.
Below is the the instruction that describes the task: ### Input: Returns a :class:`list` of (name, function) listener pairs that are defined in this cog. ### Response: def get_listeners(self): """Returns a :class:`list` of (name, function) listener pairs that are defined in this cog.""" return [(na...
def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ logger.debug("checkState setter: {}".format(checkState)) if checkState == Qt.Checked: commonData = True elif checkState == Qt.Unchecked: commonDa...
Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked).
Below is the the instruction that describes the task: ### Input: Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). ### Response: def checkState(self, checkState): """ Sets the data to given a Qt.CheckState (Qt.Checked or Qt.Unchecked). """ logger.debug("checkState setter:...
def source_analysis( source_path, group, encoding='automatic', fallback_encoding='cp1252', generated_regexes=pygount.common.regexes_from(DEFAULT_GENERATED_PATTERNS_TEXT), duplicate_pool=None): """ Analysis for line counts in source code stored in ``source_path``. :param source_path:...
Analysis for line counts in source code stored in ``source_path``. :param source_path: :param group: name of a logical group the sourc code belongs to, e.g. a package. :param encoding: encoding according to :func:`encoding_for` :param fallback_encoding: fallback encoding according to :func:...
Below is the the instruction that describes the task: ### Input: Analysis for line counts in source code stored in ``source_path``. :param source_path: :param group: name of a logical group the sourc code belongs to, e.g. a package. :param encoding: encoding according to :func:`encoding_for` ...
def read(self, filehandle): """Read data into a :class:`~mwtab.mwtab.MWTabFile` instance. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`, :py:class:`bz2.BZ2File`, :py:class:`zipfile.ZipFile` :retur...
Read data into a :class:`~mwtab.mwtab.MWTabFile` instance. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`, :py:class:`bz2.BZ2File`, :py:class:`zipfile.ZipFile` :return: None :rtype: :py:obj:`None`
Below is the the instruction that describes the task: ### Input: Read data into a :class:`~mwtab.mwtab.MWTabFile` instance. :param filehandle: file-like object. :type filehandle: :py:class:`io.TextIOWrapper`, :py:class:`gzip.GzipFile`, :py:class:`bz2.BZ2File`, :py:class:`z...
def setDocuments(self, documenting_pid, documented_pid): """Add a CiTO, the Citation Typing Ontology, triple asserting that ``documenting_pid`` documents ``documented_pid``. Adds assertion: ``documenting_pid cito:documents documented_pid`` Args: documenting_pid: str ...
Add a CiTO, the Citation Typing Ontology, triple asserting that ``documenting_pid`` documents ``documented_pid``. Adds assertion: ``documenting_pid cito:documents documented_pid`` Args: documenting_pid: str PID of a Science Object that documents ``documented_pid``. ...
Below is the the instruction that describes the task: ### Input: Add a CiTO, the Citation Typing Ontology, triple asserting that ``documenting_pid`` documents ``documented_pid``. Adds assertion: ``documenting_pid cito:documents documented_pid`` Args: documenting_pid: str ...
def identify(path_name, *, override=None, check_exists=True, default=ISDIR): """ Identify the type of a given path name (file or directory). If check_exists is specified to be false, then the function will not set the identity based on the path existing or not. If override is specified as either ISDIR o...
Identify the type of a given path name (file or directory). If check_exists is specified to be false, then the function will not set the identity based on the path existing or not. If override is specified as either ISDIR or ISFILE, then the function will try its best to over-ride the identity to be wha...
Below is the the instruction that describes the task: ### Input: Identify the type of a given path name (file or directory). If check_exists is specified to be false, then the function will not set the identity based on the path existing or not. If override is specified as either ISDIR or ISFILE, then t...
def _point_in_bbox(point, bounds): """ valid whether the point is inside the bounding box """ return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] > bounds[2] or point['coordinates'][0] < bounds[1] or point['coordinates'][0] > bounds[3])
valid whether the point is inside the bounding box
Below is the the instruction that describes the task: ### Input: valid whether the point is inside the bounding box ### Response: def _point_in_bbox(point, bounds): """ valid whether the point is inside the bounding box """ return not(point['coordinates'][1] < bounds[0] or point['coordinates'][1] >...
def get_return_description_indexes(self, data): """Get from a docstring the return parameter description indexes. In javadoc style it is after @return. :param data: string to parse :returns: start and end indexes of found element else (-1, -1) Note: the end index is the index ...
Get from a docstring the return parameter description indexes. In javadoc style it is after @return. :param data: string to parse :returns: start and end indexes of found element else (-1, -1) Note: the end index is the index after the last included character or -1 if reache...
Below is the the instruction that describes the task: ### Input: Get from a docstring the return parameter description indexes. In javadoc style it is after @return. :param data: string to parse :returns: start and end indexes of found element else (-1, -1) Note: the end index is ...
def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] raw_content = properties.get("addressSpace", None) if raw_content is not None: address_space = AddressSpace.from_raw_data(raw_content) proper...
Create a new model using raw API response.
Below is the the instruction that describes the task: ### Input: Create a new model using raw API response. ### Response: def process_raw_data(cls, raw_data): """Create a new model using raw API response.""" properties = raw_data["properties"] raw_content = properties.get("addressSpace", N...
def Matches(self, file_entry): """Compares the file entry against the filter collection. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches one of the filters. If no filters are provided or applicable the result will be True. ...
Compares the file entry against the filter collection. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches one of the filters. If no filters are provided or applicable the result will be True.
Below is the the instruction that describes the task: ### Input: Compares the file entry against the filter collection. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches one of the filters. If no filters are provided or applicabl...
def _load_build(self): """See `pickle.py` in Python's source code.""" # if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2], Ref): # Ref.__setstate__ will know it's a remote ref if the state is a tuple self.stack[-1] = (self...
See `pickle.py` in Python's source code.
Below is the the instruction that describes the task: ### Input: See `pickle.py` in Python's source code. ### Response: def _load_build(self): """See `pickle.py` in Python's source code.""" # if the ctor. function (penultimate on the stack) is the `Ref` class... if isinstance(self.stack[-2]...
def initialize(self): """Initialize the corresponding DXclass from the data. class = DXInitObject.initialize() """ return self.DXclasses[self.type](self.id,**self.args)
Initialize the corresponding DXclass from the data. class = DXInitObject.initialize()
Below is the the instruction that describes the task: ### Input: Initialize the corresponding DXclass from the data. class = DXInitObject.initialize() ### Response: def initialize(self): """Initialize the corresponding DXclass from the data. class = DXInitObject.initialize() """ ...
def PintPars(datablock, araiblock, zijdblock, start, end, accept, **kwargs): """ calculate the paleointensity magic parameters make some definitions """ if 'version' in list(kwargs.keys()) and kwargs['version'] == 3: meth_key = 'method_codes' beta_key = 'int_b_beta' temp_key, m...
calculate the paleointensity magic parameters make some definitions
Below is the the instruction that describes the task: ### Input: calculate the paleointensity magic parameters make some definitions ### Response: def PintPars(datablock, araiblock, zijdblock, start, end, accept, **kwargs): """ calculate the paleointensity magic parameters make some definitions """ ...
def logout(request, next_page=None): """ Redirects to CAS logout page :param: request RequestObj :param: next_page Page to redirect to """ auth.logout(request) if not next_page: next_page = _redirect_url(request) if settings.CAS_LOGOUT_COMPLETELY: return HttpResponse...
Redirects to CAS logout page :param: request RequestObj :param: next_page Page to redirect to
Below is the the instruction that describes the task: ### Input: Redirects to CAS logout page :param: request RequestObj :param: next_page Page to redirect to ### Response: def logout(request, next_page=None): """ Redirects to CAS logout page :param: request RequestObj :param: next_page P...
def export(self, nidm_version, export_dir): """ Create prov graph. """ self.stat = None if isinstance(self.stat_type, QualifiedName): stat = self.stat_type elif self.stat_type is not None: if self.stat_type.lower() == "t": stat = ST...
Create prov graph.
Below is the the instruction that describes the task: ### Input: Create prov graph. ### Response: def export(self, nidm_version, export_dir): """ Create prov graph. """ self.stat = None if isinstance(self.stat_type, QualifiedName): stat = self.stat_type e...
def doane(data): """ Modified Doane modified """ from scipy.stats import skew n = len(data) sigma = np.sqrt(6. * (n - 2.) / (n + 1.) / (n + 3.)) return 1 + np.log2(n) + \ np.log2(1 + np.abs(skew(data)) / sigma)
Modified Doane modified
Below is the the instruction that describes the task: ### Input: Modified Doane modified ### Response: def doane(data): """ Modified Doane modified """ from scipy.stats import skew n = len(data) sigma = np.sqrt(6. * (n - 2.) / (n + 1.) / (n + 3.)) return 1 + ...
def monte_carlo_vol(self, ctrs, ndraws=10000, rstate=None, return_overlap=False, kdtree=None): """Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of cubes. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube. Use...
Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of cubes. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube. Uses a K-D Tree to perform the search if provided.
Below is the the instruction that describes the task: ### Input: Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of cubes. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube. Uses a K-D Tree to perform the search if provided. ### R...
def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["network_name"]: net = network break else: return None # Succe...
Return a NIC spec
Below is the the instruction that describes the task: ### Input: Return a NIC spec ### Response: def create_nic(client, target, nic): """Return a NIC spec""" # Iterate through the networks and look for one matching # the requested name for network in target.network: if network.name == nic["...
def is_draft(request): """ A request is considered to be in draft mode if: - it is for *any* admin resource, since the admin site deals only with draft objects and hides the published version from admin users - it is for *any* view in *any* app that deals only with draft object...
A request is considered to be in draft mode if: - it is for *any* admin resource, since the admin site deals only with draft objects and hides the published version from admin users - it is for *any* view in *any* app that deals only with draft objects - user is a member of the "Conten...
Below is the the instruction that describes the task: ### Input: A request is considered to be in draft mode if: - it is for *any* admin resource, since the admin site deals only with draft objects and hides the published version from admin users - it is for *any* view in *any* app that de...
def _process(self, request, result=None): """ Process the rules for the request. :param request: The Request object provided by WebOb. :param result: The Result object to store the results in. If None, one will be allocated. :returns: A Result object, co...
Process the rules for the request. :param request: The Request object provided by WebOb. :param result: The Result object to store the results in. If None, one will be allocated. :returns: A Result object, containing the selected version and content ty...
Below is the the instruction that describes the task: ### Input: Process the rules for the request. :param request: The Request object provided by WebOb. :param result: The Result object to store the results in. If None, one will be allocated. :returns: A Result obj...
def get_waveform_filter_norm(approximant, psd, length, delta_f, f_lower): """ Return the normalization vector for the approximant """ if approximant in _filter_norms: return _filter_norms[approximant](psd, length, delta_f, f_lower) else: return None
Return the normalization vector for the approximant
Below is the the instruction that describes the task: ### Input: Return the normalization vector for the approximant ### Response: def get_waveform_filter_norm(approximant, psd, length, delta_f, f_lower): """ Return the normalization vector for the approximant """ if approximant in _filter_norms: ...