code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def create_objective_bank_hierarchy(self, alias, desc, genus): """ Create a bank hierarchy with the given alias :param alias: :return: """ url_path = self._urls.hierarchy() data = { 'id': re.sub(r'[ ]', '', alias.lower()), 'displayName': { ...
Create a bank hierarchy with the given alias :param alias: :return:
Below is the the instruction that describes the task: ### Input: Create a bank hierarchy with the given alias :param alias: :return: ### Response: def create_objective_bank_hierarchy(self, alias, desc, genus): """ Create a bank hierarchy with the given alias :param alias: ...
def _do_mutate_retryable_rows(self): """Mutate all the rows that are eligible for retry. A row is eligible for retry if it has not been tried or if it resulted in a transient error in a previous call. :rtype: list :return: The responses statuses, which is a list of ...
Mutate all the rows that are eligible for retry. A row is eligible for retry if it has not been tried or if it resulted in a transient error in a previous call. :rtype: list :return: The responses statuses, which is a list of :class:`~google.rpc.status_pb2.Status`. ...
Below is the the instruction that describes the task: ### Input: Mutate all the rows that are eligible for retry. A row is eligible for retry if it has not been tried or if it resulted in a transient error in a previous call. :rtype: list :return: The responses statuses, which is a...
def build_disagg_matrix(bdata, bin_edges, sid, mon=Monitor): """ :param bdata: a dictionary of probabilities of no exceedence :param bin_edges: bin edges :param sid: site index :param mon: a Monitor instance :returns: a dictionary key -> matrix|pmf for each key in bdata """ with mon('bui...
:param bdata: a dictionary of probabilities of no exceedence :param bin_edges: bin edges :param sid: site index :param mon: a Monitor instance :returns: a dictionary key -> matrix|pmf for each key in bdata
Below is the the instruction that describes the task: ### Input: :param bdata: a dictionary of probabilities of no exceedence :param bin_edges: bin edges :param sid: site index :param mon: a Monitor instance :returns: a dictionary key -> matrix|pmf for each key in bdata ### Response: def build_disa...
def wait_transition(resource, from_states, to_state, state_getter=attrgetter('state')): """ Wait until the specified EC2 resource (instance, image, volume, ...) transitions from any of the given 'from' states to the specified 'to' state. If the instance is found in a state other that...
Wait until the specified EC2 resource (instance, image, volume, ...) transitions from any of the given 'from' states to the specified 'to' state. If the instance is found in a state other that the to state or any of the from states, an exception will be thrown. :param resource: the resource to monitor ...
Below is the the instruction that describes the task: ### Input: Wait until the specified EC2 resource (instance, image, volume, ...) transitions from any of the given 'from' states to the specified 'to' state. If the instance is found in a state other that the to state or any of the from states, an excepti...
def digest_secure_bootloader(args): """ Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. """ if args.iv is not None: print("WARNING: --iv argument is for TESTING PURPOSES ONLY...
Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader.
Below is the the instruction that describes the task: ### Input: Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. ### Response: def digest_secure_bootloader(args): """ Calculate the ...
def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path in os.environ["PATH"].split(os.pathsep): abspath = osp.join(path, basename) if osp.isfile(abspath): return abspath
Return program absolute path if installed in PATH. Otherwise, return None
Below is the the instruction that describes the task: ### Input: Return program absolute path if installed in PATH. Otherwise, return None ### Response: def is_program_installed(basename): """ Return program absolute path if installed in PATH. Otherwise, return None """ for path i...
def command(self, *args, **kwargs): """ Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a grou...
Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use unless a group overrides it. :param context_settings: an opti...
Below is the the instruction that describes the task: ### Input: Commands are the basic building block of command line interfaces in Click. A basic command handles command line parsing and might dispatch more parsing to commands nested below it. :param name: the name of the command to use ...
def segment_volumes(neurites, neurite_type=NeuriteType.all): '''Volumes of the segments in a collection of neurites''' def _func(sec): '''list of segment volumes of a section''' return [morphmath.segment_volume(seg) for seg in zip(sec.points[:-1], sec.points[1:])] return map_segments(_func,...
Volumes of the segments in a collection of neurites
Below is the the instruction that describes the task: ### Input: Volumes of the segments in a collection of neurites ### Response: def segment_volumes(neurites, neurite_type=NeuriteType.all): '''Volumes of the segments in a collection of neurites''' def _func(sec): '''list of segment volumes of a s...
def add_case(self, case_obj): """Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case) """ for ind_obj in case_obj.individuals: self._add_individual(ind_obj) logger.debug("Adding case {0} to plugin...
Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case)
Below is the the instruction that describes the task: ### Input: Add a case obj with individuals to adapter Args: case_obj (puzzle.models.Case) ### Response: def add_case(self, case_obj): """Add a case obj with individuals to adapter Args: ...
def create_release(): """Creates a new release candidate for a build.""" build = g.build release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 'release_name required') url = request.form.get('url') utils.jsonify_assert(release_name, 'url required') release = mod...
Creates a new release candidate for a build.
Below is the the instruction that describes the task: ### Input: Creates a new release candidate for a build. ### Response: def create_release(): """Creates a new release candidate for a build.""" build = g.build release_name = request.form.get('release_name') utils.jsonify_assert(release_name, 're...
def sampleset(self, factor_bbox=10.0, num=1000): """Return ``x`` array that samples the feature. Parameters ---------- factor_bbox : float Factor for ``bounding_box`` calculations. num : int Number of points to generate. """ w1, w2 = sel...
Return ``x`` array that samples the feature. Parameters ---------- factor_bbox : float Factor for ``bounding_box`` calculations. num : int Number of points to generate.
Below is the the instruction that describes the task: ### Input: Return ``x`` array that samples the feature. Parameters ---------- factor_bbox : float Factor for ``bounding_box`` calculations. num : int Number of points to generate. ### Response: def sampl...
def count(self) -> "CountQuery": """ Return count of objects in queryset instead of objects. """ return CountQuery( db=self._db, model=self.model, q_objects=self._q_objects, annotations=self._annotations, custom_filters=self._cu...
Return count of objects in queryset instead of objects.
Below is the the instruction that describes the task: ### Input: Return count of objects in queryset instead of objects. ### Response: def count(self) -> "CountQuery": """ Return count of objects in queryset instead of objects. """ return CountQuery( db=self._db, ...
def parse(self, dictionary=None, end_token=None): """ Parse through the tokens. Finding names and values. This is called at the start of parsing the config but is also called to parse module definitions. """ self.level += 1 name = [] if dictionary is None:...
Parse through the tokens. Finding names and values. This is called at the start of parsing the config but is also called to parse module definitions.
Below is the the instruction that describes the task: ### Input: Parse through the tokens. Finding names and values. This is called at the start of parsing the config but is also called to parse module definitions. ### Response: def parse(self, dictionary=None, end_token=None): """ ...
def to_dict(cls): """Make dictionary version of enumerated class. Dictionary created this way can be used with def_num. Returns: A dict (name) -> number """ return dict((item.name, item.number) for item in iter(cls))
Make dictionary version of enumerated class. Dictionary created this way can be used with def_num. Returns: A dict (name) -> number
Below is the the instruction that describes the task: ### Input: Make dictionary version of enumerated class. Dictionary created this way can be used with def_num. Returns: A dict (name) -> number ### Response: def to_dict(cls): """Make dictionary version of enumerated class. ...
def _get_tokens(morph_fd): '''split a file-like into tokens: split on whitespace Note: this also strips newlines and comments ''' for line in morph_fd: line = line.rstrip() # remove \r\n line = line.split(';', 1)[0] # strip comments squash_token = [] # quoted strings get squ...
split a file-like into tokens: split on whitespace Note: this also strips newlines and comments
Below is the the instruction that describes the task: ### Input: split a file-like into tokens: split on whitespace Note: this also strips newlines and comments ### Response: def _get_tokens(morph_fd): '''split a file-like into tokens: split on whitespace Note: this also strips newlines and comments ...
def fit_interval_censoring( self, lower_bound, upper_bound, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None, ): # pylint: disable=too-many-arguments ...
Fit the model to an interval censored dataset. Parameters ---------- lower_bound: an array, or pd.Series length n, the start of the period the subject experienced the event in. upper_bound: an array, or pd.Series length n, the end of the period the subject experience...
Below is the the instruction that describes the task: ### Input: Fit the model to an interval censored dataset. Parameters ---------- lower_bound: an array, or pd.Series length n, the start of the period the subject experienced the event in. upper_bound: an array, or pd.Se...
def device_sdr_entries(self): """A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0xffff is returned. """ reservation_id = self.reserve_device_sdr_repository() record_id = 0 while True: record = self.get_device_sdr(record_id, res...
A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0xffff is returned.
Below is the the instruction that describes the task: ### Input: A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0xffff is returned. ### Response: def device_sdr_entries(self): """A generator that returns the SDR list. Starting with ID=0x0000 and end when ID=0...
def _update_object(object_key: str, event: Event): """Update the events list and events data for the object. - Adds the event Id to the list of events for the object. - Adds the event data to the hash of object event data keyed by event id. Args: object_key (str): Key of the object being...
Update the events list and events data for the object. - Adds the event Id to the list of events for the object. - Adds the event data to the hash of object event data keyed by event id. Args: object_key (str): Key of the object being updated. event (Event): Event object
Below is the the instruction that describes the task: ### Input: Update the events list and events data for the object. - Adds the event Id to the list of events for the object. - Adds the event data to the hash of object event data keyed by event id. Args: object_key (str): Key of the o...
def spotlight_search_route(context, request): """The spotlight search route """ catalogs = [ CATALOG_ANALYSIS_REQUEST_LISTING, "portal_catalog", "bika_setup_catalog", "bika_catalog", "bika_catalog_worksheet_listing" ] search_results = [] for catalog in ca...
The spotlight search route
Below is the the instruction that describes the task: ### Input: The spotlight search route ### Response: def spotlight_search_route(context, request): """The spotlight search route """ catalogs = [ CATALOG_ANALYSIS_REQUEST_LISTING, "portal_catalog", "bika_setup_catalog", ...
def add(T, w, i=0): """ :param T: trie :param string w: word to be added to T :returns: new trie consisting of w added into T :complexity: O(len(w)) """ if T is None: T = Trie_Node() if i == len(w): T.isWord = True else: T.s[w[i]] = add(T.s[w[i]], w, i + 1) ...
:param T: trie :param string w: word to be added to T :returns: new trie consisting of w added into T :complexity: O(len(w))
Below is the the instruction that describes the task: ### Input: :param T: trie :param string w: word to be added to T :returns: new trie consisting of w added into T :complexity: O(len(w)) ### Response: def add(T, w, i=0): """ :param T: trie :param string w: word to be added to T :retu...
def count_history(self, request, *args, **kwargs): """ To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: ...
To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: .. code-block:: javascript [ { ...
Below is the the instruction that describes the task: ### Input: To get a historical data of events amount - run **GET** against */api/events/count/history/*. Endpoint support same filters as events list. More about historical data - read at section *Historical data*. Response example: ...
def begin(self): """Generate the beginning part""" self.out_f.write('\n') for depth, name in enumerate(self.names): self.out_f.write( '{0}namespace {1}\n{0}{{\n'.format(self.prefix(depth), name) )
Generate the beginning part
Below is the the instruction that describes the task: ### Input: Generate the beginning part ### Response: def begin(self): """Generate the beginning part""" self.out_f.write('\n') for depth, name in enumerate(self.names): self.out_f.write( '{0}namespace {1}\n{0}...
def _handle_azure_exception(): """ Handles Azure exception and convert to class IO exceptions Raises: OSError subclasses: IO error. """ try: yield except _AzureHttpError as exception: if exception.status_code in _ERROR_CODES: raise _ERROR_CODES[exception.sta...
Handles Azure exception and convert to class IO exceptions Raises: OSError subclasses: IO error.
Below is the the instruction that describes the task: ### Input: Handles Azure exception and convert to class IO exceptions Raises: OSError subclasses: IO error. ### Response: def _handle_azure_exception(): """ Handles Azure exception and convert to class IO exceptions Raises: OSE...
def get_loc_files(galaxy_base): """ get dictionary of loc_type: loc_file, .loc files in the galaxy base for example: {"bwa": "/galaxy_base_path/tool-dir/bwa_index.loc"} """ return {k: os.path.join(galaxy_base, "tool-data", v) for k, v in REF_FILES.items()}
get dictionary of loc_type: loc_file, .loc files in the galaxy base for example: {"bwa": "/galaxy_base_path/tool-dir/bwa_index.loc"}
Below is the the instruction that describes the task: ### Input: get dictionary of loc_type: loc_file, .loc files in the galaxy base for example: {"bwa": "/galaxy_base_path/tool-dir/bwa_index.loc"} ### Response: def get_loc_files(galaxy_base): """ get dictionary of loc_type: loc_file, .loc files in the...
def apply_new_global_variable_name(self, path, new_gv_name): """Change global variable name/key according handed string Updates the global variable name only if different and already in list store. :param path: The path identifying the edited global variable tree view row, can be str, int or t...
Change global variable name/key according handed string Updates the global variable name only if different and already in list store. :param path: The path identifying the edited global variable tree view row, can be str, int or tuple. :param str new_gv_name: New global variable name
Below is the the instruction that describes the task: ### Input: Change global variable name/key according handed string Updates the global variable name only if different and already in list store. :param path: The path identifying the edited global variable tree view row, can be str, int or tupl...
def persistent_id(self, obj): """ Tags objects with a persistent ID, but do NOT emit it """ if getattr(obj, '_PERSIST_REFERENCES', None): objid = id(obj) obj._persistent_ref = objid _weakmemos[objid] = obj return None
Tags objects with a persistent ID, but do NOT emit it
Below is the the instruction that describes the task: ### Input: Tags objects with a persistent ID, but do NOT emit it ### Response: def persistent_id(self, obj): """ Tags objects with a persistent ID, but do NOT emit it """ if getattr(obj, '_PERSIST_REFERENCES', None): objid = ...
def js_adaptor(buffer): """ convert javascript objects like true, none, NaN etc. to quoted word. Arguments: buffer: string to be converted Returns: string after conversion """ buffer = re.sub('true', 'True', buffer) buffer = re.sub('false', 'False', buffer) buffer = re....
convert javascript objects like true, none, NaN etc. to quoted word. Arguments: buffer: string to be converted Returns: string after conversion
Below is the the instruction that describes the task: ### Input: convert javascript objects like true, none, NaN etc. to quoted word. Arguments: buffer: string to be converted Returns: string after conversion ### Response: def js_adaptor(buffer): """ convert javascript objects lik...
async def permits(self, identity, permission, context=None): """Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. """ # pylint: disable=unused-argument user = self.user_map.get(identity) if not...
Check user permissions. Return True if the identity is allowed the permission in the current context, else return False.
Below is the the instruction that describes the task: ### Input: Check user permissions. Return True if the identity is allowed the permission in the current context, else return False. ### Response: async def permits(self, identity, permission, context=None): """Check user permissions. ...
def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous operator. """ try: prev_op, prev_op_binding = self.nested_ops[-2] except IndexError: prev_op, prev_op_binding = None, 0 try: ...
Return the difference betweens the binding levels of the current and the previous operator.
Below is the the instruction that describes the task: ### Input: Return the difference betweens the binding levels of the current and the previous operator. ### Response: def diff_binding(self) -> int: """Return the difference betweens the binding levels of the current and the previous oper...
def _read_configuration_file(self, path): """Try to read and parse `path` as a configuration file. If the configurations were illegal (checked with `self._validate_options`), raises `IllegalConfiguration`. Returns (options, should_inherit). """ parser = RawConfigParser...
Try to read and parse `path` as a configuration file. If the configurations were illegal (checked with `self._validate_options`), raises `IllegalConfiguration`. Returns (options, should_inherit).
Below is the the instruction that describes the task: ### Input: Try to read and parse `path` as a configuration file. If the configurations were illegal (checked with `self._validate_options`), raises `IllegalConfiguration`. Returns (options, should_inherit). ### Response: def _read_conf...
def encode_token(self, token): """Encode Authorization token, return bytes token""" key = current_app.secret_key if key is None: raise RuntimeError( "please set app.secret_key before generate token") return jwt.encode(token, key, algorithm=self.config["algorit...
Encode Authorization token, return bytes token
Below is the the instruction that describes the task: ### Input: Encode Authorization token, return bytes token ### Response: def encode_token(self, token): """Encode Authorization token, return bytes token""" key = current_app.secret_key if key is None: raise RuntimeError( ...
def _prm_write_into_pytable(self, tablename, data, hdf5_group, fullname, **kwargs): """Stores data as pytable. :param tablename: Name of the data table :param data: Data to store :param hdf5_group: Group node where to store data in hdf5 file ...
Stores data as pytable. :param tablename: Name of the data table :param data: Data to store :param hdf5_group: Group node where to store data in hdf5 file :param fullname: Full name of the `data_to_store`s original container, only n...
Below is the the instruction that describes the task: ### Input: Stores data as pytable. :param tablename: Name of the data table :param data: Data to store :param hdf5_group: Group node where to store data in hdf5 file :param fullname: ...
def print(self, txt: str, hold: bool=False) -> None: """ Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return: "...
Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return:
Below is the the instruction that describes the task: ### Input: Conditionally print txt :param txt: text to print :param hold: If true, hang on to the text until another print comes through :param hold: If true, drop both print statements if another hasn't intervened :return: ### R...
def get_settings(config_uri, section=None, defaults=None): """ Load the settings from a named section. .. code-block:: python settings = plaster.get_settings(...) print(settings['foo']) :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param se...
Load the settings from a named section. .. code-block:: python settings = plaster.get_settings(...) print(settings['foo']) :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param section: The name of the section in the config file. If this is `...
Below is the the instruction that describes the task: ### Input: Load the settings from a named section. .. code-block:: python settings = plaster.get_settings(...) print(settings['foo']) :param config_uri: Anything that can be parsed by :func:`plaster.parse_uri`. :param sect...
def streaming_recognize( self, config, requests, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, ): """Perform bi-directional speech recognition. This method allows you to receive results while sending audio; ...
Perform bi-directional speech recognition. This method allows you to receive results while sending audio; it is only available via. gRPC (not REST). .. warning:: This method is EXPERIMENTAL. Its interface might change in the future. Example: >>> from...
Below is the the instruction that describes the task: ### Input: Perform bi-directional speech recognition. This method allows you to receive results while sending audio; it is only available via. gRPC (not REST). .. warning:: This method is EXPERIMENTAL. Its interface might c...
def c_Duffy(z, m, h=h): """Concentration from c(M) relation published in Duffy et al. (2008). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hu...
Concentration from c(M) relation published in Duffy et al. (2008). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar masses. h : float, optional Hubble parameter. Default is from...
Below is the the instruction that describes the task: ### Input: Concentration from c(M) relation published in Duffy et al. (2008). Parameters ---------- z : float or array_like Redshift(s) of halos. m : float or array_like Mass(es) of halos (m200 definition), in units of solar mass...
def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recursive_insert(node, [item[0], item[1]], item[-1], start, end)
loops through all the data and inserts them into the empty tree
Below is the the instruction that describes the task: ### Input: loops through all the data and inserts them into the empty tree ### Response: def insert_data(self, node, data, start, end): """loops through all the data and inserts them into the empty tree""" for item in data: self.recu...
def get_authenticated_user(self, callback): """Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods. """ # Verify the OpenID response via...
Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods.
Below is the the instruction that describes the task: ### Input: Fetches the authenticated user data upon redirect. This method should be called by the handler that receives the redirect from the authenticate_redirect() or authorize_redirect() methods. ### Response: def get_authenticated_u...
def nodeName(self, nodeName): """ The node name. Is used to construct the nodePath""" assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName = nodeName self._recursiveSetNodePath(self._constructNodePath())
The node name. Is used to construct the nodePath
Below is the the instruction that describes the task: ### Input: The node name. Is used to construct the nodePath ### Response: def nodeName(self, nodeName): """ The node name. Is used to construct the nodePath""" assert '/' not in nodeName, "nodeName may not contain slashes" self._nodeName...
def _fit(self, dataset): """Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk. Args: :dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors. Returns: A TFModel representing the trained ...
Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk. Args: :dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors. Returns: A TFModel representing the trained model, backed on disk by a Tenso...
Below is the the instruction that describes the task: ### Input: Trains a TensorFlow model and returns a TFModel instance with the same args/params pointing to a checkpoint or saved_model on disk. Args: :dataset: A Spark DataFrame with columns that will be mapped to TensorFlow tensors. Returns: ...
def get_next_slip(raw): """ Get the next slip packet from raw data. Returns the extracted packet plus the raw data with the remaining data stream. """ if not is_slip(raw): return None, raw length = raw[1:].index(SLIP_END) slip_packet = decode(raw[1:length+1]) new_raw = raw[lengt...
Get the next slip packet from raw data. Returns the extracted packet plus the raw data with the remaining data stream.
Below is the the instruction that describes the task: ### Input: Get the next slip packet from raw data. Returns the extracted packet plus the raw data with the remaining data stream. ### Response: def get_next_slip(raw): """ Get the next slip packet from raw data. Returns the extracted packet pl...
def add_severity(self, name, value): """Add a severity to the variant Args: name (str): The name of the severity value : The value of the severity """ logger.debug("Adding severity {0} with value {1} to variant {2}".format( name, value, se...
Add a severity to the variant Args: name (str): The name of the severity value : The value of the severity
Below is the the instruction that describes the task: ### Input: Add a severity to the variant Args: name (str): The name of the severity value : The value of the severity ### Response: def add_severity(self, name, value): """Add a severity to the variant ...
def _get_catalogue_bin_limits(catalogue, dmag): """ Returns the magnitude bins corresponing to the catalogue """ mag_bins = np.arange( float(np.floor(np.min(catalogue.data['magnitude']))) - dmag, float(np.ceil(np.max(catalogue.data['magnitude']))) + dmag, dmag) counter = np.h...
Returns the magnitude bins corresponing to the catalogue
Below is the the instruction that describes the task: ### Input: Returns the magnitude bins corresponing to the catalogue ### Response: def _get_catalogue_bin_limits(catalogue, dmag): """ Returns the magnitude bins corresponing to the catalogue """ mag_bins = np.arange( float(np.floor(np.mi...
def process_streamer(self, streamer, callback=None): """Start streaming a streamer. Args: streamer (DataStreamer): The streamer itself. callback (callable): An optional callable that will be called as: callable(index, success, highest_id_received_from_other_side)...
Start streaming a streamer. Args: streamer (DataStreamer): The streamer itself. callback (callable): An optional callable that will be called as: callable(index, success, highest_id_received_from_other_side)
Below is the the instruction that describes the task: ### Input: Start streaming a streamer. Args: streamer (DataStreamer): The streamer itself. callback (callable): An optional callable that will be called as: callable(index, success, highest_id_received_from_other_...
def account_create(self, wallet, work=True): """ Creates a new account, insert next deterministic key in **wallet** .. enable_control required :param wallet: Wallet to insert new account into :type wallet: str :param work: If false, disables work generation after creat...
Creates a new account, insert next deterministic key in **wallet** .. enable_control required :param wallet: Wallet to insert new account into :type wallet: str :param work: If false, disables work generation after creating account :type work: bool :raises: :py:exc:`n...
Below is the the instruction that describes the task: ### Input: Creates a new account, insert next deterministic key in **wallet** .. enable_control required :param wallet: Wallet to insert new account into :type wallet: str :param work: If false, disables work generation after c...
def __setup_native_run(self): # These options are appended to mounted volume arguments # NOTE: This tells Docker to re-label the directory for compatibility # with SELinux. See `man docker-run` for more information. self.vol_opts = ['z'] # Pass variables to scubainit se...
Normally, if the user provides no command to "docker run", the image's default CMD is run. Because we set the entrypiont, scuba must emulate the default behavior itself.
Below is the the instruction that describes the task: ### Input: Normally, if the user provides no command to "docker run", the image's default CMD is run. Because we set the entrypiont, scuba must emulate the default behavior itself. ### Response: def __setup_native_run(self): # These opti...
def __indent(self, lines, indent, initial=2): """This will indent the given set of lines by normal HTML layout. An initial indent of `2*indent` will be used to account for the `<html><head>` or `<html><body>` levels.""" tagempty = re.compile(r"""<\w+(\s+[^>]*?)*/>""") tagopen = re.compile(r"""<\w+(\s+[^>]*?)*...
This will indent the given set of lines by normal HTML layout. An initial indent of `2*indent` will be used to account for the `<html><head>` or `<html><body>` levels.
Below is the the instruction that describes the task: ### Input: This will indent the given set of lines by normal HTML layout. An initial indent of `2*indent` will be used to account for the `<html><head>` or `<html><body>` levels. ### Response: def __indent(self, lines, indent, initial=2): """This will ind...
def GetMessages(self, formatter_mediator, event): """Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. eve...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, s...
Below is the the instruction that describes the task: ### Input: Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resource...
def put_message(self, queue_name, content, visibility_timeout=None, time_to_live=None, timeout=None): ''' Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, t...
Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, the message will become visible. If a visibility timeout is not specified, the default value of 0 is used. The message time-t...
Below is the the instruction that describes the task: ### Input: Adds a new message to the back of the message queue. The visibility timeout specifies the time that the message will be invisible. After the timeout expires, the message will become visible. If a visibility timeout is not s...
def answer_shipping_query(token, shipping_query_id, ok, shipping_options=None, error_message=None): """ If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping q...
If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. :param token: Bot's token (you don't need to fill this) :param shi...
Below is the the instruction that describes the task: ### Input: If you sent an invoice requesting a shipping address and the parameter is_flexible was specified, the Bot API will send an Update with a shipping_query field to the bot. Use this method to reply to shipping queries. On success, True is returned. :...
def find_conda(): """ Try to find conda on the system """ USER_HOME = os.path.expanduser('~') CONDA_HOME = os.environ.get('CONDA_HOME', '') PROGRAMDATA = os.environ.get('PROGRAMDATA', '') # Search common install paths and sys path search_paths = [ # Windows join(PROGRAMDATA, 'mi...
Try to find conda on the system
Below is the the instruction that describes the task: ### Input: Try to find conda on the system ### Response: def find_conda(): """ Try to find conda on the system """ USER_HOME = os.path.expanduser('~') CONDA_HOME = os.environ.get('CONDA_HOME', '') PROGRAMDATA = os.environ.get('PROGRAMDATA', '') ...
def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while idx < self.number_intervals: new_idx = yield idx idx += 1 if new_idx: idx = new_idx - 1
Generator that resumes from same index, or restarts from sent index.
Below is the the instruction that describes the task: ### Input: Generator that resumes from same index, or restarts from sent index. ### Response: def index_iterator(self): """ Generator that resumes from same index, or restarts from sent index. """ idx = 0 # index while i...
def get_generation(self, *tables, **kwargs): """Get the generation key for any number of tables.""" db = kwargs.get('db', 'default') if len(tables) > 1: return self.get_multi_generation(tables, db) return self.get_single_generation(tables[0], db)
Get the generation key for any number of tables.
Below is the the instruction that describes the task: ### Input: Get the generation key for any number of tables. ### Response: def get_generation(self, *tables, **kwargs): """Get the generation key for any number of tables.""" db = kwargs.get('db', 'default') if len(tables) > 1: ...
def _to_star(self): """Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NMR-STAR or CIF formatted string. :return: NMR-STAR string. :rtype: :py:class:`str` """ star_str = io.StringIO() self.print_file(star_str) return star_str.getvalue()
Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NMR-STAR or CIF formatted string. :return: NMR-STAR string. :rtype: :py:class:`str`
Below is the the instruction that describes the task: ### Input: Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NMR-STAR or CIF formatted string. :return: NMR-STAR string. :rtype: :py:class:`str` ### Response: def _to_star(self): """Save :class:`~nmrstarlib.nmrstarlib.StarFile` into NM...
def _set_vrrpv3e(self, v, load=False): """ Setter method for vrrpv3e, mapped from YANG variable /routing_system/interface/ve/ipv6/vrrpv3e (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrrpv3e is considered as a private method. Backends looking to populate th...
Setter method for vrrpv3e, mapped from YANG variable /routing_system/interface/ve/ipv6/vrrpv3e (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrrpv3e is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._s...
Below is the the instruction that describes the task: ### Input: Setter method for vrrpv3e, mapped from YANG variable /routing_system/interface/ve/ipv6/vrrpv3e (list) If this variable is read-only (config: false) in the source YANG file, then _set_vrrpv3e is considered as a private method. Backends look...
def register(self, other, **kwargs): """ Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point. Parameters ------------ mesh : trimesh.Trimesh object Mesh to al...
Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point. Parameters ------------ mesh : trimesh.Trimesh object Mesh to align with other other : trimesh.Trimesh or (n, 3) ...
Below is the the instruction that describes the task: ### Input: Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point. Parameters ------------ mesh : trimesh.Trimesh object ...
def PSRK_groups(self): r'''Dictionary of PSRK subgroup: count groups for the PSRK subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_. Examples -------- >>> pprint(Chemical('Cumene').PSRK_groups) {1: 2, 9: 5, 13: 1} ''' ...
r'''Dictionary of PSRK subgroup: count groups for the PSRK subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_. Examples -------- >>> pprint(Chemical('Cumene').PSRK_groups) {1: 2, 9: 5, 13: 1}
Below is the the instruction that describes the task: ### Input: r'''Dictionary of PSRK subgroup: count groups for the PSRK subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_. Examples -------- >>> pprint(Chemical('Cumene').PSRK_groups) ...
def irange(self, minimum=None, maximum=None, inclusive=(True, True), reverse=False): """ Create an iterator of values between `minimum` and `maximum`. `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respe...
Create an iterator of values between `minimum` and `maximum`. `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respectively. The default is (True, True) such that the range is inclusive of both minimum and maximum. ...
Below is the the instruction that describes the task: ### Input: Create an iterator of values between `minimum` and `maximum`. `inclusive` is a pair of booleans that indicates whether the minimum and maximum ought to be included in the range, respectively. The default is (True, True) such t...
def wait_until(time_label): ''' Calculates the number of seconds that the process needs to sleep ''' if time_label == 'next_minute': gevent.sleep(60 - int(time.time()) % 60) elif time_label == 'next_hour': gevent.sleep(3600 - int(time.time()) % 3600) elif time_label == 'tomorrow...
Calculates the number of seconds that the process needs to sleep
Below is the the instruction that describes the task: ### Input: Calculates the number of seconds that the process needs to sleep ### Response: def wait_until(time_label): ''' Calculates the number of seconds that the process needs to sleep ''' if time_label == 'next_minute': gevent.sleep(...
def get_vnetwork_hosts_input_vcenter(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_hosts = ET.Element("get_vnetwork_hosts") config = get_vnetwork_hosts input = ET.SubElement(get_vnetwork_hosts, "input") vcenter = ET.SubElem...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_vnetwork_hosts_input_vcenter(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_vnetwork_hosts = ET.Element("get_vnetwork_hosts") config = ge...
def resource_list(cls): """ Get the possible list of resources (name, id and vhosts). """ items = cls.list({'items_per_page': 500}) ret = [paas['name'] for paas in items] ret.extend([str(paas['id']) for paas in items]) for paas in items: paas = cls.info(paas['id']) ...
Get the possible list of resources (name, id and vhosts).
Below is the the instruction that describes the task: ### Input: Get the possible list of resources (name, id and vhosts). ### Response: def resource_list(cls): """ Get the possible list of resources (name, id and vhosts). """ items = cls.list({'items_per_page': 500}) ret = [paas['name'] fo...
def put(properties, ttl=None, ctx=None): """Decorator dedicated to put properties on an element. """ def put_on(elt): return put_properties(elt=elt, properties=properties, ttl=ttl, ctx=ctx) return put_on
Decorator dedicated to put properties on an element.
Below is the the instruction that describes the task: ### Input: Decorator dedicated to put properties on an element. ### Response: def put(properties, ttl=None, ctx=None): """Decorator dedicated to put properties on an element. """ def put_on(elt): return put_properties(elt=elt, properties=pr...
def get_content(self, url, params=None, limit=0, place_holder=None, root_field='data', thing_field='children', after_field='after', object_filter=None, **kwargs): """A generator method to return reddit content from a URL. Starts at the initial url, and fetches co...
A generator method to return reddit content from a URL. Starts at the initial url, and fetches content using the `after` JSON data until `limit` entries have been fetched, or the `place_holder` has been reached. :param url: the url to start fetching content from :param params: ...
Below is the the instruction that describes the task: ### Input: A generator method to return reddit content from a URL. Starts at the initial url, and fetches content using the `after` JSON data until `limit` entries have been fetched, or the `place_holder` has been reached. :para...
def process(self): "Process the inner datasets." xp,yp = self.get_processors() for ds,n in zip(self.lists, ['train','valid','test']): ds.process(xp, yp, name=n) #progress_bar clear the outputs so in some case warnings issued during processing disappear. for ds in self.lists: ...
Process the inner datasets.
Below is the the instruction that describes the task: ### Input: Process the inner datasets. ### Response: def process(self): "Process the inner datasets." xp,yp = self.get_processors() for ds,n in zip(self.lists, ['train','valid','test']): ds.process(xp, yp, name=n) #progress_bar c...
def create_dataset(self, owner_id, **kwargs): """Create a new dataset :param owner_id: Username of the owner of the new dataset :type owner_id: str :param title: Dataset title (will be used to generate dataset id on creation) :type title: str :param descripti...
Create a new dataset :param owner_id: Username of the owner of the new dataset :type owner_id: str :param title: Dataset title (will be used to generate dataset id on creation) :type title: str :param description: Dataset description :type description: str, o...
Below is the the instruction that describes the task: ### Input: Create a new dataset :param owner_id: Username of the owner of the new dataset :type owner_id: str :param title: Dataset title (will be used to generate dataset id on creation) :type title: str :par...
def load_exif(album): """Loads the exif data of all images in an album from cache""" if not hasattr(album.gallery, "exifCache"): _restore_cache(album.gallery) cache = album.gallery.exifCache for media in album.medias: if media.type == "image": key = os.path.join(media.path, ...
Loads the exif data of all images in an album from cache
Below is the the instruction that describes the task: ### Input: Loads the exif data of all images in an album from cache ### Response: def load_exif(album): """Loads the exif data of all images in an album from cache""" if not hasattr(album.gallery, "exifCache"): _restore_cache(album.gallery) ...
def get_activity_objective_bank_session(self, proxy): """Gets the session for retrieving activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankSession) - an ``ActivityObjectiveBankSession`` raise: Null...
Gets the session for retrieving activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankSession) - an ``ActivityObjectiveBankSession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed ...
Below is the the instruction that describes the task: ### Input: Gets the session for retrieving activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankSession) - an ``ActivityObjectiveBankSession`` raise: ...
def import_symbol(name=None, path=None, typename=None, base_path=None): """ Import a module, or a typename within a module from its name. Arguments: name: An absolute or relative (starts with a .) Python path path: If name is relative, path is prepended to it. base_path: (DEPRECATED) Same as p...
Import a module, or a typename within a module from its name. Arguments: name: An absolute or relative (starts with a .) Python path path: If name is relative, path is prepended to it. base_path: (DEPRECATED) Same as path typename: (DEPRECATED) Same as path
Below is the the instruction that describes the task: ### Input: Import a module, or a typename within a module from its name. Arguments: name: An absolute or relative (starts with a .) Python path path: If name is relative, path is prepended to it. base_path: (DEPRECATED) Same as path typenam...
def nearestPoint(self, pos): """ Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y) """ # lookup subpaths for x, y, path in sel...
Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y)
Below is the the instruction that describes the task: ### Input: Returns the nearest graphing point for this item based on the inputed graph position. :param pos | <QPoint> :return (<variant> x, <variant> y) ### Response: def nearestPoint(self, pos): ...
def is_admin(self): """Is the user a system administrator""" return self.role == self.roles.administrator.value and self.state == State.approved
Is the user a system administrator
Below is the the instruction that describes the task: ### Input: Is the user a system administrator ### Response: def is_admin(self): """Is the user a system administrator""" return self.role == self.roles.administrator.value and self.state == State.approved
def away(self): """ This function handles both ecobee and nest thermostats which use a different field for away/home status. """ nest = self._last_reading.get('users_away', None) ecobee = self.profile() if nest is not None: return nest if ecobe...
This function handles both ecobee and nest thermostats which use a different field for away/home status.
Below is the the instruction that describes the task: ### Input: This function handles both ecobee and nest thermostats which use a different field for away/home status. ### Response: def away(self): """ This function handles both ecobee and nest thermostats which use a different fi...
def listTagged(self, *args, **kwargs): """ List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects. """ data = yield self.call('listTagged', *args, **kwargs) builds = [] for bdata in d...
List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects.
Below is the the instruction that describes the task: ### Input: List builds tagged with a tag. Calls "listTagged" XML-RPC. :returns: deferred that when fired returns a list of Build objects. ### Response: def listTagged(self, *args, **kwargs): """ List builds tagged with a tag. ...
def update(self, items): """ Updates the dependencies in the inverse relationship format, i.e. from an iterable or dict that is structured as `(item, dependent_items)`. The parent element `item` may occur multiple times. :param items: Iterable or dictionary in the format `(item, depende...
Updates the dependencies in the inverse relationship format, i.e. from an iterable or dict that is structured as `(item, dependent_items)`. The parent element `item` may occur multiple times. :param items: Iterable or dictionary in the format `(item, dependent_items)`. :type items: collections....
Below is the the instruction that describes the task: ### Input: Updates the dependencies in the inverse relationship format, i.e. from an iterable or dict that is structured as `(item, dependent_items)`. The parent element `item` may occur multiple times. :param items: Iterable or dictionary in th...
def fit_size_distribution_component_models(self, model_names, model_objs, input_columns, output_columns): """ This calculates 2 principal components for the hail size distribution between the shape and scale parameters. Separate machine learning models are fit to predict each component. ...
This calculates 2 principal components for the hail size distribution between the shape and scale parameters. Separate machine learning models are fit to predict each component. Args: model_names: List of machine learning model names model_objs: List of machine learning model ob...
Below is the the instruction that describes the task: ### Input: This calculates 2 principal components for the hail size distribution between the shape and scale parameters. Separate machine learning models are fit to predict each component. Args: model_names: List of machine learning ...
def decorate(fn): """ Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used internally. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine func...
Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used internally. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is not provided. Ret...
Below is the the instruction that describes the task: ### Input: Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used internally. Arguments: fn (function): target function to decorate. Raises: T...
def random_state(self): """ Generates a random state of the Markov Chain. Return Type: ------------ List of namedtuples, representing a random assignment to all variables of the model. Examples: --------- >>> from pgmpy.models import MarkovChain as MC ...
Generates a random state of the Markov Chain. Return Type: ------------ List of namedtuples, representing a random assignment to all variables of the model. Examples: --------- >>> from pgmpy.models import MarkovChain as MC >>> model = MC(['intel', 'diff'], [2, ...
Below is the the instruction that describes the task: ### Input: Generates a random state of the Markov Chain. Return Type: ------------ List of namedtuples, representing a random assignment to all variables of the model. Examples: --------- >>> from pgmpy.models im...
def apply_async(self, args, kwargs, **options): """ Put this task on the Celery queue as a singleton. Only one of this type of task with its distinguishing args/kwargs will be allowed on the queue at a time. Subsequent duplicate tasks called while this task is still running will ...
Put this task on the Celery queue as a singleton. Only one of this type of task with its distinguishing args/kwargs will be allowed on the queue at a time. Subsequent duplicate tasks called while this task is still running will just latch on to the results of the running task by synchron...
Below is the the instruction that describes the task: ### Input: Put this task on the Celery queue as a singleton. Only one of this type of task with its distinguishing args/kwargs will be allowed on the queue at a time. Subsequent duplicate tasks called while this task is still running will...
def subset_gridpoint(da, lon, lat, start_yr=None, end_yr=None): """Extract a nearest gridpoint from datarray based on lat lon coordinate. Time series can optionally be subsetted by year(s) Return a subsetted data array (or dataset) for the grid point falling nearest the input longitude and latitudecoor...
Extract a nearest gridpoint from datarray based on lat lon coordinate. Time series can optionally be subsetted by year(s) Return a subsetted data array (or dataset) for the grid point falling nearest the input longitude and latitudecoordinates. Optionally subset the data array for years falling within ...
Below is the the instruction that describes the task: ### Input: Extract a nearest gridpoint from datarray based on lat lon coordinate. Time series can optionally be subsetted by year(s) Return a subsetted data array (or dataset) for the grid point falling nearest the input longitude and latitudecoordi...
def randomSlugField(self): """ Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True) """ lst = [ "sample-slug-{}".format(uuid.uuid4().hex), "awesome-djipsum-{}".format(uuid.uuid4().hex), "unique-slug-{}".format(...
Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True)
Below is the the instruction that describes the task: ### Input: Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True) ### Response: def randomSlugField(self): """ Return the unique slug by generating the uuid4 to fix the duplicate slug (unique=True)...
def count_ref_associators(nickname, server, profile_insts, org_vm): """ Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile in...
Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in profile_insts with the result Role set to Dependent and then Antec...
Below is the the instruction that describes the task: ### Input: Get dict of counts of associator returns for ResultRole == Dependent and ResultRole == Antecedent for profiles in list. This method counts by executing repeated AssociationName calls on CIM_ReferencedProfile for each profile instance in p...
def make_grid(image_batch): """ Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid """ m, ir, ic, ch = image_batch.shape pad = 3 padded = np.zeros((m, ir + pad * 2, ic + p...
Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid
Below is the the instruction that describes the task: ### Input: Turns a batch of images into one big image. :param image_batch: ndarray, shape (batch_size, rows, cols, channels) :returns : a big image containing all `batch_size` images in a grid ### Response: def make_grid(image_batch): """ Turns a batch ...
def get_client_str(username: str, ip_address: str, user_agent: str, path_info: str) -> str: """ Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}`` """ client_d...
Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}``
Below is the the instruction that describes the task: ### Input: Get a readable string that can be used in e.g. logging to distinguish client requests. Example log format would be ``{username: "example", ip_address: "127.0.0.1", path_info: "/example/"}`` ### Response: def get_client_str(username: str, ip_addr...
def add_item_to_sonos_playlist(self, queueable_item, sonos_playlist): """Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the...
Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should be added
Below is the the instruction that describes the task: ### Input: Adds a queueable item to a Sonos' playlist. Args: queueable_item (DidlObject): the item to add to the Sonos' playlist sonos_playlist (DidlPlaylistContainer): the Sonos' playlist to which the item should...
def __initLock(self): """Init lock for sending request to projector when it is busy.""" self._isLocked = False self._timer = 0 self._operation = False
Init lock for sending request to projector when it is busy.
Below is the the instruction that describes the task: ### Input: Init lock for sending request to projector when it is busy. ### Response: def __initLock(self): """Init lock for sending request to projector when it is busy.""" self._isLocked = False self._timer = 0 self._operation =...
def decodeEntities(self, len, what, end, end2, end3): """This function is deprecated, we now always process entities content through xmlStringDecodeEntities TODO: remove it in next major release. [67] Reference ::= EntityRef | CharRef [69] PEReference ::= '%' Name ';' """ ...
This function is deprecated, we now always process entities content through xmlStringDecodeEntities TODO: remove it in next major release. [67] Reference ::= EntityRef | CharRef [69] PEReference ::= '%' Name ';'
Below is the the instruction that describes the task: ### Input: This function is deprecated, we now always process entities content through xmlStringDecodeEntities TODO: remove it in next major release. [67] Reference ::= EntityRef | CharRef [69] PEReference ::= '%' Name ';' ### R...
def _ancestors(collection): """Get the ancestors of the collection.""" for index, c in enumerate(collection.path_to_root()): if index > 0 and c.dbquery is not None: raise StopIteration yield c.name raise StopIteration
Get the ancestors of the collection.
Below is the the instruction that describes the task: ### Input: Get the ancestors of the collection. ### Response: def _ancestors(collection): """Get the ancestors of the collection.""" for index, c in enumerate(collection.path_to_root()): if index > 0 and c.dbquery is not None: raise ...
def default_update_function(self, n: Tuple[str, dict]) -> List[float]: """ The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued var...
The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued variable representing the node.
Below is the the instruction that describes the task: ### Input: The default update function for a CAG node. n: A 2-tuple containing the node name and node data. Returns: A list of values corresponding to the distribution of the value of the real-valued variable represen...
def deepcopy(original_obj): """ Creates a deep copy of an object with no crossed referenced lists or dicts, useful when loading from yaml as anchors generate those cross-referenced dicts and lists Args: original_obj(object): Object to deep copy Return: object: deep copy of the ...
Creates a deep copy of an object with no crossed referenced lists or dicts, useful when loading from yaml as anchors generate those cross-referenced dicts and lists Args: original_obj(object): Object to deep copy Return: object: deep copy of the object
Below is the the instruction that describes the task: ### Input: Creates a deep copy of an object with no crossed referenced lists or dicts, useful when loading from yaml as anchors generate those cross-referenced dicts and lists Args: original_obj(object): Object to deep copy Return: ...
def train_position_scales(self, layout, layers): """ Compute ranges for the x and y scales """ _layout = layout.layout panel_scales_x = layout.panel_scales_x panel_scales_y = layout.panel_scales_y # loop over each layer, training x and y scales in turn fo...
Compute ranges for the x and y scales
Below is the the instruction that describes the task: ### Input: Compute ranges for the x and y scales ### Response: def train_position_scales(self, layout, layers): """ Compute ranges for the x and y scales """ _layout = layout.layout panel_scales_x = layout.panel_scales_x ...
def check_membership(self, group): """ Check required group(s) """ user_groups = self.request.user.groups.values_list("name", flat=True) if isinstance(group, (list, tuple)): for req_group in group: if req_group in user_groups: return True ...
Check required group(s)
Below is the the instruction that describes the task: ### Input: Check required group(s) ### Response: def check_membership(self, group): """ Check required group(s) """ user_groups = self.request.user.groups.values_list("name", flat=True) if isinstance(group, (list, tuple)): fo...
def DXHTTPRequest(resource, data, method='POST', headers=None, auth=True, timeout=DEFAULT_TIMEOUT, use_compression=None, jsonify_data=True, want_full_response=False, decode_response_body=True, prepend_srv=True, session_handler=None, max_retries=DEF...
:param resource: API server route, e.g. "/record/new". If *prepend_srv* is False, a fully qualified URL is expected. If this argument is a callable, it will be called just before each request attempt, and expected to return a tuple (URL, headers). Headers returned by the callback are updated with *headers* (including h...
Below is the the instruction that describes the task: ### Input: :param resource: API server route, e.g. "/record/new". If *prepend_srv* is False, a fully qualified URL is expected. If this argument is a callable, it will be called just before each request attempt, and expected to return a tuple (URL, headers). Hea...
def send(self, sender: PytgbotApiBot): """ Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage """ return sender.send_media_group( # receiver, self.media, disable_notifi...
Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage
Below is the the instruction that describes the task: ### Input: Send the message via pytgbot. :param sender: The bot instance to send with. :type sender: pytgbot.bot.Bot :rtype: PytgbotApiMessage ### Response: def send(self, sender: PytgbotApiBot): """ Send the message v...
def request(self, persist_id=None): """Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation. """ node = new_ele("cancel-comm...
Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation.
Below is the the instruction that describes the task: ### Input: Cancel an ongoing confirmed commit. Depends on the `:candidate` and `:confirmed-commit` capabilities. *persist-id* value must be equal to the value given in the <persist> parameter to the previous <commit> operation. ### Response: def reques...
def osculating_elements_of(position, reference_frame=None): """Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and a ...
Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and a time. An instance of :class:`~skyfield.elementslib.OsculatingE...
Below is the the instruction that describes the task: ### Input: Produce the osculating orbital elements for a position. The ``position`` should be an :class:`~skyfield.positionlib.ICRF` instance like that returned by the ``at()`` method of any Solar System body, specifying a position, a velocity, and ...
def ping(dst, count, inter=0.2, maxwait=1000, size=64): """Sends ICMP echo requests to destination `dst` `count` times. Returns a deferred which fires when responses are finished. """ def _then(result, p): p.stopListening() return result d = defer.Deferred() p = ICMPPort(0, ICMP...
Sends ICMP echo requests to destination `dst` `count` times. Returns a deferred which fires when responses are finished.
Below is the the instruction that describes the task: ### Input: Sends ICMP echo requests to destination `dst` `count` times. Returns a deferred which fires when responses are finished. ### Response: def ping(dst, count, inter=0.2, maxwait=1000, size=64): """Sends ICMP echo requests to destination `dst` `c...
def fapply(f, x, tz=False): ''' fapply(f,x) yields the result of applying f either to x, if x is a normal value or array, or to x.data if x is a sparse matrix. Does not modify x (unless f modifiex x). The optional argument tz (default: False) may be set to True to specify that, if x is a sparse ...
fapply(f,x) yields the result of applying f either to x, if x is a normal value or array, or to x.data if x is a sparse matrix. Does not modify x (unless f modifiex x). The optional argument tz (default: False) may be set to True to specify that, if x is a sparse matrix that contains at least 1 element ...
Below is the the instruction that describes the task: ### Input: fapply(f,x) yields the result of applying f either to x, if x is a normal value or array, or to x.data if x is a sparse matrix. Does not modify x (unless f modifiex x). The optional argument tz (default: False) may be set to True to specify...
def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value): ''' Changes the value of a variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame is not None: result = pydevd_vars.change_attr_expression(frame, attr, value, dbg) else: ...
Changes the value of a variable
Below is the the instruction that describes the task: ### Input: Changes the value of a variable ### Response: def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value): ''' Changes the value of a variable ''' try: frame = dbg.find_frame(thread_id, frame_id) if frame i...
def getWorksheet(self): """ Returns the current worksheet from the list. Returns None when the iterator reaches the end of the array. """ ws = None if self._current_ws_index < len(self._worksheets): ws = self._ws_data(self._worksheets[self._current_ws_index]) ...
Returns the current worksheet from the list. Returns None when the iterator reaches the end of the array.
Below is the the instruction that describes the task: ### Input: Returns the current worksheet from the list. Returns None when the iterator reaches the end of the array. ### Response: def getWorksheet(self): """ Returns the current worksheet from the list. Returns None when the ite...
def update_menu(self): """Update context menu""" self.menu.clear() add_actions(self.menu, self.create_context_menu_actions())
Update context menu
Below is the the instruction that describes the task: ### Input: Update context menu ### Response: def update_menu(self): """Update context menu""" self.menu.clear() add_actions(self.menu, self.create_context_menu_actions())
def _get_indep_vector(wave_a, wave_b): """Create new independent variable vector.""" exobj = pexdoc.exh.addex(RuntimeError, "Independent variable ranges do not overlap") min_bound = max(np.min(wave_a.indep_vector), np.min(wave_b.indep_vector)) max_bound = min(np.max(wave_a.indep_vector), np.max(wave_b.i...
Create new independent variable vector.
Below is the the instruction that describes the task: ### Input: Create new independent variable vector. ### Response: def _get_indep_vector(wave_a, wave_b): """Create new independent variable vector.""" exobj = pexdoc.exh.addex(RuntimeError, "Independent variable ranges do not overlap") min_bound = ma...