code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def scenario_list(self, default=True): """ Metadata regarding the list of scenarios (e.g., models, scenarios, run identifier, etc.) in the connected data source. Parameter --------- default : bool, optional, default True Return *only* the default version of e...
Metadata regarding the list of scenarios (e.g., models, scenarios, run identifier, etc.) in the connected data source. Parameter --------- default : bool, optional, default True Return *only* the default version of each Scenario. Any (`model`, `scenario`) without...
Below is the the instruction that describes the task: ### Input: Metadata regarding the list of scenarios (e.g., models, scenarios, run identifier, etc.) in the connected data source. Parameter --------- default : bool, optional, default True Return *only* the default ve...
def im_files(self, room_id=None, user_name=None, **kwargs): """Retrieves the files from a direct message.""" if room_id: return self.__call_api_get('im.files', roomId=room_id, kwargs=kwargs) elif user_name: return self.__call_api_get('im.files', username=user_name, kwargs...
Retrieves the files from a direct message.
Below is the the instruction that describes the task: ### Input: Retrieves the files from a direct message. ### Response: def im_files(self, room_id=None, user_name=None, **kwargs): """Retrieves the files from a direct message.""" if room_id: return self.__call_api_get('im.files', roomI...
def warn (logname, msg, *args, **kwargs): """Log a warning. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.WARN): _log(log.warn, msg, args, **kwargs)
Log a warning. return: None
Below is the the instruction that describes the task: ### Input: Log a warning. return: None ### Response: def warn (logname, msg, *args, **kwargs): """Log a warning. return: None """ log = logging.getLogger(logname) if log.isEnabledFor(logging.WARN): _log(log.warn, msg, args, **k...
def _delete_branch_node(self, node, trie_key): """ Delete a key from inside or underneath a branch node """ if not trie_key: node[-1] = BLANK_NODE return self._normalize_branch_node(node) node_to_delete = self.get_node(node[trie_key[0]]) sub_node...
Delete a key from inside or underneath a branch node
Below is the the instruction that describes the task: ### Input: Delete a key from inside or underneath a branch node ### Response: def _delete_branch_node(self, node, trie_key): """ Delete a key from inside or underneath a branch node """ if not trie_key: node[-1] = BLA...
def stopFactory(self): """Stop the factory. See the documentation of `twisted.internet.protocol.ReconnectingClientFactory` for details. """ if self.client: yield self.client.stopProducing() protocol.ReconnectingClientFactory.stopFactory(self)
Stop the factory. See the documentation of `twisted.internet.protocol.ReconnectingClientFactory` for details.
Below is the the instruction that describes the task: ### Input: Stop the factory. See the documentation of `twisted.internet.protocol.ReconnectingClientFactory` for details. ### Response: def stopFactory(self): """Stop the factory. See the documentation of `twisted.intern...
def force_list(value, min=None, max=None): """ Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing comma that turns a single value into a list. You can optionally specify the minimum and maximum number of members. A minumum of great...
Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing comma that turns a single value into a list. You can optionally specify the minimum and maximum number of members. A minumum of greater than one will fail if the user only supplies a s...
Below is the the instruction that describes the task: ### Input: Check that a value is a list, coercing strings into a list with one member. Useful where users forget the trailing comma that turns a single value into a list. You can optionally specify the minimum and maximum number of members. A mi...
def create_packet(header, data): """Creates an IncomingPacket object from header and data This method is for testing purposes """ packet = IncomingPacket() packet.header = header packet.data = data if len(header) == HeronProtocol.HEADER_SIZE: packet.is_header_read = True if len...
Creates an IncomingPacket object from header and data This method is for testing purposes
Below is the the instruction that describes the task: ### Input: Creates an IncomingPacket object from header and data This method is for testing purposes ### Response: def create_packet(header, data): """Creates an IncomingPacket object from header and data This method is for testing purposes ""...
def get_X(self): ''' :return: term freq matrix or metadata freq matrix ''' if self._use_non_text_features: return self._term_doc_matrix._mX else: return self._term_doc_matrix._X
:return: term freq matrix or metadata freq matrix
Below is the the instruction that describes the task: ### Input: :return: term freq matrix or metadata freq matrix ### Response: def get_X(self): ''' :return: term freq matrix or metadata freq matrix ''' if self._use_non_text_features: return self._term_doc_matrix._mX else: return self._term_doc_ma...
def update_dependency_kinds(apps, schema_editor): """Update historical dependency kinds as they may be wrong.""" DataDependency = apps.get_model('flow', 'DataDependency') for dependency in DataDependency.objects.all(): # Assume dependency is of subprocess kind. dependency.kind = 'subprocess'...
Update historical dependency kinds as they may be wrong.
Below is the the instruction that describes the task: ### Input: Update historical dependency kinds as they may be wrong. ### Response: def update_dependency_kinds(apps, schema_editor): """Update historical dependency kinds as they may be wrong.""" DataDependency = apps.get_model('flow', 'DataDependency') ...
def add_song(fpath, g_songs, g_artists, g_albums): """ parse music file metadata with Easymp3 and return a song model. """ try: if fpath.endswith('mp3') or fpath.endswith('ogg') or fpath.endswith('wma'): metadata = EasyMP3(fpath) elif fpath.endswith('m4a'): me...
parse music file metadata with Easymp3 and return a song model.
Below is the the instruction that describes the task: ### Input: parse music file metadata with Easymp3 and return a song model. ### Response: def add_song(fpath, g_songs, g_artists, g_albums): """ parse music file metadata with Easymp3 and return a song model. """ try: if fpath.end...
def add(self, *names): '''Returns back a class decorator that enables registering Blox to this factory''' def decorator(blok): for name in names or (blok.__name__, ): self[name] = blok return blok return decorator
Returns back a class decorator that enables registering Blox to this factory
Below is the the instruction that describes the task: ### Input: Returns back a class decorator that enables registering Blox to this factory ### Response: def add(self, *names): '''Returns back a class decorator that enables registering Blox to this factory''' def decorator(blok): for ...
def moveOrder(self, orderNumber, rate, amount=None, postOnly=None, immediateOrCancel=None): """Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "or...
Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "orderNumber" and "rate"; you may optionally specify "amount" if you wish to change the amount of the new ...
Below is the the instruction that describes the task: ### Input: Cancels an order and places a new one of the same type in a single atomic transaction, meaning either both operations will succeed or both will fail. Required POST parameters are "orderNumber" and "rate"; you may optionally s...
def generate_node_command(command, command_opts, path): """Return node bin command list for subprocess execution.""" if which(NPX_BIN): # Use npx if available (npm v5.2+) LOGGER.debug("Using npx to invoke %s.", command) if platform.system().lower() == 'windows': cmd_list = [N...
Return node bin command list for subprocess execution.
Below is the the instruction that describes the task: ### Input: Return node bin command list for subprocess execution. ### Response: def generate_node_command(command, command_opts, path): """Return node bin command list for subprocess execution.""" if which(NPX_BIN): # Use npx if available (npm v...
def print_obj(arg, frame, format=None, short=False): """Return a string representation of an object """ try: if not frame: # ?? Should we have set up a dummy globals # to have persistence? obj = eval(arg, None, None) else: obj = eval(arg, frame.f_g...
Return a string representation of an object
Below is the the instruction that describes the task: ### Input: Return a string representation of an object ### Response: def print_obj(arg, frame, format=None, short=False): """Return a string representation of an object """ try: if not frame: # ?? Should we have set up a dummy global...
def get_jclass(classname): """ Returns the Java class object associated with the dot-notation classname. :param classname: the classname :type classname: str :return: the class object :rtype: JB_Object """ try: return javabridge.class_for_name(classname) except: retu...
Returns the Java class object associated with the dot-notation classname. :param classname: the classname :type classname: str :return: the class object :rtype: JB_Object
Below is the the instruction that describes the task: ### Input: Returns the Java class object associated with the dot-notation classname. :param classname: the classname :type classname: str :return: the class object :rtype: JB_Object ### Response: def get_jclass(classname): """ Returns t...
def randomize_nb_elements( self, number=10, le=False, ge=False, min=None, max=None): """ Returns a random value near number. :param number: value to which the result must be near :param le: result must be lower or e...
Returns a random value near number. :param number: value to which the result must be near :param le: result must be lower or equal to number :param ge: result must be greater or equal to number :returns: a random int near number
Below is the the instruction that describes the task: ### Input: Returns a random value near number. :param number: value to which the result must be near :param le: result must be lower or equal to number :param ge: result must be greater or equal to number :returns: a random int n...
def summarize(self, n_timescales_to_report=5): """Some summary information.""" nonzeros = np.sum(np.abs(self.eigenvectors_) > 0, axis=0) active = '[%s]' % ', '.join(['%d/%d' % (n, self.n_features) for n in nonzeros[:n_timescales_to_report]]) return """K-sparse time-structure Independent...
Some summary information.
Below is the the instruction that describes the task: ### Input: Some summary information. ### Response: def summarize(self, n_timescales_to_report=5): """Some summary information.""" nonzeros = np.sum(np.abs(self.eigenvectors_) > 0, axis=0) active = '[%s]' % ', '.join(['%d/%d' % (n, self.n...
def enable_service(conn, service='ceph'): """ Enable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. """ if is_systemd(conn): remoto.process.run( ...
Enable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection.
Below is the the instruction that describes the task: ### Input: Enable a service on a remote host depending on the type of init system. Obviously, this should be done for RHEL/Fedora/CentOS systems. This function does not do any kind of detection. ### Response: def enable_service(conn, service='ceph'): ...
def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ content = smart_unicode(content) uri, _, content = content.partition(u'|') if content == self.NONE: content = None return uri or None, content
Split node string to uri and content and convert back to unicode.
Below is the the instruction that describes the task: ### Input: Split node string to uri and content and convert back to unicode. ### Response: def _decode_content(self, content): """ Split node string to uri and content and convert back to unicode. """ content = smart_unicode(cont...
def trace_emit(self): """ A decorator that allows to change the trace emitter. By default Python logging is used to emit the trace data. """ def decorator(f): self.tracer.emitter = f return f return decorator
A decorator that allows to change the trace emitter. By default Python logging is used to emit the trace data.
Below is the the instruction that describes the task: ### Input: A decorator that allows to change the trace emitter. By default Python logging is used to emit the trace data. ### Response: def trace_emit(self): """ A decorator that allows to change the trace emitter. By default Pyt...
def fmt_num(num, zero_num=None): """ humanize number(9000 to 9,000) """ if zero_num is not None: num = floatformat(num, zero_num) return intcomma(num, False)
humanize number(9000 to 9,000)
Below is the the instruction that describes the task: ### Input: humanize number(9000 to 9,000) ### Response: def fmt_num(num, zero_num=None): """ humanize number(9000 to 9,000) """ if zero_num is not None: num = floatformat(num, zero_num) return intcomma(num, False)
def monte_carlo_vol(self, ndraws=10000, rstate=None, return_overlap=True): """Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of ellipsoids. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube.""" if rst...
Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of ellipsoids. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube.
Below is the the instruction that describes the task: ### Input: Using `ndraws` Monte Carlo draws, estimate the volume of the *union* of ellipsoids. If `return_overlap=True`, also returns the estimated fractional overlap with the unit cube. ### Response: def monte_carlo_vol(self, ndraws=10000, rsta...
def tfpdef(self, ident_tok, annotation_opt): """(3.0-) tfpdef: NAME [':' test]""" if annotation_opt: colon_loc, annotation = annotation_opt return self._arg(ident_tok, colon_loc, annotation) return self._arg(ident_tok)
(3.0-) tfpdef: NAME [':' test]
Below is the the instruction that describes the task: ### Input: (3.0-) tfpdef: NAME [':' test] ### Response: def tfpdef(self, ident_tok, annotation_opt): """(3.0-) tfpdef: NAME [':' test]""" if annotation_opt: colon_loc, annotation = annotation_opt return self._arg(ident_to...
def has_group_perms(self, perm, obj, approved): """ Check if group has the permission for the given object """ if not self.group: return False if self.use_smart_cache: content_type_pk = Permission.objects.get_content_type(obj).pk def _group_h...
Check if group has the permission for the given object
Below is the the instruction that describes the task: ### Input: Check if group has the permission for the given object ### Response: def has_group_perms(self, perm, obj, approved): """ Check if group has the permission for the given object """ if not self.group: return ...
def compute_log_degrees(brands, exemplars): """ For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower. """ counts = Counter() for followers in brands.values(): # + exemplars.values(): # Include exemplars in these counts? No, don't...
For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower.
Below is the the instruction that describes the task: ### Input: For each follower, let Z be the total number of brands they follow. Return a dictionary of 1. / log(Z), for each follower. ### Response: def compute_log_degrees(brands, exemplars): """ For each follower, let Z be the total number of brands th...
def timeline(self): """ >>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline 0 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline 1 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline 0 """ if self....
>>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline 0 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline 1 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline 0
Below is the the instruction that describes the task: ### Input: >>> Cluster(0, 0, 0, 0, 0, 0, 0, 0).timeline 0 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[]')).timeline 1 >>> Cluster(0, 0, 0, 0, 0, 0, 0, TimelineHistory.from_node(1, '[["a"]]')).timeline 0...
def visit_and_update_expressions(self, visitor_fn): """Create an updated version (if needed) of the ConstructResult via the visitor pattern.""" new_fields = {} for key, value in six.iteritems(self.fields): new_value = value.visit_and_update(visitor_fn) if new_value is no...
Create an updated version (if needed) of the ConstructResult via the visitor pattern.
Below is the the instruction that describes the task: ### Input: Create an updated version (if needed) of the ConstructResult via the visitor pattern. ### Response: def visit_and_update_expressions(self, visitor_fn): """Create an updated version (if needed) of the ConstructResult via the visitor pattern.""...
def parse(self): """ Parse a replay """ self.important("Parsing demo file '%s'" % (self.filename, )) with open(self.filename, 'rb') as f: reader = Reader(StringIO(f.read())) filestamp = reader.read(8) offset = reader.read_int32() ...
Parse a replay
Below is the the instruction that describes the task: ### Input: Parse a replay ### Response: def parse(self): """ Parse a replay """ self.important("Parsing demo file '%s'" % (self.filename, )) with open(self.filename, 'rb') as f: reader = Reader(StringIO(f.re...
def _diff(state_data, resource_object): '''helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update. ''' state_data['id'] = resource_object['schedule'...
helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update.
Below is the the instruction that describes the task: ### Input: helper method to compare salt state info with the PagerDuty API json structure, and determine if we need to update. returns the dict to pass to the PD API to perform the update, or empty dict if no update. ### Response: def _diff(state_data,...
def getChanges(self, request): """ Reponds only to POST events and starts the build process :arguments: request the http request object """ expected_secret = isinstance(self.options, dict) and self.options.get('secret') if expected_secret: ...
Reponds only to POST events and starts the build process :arguments: request the http request object
Below is the the instruction that describes the task: ### Input: Reponds only to POST events and starts the build process :arguments: request the http request object ### Response: def getChanges(self, request): """ Reponds only to POST events and starts the buil...
def parse_args(parser): """Process args.""" args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: util.Color.alpha_num = args.a if args.i: image_file = image.get(args.i, iterative=args.i...
Process args.
Below is the the instruction that describes the task: ### Input: Process args. ### Response: def parse_args(parser): """Process args.""" args = parser.parse_args() if args.q: logging.getLogger().disabled = True sys.stdout = sys.stderr = open(os.devnull, "w") if args.a: uti...
def assets(self) -> List[Asset]: """ Returns the assets in the transaction. """ return list(filter(is_element(Asset), self.content))
Returns the assets in the transaction.
Below is the the instruction that describes the task: ### Input: Returns the assets in the transaction. ### Response: def assets(self) -> List[Asset]: """ Returns the assets in the transaction. """ return list(filter(is_element(Asset), self.content))
def register_defaults(self): """Register default compilers, preprocessors and MIME types.""" self.mimetypes.register_defaults() self.preprocessors.register_defaults() self.postprocessors.register_defaults()
Register default compilers, preprocessors and MIME types.
Below is the the instruction that describes the task: ### Input: Register default compilers, preprocessors and MIME types. ### Response: def register_defaults(self): """Register default compilers, preprocessors and MIME types.""" self.mimetypes.register_defaults() self.preprocessors.registe...
def content_check(self, result): ''' Checks for specific types in the state output. Raises an Exception in case particular rule is broken. :param result: :return: ''' if not isinstance(result, dict): err_msg = 'Malformed state return. Data must be a d...
Checks for specific types in the state output. Raises an Exception in case particular rule is broken. :param result: :return:
Below is the the instruction that describes the task: ### Input: Checks for specific types in the state output. Raises an Exception in case particular rule is broken. :param result: :return: ### Response: def content_check(self, result): ''' Checks for specific types in the...
def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): """ Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference """ if not s...
Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference
Below is the the instruction that describes the task: ### Input: Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference ### Response: def discretize(self, contac...
def build_permuted_index(self): """ Build PermutedIndex for all your binary hashings. PermutedIndex would be used to find the neighbour bucket key in terms of Hamming distance. Permute_configs is nested dict in the following format: permuted_config = {"<hash_name>": ...
Build PermutedIndex for all your binary hashings. PermutedIndex would be used to find the neighbour bucket key in terms of Hamming distance. Permute_configs is nested dict in the following format: permuted_config = {"<hash_name>": { "num_permutation":50, ...
Below is the the instruction that describes the task: ### Input: Build PermutedIndex for all your binary hashings. PermutedIndex would be used to find the neighbour bucket key in terms of Hamming distance. Permute_configs is nested dict in the following format: permuted_config = {"<h...
def render_impl(self, template, context, at_paths=None, at_encoding=anytemplate.compat.ENCODING, **kwargs): """ Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given ...
Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :param at_encoding: Template encoding :param kwargs: Keyword arg...
Below is the the instruction that describes the task: ### Input: Render given template file and return the result. :param template: Template file path :param context: A dict or dict-like object to instantiate given template file :param at_paths: Template search paths :pa...
def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): click.echo('{type:<6} {offset:<6} {magic}'.format( type=k, magic=v['magic'].encode('hex'), offset=v...
List available types for 'smudge'
Below is the the instruction that describes the task: ### Input: List available types for 'smudge' ### Response: def available(): """ List available types for 'smudge' """ db = smudge_db.get() click.echo('{:<6} {:<6} {:<50}'.format('Type', 'Offset', 'Magic')) for k, v in db.items(): ...
def buscar_por_id(self, id_ambiente): """Obtém um ambiente a partir da chave primária (identificador). :param id_ambiente: Identificador do ambiente. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, ...
Obtém um ambiente a partir da chave primária (identificador). :param id_ambiente: Identificador do ambiente. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'link': < link >, 'id_divisao': < id_divisao >, '...
Below is the the instruction that describes the task: ### Input: Obtém um ambiente a partir da chave primária (identificador). :param id_ambiente: Identificador do ambiente. :return: Dicionário com a seguinte estrutura: :: {'ambiente': {'id': < id_ambiente >, 'lin...
def run_cell(self, raw_cell, store_history=False, silent=False): """Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell ...
Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be stored in IPython's history. For user code calling back in...
Below is the the instruction that describes the task: ### Input: Run a complete IPython cell. Parameters ---------- raw_cell : str The code (including IPython code such as %magic functions) to run. store_history : bool If True, the raw and translated cell will be...
def search_by_age(cls, *, limit=100, page=1, accounts=None, locations=None, age=720, properties=None, include_disabled=False): """Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`):...
Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list of account id's to limit the returned resources to locatio...
Below is the the instruction that describes the task: ### Input: Search for resources based on the provided filters Args: limit (`int`): Number of results to return. Default: 100 page (`int`): Pagination offset for results. Default: 1 accounts (`list` of `int`): A list o...
def get_chat_ids(self): """Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list """ updates = self.get_updates() chat_ids = [] if updates: for update in upd...
Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list
Below is the the instruction that describes the task: ### Input: Returns unique chat IDs from `/start` command messages sent to our bot by users. Those chat IDs can be used to send messages to chats. :rtype: list ### Response: def get_chat_ids(self): """Returns unique chat IDs from `/start...
def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, reward_mask, gamma=0.99): """Value optimizer step.""" value_params = trax_opt.get_pa...
Value optimizer step.
Below is the the instruction that describes the task: ### Input: Value optimizer step. ### Response: def value_opt_step(i, opt_state, opt_update, value_net_apply, padded_observations, padded_rewards, r...
def build_phenotype(phenotype_id, adapter): """Build a small phenotype object Build a dictionary with phenotype_id and description Args: phenotype_id (str): The phenotype id adapter (scout.adapter.MongoAdapter) Returns: phenotype_obj (dict): dict( phen...
Build a small phenotype object Build a dictionary with phenotype_id and description Args: phenotype_id (str): The phenotype id adapter (scout.adapter.MongoAdapter) Returns: phenotype_obj (dict): dict( phenotype_id = str, feature = str, # descri...
Below is the the instruction that describes the task: ### Input: Build a small phenotype object Build a dictionary with phenotype_id and description Args: phenotype_id (str): The phenotype id adapter (scout.adapter.MongoAdapter) Returns: phenotype_obj (dict): dict...
def add(self, src_cls, module, package=None): """ Add layer class to model. This method may be overloaded by layer. :param src_cls: layer class to add, should not start with underscores :type src_cls: str :param module: Python module that contains layer class :type modul...
Add layer class to model. This method may be overloaded by layer. :param src_cls: layer class to add, should not start with underscores :type src_cls: str :param module: Python module that contains layer class :type module: str :param package: optional package containing module ...
Below is the the instruction that describes the task: ### Input: Add layer class to model. This method may be overloaded by layer. :param src_cls: layer class to add, should not start with underscores :type src_cls: str :param module: Python module that contains layer class :type mo...
def reverse_pad(self, data, block_size): """ :meth:`.WBlockPadding.reverse_pad` method implementation """ pad_byte = data[-1] if pad_byte > block_size: raise ValueError('Invalid padding') padding = bytes([pad_byte] * pad_byte) if data[-pad_byte:] != padding: raise ValueError('Invalid padding') ret...
:meth:`.WBlockPadding.reverse_pad` method implementation
Below is the the instruction that describes the task: ### Input: :meth:`.WBlockPadding.reverse_pad` method implementation ### Response: def reverse_pad(self, data, block_size): """ :meth:`.WBlockPadding.reverse_pad` method implementation """ pad_byte = data[-1] if pad_byte > block_size: raise ValueError...
def markUnwatched(self): """ Mark video unwatched. """ key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey self._server.query(key) self.reload()
Mark video unwatched.
Below is the the instruction that describes the task: ### Input: Mark video unwatched. ### Response: def markUnwatched(self): """ Mark video unwatched. """ key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey self._server.query(key) self.reload()
def bootstrap(self, path_or_uri): """ Initialize a database. :param database_path: The absolute path to the database to initialize. """ _logger.debug("Bootstrapping new database: %s", path_or_uri) self.database_uri = _urify_db(path_or_uri) db = sa.create_engine(self.data...
Initialize a database. :param database_path: The absolute path to the database to initialize.
Below is the the instruction that describes the task: ### Input: Initialize a database. :param database_path: The absolute path to the database to initialize. ### Response: def bootstrap(self, path_or_uri): """ Initialize a database. :param database_path: The absolute path to the database...
def record_by_name(self, hostname): """ Returns dictionary with city data containing `country_code`, `country_name`, `region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`, `metro_code`, `area_code`, `region_code` and `time_zone`. :arg hostname: Hostname (e.g. exam...
Returns dictionary with city data containing `country_code`, `country_name`, `region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`, `metro_code`, `area_code`, `region_code` and `time_zone`. :arg hostname: Hostname (e.g. example.com)
Below is the the instruction that describes the task: ### Input: Returns dictionary with city data containing `country_code`, `country_name`, `region`, `city`, `postal_code`, `latitude`, `longitude`, `dma_code`, `metro_code`, `area_code`, `region_code` and `time_zone`. :arg hostname: Hostna...
def ServiceWorker_setForceUpdateOnPageLoad(self, forceUpdateOnPageLoad): """ Function path: ServiceWorker.setForceUpdateOnPageLoad Domain: ServiceWorker Method name: setForceUpdateOnPageLoad Parameters: Required arguments: 'forceUpdateOnPageLoad' (type: boolean) -> No description No return v...
Function path: ServiceWorker.setForceUpdateOnPageLoad Domain: ServiceWorker Method name: setForceUpdateOnPageLoad Parameters: Required arguments: 'forceUpdateOnPageLoad' (type: boolean) -> No description No return value.
Below is the the instruction that describes the task: ### Input: Function path: ServiceWorker.setForceUpdateOnPageLoad Domain: ServiceWorker Method name: setForceUpdateOnPageLoad Parameters: Required arguments: 'forceUpdateOnPageLoad' (type: boolean) -> No description No return value. ### Re...
def wkt_rewind(x, digits = None): ''' reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. :return: a string Usage:: from py...
reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. :return: a string Usage:: from pygbif import wkt_rewind x = 'POLYGON((1...
Below is the the instruction that describes the task: ### Input: reverse WKT winding order :param x: [str] WKT string :param digits: [int] number of digits after decimal to use for the return string. by default, we use the mean number of digits in your string. :return: a string Usage:: ...
def get_nic(self, datacenter_id, server_id, nic_id, depth=1): """ Retrieves a NIC by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`...
Retrieves a NIC by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :param nic_id: The unique ID of the NIC. :type nic_i...
Below is the the instruction that describes the task: ### Input: Retrieves a NIC by its ID. :param datacenter_id: The unique ID of the data center. :type datacenter_id: ``str`` :param server_id: The unique ID of the server. :type server_id: ``str`` :p...
def get_list(self, list_id): """ Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object """ return List(tweepy_list_to_json(self._client.get_list(list_id=list_id)))
Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object
Below is the the instruction that describes the task: ### Input: Get info of specified list :param list_id: list ID number :return: :class:`~responsebot.models.List` object ### Response: def get_list(self, list_id): """ Get info of specified list :param list_id: list ID nu...
def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.json()[ resource_name] if resource_name else response.json() if is_list: return [clazz.from_json(resource) for res...
Parse a Marathon response into an object or list of objects.
Below is the the instruction that describes the task: ### Input: Parse a Marathon response into an object or list of objects. ### Response: def _parse_response(response, clazz, is_list=False, resource_name=None): """Parse a Marathon response into an object or list of objects.""" target = response.j...
def _extend_module_definitions(self, graph): """ Using collected module definitions extend linkages """ for mod_id in self._modules: mod_identity = self._get_triplet_value(graph, URIRef(mod_id), SBOL.module) modules = [] for mod in graph.triples((mod_i...
Using collected module definitions extend linkages
Below is the the instruction that describes the task: ### Input: Using collected module definitions extend linkages ### Response: def _extend_module_definitions(self, graph): """ Using collected module definitions extend linkages """ for mod_id in self._modules: mod_iden...
def exif_orientation(im): """ Rotate and/or flip an image to respect the image's EXIF orientation data. """ try: exif = im._getexif() except Exception: # There are many ways that _getexif fails, we're just going to blanket # cover them all. exif = None if exif: ...
Rotate and/or flip an image to respect the image's EXIF orientation data.
Below is the the instruction that describes the task: ### Input: Rotate and/or flip an image to respect the image's EXIF orientation data. ### Response: def exif_orientation(im): """ Rotate and/or flip an image to respect the image's EXIF orientation data. """ try: exif = im._getexif() ...
def get_filters(self, filters=None, filters_map=None): """Converts a string given by the user into a valid api filter value. :filters: Default filter values. {'filter1': filter_value, 'filter2': filter_value} :filters_map: mapping between user input and valid api filter values. ...
Converts a string given by the user into a valid api filter value. :filters: Default filter values. {'filter1': filter_value, 'filter2': filter_value} :filters_map: mapping between user input and valid api filter values. {'filter_name':{_("true_value"):True, _("false_value"):Fal...
Below is the the instruction that describes the task: ### Input: Converts a string given by the user into a valid api filter value. :filters: Default filter values. {'filter1': filter_value, 'filter2': filter_value} :filters_map: mapping between user input and valid api filter values. ...
def task_assignments(self): '''Retrieves all tasks currently assigned to this project.''' url = str.format( 'projects/{}/task_assignments', self.id ) response = self.hv.get_request(url) return [TaskAssignment(self.hv, tj['task_assignment']) for tj in respo...
Retrieves all tasks currently assigned to this project.
Below is the the instruction that describes the task: ### Input: Retrieves all tasks currently assigned to this project. ### Response: def task_assignments(self): '''Retrieves all tasks currently assigned to this project.''' url = str.format( 'projects/{}/task_assignments', ...
def __execute_cmd(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: # -a takes 'server' or 'switch' to represent all servers # or all switches in a chassis. Allow # user to say ...
Execute rac commands
Below is the the instruction that describes the task: ### Input: Execute rac commands ### Response: def __execute_cmd(command, host=None, admin_username=None, admin_password=None, module=None): ''' Execute rac commands ''' if module: # -a takes 'server' o...
def publish_topology_description_changed(self, previous_description, new_description, topology_id): """Publish a TopologyDescriptionChangedEvent to all topology listeners. :Parameters: - `previous_description`: The previous topology description. ...
Publish a TopologyDescriptionChangedEvent to all topology listeners. :Parameters: - `previous_description`: The previous topology description. - `new_description`: The new topology description. - `topology_id`: A unique identifier for the topology this server is a part of.
Below is the the instruction that describes the task: ### Input: Publish a TopologyDescriptionChangedEvent to all topology listeners. :Parameters: - `previous_description`: The previous topology description. - `new_description`: The new topology description. - `topology_id`: A un...
def get_global_rate_limit(self): """Get the global rate limit per client. :rtype: int :returns: The global rate limit for each client. """ r = urllib.request.urlopen('https://archive.org/metadata/iamine-rate-limiter') j = json.loads(r.read().decode('utf-8')) retu...
Get the global rate limit per client. :rtype: int :returns: The global rate limit for each client.
Below is the the instruction that describes the task: ### Input: Get the global rate limit per client. :rtype: int :returns: The global rate limit for each client. ### Response: def get_global_rate_limit(self): """Get the global rate limit per client. :rtype: int :returns:...
def is_cell_empty(self, cell): """Checks if the cell is empty.""" if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell is None
Checks if the cell is empty.
Below is the the instruction that describes the task: ### Input: Checks if the cell is empty. ### Response: def is_cell_empty(self, cell): """Checks if the cell is empty.""" if cell is None: return True elif self._is_cell_empty: return self._is_cell_empty(cell) else: return cell i...
def _loadBatch(self, item, batch): """ Loads the batch of items for this tree based on the inputed batch item. :param item | <XBatchItem> batch | <orb.RecordSet> """ if self.isThreadEnabled() and batch.isThreadEnabled(): self...
Loads the batch of items for this tree based on the inputed batch item. :param item | <XBatchItem> batch | <orb.RecordSet>
Below is the the instruction that describes the task: ### Input: Loads the batch of items for this tree based on the inputed batch item. :param item | <XBatchItem> batch | <orb.RecordSet> ### Response: def _loadBatch(self, item, batch): """ Loads the ...
def setStartdatetime(self, recording_start_time): """ Sets the recording start Time Parameters ---------- recording_start_time: datetime object Sets the recording start Time """ if isinstance(recording_start_time,datetime): self.recording_...
Sets the recording start Time Parameters ---------- recording_start_time: datetime object Sets the recording start Time
Below is the the instruction that describes the task: ### Input: Sets the recording start Time Parameters ---------- recording_start_time: datetime object Sets the recording start Time ### Response: def setStartdatetime(self, recording_start_time): """ Sets the ...
def update(self, fontsize=0.0, text_color=None, border_color=None, fill_color=None, rotate=-1): """Update the appearance of an annotation.""" if self.type[0] == ANNOT_WIDGET: print("Use updateWidget method for form fields.") return False val = _fitz.Annot_update(self, f...
Update the appearance of an annotation.
Below is the the instruction that describes the task: ### Input: Update the appearance of an annotation. ### Response: def update(self, fontsize=0.0, text_color=None, border_color=None, fill_color=None, rotate=-1): """Update the appearance of an annotation.""" if self.type[0] == ANNOT_WIDGET: ...
def citedReferencesRetrieve(self, queryId, count=100, offset=1, retrieveParameters=None): """The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100...
The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100 records per query. For example, a citedReferences operation may find 106 cited references, as revealed by the conten...
Below is the the instruction that describes the task: ### Input: The citedReferencesRetrieve operation submits a query returned by a previous citedReferences operation. This operation is useful for overcoming the retrieval limit of 100 records per query. For example, a citedReferences opera...
def sample(self, samples=[], **sample_values): """ Sample the Raster along one or both of its dimensions, returning a reduced dimensionality type, which is either a ItemTable, Curve or Scatter. If two dimension samples and a new_xaxis is provided the sample will be the value ...
Sample the Raster along one or both of its dimensions, returning a reduced dimensionality type, which is either a ItemTable, Curve or Scatter. If two dimension samples and a new_xaxis is provided the sample will be the value of the sampled unit indexed by the value in the new_xaxis ...
Below is the the instruction that describes the task: ### Input: Sample the Raster along one or both of its dimensions, returning a reduced dimensionality type, which is either a ItemTable, Curve or Scatter. If two dimension samples and a new_xaxis is provided the sample will be the value ...
def _kl_half_normal_half_normal(a, b, name=None): """Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`. Args: a: Instance of a `HalfNormal` distribution object. b: Instance of a `HalfNormal` distribution object. name: (optional) Name to use for created operations. default i...
Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`. Args: a: Instance of a `HalfNormal` distribution object. b: Instance of a `HalfNormal` distribution object. name: (optional) Name to use for created operations. default is "kl_half_normal_half_normal". Returns: Batchwi...
Below is the the instruction that describes the task: ### Input: Calculate the batched KL divergence KL(a || b) with a and b `HalfNormal`. Args: a: Instance of a `HalfNormal` distribution object. b: Instance of a `HalfNormal` distribution object. name: (optional) Name to use for created operations. ...
def _init_ca(self): """Generate the root ca's cert and key. """ if not exists(path_join(self.ca_dir, 'ca.cnf')): with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh: fh.write( CA_CONF_TEMPLATE % (self.get_conf_variables())) if not exist...
Generate the root ca's cert and key.
Below is the the instruction that describes the task: ### Input: Generate the root ca's cert and key. ### Response: def _init_ca(self): """Generate the root ca's cert and key. """ if not exists(path_join(self.ca_dir, 'ca.cnf')): with open(path_join(self.ca_dir, 'ca.cnf'), 'w') a...
def __generate_new_sandbox_user(): """ :rtype: endpoint.SandboxUser """ url = ApiEnvironmentType.SANDBOX.uri_base + __ENDPOINT_SANDBOX_USER headers = { ApiClient.HEADER_REQUEST_ID: __UNIQUE_REQUEST_ID, ApiClient.HEADER_CACHE_CONTROL: ApiClient._CACHE_CONTROL_NONE, ApiClient...
:rtype: endpoint.SandboxUser
Below is the the instruction that describes the task: ### Input: :rtype: endpoint.SandboxUser ### Response: def __generate_new_sandbox_user(): """ :rtype: endpoint.SandboxUser """ url = ApiEnvironmentType.SANDBOX.uri_base + __ENDPOINT_SANDBOX_USER headers = { ApiClient.HEADER_REQUEST_...
def genargs(prog: Optional[str] = None) -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser(prog) parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options") parser.add_argument("shex", help="ShEx specification...
Create a command line parser :return: parser
Below is the the instruction that describes the task: ### Input: Create a command line parser :return: parser ### Response: def genargs(prog: Optional[str] = None) -> ArgumentParser: """ Create a command line parser :return: parser """ parser = ArgumentParser(prog) parser.add_argument("...
def currentValue(self): """ Returns the current value for the widget. If this widget is checkable then the bitor value for all checked items is returned, otherwise, the selected value is returned. :return <int> """ enum = self.enum() ...
Returns the current value for the widget. If this widget is checkable then the bitor value for all checked items is returned, otherwise, the selected value is returned. :return <int>
Below is the the instruction that describes the task: ### Input: Returns the current value for the widget. If this widget is checkable then the bitor value for all checked items is returned, otherwise, the selected value is returned. :return <int> ### Response: def current...
def info(gandi, resource): """ Display information about a disk. Resource can be a disk name or ID """ output_keys = ['name', 'state', 'size', 'type', 'id', 'dc', 'vm', 'profile', 'kernel', 'cmdline'] resource = sorted(tuple(set(resource))) vms = dict([(vm['id'], vm) for vm ...
Display information about a disk. Resource can be a disk name or ID
Below is the the instruction that describes the task: ### Input: Display information about a disk. Resource can be a disk name or ID ### Response: def info(gandi, resource): """ Display information about a disk. Resource can be a disk name or ID """ output_keys = ['name', 'state', 'size', 'ty...
def items(self): """Yield the async reuslts for the context.""" for key, task in self._tasks: if not (task and task.result): yield key, None else: yield key, json.loads(task.result)["payload"]
Yield the async reuslts for the context.
Below is the the instruction that describes the task: ### Input: Yield the async reuslts for the context. ### Response: def items(self): """Yield the async reuslts for the context.""" for key, task in self._tasks: if not (task and task.result): yield key, None ...
def schedule_in(self, job, timedelta): """ Schedule job to run at datetime.timedelta from now.""" now = long(self._now() * 1e6) when = now + timedelta.total_seconds() * 1e6 self.schedule(job, when)
Schedule job to run at datetime.timedelta from now.
Below is the the instruction that describes the task: ### Input: Schedule job to run at datetime.timedelta from now. ### Response: def schedule_in(self, job, timedelta): """ Schedule job to run at datetime.timedelta from now.""" now = long(self._now() * 1e6) when = now + timedelta.total_sec...
def get_content_type(content_type): """Extract the MIME type value from a content type string. Removes any subtype and parameter values that may be present in the string. Args: content_type: str String with content type and optional subtype and parameter fields. Returns: str: Stri...
Extract the MIME type value from a content type string. Removes any subtype and parameter values that may be present in the string. Args: content_type: str String with content type and optional subtype and parameter fields. Returns: str: String with only content type Example: ...
Below is the the instruction that describes the task: ### Input: Extract the MIME type value from a content type string. Removes any subtype and parameter values that may be present in the string. Args: content_type: str String with content type and optional subtype and parameter fields. ...
def plot(self, columns=None, **errorbar_kwargs): """ Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot errorbar_kwargs: ...
Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot errorbar_kwargs: pass in additional plotting commands to matplotlib errorb...
Below is the the instruction that describes the task: ### Input: Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot errorbar_kwargs: ...
def change_existence(self, is_hidden): # type: (bool) -> None ''' Change the ISO9660 existence flag of this Directory Record. Parameters: is_hidden - True if this Directory Record should be hidden, False otherwise. Returns: Nothing. ''' if not s...
Change the ISO9660 existence flag of this Directory Record. Parameters: is_hidden - True if this Directory Record should be hidden, False otherwise. Returns: Nothing.
Below is the the instruction that describes the task: ### Input: Change the ISO9660 existence flag of this Directory Record. Parameters: is_hidden - True if this Directory Record should be hidden, False otherwise. Returns: Nothing. ### Response: def change_existence(self, is_hidd...
def hardware_flexport_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hardware") flexport = ET.SubElement(hardware, "flexport") id = ET.SubElement(flexport, "id")...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def hardware_flexport_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hardware = ET.SubElement(config, "hardware", xmlns="urn:brocade.com:mgmt:brocade-hard...
def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) # Connecting the following signal once the dockwidget has been created: self.shell.exception_occurred.connect(se...
Register plugin in Spyder's main window
Below is the the instruction that describes the task: ### Input: Register plugin in Spyder's main window ### Response: def register_plugin(self): """Register plugin in Spyder's main window""" self.focus_changed.connect(self.main.plugin_focus_changed) self.main.add_dockwidget(self) ...
def value(self): """gets the color value""" if self._outline is None: return { "type" : self._type, "style" : self._style, "color" : self._color.value, } else: return { "type" : self._type, ...
gets the color value
Below is the the instruction that describes the task: ### Input: gets the color value ### Response: def value(self): """gets the color value""" if self._outline is None: return { "type" : self._type, "style" : self._style, "color" : self._...
def download_needed(self, response, outfile, quiet=True): """ determine if a download is needed based on timestamp. Return True if needed (remote is newer) or False if local is newest. Parameters ========== response: the response from the API outfile:...
determine if a download is needed based on timestamp. Return True if needed (remote is newer) or False if local is newest. Parameters ========== response: the response from the API outfile: the output file to write to quiet: suppress verbose outpu...
Below is the the instruction that describes the task: ### Input: determine if a download is needed based on timestamp. Return True if needed (remote is newer) or False if local is newest. Parameters ========== response: the response from the API outfile: ...
def is_denied(self, role, method, resource): """Check wherther role is denied to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. """ return (role, method, resource) in self._denied
Check wherther role is denied to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked.
Below is the the instruction that describes the task: ### Input: Check wherther role is denied to access resource :param role: Role to be checked. :param method: Method to be checked. :param resource: View function to be checked. ### Response: def is_denied(self, role, method, resource): ...
def convertDict2Attrs(self, *args, **kwargs): """The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute (which just ...
The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute (which just holds a list of plain dictionaries) with a MambuB...
Below is the the instruction that describes the task: ### Input: The trick for iterable Mambu Objects comes here: You iterate over each element of the responded List from Mambu, and create a Mambu Branch object for each one, initializing them one at a time, and changing the attrs attribute ...
def err(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Per step status messages Use this locally in a command definition to highlight more important information. """ if len(args) or len(kw): msg = msg.format(*args, **kw) shell.cprint('-- <31>{}<0>'.format(msg))
Per step status messages Use this locally in a command definition to highlight more important information.
Below is the the instruction that describes the task: ### Input: Per step status messages Use this locally in a command definition to highlight more important information. ### Response: def err(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Per step status messages Use this locally...
def get_max_bond_distance(self, el1_sym, el2_sym): """ Use Jmol algorithm to determine bond length from atomic parameters Args: el1_sym: (str) symbol of atom 1 el2_sym: (str) symbol of atom 2 Returns: (float) max bond length """ return sqrt( ...
Use Jmol algorithm to determine bond length from atomic parameters Args: el1_sym: (str) symbol of atom 1 el2_sym: (str) symbol of atom 2 Returns: (float) max bond length
Below is the the instruction that describes the task: ### Input: Use Jmol algorithm to determine bond length from atomic parameters Args: el1_sym: (str) symbol of atom 1 el2_sym: (str) symbol of atom 2 Returns: (float) max bond length ### Response: def get_max_bond_distance...
def signature_str(self): """ str: func_name(type1,type2) returns (type3) Return the function signature as a str (contains the return values) """ name, parameters, returnVars = self.signature return name+'('+','.join(parameters)+') returns('+','.join(returnVars)+')...
str: func_name(type1,type2) returns (type3) Return the function signature as a str (contains the return values)
Below is the the instruction that describes the task: ### Input: str: func_name(type1,type2) returns (type3) Return the function signature as a str (contains the return values) ### Response: def signature_str(self): """ str: func_name(type1,type2) returns (type3) Return ...
def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security = SecuritySymbol("", "") price.symbol.parse(symbol) # price.symbol.mnemonic = price.symbol.mnemo...
Add individual price
Below is the the instruction that describes the task: ### Input: Add individual price ### Response: def add(symbol: str, date, value, currency: str): """ Add individual price """ symbol = symbol.upper() currency = currency.upper() app = PriceDbApplication() price = PriceModel() # security...
def pivot_wavelength(self): """Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available. """ wl = self.registry._pivot_wavelengths.get((self.telescope, self.band)) if wl is not None: return wl ...
Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available.
Below is the the instruction that describes the task: ### Input: Get the bandpass' pivot wavelength. Unlike calc_pivot_wavelength(), this function will use a cached value if available. ### Response: def pivot_wavelength(self): """Get the bandpass' pivot wavelength. Unlike calc_piv...
def _opcode_set(*names): """Return a set of opcodes by the names in `names`.""" s = set() for name in names: try: s.add(_opcode(name)) except KeyError: pass return s
Return a set of opcodes by the names in `names`.
Below is the the instruction that describes the task: ### Input: Return a set of opcodes by the names in `names`. ### Response: def _opcode_set(*names): """Return a set of opcodes by the names in `names`.""" s = set() for name in names: try: s.add(_opcode(name)) except KeyEr...
def destroy_all(cls, objs): """ 在一个请求中 destroy 多个 leancloud.Object 对象实例。 :param objs: 需要 destroy 的对象 :type objs: list """ if not objs: return if any(x.is_new() for x in objs): raise ValueError("Could not destroy unsaved object") d...
在一个请求中 destroy 多个 leancloud.Object 对象实例。 :param objs: 需要 destroy 的对象 :type objs: list
Below is the the instruction that describes the task: ### Input: 在一个请求中 destroy 多个 leancloud.Object 对象实例。 :param objs: 需要 destroy 的对象 :type objs: list ### Response: def destroy_all(cls, objs): """ 在一个请求中 destroy 多个 leancloud.Object 对象实例。 :param objs: 需要 destroy 的对象 ...
def body_processor(self, chunk): """ Process body of response. """ if self.config_nobody: self.curl.grab_callback_interrupted = True return 0 bytes_read = len(chunk) self.response_body_bytes_read += bytes_read if self.body_file: ...
Process body of response.
Below is the the instruction that describes the task: ### Input: Process body of response. ### Response: def body_processor(self, chunk): """ Process body of response. """ if self.config_nobody: self.curl.grab_callback_interrupted = True return 0 by...
def json2paramater(self, ss_spec): ''' generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space ''' if isinstance(ss_spec, dict): if '_type' in ss_spec.keys(): _type = ss_spec['_type'] _...
generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space
Below is the the instruction that describes the task: ### Input: generate all possible configs for hyperparameters from hyperparameter space. ss_spec: hyperparameter space ### Response: def json2paramater(self, ss_spec): ''' generate all possible configs for hyperparameters from hyperparame...
def _homogenize_waves(wave_a, wave_b): """ Generate combined independent variable vector. The combination is from two waveforms and the (possibly interpolated) dependent variable vectors of these two waveforms """ indep_vector = _get_indep_vector(wave_a, wave_b) dep_vector_a = _interp_dep_v...
Generate combined independent variable vector. The combination is from two waveforms and the (possibly interpolated) dependent variable vectors of these two waveforms
Below is the the instruction that describes the task: ### Input: Generate combined independent variable vector. The combination is from two waveforms and the (possibly interpolated) dependent variable vectors of these two waveforms ### Response: def _homogenize_waves(wave_a, wave_b): """ Generate ...
def prt_txt(prt, goea_results, prtfmt=None, **kws): """Print GOEA results in text format.""" objprt = PrtFmt() if prtfmt is None: flds = ['GO', 'NS', 'p_uncorrected', 'ratio_in_study', 'ratio_in_pop', 'depth', 'name', 'study_items'] prtfmt = objprt.get...
Print GOEA results in text format.
Below is the the instruction that describes the task: ### Input: Print GOEA results in text format. ### Response: def prt_txt(prt, goea_results, prtfmt=None, **kws): """Print GOEA results in text format.""" objprt = PrtFmt() if prtfmt is None: flds = ['GO', 'NS', 'p_uncorrected'...
def _rotate_and_chop(self, verts, normal, axis=[0, 0, 1]): r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating con...
r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating convex hull in order to arrange them in hull order for calcula...
Below is the the instruction that describes the task: ### Input: r""" Method to rotate a set of vertices (or coords) to align with an axis points must be coplanar and normal must be given Chops axis coord to give vertices back in 2D Used to prepare verts for printing or calculating c...
def assign_default_storage_policy_to_datastore(policy, datastore, service_instance=None): ''' Assigns a storage policy as the default policy to a datastore. policy Name of the policy to assign. datastore Name of the datastore to assign. ...
Assigns a storage policy as the default policy to a datastore. policy Name of the policy to assign. datastore Name of the datastore to assign. The datastore needs to be visible to the VMware entity the proxy points to. service_instance Service instance (vim.Service...
Below is the the instruction that describes the task: ### Input: Assigns a storage policy as the default policy to a datastore. policy Name of the policy to assign. datastore Name of the datastore to assign. The datastore needs to be visible to the VMware entity the proxy p...
def _serial_close(self, port): ''' Handle close request. Parameters ---------- port : str Device name/port. ''' if port in self.open_devices: try: self.open_devices[port].close() except Exception as exception: ...
Handle close request. Parameters ---------- port : str Device name/port.
Below is the the instruction that describes the task: ### Input: Handle close request. Parameters ---------- port : str Device name/port. ### Response: def _serial_close(self, port): ''' Handle close request. Parameters ---------- port :...
def near_to_position(self, position, max_distance): '''Returns true iff the record is within max_distance of the given position. Note: chromosome name not checked, so that's up to you to do first.''' end = self.ref_end_pos() return self.POS <= position <= end or abs(position - self.POS) ...
Returns true iff the record is within max_distance of the given position. Note: chromosome name not checked, so that's up to you to do first.
Below is the the instruction that describes the task: ### Input: Returns true iff the record is within max_distance of the given position. Note: chromosome name not checked, so that's up to you to do first. ### Response: def near_to_position(self, position, max_distance): '''Returns true iff the re...
def exporter(directory, method, datasets): """Export the results.""" if method.lower() == 'json': # Convert json_dict to a JSON styled string json_string = json.dumps(datasets, indent=4) savefile = open('{}/exported.json'.format(directory), 'w+') savefile.write(json_string) ...
Export the results.
Below is the the instruction that describes the task: ### Input: Export the results. ### Response: def exporter(directory, method, datasets): """Export the results.""" if method.lower() == 'json': # Convert json_dict to a JSON styled string json_string = json.dumps(datasets, indent=4) ...