code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def load_messages(self, directory, catalogue): """ Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError ...
Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError
Below is the the instruction that describes the task: ### Input: Loads translation found in a directory. @type directory: string @param directory: The directory to search @type catalogue: MessageCatalogue @param catalogue: The message catalogue to dump @raises: ValueError ...
def directory_is_present(self, directory_path): """ check if directory 'directory_path' is present, raise IOError if it's not a directory :param directory_path: str, directory to check :return: True if directory exists, False if directory does not exist """ p = self.p(di...
check if directory 'directory_path' is present, raise IOError if it's not a directory :param directory_path: str, directory to check :return: True if directory exists, False if directory does not exist
Below is the the instruction that describes the task: ### Input: check if directory 'directory_path' is present, raise IOError if it's not a directory :param directory_path: str, directory to check :return: True if directory exists, False if directory does not exist ### Response: def directory_is_...
def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks, remainder = divmod(count, BLOCKSIZE) if remainder: blocks += 1 return blocks * BLOCKSIZE
Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024.
Below is the the instruction that describes the task: ### Input: Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. ### Response: def _block(self, count): """Round up a byte count by BLOCKSIZE and return it, e.g. _block(834) => 1024. """ blocks...
def tdSensor(self): """Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. """ protocol = create_string_buffer(20) model = create_string_buffer(20) sid = c_int() datatypes = c_int() self._lib.tdSensor(proto...
Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes.
Below is the the instruction that describes the task: ### Input: Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id, datatypes. ### Response: def tdSensor(self): """Get the next sensor while iterating. :return: a dict with the keys: protocol, model, id...
def describe_directory(self, path): """ Returns a dictionary of {filename: {attributes}} for all files on the remote system (where the MLSD command is supported). :param path: full path to the remote directory :type path: str """ conn = self.get_conn() fli...
Returns a dictionary of {filename: {attributes}} for all files on the remote system (where the MLSD command is supported). :param path: full path to the remote directory :type path: str
Below is the the instruction that describes the task: ### Input: Returns a dictionary of {filename: {attributes}} for all files on the remote system (where the MLSD command is supported). :param path: full path to the remote directory :type path: str ### Response: def describe_directory(sel...
def contains (self, point): """contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2, 3) ) False """ return...
contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2, 3) ) False
Below is the the instruction that describes the task: ### Input: contains(point) -> True | False Returns True if point is contained inside this Rectangle, False otherwise. Examples: >>> r = Rect( Point(-1, -1), Point(1, 1) ) >>> r.contains( Point(0, 0) ) True >>> r.contains( Point(2,...
def add(i): """ Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (data_uid) - data UID (if uoa is an alias) (data_name) - user friendly data name ...
Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (data_uid) - data UID (if uoa is an alias) (data_name) - user friendly data name (dict_from_cid) ...
Below is the the instruction that describes the task: ### Input: Input: { (repo_uoa) - repo UOA module_uoa - module UOA data_uoa - data UOA (data_uid) - data UID (if uoa is an alias) (data_name) ...
def repr(self, changed_widgets=None): """Represents the widget as HTML format, packs all the attributes, children and so on. Args: client (App): Client instance. changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated. The ...
Represents the widget as HTML format, packs all the attributes, children and so on. Args: client (App): Client instance. changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated. The Widget that have to be updated is the key, and th...
Below is the the instruction that describes the task: ### Input: Represents the widget as HTML format, packs all the attributes, children and so on. Args: client (App): Client instance. changed_widgets (dict): A dictionary containing a collection of widgets that have to be updated. ...
def _find_observable_paths(extra_files=None): """Finds all paths that should be observed.""" rv = set( os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspath(x) for x in sys.path ) for filename in extra_files or (): rv.add(os.path.dirname(os.path.abspath(f...
Finds all paths that should be observed.
Below is the the instruction that describes the task: ### Input: Finds all paths that should be observed. ### Response: def _find_observable_paths(extra_files=None): """Finds all paths that should be observed.""" rv = set( os.path.dirname(os.path.abspath(x)) if os.path.isfile(x) else os.path.abspat...
def getrouteaddr(self): """Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. """ if self.field[self.pos] != '<': return expectroute = 0 self.pos += 1 self.gotonext() adlist = "" ...
Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec.
Below is the the instruction that describes the task: ### Input: Parse a route address (Return-path value). This method just skips all the route stuff and returns the addrspec. ### Response: def getrouteaddr(self): """Parse a route address (Return-path value). This method just skips all t...
def p_subidentifier_defval(self, p): """subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER""" n = len(p) if n == 2: p[0] = ('subidentifier_defval', p[1]) elif n == 5: p[0] = ('subidentifier_defval', p[1], p[3])
subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER
Below is the the instruction that describes the task: ### Input: subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' | NUMBER ### Response: def p_subidentifier_defval(self, p): """subidentifier_defval : LOWERCASE_IDENTIFIER '(' NUMBER ')' ...
def start_adc(self, channel, gain=1, data_rate=None): """Start continuous ADC conversions on the specified channel (0-3). Will return an initial conversion result, then call the get_last_result() function to read the most recent conversion result. Call stop_adc() to stop conversions. ...
Start continuous ADC conversions on the specified channel (0-3). Will return an initial conversion result, then call the get_last_result() function to read the most recent conversion result. Call stop_adc() to stop conversions.
Below is the the instruction that describes the task: ### Input: Start continuous ADC conversions on the specified channel (0-3). Will return an initial conversion result, then call the get_last_result() function to read the most recent conversion result. Call stop_adc() to stop conversions....
def start(self): """ Try to init the main sub-components (:func:`~responsebot.utils.handler_utils.discover_handler_classes`, \ :func:`~responsebot.utils.auth_utils.auth`, :class:`~responsebot.responsebot_stream.ResponseBotStream`, etc.) """ logging.info('ResponseBot started') ...
Try to init the main sub-components (:func:`~responsebot.utils.handler_utils.discover_handler_classes`, \ :func:`~responsebot.utils.auth_utils.auth`, :class:`~responsebot.responsebot_stream.ResponseBotStream`, etc.)
Below is the the instruction that describes the task: ### Input: Try to init the main sub-components (:func:`~responsebot.utils.handler_utils.discover_handler_classes`, \ :func:`~responsebot.utils.auth_utils.auth`, :class:`~responsebot.responsebot_stream.ResponseBotStream`, etc.) ### Response: def start(se...
def _detects_peaks(ecg_integrated, sample_rate): """ Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. ...
Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took place. Returns ------- choosen_peaks : list List of...
Below is the the instruction that describes the task: ### Input: Detects peaks from local maximum ---------- Parameters ---------- ecg_integrated : ndarray Array that contains the samples of the integrated signal. sample_rate : int Sampling rate at which the acquisition took pla...
def _recv_loop(self): """Service socket recv, returning responses to the correct queue""" self._completed_response_lines = [] self._is_multiline = None lines_iterator = self._get_lines() while True: try: line = next(lines_iterator) if s...
Service socket recv, returning responses to the correct queue
Below is the the instruction that describes the task: ### Input: Service socket recv, returning responses to the correct queue ### Response: def _recv_loop(self): """Service socket recv, returning responses to the correct queue""" self._completed_response_lines = [] self._is_multiline = Non...
def recarray_to_hdf5_group(ra, parent, name, **kwargs): """Write each column in a recarray to a dataset in an HDF5 group. Parameters ---------- ra : recarray Numpy recarray to store. parent : string or h5py group Parent HDF5 file or group. If a string, will be treated as HDF5 file ...
Write each column in a recarray to a dataset in an HDF5 group. Parameters ---------- ra : recarray Numpy recarray to store. parent : string or h5py group Parent HDF5 file or group. If a string, will be treated as HDF5 file name. name : string Name or path of group to...
Below is the the instruction that describes the task: ### Input: Write each column in a recarray to a dataset in an HDF5 group. Parameters ---------- ra : recarray Numpy recarray to store. parent : string or h5py group Parent HDF5 file or group. If a string, will be treated as HDF5 ...
def processLedger(self) -> None: """ Checks ledger for planned but not yet performed upgrades and schedules upgrade for the most recent one Assumption: Only version is enough to identify a release, no hash checking is done :return: """ logger.debug( ...
Checks ledger for planned but not yet performed upgrades and schedules upgrade for the most recent one Assumption: Only version is enough to identify a release, no hash checking is done :return:
Below is the the instruction that describes the task: ### Input: Checks ledger for planned but not yet performed upgrades and schedules upgrade for the most recent one Assumption: Only version is enough to identify a release, no hash checking is done :return: ### Response: def proc...
def reload(self): """Reload source from disk and initialize state.""" # read data and parse into blocks self.fload() lines = self.fobj.readlines() src_b = [l for l in lines if l.strip()] nblocks = len(src_b) self.src = ''.join(li...
Reload source from disk and initialize state.
Below is the the instruction that describes the task: ### Input: Reload source from disk and initialize state. ### Response: def reload(self): """Reload source from disk and initialize state.""" # read data and parse into blocks self.fload() lines = self.fobj.readlines() ...
def matches(self, other, **kwargs): """ Check whether this structure is similar to another structure. Basically a convenience method to call structure matching fitting. Args: other (IStructure/Structure): Another structure. **kwargs: Same **kwargs as in ...
Check whether this structure is similar to another structure. Basically a convenience method to call structure matching fitting. Args: other (IStructure/Structure): Another structure. **kwargs: Same **kwargs as in :class:`pymatgen.analysis.structure_matcher.Struc...
Below is the the instruction that describes the task: ### Input: Check whether this structure is similar to another structure. Basically a convenience method to call structure matching fitting. Args: other (IStructure/Structure): Another structure. **kwargs: Same **kwargs as...
def contours( self, elevation, interval=100, field='elev', base=0 ): """ Extract contour lines from elevation data. Parameters ---------- elevation : array input elevation data interval : integer elevation value interval when drawing c...
Extract contour lines from elevation data. Parameters ---------- elevation : array input elevation data interval : integer elevation value interval when drawing contour lines field : string output field name containing elevation value ...
Below is the the instruction that describes the task: ### Input: Extract contour lines from elevation data. Parameters ---------- elevation : array input elevation data interval : integer elevation value interval when drawing contour lines field : str...
def shall_skip(module, opts): """Check if we want to skip this module.""" # skip it if there is nothing (or just \n or \r\n) in the file if path.getsize(module) <= 2: return True # skip if it has a "private" name and this is selected filename = path.basename(module) if filename != '__ini...
Check if we want to skip this module.
Below is the the instruction that describes the task: ### Input: Check if we want to skip this module. ### Response: def shall_skip(module, opts): """Check if we want to skip this module.""" # skip it if there is nothing (or just \n or \r\n) in the file if path.getsize(module) <= 2: return True...
def get_stats(self, container_id): """ :param container_id: :return: an iterable that contains dictionnaries with the stats of the running container. See the docker api for content. """ return self._docker.containers.get(container_id).stats(decode=True)
:param container_id: :return: an iterable that contains dictionnaries with the stats of the running container. See the docker api for content.
Below is the the instruction that describes the task: ### Input: :param container_id: :return: an iterable that contains dictionnaries with the stats of the running container. See the docker api for content. ### Response: def get_stats(self, container_id): """ :param container_id: :...
def optimize(self, n_particles=50, n_iterations=250, restart=1): """ the best result of all optimizations will be returned. total number of lens models sovled: n_particles*n_iterations :param n_particles: number of particle swarm particles :param n_iterations: number of particl...
the best result of all optimizations will be returned. total number of lens models sovled: n_particles*n_iterations :param n_particles: number of particle swarm particles :param n_iterations: number of particle swarm iternations :param restart: number of times to execute the optimizatio...
Below is the the instruction that describes the task: ### Input: the best result of all optimizations will be returned. total number of lens models sovled: n_particles*n_iterations :param n_particles: number of particle swarm particles :param n_iterations: number of particle swarm iternatio...
def flash_spi_attach(self, hspi_arg): """Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command. """ # last 3 bytes in ESP_SPI_ATTACH argument are reserved values arg = struct.pack('<I', hsp...
Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command.
Below is the the instruction that describes the task: ### Input: Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command. ### Response: def flash_spi_attach(self, hspi_arg): """Send SPI attach command to enable...
def unlock_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") unlock = ET.Element("unlock") config = unlock input = ET.SubElement(unlock, "input") target = ET.SubElement(input, "target") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def unlock_input_target_config_target_candidate_candidate(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") unlock = ET.Element("unlock") config = unloc...
def _process_mrk_acc_view(self): """ Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return: """ # make a pass through the table first, # to create the mapping between the e...
Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return:
Below is the the instruction that describes the task: ### Input: Use this table to create the idmap between the internal marker id and the public mgiid. No triples are produced in this process :return: ### Response: def _process_mrk_acc_view(self): """ Use this table to crea...
def add(self, field, data_type=None, nullable=True, metadata=None): """ Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_...
Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_type, nullable (optional), metadata(optional). The data_type parameter ma...
Below is the the instruction that describes the task: ### Input: Construct a StructType by adding new elements to it to define the schema. The method accepts either: a) A single parameter which is a StructField object. b) Between 2 and 4 parameters as (name, data_type, nullable (opt...
def dasrfr(handle, lenout=_default_len_out): """ Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :type lenout: ...
Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :type lenout: str :return: ID word, DAS internal file name, Number ...
Below is the the instruction that describes the task: ### Input: Return the contents of the file record of a specified DAS file. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dasrfr_c.html :param handle: DAS file handle. :type handle: int :param lenout: length of output strs :t...
def save(filename_audio, filename_jam, jam, strict=True, fmt='auto', **kwargs): '''Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool Strict safety checking...
Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool Strict safety checking for jams output fmt : str Output format parameter for `jams.JAMS.save` ...
Below is the the instruction that describes the task: ### Input: Save a muda jam to disk Parameters ---------- filename_audio: str The path to store the audio file filename_jam: str The path to store the jams object strict: bool Strict safety checking for jams output ...
def select(self, columns=(), by=(), where=(), **kwds): """select from self >>> t = q('([]a:1 2 3; b:10 20 30)') >>> t.select('a', where='b > 20').show() a - 3 """ return self._seu('select', columns, by, where, kwds)
select from self >>> t = q('([]a:1 2 3; b:10 20 30)') >>> t.select('a', where='b > 20').show() a - 3
Below is the the instruction that describes the task: ### Input: select from self >>> t = q('([]a:1 2 3; b:10 20 30)') >>> t.select('a', where='b > 20').show() a - 3 ### Response: def select(self, columns=(), by=(), where=(), **kwds): """select from self >>...
def get_code(dag_id): """Return python code of a given dag_id.""" session = settings.Session() DM = models.DagModel dag = session.query(DM).filter(DM.dag_id == dag_id).first() session.close() # Check DAG exists. if dag is None: error_message = "Dag id {} not found".format(dag_id) ...
Return python code of a given dag_id.
Below is the the instruction that describes the task: ### Input: Return python code of a given dag_id. ### Response: def get_code(dag_id): """Return python code of a given dag_id.""" session = settings.Session() DM = models.DagModel dag = session.query(DM).filter(DM.dag_id == dag_id).first() se...
def send_to_output(master_dict, mash_output, sample_id, assembly_file): """Send dictionary to output json file This function sends master_dict dictionary to a json file if master_dict is populated with entries, otherwise it won't create the file Parameters ---------- master_dict: dict d...
Send dictionary to output json file This function sends master_dict dictionary to a json file if master_dict is populated with entries, otherwise it won't create the file Parameters ---------- master_dict: dict dictionary that stores all entries for a specific query sequence in mult...
Below is the the instruction that describes the task: ### Input: Send dictionary to output json file This function sends master_dict dictionary to a json file if master_dict is populated with entries, otherwise it won't create the file Parameters ---------- master_dict: dict dictionary ...
def to_dict(self): """ Convert this FunctionDoc to a dictionary. In addition to `CommentDoc` keys, this adds: - **name**: The function name - **params**: A list of parameter dictionaries - **options**: A list of option dictionaries - **exceptions...
Convert this FunctionDoc to a dictionary. In addition to `CommentDoc` keys, this adds: - **name**: The function name - **params**: A list of parameter dictionaries - **options**: A list of option dictionaries - **exceptions**: A list of exception dictionaries ...
Below is the the instruction that describes the task: ### Input: Convert this FunctionDoc to a dictionary. In addition to `CommentDoc` keys, this adds: - **name**: The function name - **params**: A list of parameter dictionaries - **options**: A list of option dictionar...
def print_dot(docgraph): """ converts a document graph into a dot file and returns it as a string. If this function call is prepended by %dotstr, it will display the given document graph as a dot/graphviz graph in the currently running IPython notebook session. To use this function, the gvmagi...
converts a document graph into a dot file and returns it as a string. If this function call is prepended by %dotstr, it will display the given document graph as a dot/graphviz graph in the currently running IPython notebook session. To use this function, the gvmagic IPython notebook extension need...
Below is the the instruction that describes the task: ### Input: converts a document graph into a dot file and returns it as a string. If this function call is prepended by %dotstr, it will display the given document graph as a dot/graphviz graph in the currently running IPython notebook session. ...
def load_args_and_kwargs(func, args, data=None, ignore_invalid=False): ''' Detect the args and kwargs that need to be passed to a function call, and check them against what was passed. ''' argspec = salt.utils.args.get_function_argspec(func) _args = [] _kwargs = {} invalid_kwargs = [] ...
Detect the args and kwargs that need to be passed to a function call, and check them against what was passed.
Below is the the instruction that describes the task: ### Input: Detect the args and kwargs that need to be passed to a function call, and check them against what was passed. ### Response: def load_args_and_kwargs(func, args, data=None, ignore_invalid=False): ''' Detect the args and kwargs that need to...
def cache_set(self, to_cache): """ Set content into the cache """ self.cache.set(self.cache_key, to_cache, self.expire_time)
Set content into the cache
Below is the the instruction that describes the task: ### Input: Set content into the cache ### Response: def cache_set(self, to_cache): """ Set content into the cache """ self.cache.set(self.cache_key, to_cache, self.expire_time)
def save_as(self): """Save *as* the currently edited file""" editorstack = self.get_current_editorstack() if editorstack.save_as(): fname = editorstack.get_current_filename() self.__add_recent_file(fname)
Save *as* the currently edited file
Below is the the instruction that describes the task: ### Input: Save *as* the currently edited file ### Response: def save_as(self): """Save *as* the currently edited file""" editorstack = self.get_current_editorstack() if editorstack.save_as(): fname = editorstack.get_curr...
def strip_html(string, keep_tag_content=False): """ Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool ...
Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content: bool :return: String with html removed. :rtype: str
Below is the the instruction that describes the task: ### Input: Remove html code contained into the given string. :param string: String to manipulate. :type string: str :param keep_tag_content: True to preserve tag content, False to remove tag and its content too (default). :type keep_tag_content:...
def _refresh(self): """Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query. """ if l...
Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error on the query.
Below is the the instruction that describes the task: ### Input: Refreshes the cursor with more data from Mongo. Returns the length of self.__data after refresh. Will exit early if self.__data is already non-empty. Raises OperationFailure when the cursor cannot be refreshed due to an error ...
def mark(self, channel_name, ts): """ https://api.slack.com/methods/channels.mark """ channel_id = self.get_channel_id(channel_name) self.params.update({ 'channel': channel_id, 'ts': ts, }) return FromUrl('https://slack.com/api/channels....
https://api.slack.com/methods/channels.mark
Below is the the instruction that describes the task: ### Input: https://api.slack.com/methods/channels.mark ### Response: def mark(self, channel_name, ts): """ https://api.slack.com/methods/channels.mark """ channel_id = self.get_channel_id(channel_name) self.params.update({ ...
def mouse_press_event(self, event): """ Forward mouse press events to the example """ # Support left and right mouse button for now if event.button() not in [1, 2]: return self.example.mouse_press_event(event.x(), event.y(), event.button())
Forward mouse press events to the example
Below is the the instruction that describes the task: ### Input: Forward mouse press events to the example ### Response: def mouse_press_event(self, event): """ Forward mouse press events to the example """ # Support left and right mouse button for now if event.button()...
def list_snapshots_for_a_minute(path, cam_id, day, hourm): """Returns a list of screenshots""" screenshoots_path = path+"/"+str(cam_id)+"/"+day+"/"+hourm if os.path.exists(screenshoots_path): screenshots = [scr for scr in sorted(os.listdir(screenshoots_path))] return screenshots else: ...
Returns a list of screenshots
Below is the the instruction that describes the task: ### Input: Returns a list of screenshots ### Response: def list_snapshots_for_a_minute(path, cam_id, day, hourm): """Returns a list of screenshots""" screenshoots_path = path+"/"+str(cam_id)+"/"+day+"/"+hourm if os.path.exists(screenshoots_path): ...
def _get_vrfs(self): """Get the current VRFs configured in the device. :return: A list of vrf names as string """ vrfs = [] ios_cfg = self._get_running_config() parse = HTParser(ios_cfg) vrfs_raw = parse.find_lines("^vrf definition") for line in vrfs_raw:...
Get the current VRFs configured in the device. :return: A list of vrf names as string
Below is the the instruction that describes the task: ### Input: Get the current VRFs configured in the device. :return: A list of vrf names as string ### Response: def _get_vrfs(self): """Get the current VRFs configured in the device. :return: A list of vrf names as string """ ...
def getVersion(self, agent, word): """ => version string /None """ version_markers = self.version_markers if \ isinstance(self.version_markers[0], (list, tuple)) else [self.version_markers] version_part = agent.split(word, 1)[-1] for start, end in version_mark...
=> version string /None
Below is the the instruction that describes the task: ### Input: => version string /None ### Response: def getVersion(self, agent, word): """ => version string /None """ version_markers = self.version_markers if \ isinstance(self.version_markers[0], (list, tuple)) else [...
def _extract_jump_targets(stmt): """ Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list """ targets = [ ] # FIXME: We are...
Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list
Below is the the instruction that describes the task: ### Input: Extract goto targets from a Jump or a ConditionalJump statement. :param stmt: The statement to analyze. :return: A list of known concrete jump targets. :rtype: list ### Response: def _extract_jump_targets(st...
def p_localparamdecl_integer(self, p): 'localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON' paramlist = [Localparam(rname, rvalue, lineno=p.lineno(3)) for rname, rvalue in p[3]] p[0] = Decl(tuple(paramlist), lineno=p.lineno(1)) p.set_lineno(0, p.li...
localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON
Below is the the instruction that describes the task: ### Input: localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON ### Response: def p_localparamdecl_integer(self, p): 'localparamdecl : LOCALPARAM INTEGER param_substitution_list SEMICOLON' paramlist = [Localparam(rname, rvalue, ...
def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ ...
Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp
Below is the the instruction that describes the task: ### Input: Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp ###...
def push_uci(self, uci: str) -> Move: """ Parses a move in UCI notation and puts it on the move stack. Returns the move. :raises: :exc:`ValueError` if the move is invalid or illegal in the current position (but not a null move). """ move = self.parse_uci(uci...
Parses a move in UCI notation and puts it on the move stack. Returns the move. :raises: :exc:`ValueError` if the move is invalid or illegal in the current position (but not a null move).
Below is the the instruction that describes the task: ### Input: Parses a move in UCI notation and puts it on the move stack. Returns the move. :raises: :exc:`ValueError` if the move is invalid or illegal in the current position (but not a null move). ### Response: def push_uci(self, ...
def _filter_fields(self, filter_function): """ Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted. """...
Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted.
Below is the the instruction that describes the task: ### Input: Utility to iterate through all fields (super types first) of a type. :param filter: A function that takes in a Field object. If it returns True, the field is part of the generated output. If False, it is omitted. ### R...
def _get_sorted_section(self, nts_section): """Sort GO IDs in each section, if requested by user.""" #pylint: disable=unnecessary-lambda if self.section_sortby is True: return sorted(nts_section, key=lambda nt: self.sortgos.usrgo_sortby(nt)) if self.section_sortby is False or...
Sort GO IDs in each section, if requested by user.
Below is the the instruction that describes the task: ### Input: Sort GO IDs in each section, if requested by user. ### Response: def _get_sorted_section(self, nts_section): """Sort GO IDs in each section, if requested by user.""" #pylint: disable=unnecessary-lambda if self.section_sortby i...
def load_collectors_from_paths(paths): """ Scan for collectors to load from path """ # Initialize return value collectors = {} if paths is None: return if isinstance(paths, basestring): paths = paths.split(',') paths = map(str.strip, paths) load_include_path(pa...
Scan for collectors to load from path
Below is the the instruction that describes the task: ### Input: Scan for collectors to load from path ### Response: def load_collectors_from_paths(paths): """ Scan for collectors to load from path """ # Initialize return value collectors = {} if paths is None: return if isins...
def parse_euro_date(self, date_string: str): """ Parses dd/MM/yyyy dates """ self.date = datetime.strptime(date_string, "%d/%m/%Y") return self.date
Parses dd/MM/yyyy dates
Below is the the instruction that describes the task: ### Input: Parses dd/MM/yyyy dates ### Response: def parse_euro_date(self, date_string: str): """ Parses dd/MM/yyyy dates """ self.date = datetime.strptime(date_string, "%d/%m/%Y") return self.date
def run_nested_groups(): """Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase """ test = htf.Test( htf.PhaseGroup( main=[ ...
Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase
Below is the the instruction that describes the task: ### Input: Run the nested groups example. This example shows a PhaseGroup in a PhaseGroup. No phase is terminal, so all are run in the order; main_phase inner_main_phase inner_teardown_phase teardown_phase ### Response: def run_nested_grou...
def TexSoup(tex_code): r""" At a high-level, parses provided Tex into a navigable, searchable structure. This is accomplished in two steps: 1. Tex is parsed, cleaned, and packaged. 2. Structure fed to TexNodes for a searchable, coder-friendly interface. :param Union[str,iterable] tex_code: the...
r""" At a high-level, parses provided Tex into a navigable, searchable structure. This is accomplished in two steps: 1. Tex is parsed, cleaned, and packaged. 2. Structure fed to TexNodes for a searchable, coder-friendly interface. :param Union[str,iterable] tex_code: the Tex source :return: :c...
Below is the the instruction that describes the task: ### Input: r""" At a high-level, parses provided Tex into a navigable, searchable structure. This is accomplished in two steps: 1. Tex is parsed, cleaned, and packaged. 2. Structure fed to TexNodes for a searchable, coder-friendly interface. ...
def create_theta(self): """ Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. """ import itertools from pylocus.basics_angles import from_0_to_pi theta = ...
Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta.
Below is the the instruction that describes the task: ### Input: Returns the set of inner angles (between 0 and pi) reconstructed from point coordinates. Also returns the corners corresponding to each entry of theta. ### Response: def create_theta(self): """ Returns the set of inner...
def read_int(self, lpBaseAddress): """ Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. ...
Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the process memory. @raise WindowsError: On error an exception is ra...
Below is the the instruction that describes the task: ### Input: Reads a signed integer from the memory of the process. @see: L{peek_int} @type lpBaseAddress: int @param lpBaseAddress: Memory address to begin reading. @rtype: int @return: Integer value read from the proc...
def result(self): """ The result of the jobs execution. Accessing this property while the job is pending or running will raise #InvalidState. If an exception occured during the jobs execution, it will be raised. # Raises InvalidState: If the job is not in state #FINISHED. Cancelled: If the ...
The result of the jobs execution. Accessing this property while the job is pending or running will raise #InvalidState. If an exception occured during the jobs execution, it will be raised. # Raises InvalidState: If the job is not in state #FINISHED. Cancelled: If the job was cancelled. any: If...
Below is the the instruction that describes the task: ### Input: The result of the jobs execution. Accessing this property while the job is pending or running will raise #InvalidState. If an exception occured during the jobs execution, it will be raised. # Raises InvalidState: If the job is not in ...
def verify(expr, params=None): """ Determine if expression can be successfully translated to execute on MapD """ try: compile(expr, params=params) return True except com.TranslationError: return False
Determine if expression can be successfully translated to execute on MapD
Below is the the instruction that describes the task: ### Input: Determine if expression can be successfully translated to execute on MapD ### Response: def verify(expr, params=None): """ Determine if expression can be successfully translated to execute on MapD """ try: compile(expr...
def can(obj): """Prepare an object for pickling.""" import_needed = False for cls, canner in iteritems(can_map): if isinstance(cls, string_types): import_needed = True break elif istype(obj, cls): return canner(obj) if import_needed: # perfor...
Prepare an object for pickling.
Below is the the instruction that describes the task: ### Input: Prepare an object for pickling. ### Response: def can(obj): """Prepare an object for pickling.""" import_needed = False for cls, canner in iteritems(can_map): if isinstance(cls, string_types): import_needed = True ...
def calc_information_ratio(returns, benchmark_returns): """ Calculates the `Information ratio <https://www.investopedia.com/terms/i/informationratio.asp>`_ (or `from Wikipedia <http://en.wikipedia.org/wiki/Information_ratio>`_). """ diff_rets = returns - benchmark_returns diff_std = np.std(diff_rets...
Calculates the `Information ratio <https://www.investopedia.com/terms/i/informationratio.asp>`_ (or `from Wikipedia <http://en.wikipedia.org/wiki/Information_ratio>`_).
Below is the the instruction that describes the task: ### Input: Calculates the `Information ratio <https://www.investopedia.com/terms/i/informationratio.asp>`_ (or `from Wikipedia <http://en.wikipedia.org/wiki/Information_ratio>`_). ### Response: def calc_information_ratio(returns, benchmark_returns): """ ...
def client_start(request, socket, context): """ Adds the client triple to CLIENTS. """ CLIENTS[socket.session.session_id] = (request, socket, context)
Adds the client triple to CLIENTS.
Below is the the instruction that describes the task: ### Input: Adds the client triple to CLIENTS. ### Response: def client_start(request, socket, context): """ Adds the client triple to CLIENTS. """ CLIENTS[socket.session.session_id] = (request, socket, context)
def check_output(self, cmd, timeout=None, keep_rc=False, env=None): """ Subclasses can override to provide special environment setup, command prefixes, etc. """ return subproc.call(cmd, timeout=timeout or self.timeout, keep_rc=keep_rc, env=env)
Subclasses can override to provide special environment setup, command prefixes, etc.
Below is the the instruction that describes the task: ### Input: Subclasses can override to provide special environment setup, command prefixes, etc. ### Response: def check_output(self, cmd, timeout=None, keep_rc=False, env=None): """ Subclasses can override to provide special envi...
def serialize_footnote(ctx, document, el, root): "Serializes footnotes." footnote_num = el.rid if el.rid not in ctx.footnote_list: ctx.footnote_id += 1 ctx.footnote_list[el.rid] = ctx.footnote_id footnote_num = ctx.footnote_list[el.rid] note = etree.SubElement(root, 'sup') li...
Serializes footnotes.
Below is the the instruction that describes the task: ### Input: Serializes footnotes. ### Response: def serialize_footnote(ctx, document, el, root): "Serializes footnotes." footnote_num = el.rid if el.rid not in ctx.footnote_list: ctx.footnote_id += 1 ctx.footnote_list[el.rid] = ctx....
def analyze_number(var, err=''): """ Analyse number for type and split from unit 1px -> (q, 'px') args: var (str): number string kwargs: err (str): Error message raises: SyntaxError returns: tuple """ n, u = split_unit(var) if not isinstance(var, s...
Analyse number for type and split from unit 1px -> (q, 'px') args: var (str): number string kwargs: err (str): Error message raises: SyntaxError returns: tuple
Below is the the instruction that describes the task: ### Input: Analyse number for type and split from unit 1px -> (q, 'px') args: var (str): number string kwargs: err (str): Error message raises: SyntaxError returns: tuple ### Response: def analyze_number(v...
def slim_optimize(self, error_value=float('nan'), message=None): """Optimize model without creating a solution object. Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some tim...
Optimize model without creating a solution object. Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and in cases where only one or two values are of interest, it is r...
Below is the the instruction that describes the task: ### Input: Optimize model without creating a solution object. Creating a full solution object implies fetching shadow prices and flux values for all reactions and metabolites from the solver object. This necessarily takes some time and i...
def invisible_canvas(): """ Context manager yielding a temporary canvas drawn in batch mode, invisible to the user. Original state is restored on exit. Example use; obtain X axis object without interfering with anything:: with invisible_canvas() as c: efficiency.Draw() ...
Context manager yielding a temporary canvas drawn in batch mode, invisible to the user. Original state is restored on exit. Example use; obtain X axis object without interfering with anything:: with invisible_canvas() as c: efficiency.Draw() g = efficiency.GetPaintedGraph() ...
Below is the the instruction that describes the task: ### Input: Context manager yielding a temporary canvas drawn in batch mode, invisible to the user. Original state is restored on exit. Example use; obtain X axis object without interfering with anything:: with invisible_canvas() as c: ...
def is_port_default(self): '''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEFAULT_PORTS[self.scheme] == self.port
Return whether the URL is using the default port.
Below is the the instruction that describes the task: ### Input: Return whether the URL is using the default port. ### Response: def is_port_default(self): '''Return whether the URL is using the default port.''' if self.scheme in RELATIVE_SCHEME_DEFAULT_PORTS: return RELATIVE_SCHEME_DEF...
def bohachevsky1(theta): """One of the Bohachevsky functions""" x, y = theta obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7 grad = np.array([ 2 * x + 0.3 * np.sin(3 * np.pi * x) * 3 * np.pi, 4 * y + 0.4 * np.sin(4 * np.pi * y) * 4 * np.pi, ...
One of the Bohachevsky functions
Below is the the instruction that describes the task: ### Input: One of the Bohachevsky functions ### Response: def bohachevsky1(theta): """One of the Bohachevsky functions""" x, y = theta obj = x ** 2 + 2 * y ** 2 - 0.3 * np.cos(3 * np.pi * x) - 0.4 * np.cos(4 * np.pi * y) + 0.7 grad = np.array([ ...
def remove_none_value(data): """remove item from dict if value is None. return new dict. """ return dict((k, v) for k, v in data.items() if v is not None)
remove item from dict if value is None. return new dict.
Below is the the instruction that describes the task: ### Input: remove item from dict if value is None. return new dict. ### Response: def remove_none_value(data): """remove item from dict if value is None. return new dict. """ return dict((k, v) for k, v in data.items() if v is not None)
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): ''' Make a web call to GoGrid .. versionadded:: 2015.8.0 ''' vm_ = get_configured_provider() apikey = config.get_cloud_config_value( 'apike...
Make a web call to GoGrid .. versionadded:: 2015.8.0
Below is the the instruction that describes the task: ### Input: Make a web call to GoGrid .. versionadded:: 2015.8.0 ### Response: def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None): ''' Make a web call to...
def export_launch_vm(self, description, progress, virtual_box): """Exports and optionally launch a VM described in description parameter in description of type :class:`IVirtualSystemDescription` VirtualSystemDescription object which is describing a machine and all required parameters. ...
Exports and optionally launch a VM described in description parameter in description of type :class:`IVirtualSystemDescription` VirtualSystemDescription object which is describing a machine and all required parameters. in progress of type :class:`IProgress` Progress object to t...
Below is the the instruction that describes the task: ### Input: Exports and optionally launch a VM described in description parameter in description of type :class:`IVirtualSystemDescription` VirtualSystemDescription object which is describing a machine and all required parameters. in...
def _get_char(self, win, char): def get_check_next_byte(): char = win.getch() if 128 <= char <= 191: return char else: raise UnicodeError bytes = [] if char <= 127: # 1 bytes bytes.append(char) #...
no zero byte allowed
Below is the the instruction that describes the task: ### Input: no zero byte allowed ### Response: def _get_char(self, win, char): def get_check_next_byte(): char = win.getch() if 128 <= char <= 191: return char else: raise UnicodeError ...
def add_tooltip_to_highlighted_item(self, index): """ Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. """ self.setItemData(index, self.itemText(index), Qt.ToolTipRole)
Add a tooltip showing the full path of the currently highlighted item of the PathComboBox.
Below is the the instruction that describes the task: ### Input: Add a tooltip showing the full path of the currently highlighted item of the PathComboBox. ### Response: def add_tooltip_to_highlighted_item(self, index): """ Add a tooltip showing the full path of the currently highlighted...
def delete(args): """ Delete a river by name """ m = RiverManager(args.hosts) m.delete(args.name)
Delete a river by name
Below is the the instruction that describes the task: ### Input: Delete a river by name ### Response: def delete(args): """ Delete a river by name """ m = RiverManager(args.hosts) m.delete(args.name)
def as_dict(df, ix=':'): """ converts df to dict and adds a datetime field if df is datetime """ if isinstance(df.index, pd.DatetimeIndex): df['datetime'] = df.index return df.to_dict(orient='records')[ix]
converts df to dict and adds a datetime field if df is datetime
Below is the the instruction that describes the task: ### Input: converts df to dict and adds a datetime field if df is datetime ### Response: def as_dict(df, ix=':'): """ converts df to dict and adds a datetime field if df is datetime """ if isinstance(df.index, pd.DatetimeIndex): df['datetime'] =...
def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: try: stdout = str(bytes(completed_cmd.stdout), 'big5').strip() except ...
return a standard message
Below is the the instruction that describes the task: ### Input: return a standard message ### Response: def decode_cmd_out(self, completed_cmd): """ return a standard message """ try: stdout = completed_cmd.stdout.encode('utf-8').decode() except AttributeError: ...
def resolve_field_instance(cls_or_instance): """Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance. """ if isinstance(cls_or_instance, type): if not issubclass(cls_or_instance, FieldABC): raise FieldInst...
Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance.
Below is the the instruction that describes the task: ### Input: Return a Schema instance from a Schema class or instance. :param type|Schema cls_or_instance: Marshmallow Schema class or instance. ### Response: def resolve_field_instance(cls_or_instance): """Return a Schema instance from a Schema class or...
def _rotate_point(point, angle, ishape, rshape, reverse=False): """Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image. This works on a simple rotation transformation:: newx = (startx) * np.cos(angle) ...
Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image. This works on a simple rotation transformation:: newx = (startx) * np.cos(angle) - (starty) * np.sin(angle) newy = (startx) * np.sin(angle) + (s...
Below is the the instruction that describes the task: ### Input: Transform a point from original image coordinates to rotated image coordinates and back. It assumes the rotation point is the center of an image. This works on a simple rotation transformation:: newx = (startx) * np.cos(angle) - ...
def trackjobs(func, results, spacer): """ Blocks and prints progress for just the func being requested from a list of submitted engine jobs. Returns whether any of the jobs failed. func = str results = dict of asyncs """ ## TODO: try to insert a better way to break on KBD here. LOGGER....
Blocks and prints progress for just the func being requested from a list of submitted engine jobs. Returns whether any of the jobs failed. func = str results = dict of asyncs
Below is the the instruction that describes the task: ### Input: Blocks and prints progress for just the func being requested from a list of submitted engine jobs. Returns whether any of the jobs failed. func = str results = dict of asyncs ### Response: def trackjobs(func, results, spacer): """ ...
def terminate(self): '''Stop the server process and change our state to TERMINATING. Only valid if state=READY.''' logger.debug('client.terminate() called (state=%s)', self.strstate) if self.state == ClientState.WAITING_FOR_RESULT: raise ClientStateError('terimate() called while stat...
Stop the server process and change our state to TERMINATING. Only valid if state=READY.
Below is the the instruction that describes the task: ### Input: Stop the server process and change our state to TERMINATING. Only valid if state=READY. ### Response: def terminate(self): '''Stop the server process and change our state to TERMINATING. Only valid if state=READY.''' logger.debug('cli...
def _read_body_by_length(self, response, file): '''Read the connection specified by a length. Coroutine. ''' _logger.debug('Reading body by length.') file_is_async = hasattr(file, 'drain') try: body_size = int(response.fields['Content-Length']) ...
Read the connection specified by a length. Coroutine.
Below is the the instruction that describes the task: ### Input: Read the connection specified by a length. Coroutine. ### Response: def _read_body_by_length(self, response, file): '''Read the connection specified by a length. Coroutine. ''' _logger.debug('Reading body by ...
def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Qt.Key_Slash and self.isVisible(): self.show_find_widget.emit()
Reimplement Qt Method - Basic keypress event handler
Below is the the instruction that describes the task: ### Input: Reimplement Qt Method - Basic keypress event handler ### Response: def keyPressEvent(self, event): """Reimplement Qt Method - Basic keypress event handler""" event, text, key, ctrl, shift = restore_keyevent(event) if key == Q...
def rhymes(word): """Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhym...
Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> import pronouncing >>> pronouncing.rhymes("conditioner") ...
Below is the the instruction that describes the task: ### Input: Get words rhyming with a given word. This function may return an empty list if no rhyming words are found in the dictionary, or if the word you pass to the function is itself not found in the dictionary. .. doctest:: >>> imp...
def _get_ancestors_of(self, obs_nodes_list): """ Returns a list of all ancestors of all the observed nodes. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes """ if not obs_nodes_list: return set() ...
Returns a list of all ancestors of all the observed nodes. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes
Below is the the instruction that describes the task: ### Input: Returns a list of all ancestors of all the observed nodes. Parameters ---------- obs_nodes_list: string, list-type name of all the observed nodes ### Response: def _get_ancestors_of(self, obs_nodes_list): ...
def GlobForPaths(self, paths, pathtype="OS", root_path=None, process_non_regular_files=False, collect_ext_attrs=False): """Starts the Glob. This is the main entry point for this flow mixin. First we convert the ...
Starts the Glob. This is the main entry point for this flow mixin. First we convert the pattern into regex components, and then we interpolate each component. Finally, we generate a cartesian product of all combinations. Args: paths: A list of GlobExpression instances. pathtype: The p...
Below is the the instruction that describes the task: ### Input: Starts the Glob. This is the main entry point for this flow mixin. First we convert the pattern into regex components, and then we interpolate each component. Finally, we generate a cartesian product of all combinations. Args: ...
def is_allowed(func): """Check user password, when is correct, then run decorated function. :returns: decorated function """ @wraps(func) def _is_allowed(user, *args, **kwargs): password = kwargs.pop('password', None) if user.check_password(password): return func(user, ...
Check user password, when is correct, then run decorated function. :returns: decorated function
Below is the the instruction that describes the task: ### Input: Check user password, when is correct, then run decorated function. :returns: decorated function ### Response: def is_allowed(func): """Check user password, when is correct, then run decorated function. :returns: decorated function ...
def get_object(self, path): """Get single object.""" obj = self.native_container.get_object(path) return self.obj_cls.from_obj(self, obj)
Get single object.
Below is the the instruction that describes the task: ### Input: Get single object. ### Response: def get_object(self, path): """Get single object.""" obj = self.native_container.get_object(path) return self.obj_cls.from_obj(self, obj)
def getpass(self, prompt, default=None): """Provide a password prompt.""" return click.prompt(prompt, hide_input=True, default=default)
Provide a password prompt.
Below is the the instruction that describes the task: ### Input: Provide a password prompt. ### Response: def getpass(self, prompt, default=None): """Provide a password prompt.""" return click.prompt(prompt, hide_input=True, default=default)
def fetch_pool(repo_url, branch='master', reuse_existing=False): """Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object.""" repo_name = get_repo_name(repo_url) lib_dir = get_lib_dir() pool_dir = get_pool_dir(repo_name) print('... fetching %s ' % repo_name) if os.path.e...
Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object.
Below is the the instruction that describes the task: ### Input: Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object. ### Response: def fetch_pool(repo_url, branch='master', reuse_existing=False): """Fetch a git repository from ``repo_url`` and returns a ``FeaturePool`` object.""" ...
def get_numpy_include_path(): """ Gets the path to the numpy headers. """ # We need to go through this nonsense in case setuptools # downloaded and installed Numpy for us as part of the build or # install, since Numpy may still think it's in "setup mode", when # in fact we're ready to use it...
Gets the path to the numpy headers.
Below is the the instruction that describes the task: ### Input: Gets the path to the numpy headers. ### Response: def get_numpy_include_path(): """ Gets the path to the numpy headers. """ # We need to go through this nonsense in case setuptools # downloaded and installed Numpy for us as part o...
def history(location, model, filename, deployment, custom_config): """Generate a report over a model's git commit history.""" callbacks.git_installed() LOGGER.info("Initialising history report generation.") if location is None: raise click.BadParameter("No 'location' given or configured.") t...
Generate a report over a model's git commit history.
Below is the the instruction that describes the task: ### Input: Generate a report over a model's git commit history. ### Response: def history(location, model, filename, deployment, custom_config): """Generate a report over a model's git commit history.""" callbacks.git_installed() LOGGER.info("Initia...
def mqtt_connected(func): """ MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result """ @asyncio.coroutine @wraps(func) def wrapper(self, *args, **kwar...
MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result
Below is the the instruction that describes the task: ### Input: MQTTClient coroutines decorator which will wait until connection before calling the decorated method. :param func: coroutine to be called once connected :return: coroutine result ### Response: def mqtt_connected(func): """ ...
def hs_demux(sel, hsi, ls_hso): """ [One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (read...
[One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of output handshake tuples (ready, valid)
Below is the the instruction that describes the task: ### Input: [One-to-many] Demultiplexes to a list of output handshake interfaces sel - (i) selects an output handshake interface to connect to the input hsi - (i) input handshake tuple (ready, valid) ls_hso - (o) list of ...
def get_relationship_targets(item_ids, relationships, id2rec): """Get item ID set of item IDs in a relationship target set.""" # Requirements to use this function: # 1) item Terms must have been loaded with 'relationships' # 2) item IDs in 'item_ids' arguement must be present in id2rec # ...
Get item ID set of item IDs in a relationship target set.
Below is the the instruction that describes the task: ### Input: Get item ID set of item IDs in a relationship target set. ### Response: def get_relationship_targets(item_ids, relationships, id2rec): """Get item ID set of item IDs in a relationship target set.""" # Requirements to use this function: # ...
def simplify_script(self) -> 'Language': """ Remove the script from some parsed language data, if the script is redundant with the language. >>> Language.make(language='en', script='Latn').simplify_script() Language.make(language='en') >>> Language.make(language='yi', s...
Remove the script from some parsed language data, if the script is redundant with the language. >>> Language.make(language='en', script='Latn').simplify_script() Language.make(language='en') >>> Language.make(language='yi', script='Latn').simplify_script() Language.make(languag...
Below is the the instruction that describes the task: ### Input: Remove the script from some parsed language data, if the script is redundant with the language. >>> Language.make(language='en', script='Latn').simplify_script() Language.make(language='en') >>> Language.make(language...
def _missing_datetimes(self, finite_datetimes): """ Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) """ try: return self.missing_datetimes(finite_datetimes) except TypeError as ex: if 'missing_datetimes()' in repr(ex): ...
Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015)
Below is the the instruction that describes the task: ### Input: Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) ### Response: def _missing_datetimes(self, finite_datetimes): """ Backward compatible wrapper. Will be deleted eventually (stated on Dec 2015) """ ...
def hotkey(*args, **kwargs): """Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: key(s) (str): The series of ke...
Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: key(s) (str): The series of keys to press, in order. This can also...
Below is the the instruction that describes the task: ### Input: Performs key down presses on the arguments passed in order, then performs key releases in reverse order. The effect is that calling hotkey('ctrl', 'shift', 'c') would perform a "Ctrl-Shift-C" hotkey/keyboard shortcut press. Args: ...
def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < 0: return False else: return True except: return False
Returns True if OK to use, else False
Below is the the instruction that describes the task: ### Input: Returns True if OK to use, else False ### Response: def ok(self): """ Returns True if OK to use, else False """ try: v = int(self._value) if v < 0: return False else:...
def special_case_mysql(self, u, kwargs): """For mysql, take max_idle out of the query arguments, and use its value for pool_recycle. Also, force use_unicode and charset to be True and 'utf8', failing if they were set to anything else.""" kwargs['pool_recycle'] = int(u.query.pop...
For mysql, take max_idle out of the query arguments, and use its value for pool_recycle. Also, force use_unicode and charset to be True and 'utf8', failing if they were set to anything else.
Below is the the instruction that describes the task: ### Input: For mysql, take max_idle out of the query arguments, and use its value for pool_recycle. Also, force use_unicode and charset to be True and 'utf8', failing if they were set to anything else. ### Response: def special_case_mys...
def replicate_vm_image(self, vm_image_name, regions, offer, sku, version): ''' Replicate a VM image to multiple target locations. This operation is only for publishers. You have to be registered as image publisher with Microsoft Azure to be able to call this. vm_image_name: ...
Replicate a VM image to multiple target locations. This operation is only for publishers. You have to be registered as image publisher with Microsoft Azure to be able to call this. vm_image_name: Specifies the name of the VM Image that is to be used for replication ...
Below is the the instruction that describes the task: ### Input: Replicate a VM image to multiple target locations. This operation is only for publishers. You have to be registered as image publisher with Microsoft Azure to be able to call this. vm_image_name: Specifies the name...