code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def is_gff_db(db_fname): """ Return True if the given filename is a GFF database. For now, rely on .db extension. """ if not os.path.isfile(db_fname): return False if db_fname.endswith(".db"): return True return False
Return True if the given filename is a GFF database. For now, rely on .db extension.
Below is the the instruction that describes the task: ### Input: Return True if the given filename is a GFF database. For now, rely on .db extension. ### Response: def is_gff_db(db_fname): """ Return True if the given filename is a GFF database. For now, rely on .db extension. """ if not ...
def _fromData(cls, header, tflags, data): """Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted. """ ...
Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted.
Below is the the instruction that describes the task: ### Input: Construct this ID3 frame from raw string data. Raises: ID3JunkFrameError in case parsing failed NotImplementedError in case parsing isn't implemented ID3EncryptionUnsupportedError in case the frame is encrypted. ### R...
def write_without_mac(self, data, block): """Write a data block without integrity check. This is the standard write method for a FeliCa Lite. The 16-byte string or bytearray *data* is written to the numbered *block* in service 0x0009 (NDEF write service). :: data = bytearra...
Write a data block without integrity check. This is the standard write method for a FeliCa Lite. The 16-byte string or bytearray *data* is written to the numbered *block* in service 0x0009 (NDEF write service). :: data = bytearray(range(16)) # 0x00, 0x01, ... 0x0F try: ...
Below is the the instruction that describes the task: ### Input: Write a data block without integrity check. This is the standard write method for a FeliCa Lite. The 16-byte string or bytearray *data* is written to the numbered *block* in service 0x0009 (NDEF write service). :: ...
def truepath(path, real=False): """ Normalizes a string representation of a path and does shell-like expansion. Args: path (PathLike): string representation of a path real (bool): if True, all symbolic links are followed. (default: False) Returns: PathLike : normalized path ...
Normalizes a string representation of a path and does shell-like expansion. Args: path (PathLike): string representation of a path real (bool): if True, all symbolic links are followed. (default: False) Returns: PathLike : normalized path Note: This function is similar to ...
Below is the the instruction that describes the task: ### Input: Normalizes a string representation of a path and does shell-like expansion. Args: path (PathLike): string representation of a path real (bool): if True, all symbolic links are followed. (default: False) Returns: PathL...
def _check_stop_iteration_inside_generator(self, node): """Check if an exception of type StopIteration is raised inside a generator""" frame = node.frame() if not isinstance(frame, astroid.FunctionDef) or not frame.is_generator(): return if utils.node_ignores_exception(node, ...
Check if an exception of type StopIteration is raised inside a generator
Below is the the instruction that describes the task: ### Input: Check if an exception of type StopIteration is raised inside a generator ### Response: def _check_stop_iteration_inside_generator(self, node): """Check if an exception of type StopIteration is raised inside a generator""" frame = node...
def create_product(name, abbreviation, **kwargs): """ Create a new Product """ data = create_product_raw(name, abbreviation, **kwargs) if data: return utils.format_json(data)
Create a new Product
Below is the the instruction that describes the task: ### Input: Create a new Product ### Response: def create_product(name, abbreviation, **kwargs): """ Create a new Product """ data = create_product_raw(name, abbreviation, **kwargs) if data: return utils.format_json(data)
def decode_packet(packet: str) -> dict: """Break packet down into primitives, and do basic interpretation. >>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == { ... 'node': 'gateway', ... 'protocol': 'kaku', ... 'id': '000041', ... 'switch': '1', ... 'command': 'on...
Break packet down into primitives, and do basic interpretation. >>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == { ... 'node': 'gateway', ... 'protocol': 'kaku', ... 'id': '000041', ... 'switch': '1', ... 'command': 'on', ... } True
Below is the the instruction that describes the task: ### Input: Break packet down into primitives, and do basic interpretation. >>> decode_packet('20;06;Kaku;ID=41;SWITCH=1;CMD=ON;') == { ... 'node': 'gateway', ... 'protocol': 'kaku', ... 'id': '000041', ... 'switch': '1', ...
def get_user_token(login, password): """Retrieve user token from the API (via authentication).""" client = get_user_api() # Never use API key for the token endpoint config = cloudsmith_api.Configuration() set_api_key(config, None) with catch_raise_api_exception(): data, _, headers = cl...
Retrieve user token from the API (via authentication).
Below is the the instruction that describes the task: ### Input: Retrieve user token from the API (via authentication). ### Response: def get_user_token(login, password): """Retrieve user token from the API (via authentication).""" client = get_user_api() # Never use API key for the token endpoint ...
def shellne(command): """ Runs 'commands' on the underlying shell; any stderr is echo'd to the console. Raises a RuntimeException on any shell exec errors. """ child = os.popen(command) data = child.read() err = child.close() if err: raise RuntimeError('%s faile...
Runs 'commands' on the underlying shell; any stderr is echo'd to the console. Raises a RuntimeException on any shell exec errors.
Below is the the instruction that describes the task: ### Input: Runs 'commands' on the underlying shell; any stderr is echo'd to the console. Raises a RuntimeException on any shell exec errors. ### Response: def shellne(command): """ Runs 'commands' on the underlying shell; any stderr...
def main(): """ Commandline interface to initialize Sockeye embedding weights with pretrained word representations. """ setup_main_logger(console=True, file_logging=False) params = argparse.ArgumentParser(description='Quick usage: python3 -m sockeye.init_embedding ' ...
Commandline interface to initialize Sockeye embedding weights with pretrained word representations.
Below is the the instruction that describes the task: ### Input: Commandline interface to initialize Sockeye embedding weights with pretrained word representations. ### Response: def main(): """ Commandline interface to initialize Sockeye embedding weights with pretrained word representations. """ ...
def seek(self, offset, from_what=0): """ seek(offset, from_what=0) -> int. Change stream position. Seek to byte offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= tell(); 1 Current position - negative pos not impl...
seek(offset, from_what=0) -> int. Change stream position. Seek to byte offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= tell(); 1 Current position - negative pos not implemented; 2 End of stream - not implemented....
Below is the the instruction that describes the task: ### Input: seek(offset, from_what=0) -> int. Change stream position. Seek to byte offset pos relative to position indicated by whence: 0 Start of stream (the default). pos should be >= tell(); 1 Current position - negative ...
def solve_for(self, var=None): """ Ensure that the children is within its parent """ margin = self.margin_method() if self.parent_nw[0].value > self.child[0].value - margin: _update(self.child[0], self.parent_nw[0].value + margin) # Right edge (east) i...
Ensure that the children is within its parent
Below is the the instruction that describes the task: ### Input: Ensure that the children is within its parent ### Response: def solve_for(self, var=None): """ Ensure that the children is within its parent """ margin = self.margin_method() if self.parent_nw[0].value > self.c...
def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixed()) self._json_params = dictset(_json_params) ctype = self.request.content_type if self.req...
Prepare query and update params.
Below is the the instruction that describes the task: ### Input: Prepare query and update params. ### Response: def prepare_request_params(self, _query_params, _json_params): """ Prepare query and update params. """ self._query_params = dictset( _query_params or self.request.params.mixe...
def from_arrays(event, time, name_event=None, name_time=None): """Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None ...
Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None Name of event, optional, default: 'event' name_time : s...
Below is the the instruction that describes the task: ### Input: Create structured array. Parameters ---------- event : array-like Event indicator. A boolean array or array with values 0/1. time : array-like Observed time. name_event : str|None ...
def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Element("get_lldp_neighbor_detail") config = get_lldp_neighbor_detail input = ET.SubElement(g...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_lldp_neighbor_detail_input_request_type_get_request_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_lldp_neighbor_detail = ET.Eleme...
def Unzip(iterable): """Unzips specified iterable of pairs to pair of two iterables. This function is an inversion of the standard `zip` function and the following hold: * ∀ l, r. l, r == unzip(zip(l, r)) * ∀ p. p == zip(unzip(p)) Examples: >>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)]) (["f...
Unzips specified iterable of pairs to pair of two iterables. This function is an inversion of the standard `zip` function and the following hold: * ∀ l, r. l, r == unzip(zip(l, r)) * ∀ p. p == zip(unzip(p)) Examples: >>> Unzip([("foo", 1), ("bar", 2), ("baz", 3)]) (["foo", "bar", "baz"], [1, 2,...
Below is the the instruction that describes the task: ### Input: Unzips specified iterable of pairs to pair of two iterables. This function is an inversion of the standard `zip` function and the following hold: * ∀ l, r. l, r == unzip(zip(l, r)) * ∀ p. p == zip(unzip(p)) Examples: >>> Unzip([("...
def stop(self, io_loop): """ Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped on...
Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The IOLoop will be stopped once the application is completely shut...
Below is the the instruction that describes the task: ### Input: Asynchronously stop the application. :param tornado.ioloop.IOLoop io_loop: loop to run until all callbacks, timeouts, and queued calls are complete Call this method to start the application shutdown process. The I...
def _get_shards(self): """ Returns comma separated list of configured Solr cores """ if self._shards is None: endpoints = [] for endpoint in self.endpoints: # We need to remove and http:// prefixes from URLs url = urlparse.urlparse(...
Returns comma separated list of configured Solr cores
Below is the the instruction that describes the task: ### Input: Returns comma separated list of configured Solr cores ### Response: def _get_shards(self): """ Returns comma separated list of configured Solr cores """ if self._shards is None: endpoints = [] f...
def build_wheel(source_dir, wheel_dir, config_settings=None): """Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build b...
Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build backend This is a blocking function which will run pip in a subpr...
Below is the the instruction that describes the task: ### Input: Build a wheel from a source directory using PEP 517 hooks. :param str source_dir: Source directory containing pyproject.toml :param str wheel_dir: Target directory to create wheel in :param dict config_settings: Options to pass to build b...
def put_event(self, evt): """ Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): """ evt.step = self.global_step evt.wall_time = time.time() self._dispatch(lambda m:...
Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event):
Below is the the instruction that describes the task: ### Input: Put an :class:`tf.Event`. `step` and `wall_time` fields of :class:`tf.Event` will be filled automatically. Args: evt (tf.Event): ### Response: def put_event(self, evt): """ Put an :class:`tf.Event`. ...
def get_password(self, service, username): """ Read the password from the file. """ assoc = self._generate_assoc(service, username) service = escape_for_ini(service) username = escape_for_ini(username) # load the passwords from the file config = configpar...
Read the password from the file.
Below is the the instruction that describes the task: ### Input: Read the password from the file. ### Response: def get_password(self, service, username): """ Read the password from the file. """ assoc = self._generate_assoc(service, username) service = escape_for_ini(servic...
def proto_value_for_feature(example, feature_name): """Get the value of a feature from Example regardless of feature type.""" feature = get_example_features(example)[feature_name] if feature is None: raise ValueError('Feature {} is not on example proto.'.format(feature_name)) feature_type = feature.WhichOne...
Get the value of a feature from Example regardless of feature type.
Below is the the instruction that describes the task: ### Input: Get the value of a feature from Example regardless of feature type. ### Response: def proto_value_for_feature(example, feature_name): """Get the value of a feature from Example regardless of feature type.""" feature = get_example_features(example...
def set_value(instance, path, value, ref=None): """ Set `value` on `instance` at the given `path` and create missing intermediate objects. Parameters ---------- instance : dict or list instance from which to retrieve a value path : str path to retrieve a value from value : ...
Set `value` on `instance` at the given `path` and create missing intermediate objects. Parameters ---------- instance : dict or list instance from which to retrieve a value path : str path to retrieve a value from value : value to set ref : str or None reference ...
Below is the the instruction that describes the task: ### Input: Set `value` on `instance` at the given `path` and create missing intermediate objects. Parameters ---------- instance : dict or list instance from which to retrieve a value path : str path to retrieve a value from ...
def _bitForCoordinate(cls, coordinate, n): """ Maps the coordinate to a bit in the SDR. @param coordinate (numpy.array) Coordinate @param n (int) The number of available bits in the SDR @return (int) The index to a bit in the SDR """ seed = cls._hashCoordinate(coordinate) rng = Random(s...
Maps the coordinate to a bit in the SDR. @param coordinate (numpy.array) Coordinate @param n (int) The number of available bits in the SDR @return (int) The index to a bit in the SDR
Below is the the instruction that describes the task: ### Input: Maps the coordinate to a bit in the SDR. @param coordinate (numpy.array) Coordinate @param n (int) The number of available bits in the SDR @return (int) The index to a bit in the SDR ### Response: def _bitForCoordinate(cls, coordinate, n...
def plot_results( allresults, *, xy_fn=default_xy_fn, split_fn=default_split_fn, group_fn=default_split_fn, average_group=False, shaded_std=True, shaded_err=True, figsize=None, legend_outside=False, resample=0, smooth_step=1.0 ): ''' Plot multiple Results objects ...
Plot multiple Results objects xy_fn: function Result -> x,y - function that converts results objects into tuple of x and y values. By default, x is cumsum of episode lengths, and y is episode rewards split_fn: function Result -> hashable - function tha...
Below is the the instruction that describes the task: ### Input: Plot multiple Results objects xy_fn: function Result -> x,y - function that converts results objects into tuple of x and y values. By default, x is cumsum of episode lengths, and y is episod...
def has_pattern(self, decl_string): """ Implementation detail """ if self.__begin == "<": # Cleanup parentheses blocks before checking for the pattern # See also the args() method (in this file) for more explanations. decl_string = re.sub("\\s\\(.*?\\...
Implementation detail
Below is the the instruction that describes the task: ### Input: Implementation detail ### Response: def has_pattern(self, decl_string): """ Implementation detail """ if self.__begin == "<": # Cleanup parentheses blocks before checking for the pattern # See ...
def get_selected_filenames(self): """Return selected filenames""" if self.selectionMode() == self.ExtendedSelection: if self.selectionModel() is None: return [] return [self.get_filename(idx) for idx in self.selectionModel().selectedRows...
Return selected filenames
Below is the the instruction that describes the task: ### Input: Return selected filenames ### Response: def get_selected_filenames(self): """Return selected filenames""" if self.selectionMode() == self.ExtendedSelection: if self.selectionModel() is None: return [] ...
def process_memberdocs(self, docs, codeEl, add=True): """Associates member type DocElements with their corresponding members in the specified code element. The element must have a dictionary of members already.""" #Now we need to associate the members with their docstrings ...
Associates member type DocElements with their corresponding members in the specified code element. The element must have a dictionary of members already.
Below is the the instruction that describes the task: ### Input: Associates member type DocElements with their corresponding members in the specified code element. The element must have a dictionary of members already. ### Response: def process_memberdocs(self, docs, codeEl, add=True): """A...
def _add_operations_bulk(self, chunked_data): """Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :return: list of age...
Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :return: list of agents containing a message about the added operatio...
Below is the the instruction that describes the task: ### Input: Tool for the function add_operations_bulk. It send the requests to add the operations to the agents. :param list chunked_data: list of list of the agents and their operations to add. Each chunk can be requested at the same time. :ret...
def _fill_topology_cfg(self, topo_dict): """Fills the extra configurations in the topology. """ cfg_dict = {} if topo_dict.bond_member_ports is not None: cfg_dict.update({'bond_member_ports': topo_dict.bond_member_ports}) if topo_dict.bond_interfa...
Fills the extra configurations in the topology.
Below is the the instruction that describes the task: ### Input: Fills the extra configurations in the topology. ### Response: def _fill_topology_cfg(self, topo_dict): """Fills the extra configurations in the topology. """ cfg_dict = {} if topo_dict.bond_member_ports is not None: ...
def export(self, top=True): """Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist ...
Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are embedded in as fields inlist objects should be expor...
Below is the the instruction that describes the task: ### Input: Exports object to its string representation. Args: top (bool): if True appends `internal_name` before values. All non list objects should be exported with value top=True, all list objects, that are...
def _load_dx(self, filename): """Initializes Grid from a OpenDX file.""" dx = OpenDX.field(0) dx.read(filename) grid, edges = dx.histogramdd() self.__init__(grid=grid, edges=edges, metadata=self.metadata)
Initializes Grid from a OpenDX file.
Below is the the instruction that describes the task: ### Input: Initializes Grid from a OpenDX file. ### Response: def _load_dx(self, filename): """Initializes Grid from a OpenDX file.""" dx = OpenDX.field(0) dx.read(filename) grid, edges = dx.histogramdd() self.__init__(gr...
def guard_cancel(analysis_request): """Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status """ # Ask to partitions for partition in analysis_request.getDescendants(all_descendants=False): if not isTransitionAllowed(partiti...
Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status
Below is the the instruction that describes the task: ### Input: Returns whether 'cancel' transition can be performed or not. Returns True only if all analyses are in "unassigned" status ### Response: def guard_cancel(analysis_request): """Returns whether 'cancel' transition can be performed or not. Return...
def apply( self, docs=None, split=0, train=False, lfs=None, clear=True, parallelism=None, progress_bar=True, ): """Apply the labels of the specified candidates based on the provided LFs. :param docs: If provided, apply the LFs to all t...
Apply the labels of the specified candidates based on the provided LFs. :param docs: If provided, apply the LFs to all the candidates in these documents. :param split: If docs is None, apply the LFs to the candidates in this particular split. :type split: int :pa...
Below is the the instruction that describes the task: ### Input: Apply the labels of the specified candidates based on the provided LFs. :param docs: If provided, apply the LFs to all the candidates in these documents. :param split: If docs is None, apply the LFs to the candidates in th...
def run(self, steps=None): """Run threaded code in machine. Args: steps: If specified, run that many number of instructions before stopping. """ try: while self.instruction_pointer < len(self.code): self.step() if step...
Run threaded code in machine. Args: steps: If specified, run that many number of instructions before stopping.
Below is the the instruction that describes the task: ### Input: Run threaded code in machine. Args: steps: If specified, run that many number of instructions before stopping. ### Response: def run(self, steps=None): """Run threaded code in machine. Args: ...
def cos_r(self, N=None): # percent=0.9 """Return the squared cosines for each row.""" if not hasattr(self, 'F') or self.F.shape[1] < self.rank: self.fs_r(N=self.rank) # generate F self.dr = norm(self.F, axis=1)**2 # cheaper than diag(self.F.dot(self.F.T))? return apply_along_axis(lambda _: _/self.dr, 0...
Return the squared cosines for each row.
Below is the the instruction that describes the task: ### Input: Return the squared cosines for each row. ### Response: def cos_r(self, N=None): # percent=0.9 """Return the squared cosines for each row.""" if not hasattr(self, 'F') or self.F.shape[1] < self.rank: self.fs_r(N=self.rank) # generate F sel...
def _retrieve_page(self, page_index): """Returns the node of matches to be processed""" params = self._get_params() params["page"] = str(page_index) doc = self._request(self._ws_prefix + ".search", True, params) return doc.getElementsByTagName(self._ws_prefix + "matches")[0]
Returns the node of matches to be processed
Below is the the instruction that describes the task: ### Input: Returns the node of matches to be processed ### Response: def _retrieve_page(self, page_index): """Returns the node of matches to be processed""" params = self._get_params() params["page"] = str(page_index) doc = self...
def create_sample_input_files(template_filename, database_filename, config_filename): """Create sample template email and database.""" print("Creating sample template email {}".format(template_filename)) if os.path.exists(template_filename): ...
Create sample template email and database.
Below is the the instruction that describes the task: ### Input: Create sample template email and database. ### Response: def create_sample_input_files(template_filename, database_filename, config_filename): """Create sample template email and databas...
def gmres_prolongation_smoothing(A, T, B, BtBinv, Sparsity_Pattern, maxiter, tol, weighting='local', Cpt_params=None): """Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints. Parameters ---------- A : csr_matrix, bsr_matrix SP...
Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints. Parameters ---------- A : csr_matrix, bsr_matrix SPD sparse NxN matrix Should be at least nonsymmetric or indefinite T : bsr_matrix Tentative prolongator, a NxM sparse matrix (M < N). ...
Below is the the instruction that describes the task: ### Input: Use GMRES to smooth T by solving A T = 0, subject to nullspace and sparsity constraints. Parameters ---------- A : csr_matrix, bsr_matrix SPD sparse NxN matrix Should be at least nonsymmetric or indefinite T : bsr_matr...
def favorites_getPublicList(user_id, per_page='', page=''): """Returns list of Photo objects.""" method = 'flickr.favorites.getPublicList' data = _doget(method, auth=False, user_id=user_id, per_page=per_page,\ page=page) photos = [] if isinstance(data.rsp.photos.photo, list): ...
Returns list of Photo objects.
Below is the the instruction that describes the task: ### Input: Returns list of Photo objects. ### Response: def favorites_getPublicList(user_id, per_page='', page=''): """Returns list of Photo objects.""" method = 'flickr.favorites.getPublicList' data = _doget(method, auth=False, user_id=user_id, per...
def _pretend_to_run(self, migration, method): """ Pretend to run the migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str """ self._note("") names...
Pretend to run the migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str
Below is the the instruction that describes the task: ### Input: Pretend to run the migration. :param migration: The migration :type migration: orator.migrations.migration.Migration :param method: The method to execute :type method: str ### Response: def _pretend_to_run(self, migr...
def save(self): """ Save this node (and all its attributes) to config """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read(cfg_file) result = {} token = self.data.pop("token", self.token) if token != self._original_token: ...
Save this node (and all its attributes) to config
Below is the the instruction that describes the task: ### Input: Save this node (and all its attributes) to config ### Response: def save(self): """ Save this node (and all its attributes) to config """ cfg_file = "/etc/nago/nago.ini" config = ConfigParser.ConfigParser() config.read...
def notify_callback(self, notify): """Process State from NOTIFY message.""" _LOGGER.debug(notify) if notify.ip_address != self.stb_ip: return if notify.tune: self._state = State.PLAYING_LIVE_TV self.tune_src = notify.tune['@src'] try: ...
Process State from NOTIFY message.
Below is the the instruction that describes the task: ### Input: Process State from NOTIFY message. ### Response: def notify_callback(self, notify): """Process State from NOTIFY message.""" _LOGGER.debug(notify) if notify.ip_address != self.stb_ip: return if notify.tune...
def set_branching_model(self, project, repository, data): """ Set branching model :param project: :param repository: :param data: :return: """ url = 'rest/branch-utils/1.0/projects/{project}/repos/{repository}/branchmodel/configuration'.format( ...
Set branching model :param project: :param repository: :param data: :return:
Below is the the instruction that describes the task: ### Input: Set branching model :param project: :param repository: :param data: :return: ### Response: def set_branching_model(self, project, repository, data): """ Set branching model :param project: ...
def owned(self): """ Returns True if this key is locked by this lock, otherwise False. """ stored_token = self.redis.get(self.name) # need to always compare bytes to bytes # TODO: this can be simplified when the context manager is finished if stored_token and not ...
Returns True if this key is locked by this lock, otherwise False.
Below is the the instruction that describes the task: ### Input: Returns True if this key is locked by this lock, otherwise False. ### Response: def owned(self): """ Returns True if this key is locked by this lock, otherwise False. """ stored_token = self.redis.get(self.name) ...
def create_organisation(self, organisation_json): ''' Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`. ''' return trolly.organisation.Organisation( trello_client=self, ...
Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`.
Below is the the instruction that describes the task: ### Input: Create an Organisation object from a JSON object Returns: Organisation: The organisation from the given `organisation_json`. ### Response: def create_organisation(self, organisation_json): ''' Create an Organisati...
def updatepLvlGrid(self): ''' Update the grid of persistent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1 because the distribution of persistent income will be different within a p...
Update the grid of persistent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1 because the distribution of persistent income will be different within a period depending on how many cycles hav...
Below is the the instruction that describes the task: ### Input: Update the grid of persistent income levels. Currently only works for infinite horizon models (cycles=0) and lifecycle models (cycles=1). Not clear what to do about cycles>1 because the distribution of persistent income will ...
def delete_row(self): """Delete bookmarks or event from annotations, based on row.""" sel_model = self.idx_annot_list.selectionModel() for row in sel_model.selectedRows(): i = row.row() start = self.idx_annot_list.property('start')[i] end = self.idx_annot_list...
Delete bookmarks or event from annotations, based on row.
Below is the the instruction that describes the task: ### Input: Delete bookmarks or event from annotations, based on row. ### Response: def delete_row(self): """Delete bookmarks or event from annotations, based on row.""" sel_model = self.idx_annot_list.selectionModel() for row in sel_mode...
def StatusActionFactory(version, build=None, base_class=BaseStatusAction): # noqa """ A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: ...
A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: union[str, unicode] :param base_class: The optional base class, to override `BaseStatusActi...
Below is the the instruction that describes the task: ### Input: A factory for creating a new status action class specific to a service. :param version: The service version :type version: union[str, unicode] :param build: The optional service build identifier :type build: union[str, unicode] :p...
def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]: """Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] """ return self.__func
Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]]
Below is the the instruction that describes the task: ### Input: Get wrapped function. :rtype: typing.Optional[typing.Callable[..., typing.Union[typing.Awaitable, typing.Any]]] ### Response: def _func(self) -> typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]]:...
def _mainType(self, resp): """ gets the main type from the response object""" if self.PY2: return resp.headers.maintype elif self.PY3: return resp.headers.get_content_maintype() else: return None
gets the main type from the response object
Below is the the instruction that describes the task: ### Input: gets the main type from the response object ### Response: def _mainType(self, resp): """ gets the main type from the response object""" if self.PY2: return resp.headers.maintype elif self.PY3: return re...
def guess_param_types(**kwargs): """ Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics. """ params = {} for k, v in kwargs.items(): kws = dict(default=v, constant=True) if isinstance(v, Parameter): params[k] = v...
Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics.
Below is the the instruction that describes the task: ### Input: Given a set of keyword literals, promote to the appropriate parameter type based on some simple heuristics. ### Response: def guess_param_types(**kwargs): """ Given a set of keyword literals, promote to the appropriate parameter type ...
def __get_merge_versions(self, merge_id): """Get merge versions""" versions = [] group_versions = self.client.merge_versions(merge_id) for raw_versions in group_versions: for version in json.loads(raw_versions): version_id = version['id'] ve...
Get merge versions
Below is the the instruction that describes the task: ### Input: Get merge versions ### Response: def __get_merge_versions(self, merge_id): """Get merge versions""" versions = [] group_versions = self.client.merge_versions(merge_id) for raw_versions in group_versions: ...
def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. """ if n > 0 and other_day < reference_day: n = n - 1 elif n <= 0 and other_day > reference_day: n = n + 1 ...
Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided.
Below is the the instruction that describes the task: ### Input: Adjust the number of times a monthly offset is applied based on the day of a given date, and the reference day provided. ### Response: def _adjust_n_months(other_day, n, reference_day): """Adjust the number of times a monthly offset is applie...
def _proxy_to_logger(self, method_name, event, *event_args, **event_kw): """ Propagate a method call to the wrapped logger. This is the same as the superclass implementation, except that it also preserves positional arguments in the `event_dict` so that ...
Propagate a method call to the wrapped logger. This is the same as the superclass implementation, except that it also preserves positional arguments in the `event_dict` so that the stdblib's support for format strings can be used.
Below is the the instruction that describes the task: ### Input: Propagate a method call to the wrapped logger. This is the same as the superclass implementation, except that it also preserves positional arguments in the `event_dict` so that the stdblib's support for format strings can be u...
def load_index(self, filename, reindex=False): ''' Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every fil...
Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every file in the loaded index against the entities ...
Below is the the instruction that describes the task: ### Input: Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes...
def secret_loader(self, callback): """ Decorate a method that receives a key id and returns a secret key """ if not callback or not callable(callback): raise Exception("Please pass in a callable that loads secret keys") self.secret_loader_callback = callback r...
Decorate a method that receives a key id and returns a secret key
Below is the the instruction that describes the task: ### Input: Decorate a method that receives a key id and returns a secret key ### Response: def secret_loader(self, callback): """ Decorate a method that receives a key id and returns a secret key """ if not callback or not callab...
def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--name', '-n', required=True, action='store', help='Name of vmss') arg_parser.add_argument('--capacity', '-c', required=True, action='store',...
Main routine.
Below is the the instruction that describes the task: ### Input: Main routine. ### Response: def main(): '''Main routine.''' # validate command line arguments arg_parser = argparse.ArgumentParser() arg_parser.add_argument('--name', '-n', required=True, action='store', h...
async def fetch_invite(self, *, with_counts=True): """|coro| Retrieves an :class:`Invite` from a invite URL or ID. This is the same as :meth:`Client.get_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` Wh...
|coro| Retrieves an :class:`Invite` from a invite URL or ID. This is the same as :meth:`Client.get_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` Whether to include count information in the invite. This fills t...
Below is the the instruction that describes the task: ### Input: |coro| Retrieves an :class:`Invite` from a invite URL or ID. This is the same as :meth:`Client.get_invite`; the invite code is abstracted away. Parameters ----------- with_counts: :class:`bool` ...
def __WaitForVolume(volume, desired_state): """ Blocks until EBS volume is in desired state. """ print 'Waiting for volume %s to be %s...' % (volume.id, desired_state) while True: volume.update() sys.stdout.write('.') sys.stdout.flush() #print 'status is: %s' % volume.status if volume.status =...
Blocks until EBS volume is in desired state.
Below is the the instruction that describes the task: ### Input: Blocks until EBS volume is in desired state. ### Response: def __WaitForVolume(volume, desired_state): """ Blocks until EBS volume is in desired state. """ print 'Waiting for volume %s to be %s...' % (volume.id, desired_state) while True: v...
def get_thumbnail_format(self): """ Determines the target thumbnail type either by looking for a format override specified at the model level, or by using the format the user uploaded. """ if self.field.thumbnail_format: # Over-ride was given, use that instead...
Determines the target thumbnail type either by looking for a format override specified at the model level, or by using the format the user uploaded.
Below is the the instruction that describes the task: ### Input: Determines the target thumbnail type either by looking for a format override specified at the model level, or by using the format the user uploaded. ### Response: def get_thumbnail_format(self): """ Determines the targ...
def _example_stock_quote(quote_ctx): """ 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 """ stock_code_list = ["US.AAPL", "HK.00700"] # subscribe "QUOTE" ret_status, ret_data = quote_ctx.subscribe(stock_code_list, ft.SubType.QUOTE) if ret_status != ft.RET_OK: print("%s ...
获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态
Below is the the instruction that describes the task: ### Input: 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 ### Response: def _example_stock_quote(quote_ctx): """ 获取批量报价,输出 股票名称,时间,当前价,开盘价,最高价,最低价,昨天收盘价,成交量,成交额,换手率,振幅,股票状态 """ stock_code_list = ["US.AAPL", "HK.00700"] # subscr...
def is_carrier_specific(numobj): """Given a valid short number, determines whether it is carrier-specific (however, nothing is implied about its validity). Carrier-specific numbers may connect to a different end-point, or not connect at all, depending on the user's carrier. If it is important that the ...
Given a valid short number, determines whether it is carrier-specific (however, nothing is implied about its validity). Carrier-specific numbers may connect to a different end-point, or not connect at all, depending on the user's carrier. If it is important that the number is valid, then its validity m...
Below is the the instruction that describes the task: ### Input: Given a valid short number, determines whether it is carrier-specific (however, nothing is implied about its validity). Carrier-specific numbers may connect to a different end-point, or not connect at all, depending on the user's carrier....
def _add_seg_to_output(out, data, enumerate_chroms=False): """Export outputs to 'seg' format compatible with IGV and GenePattern. """ out_file = "%s.seg" % os.path.splitext(out["cns"])[0] if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: cmd = ...
Export outputs to 'seg' format compatible with IGV and GenePattern.
Below is the the instruction that describes the task: ### Input: Export outputs to 'seg' format compatible with IGV and GenePattern. ### Response: def _add_seg_to_output(out, data, enumerate_chroms=False): """Export outputs to 'seg' format compatible with IGV and GenePattern. """ out_file = "%s.seg" % ...
def extractContent(self, text): """Extract the content of comment text. """ m = self.nextValidComment(text) return '' if m is None else m.group(1)
Extract the content of comment text.
Below is the the instruction that describes the task: ### Input: Extract the content of comment text. ### Response: def extractContent(self, text): """Extract the content of comment text. """ m = self.nextValidComment(text) return '' if m is None else m.group(1)
def save_current_nb_as_html(info=False): """ Save the current notebook as html file in the same directory """ assert in_ipynb() full_path = get_notebook_name() path, filename = os.path.split(full_path) wd_save = os.getcwd() os.chdir(path) cmd = 'jupyter nbconvert --to html "{}"'.fo...
Save the current notebook as html file in the same directory
Below is the the instruction that describes the task: ### Input: Save the current notebook as html file in the same directory ### Response: def save_current_nb_as_html(info=False): """ Save the current notebook as html file in the same directory """ assert in_ipynb() full_path = get_notebook_n...
def start(self): """Start scheduling""" self.stop() self.initialize() self.handle = self.loop.call_at(self.get_next(), self.call_next)
Start scheduling
Below is the the instruction that describes the task: ### Input: Start scheduling ### Response: def start(self): """Start scheduling""" self.stop() self.initialize() self.handle = self.loop.call_at(self.get_next(), self.call_next)
def _set_tacacs_server(self, v, load=False): """ Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_tacacs_server is considered as a private method. Backends looking to populate this v...
Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_tacacs_server is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_tacacs_...
Below is the the instruction that describes the task: ### Input: Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container) If this variable is read-only (config: false) in the source YANG file, then _set_tacacs_server is considered as a private method. Backends looking to pop...
def RecurseKeys(self): """Recurses the subkeys starting with the key. Yields: WinRegistryKey: Windows Registry key. """ yield self for subkey in self.GetSubkeys(): for key in subkey.RecurseKeys(): yield key
Recurses the subkeys starting with the key. Yields: WinRegistryKey: Windows Registry key.
Below is the the instruction that describes the task: ### Input: Recurses the subkeys starting with the key. Yields: WinRegistryKey: Windows Registry key. ### Response: def RecurseKeys(self): """Recurses the subkeys starting with the key. Yields: WinRegistryKey: Windows Registry key. ...
def _random_block(): """ Generate a random string of `BLOCK_SIZE` length. """ # TODO: Use a better RNG than random.randint random_number = random.randint(0, DISCRETE_VALUES) random_string = _to_base36(random_number) return _pad(random_string, BLOCK_SIZE)
Generate a random string of `BLOCK_SIZE` length.
Below is the the instruction that describes the task: ### Input: Generate a random string of `BLOCK_SIZE` length. ### Response: def _random_block(): """ Generate a random string of `BLOCK_SIZE` length. """ # TODO: Use a better RNG than random.randint random_number = random.randint(0, DISCRETE_V...
def body(self): """Gets the JSON body of the request""" if self._decoded_body == None: # Try to decode the JSON body. But raise an error if the # content-type is unexpected, or the JSON is invalid. raw_content_type = self.request.headers.get("content-type") or "" ...
Gets the JSON body of the request
Below is the the instruction that describes the task: ### Input: Gets the JSON body of the request ### Response: def body(self): """Gets the JSON body of the request""" if self._decoded_body == None: # Try to decode the JSON body. But raise an error if the # content-type is...
def argv2line(argv): r"""Put together the given argument vector into a command line. "argv" is the argument vector to process. >>> from cmdln import argv2line >>> argv2line(['foo']) 'foo' >>> argv2line(['foo', 'bar']) 'foo bar' >>> argv2line(['foo', 'bar baz']) 'foo "bar baz"' ...
r"""Put together the given argument vector into a command line. "argv" is the argument vector to process. >>> from cmdln import argv2line >>> argv2line(['foo']) 'foo' >>> argv2line(['foo', 'bar']) 'foo bar' >>> argv2line(['foo', 'bar baz']) 'foo "bar baz"' >>> argv2line(['foo"b...
Below is the the instruction that describes the task: ### Input: r"""Put together the given argument vector into a command line. "argv" is the argument vector to process. >>> from cmdln import argv2line >>> argv2line(['foo']) 'foo' >>> argv2line(['foo', 'bar']) 'foo bar' >>> argv2l...
def read(self, n): """Read `n` chars from buffer""" r = self.buf[self.offset:self.offset + n] if isinstance(r, array): r = r.tostring() self.offset += n return r
Read `n` chars from buffer
Below is the the instruction that describes the task: ### Input: Read `n` chars from buffer ### Response: def read(self, n): """Read `n` chars from buffer""" r = self.buf[self.offset:self.offset + n] if isinstance(r, array): r = r.tostring() self.offset += n retu...
async def _get_entity_from_string(self, string): """ Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side eff...
Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side effect of adding the found users to the session database, so it ...
Below is the the instruction that describes the task: ### Input: Gets a full entity from the given string, which may be a phone or a username, and processes all the found entities on the session. The string may also be a user link, or a channel/chat invite link. This method has the side eff...
def set_scale(self): """generate the lookup which translates y-coordinate to fft-bin""" f_min = float(self.lower_freq) f_max = float(self.higher_freq) y_min = f_min y_max = f_max for y in range(self.image_height): freq = y_min + y / (self.image_height - 1.0) ...
generate the lookup which translates y-coordinate to fft-bin
Below is the the instruction that describes the task: ### Input: generate the lookup which translates y-coordinate to fft-bin ### Response: def set_scale(self): """generate the lookup which translates y-coordinate to fft-bin""" f_min = float(self.lower_freq) f_max = float(self.higher_freq)...
def _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles Pandas DataFrames. """ if schema is None: schema = google.datalab.bigquery.Schema.from_data(source) fields = get_field_list(fields, schema) rows = [] if count < 0: count...
Helper function for _get_data that handles Pandas DataFrames.
Below is the the instruction that describes the task: ### Input: Helper function for _get_data that handles Pandas DataFrames. ### Response: def _get_data_from_dataframe(source, fields='*', first_row=0, count=-1, schema=None): """ Helper function for _get_data that handles Pandas DataFrames. """ if schema is N...
def _construct_message(self): """Build the message params.""" self.message["chat_id"] = self.chat_id self.message["text"] = "" if self.from_: self.message["text"] += "From: " + self.from_ + "\n" if self.subject: self.message["text"] += "Subject: " + self.s...
Build the message params.
Below is the the instruction that describes the task: ### Input: Build the message params. ### Response: def _construct_message(self): """Build the message params.""" self.message["chat_id"] = self.chat_id self.message["text"] = "" if self.from_: self.message["text"] += ...
def kdf_hmac(self): """ Returns the HMAC algorithm to use with the KDF. :return: A unicode string of one of the following: "md2", "md5", "sha1", "sha224", "sha256", "sha384", "sha512" """ encryption_algo = self['algorithm'].native if encryption_...
Returns the HMAC algorithm to use with the KDF. :return: A unicode string of one of the following: "md2", "md5", "sha1", "sha224", "sha256", "sha384", "sha512"
Below is the the instruction that describes the task: ### Input: Returns the HMAC algorithm to use with the KDF. :return: A unicode string of one of the following: "md2", "md5", "sha1", "sha224", "sha256", "sha384", "sha512" ### Response: def kdf_hmac(self): """ Ret...
def get_best_single_experiments(nets,expvars): ''' returns the experiments as a``TermSet`` object [instance]. ''' netsf = nets.to_file() expvarsf = expvars.to_file() i = 1 #single experiment num_exp = String2TermSet('pexperiment('+str(i)+')') num_expf = num_exp.to_file() prg = [ netsf, e...
returns the experiments as a``TermSet`` object [instance].
Below is the the instruction that describes the task: ### Input: returns the experiments as a``TermSet`` object [instance]. ### Response: def get_best_single_experiments(nets,expvars): ''' returns the experiments as a``TermSet`` object [instance]. ''' netsf = nets.to_file() expvarsf = expvars.to_file(...
def unwrap(klass, value): """Unpack a Value into an augmented python type (selected from the 'value' field) """ assert isinstance(value, Value), value V = value.value try: T = klass.typeMap[type(V)] except KeyError: raise ValueError("Can't unwrap v...
Unpack a Value into an augmented python type (selected from the 'value' field)
Below is the the instruction that describes the task: ### Input: Unpack a Value into an augmented python type (selected from the 'value' field) ### Response: def unwrap(klass, value): """Unpack a Value into an augmented python type (selected from the 'value' field) """ assert isinstance(val...
def finalize(self): """ Add title and modify axes to make the image ready for display. """ self.set_title( '{} Manifold (fit in {:0.2f} seconds)'.format( self._name, self.fit_time_.interval ) ) self.ax.set_xticklabels([]) se...
Add title and modify axes to make the image ready for display.
Below is the the instruction that describes the task: ### Input: Add title and modify axes to make the image ready for display. ### Response: def finalize(self): """ Add title and modify axes to make the image ready for display. """ self.set_title( '{} Manifold (fit in {...
def get_fw_version(self): ''' Queries Smoothieware for it's build version, and returns the parsed response. returns: str Current version of attached Smoothi-driver. Versions are derived from git branch-hash (eg: edge-66ec883NOMSD) Example Smoothieware re...
Queries Smoothieware for it's build version, and returns the parsed response. returns: str Current version of attached Smoothi-driver. Versions are derived from git branch-hash (eg: edge-66ec883NOMSD) Example Smoothieware response: Build version: edge-66ec883NO...
Below is the the instruction that describes the task: ### Input: Queries Smoothieware for it's build version, and returns the parsed response. returns: str Current version of attached Smoothi-driver. Versions are derived from git branch-hash (eg: edge-66ec883NOMSD) ...
def get_queryset(self): """ Returns the list of items for this view. """ # Determines the forums that can be accessed by the current user forums = self.request.forum_permission_handler.get_readable_forums( Forum.objects.all(), self.request.user, ) # Returns the posts...
Returns the list of items for this view.
Below is the the instruction that describes the task: ### Input: Returns the list of items for this view. ### Response: def get_queryset(self): """ Returns the list of items for this view. """ # Determines the forums that can be accessed by the current user forums = self.request.forum_permi...
def get_handler_fp(logger): """ Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`...
Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's stream. We call it `handler_fp`.
Below is the the instruction that describes the task: ### Input: Get handler_fp. This method is integrated to LoggerFactory Object in the future. :param logging.Logger logger: Python logging.Logger. logger instance. :rtype: logging.Logger.handlers.BaseRotatingHandler :return: Handler or Handler's st...
def _handle_put(self, request): # type: (Put) -> CallbackResponses """Called with the lock taken""" attribute_name = request.path[1] attribute = self._block[attribute_name] assert isinstance(attribute, AttributeModel), \ "Cannot Put to %s which is a %s" % (attribute....
Called with the lock taken
Below is the the instruction that describes the task: ### Input: Called with the lock taken ### Response: def _handle_put(self, request): # type: (Put) -> CallbackResponses """Called with the lock taken""" attribute_name = request.path[1] attribute = self._block[attribute_name] ...
def nextstate(self, newstate, treenode=None, user_data=None): """ Manage transition of state. """ if newstate is None: return self if isinstance(newstate, State) and id(newstate) != id(self): return newstate elif isinstance(newstate, StateEvent): ...
Manage transition of state.
Below is the the instruction that describes the task: ### Input: Manage transition of state. ### Response: def nextstate(self, newstate, treenode=None, user_data=None): """ Manage transition of state. """ if newstate is None: return self if isinstance(newstate, S...
def softmax(attrs, inputs, proto_obj): """Softmax function.""" if 'axis' not in attrs: attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1}) return 'softmax', attrs, inputs
Softmax function.
Below is the the instruction that describes the task: ### Input: Softmax function. ### Response: def softmax(attrs, inputs, proto_obj): """Softmax function.""" if 'axis' not in attrs: attrs = translation_utils._add_extra_attributes(attrs, {'axis': 1}) return 'softmax', attrs, inputs
def schedule_start(self) -> bool: """Schedule the task: check first if the task can start: 1. we check that the task is still in the CREATED state. 2. we check that the upstream dependency is met. 3. we check that pipeline can start a new task; i.e. we check the...
Schedule the task: check first if the task can start: 1. we check that the task is still in the CREATED state. 2. we check that the upstream dependency is met. 3. we check that pipeline can start a new task; i.e. we check the concurrency of the pipeline. 4. ...
Below is the the instruction that describes the task: ### Input: Schedule the task: check first if the task can start: 1. we check that the task is still in the CREATED state. 2. we check that the upstream dependency is met. 3. we check that pipeline can start a new task; ...
def get_estimator(output_dir, train_config, args): """Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config ...
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean...
Below is the the instruction that describes the task: ### Input: Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our trai...
def tokenize(self, s): """Splits a string into tokens.""" s = tf.compat.as_text(s) if self.reserved_tokens: # First split out the reserved tokens substrs = self._reserved_tokens_re.split(s) else: substrs = [s] toks = [] for substr in substrs: if substr in self.reserved_...
Splits a string into tokens.
Below is the the instruction that describes the task: ### Input: Splits a string into tokens. ### Response: def tokenize(self, s): """Splits a string into tokens.""" s = tf.compat.as_text(s) if self.reserved_tokens: # First split out the reserved tokens substrs = self._reserved_tokens_re.s...
def _get_art_abs(story_file): """Get abstract (highlights) and article from a story file path.""" # Based on https://github.com/abisee/cnn-dailymail/blob/master/ # make_datafiles.py lines = _read_text_file(story_file) # Lowercase everything lines = [line.lower() for line in lines] # Put periods on ...
Get abstract (highlights) and article from a story file path.
Below is the the instruction that describes the task: ### Input: Get abstract (highlights) and article from a story file path. ### Response: def _get_art_abs(story_file): """Get abstract (highlights) and article from a story file path.""" # Based on https://github.com/abisee/cnn-dailymail/blob/master/ # ...
def reject_record(self, record): """Reject a record for inclusion in the community. :param record: Record object. """ with db.session.begin_nested(): req = InclusionRequest.get(self.id, record.id) if req is None: raise InclusionRequestMissingError...
Reject a record for inclusion in the community. :param record: Record object.
Below is the the instruction that describes the task: ### Input: Reject a record for inclusion in the community. :param record: Record object. ### Response: def reject_record(self, record): """Reject a record for inclusion in the community. :param record: Record object. """ ...
def get_stp_mst_detail_output_cist_cist_bridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") cist ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def get_stp_mst_detail_output_cist_cist_bridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") ...
def update(self, *args, **kwargs): """See `__setitem__`.""" super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: item.name = key
See `__setitem__`.
Below is the the instruction that describes the task: ### Input: See `__setitem__`. ### Response: def update(self, *args, **kwargs): """See `__setitem__`.""" super(TAG_Compound, self).update(*args, **kwargs) for key, item in self.items(): if item.name is None: it...
def execute_lite(self, instructions, context=None): """Execute a list of instructions. It does not support loops. """ if context: self.__cpu.registers = dict(context) for instr in instructions: self.__execute_one(instr) return dict(self.__cpu.registers),...
Execute a list of instructions. It does not support loops.
Below is the the instruction that describes the task: ### Input: Execute a list of instructions. It does not support loops. ### Response: def execute_lite(self, instructions, context=None): """Execute a list of instructions. It does not support loops. """ if context: self.__cpu....
def on_episode_end(self, episode, logs): """ Compute and print metrics at the end of each episode """ duration = timeit.default_timer() - self.starts[episode] metrics = self.metrics[episode] if np.isnan(metrics).all(): mean_metrics = np.array([np.nan for _ in self.metrics_n...
Compute and print metrics at the end of each episode
Below is the the instruction that describes the task: ### Input: Compute and print metrics at the end of each episode ### Response: def on_episode_end(self, episode, logs): """ Compute and print metrics at the end of each episode """ duration = timeit.default_timer() - self.starts[episode] ...
def concatenate(vars, axis=-1): """ A utility function of concatenate. """ from deepy.core.neural_var import NeuralVariable if isinstance(vars[0], NeuralVariable): concat_var = Concatenate(axis=axis).compute(*vars) if axis == -1 or axis == vars[0].tensor.ndim - 1: concat_...
A utility function of concatenate.
Below is the the instruction that describes the task: ### Input: A utility function of concatenate. ### Response: def concatenate(vars, axis=-1): """ A utility function of concatenate. """ from deepy.core.neural_var import NeuralVariable if isinstance(vars[0], NeuralVariable): concat_va...
def start(self): ''' Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ''' super(ProxyMinion, self).start() try: if check_...
Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`.
Below is the the instruction that describes the task: ### Input: Start the actual proxy minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).start() NOTE: Run any required code before calling `super()`. ### Response: def start(self): ''' Sta...
def timed (log=sys.stderr, limit=2.0): """Decorator to run a function with timing info.""" return lambda func: timeit(func, log, limit)
Decorator to run a function with timing info.
Below is the the instruction that describes the task: ### Input: Decorator to run a function with timing info. ### Response: def timed (log=sys.stderr, limit=2.0): """Decorator to run a function with timing info.""" return lambda func: timeit(func, log, limit)
def _GetComparable(self, sub_comparable_string=''): """Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specification. """...
Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specification.
Below is the the instruction that describes the task: ### Input: Retrieves the comparable representation. This is a convenience function for constructing comparables. Args: sub_comparable_string (str): sub comparable string. Returns: str: comparable representation of the path specificatio...