code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def event(self, event_data, priority="normal", event_method="EVENT"): """This function will send event packets to the server. This is the main method you would use to send data from your application to the server. Whenever an event is sent to the server, a universally unique event id ...
This function will send event packets to the server. This is the main method you would use to send data from your application to the server. Whenever an event is sent to the server, a universally unique event id (euuid) is created for each event and stored in the "event_uuids" d...
Below is the the instruction that describes the task: ### Input: This function will send event packets to the server. This is the main method you would use to send data from your application to the server. Whenever an event is sent to the server, a universally unique event id (euuid...
def format_error_message(exception_message, task_exception=False): """Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. ...
Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. Args: exception_message (str): A message generated by traceba...
Below is the the instruction that describes the task: ### Input: Improve the formatting of an exception thrown by a remote function. This method takes a traceback from an exception and makes it nicer by removing a few uninformative lines and adding some space to indent the remaining lines nicely. ...
def translate(offset, dtype=None): """Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix descr...
Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray Transformation matrix describing the translation.
Below is the the instruction that describes the task: ### Input: Translate by an offset (x, y, z) . Parameters ---------- offset : array-like, shape (3,) Translation in x, y, z. dtype : dtype | None Output type (if None, don't cast). Returns ------- M : ndarray ...
def find_reference_section_no_title_generic(docbody, marker_patterns): """This function would generally be used when it was not possible to locate the start of a document's reference section by means of its title. Instead, this function will look for reference lines that have numeric markers of...
This function would generally be used when it was not possible to locate the start of a document's reference section by means of its title. Instead, this function will look for reference lines that have numeric markers of the format [1], [2], {1}, {2}, etc. @param docbody: (list) of strings ...
Below is the the instruction that describes the task: ### Input: This function would generally be used when it was not possible to locate the start of a document's reference section by means of its title. Instead, this function will look for reference lines that have numeric markers of the form...
def calc_missingremoterelease_v1(self): """Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation:...
Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation: :math:`MissingRemoteRelease = max( ...
Below is the the instruction that describes the task: ### Input: Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease...
def _init_file_logger(logger, level, log_path, log_size, log_count): """ one logger only have one level RotatingFileHandler """ if level not in [logging.NOTSET, logging.DEBUG, logging.INFO, logging.WARNING, logging.ERROR, logging.CRITICAL]: level = logging.DEBUG for h in logger.handlers: ...
one logger only have one level RotatingFileHandler
Below is the the instruction that describes the task: ### Input: one logger only have one level RotatingFileHandler ### Response: def _init_file_logger(logger, level, log_path, log_size, log_count): """ one logger only have one level RotatingFileHandler """ if level not in [logging.NOTSET, logging....
def phase_shifted_coefficients(amplitude_coefficients, form='cos', shift=0.0): r""" Converts Fourier coefficients from the amplitude form to the phase-shifted form, as either a sine or cosine series. Amplitude form: .. math:: m(t) ...
r""" Converts Fourier coefficients from the amplitude form to the phase-shifted form, as either a sine or cosine series. Amplitude form: .. math:: m(t) = A_0 + \sum_{k=1}^n (a_k \sin(k \omega t) + b_k \cos(k \omega t)) Sine form...
Below is the the instruction that describes the task: ### Input: r""" Converts Fourier coefficients from the amplitude form to the phase-shifted form, as either a sine or cosine series. Amplitude form: .. math:: m(t) = A_0 + \sum_{k=1}^n (a_k \sin(k \omega t) ...
def na_value_for_dtype(dtype, compat=True): """ Return a dtype compat na value Parameters ---------- dtype : string / dtype compat : boolean, default True Returns ------- np.dtype or a pandas dtype Examples -------- >>> na_value_for_dtype(np.dtype('int64')) 0 >...
Return a dtype compat na value Parameters ---------- dtype : string / dtype compat : boolean, default True Returns ------- np.dtype or a pandas dtype Examples -------- >>> na_value_for_dtype(np.dtype('int64')) 0 >>> na_value_for_dtype(np.dtype('int64'), compat=False) ...
Below is the the instruction that describes the task: ### Input: Return a dtype compat na value Parameters ---------- dtype : string / dtype compat : boolean, default True Returns ------- np.dtype or a pandas dtype Examples -------- >>> na_value_for_dtype(np.dtype('int64')...
def set(self, key, value, **kw): """Place a value in the cache. :param key: the value's key. :param value: the value. :param \**kw: cache configuration arguments. """ self.impl.set(key, value, **self._get_cache_kw(kw, None))
Place a value in the cache. :param key: the value's key. :param value: the value. :param \**kw: cache configuration arguments.
Below is the the instruction that describes the task: ### Input: Place a value in the cache. :param key: the value's key. :param value: the value. :param \**kw: cache configuration arguments. ### Response: def set(self, key, value, **kw): """Place a value in the cache. :pa...
def getElementsByTagName(self, tagName, root='root', useIndex=True): ''' getElementsByTagName - Searches and returns all elements with a specific tag name. @param tagName <lowercase str> - A lowercase string of the tag name. @param root <AdvancedTag/'...
getElementsByTagName - Searches and returns all elements with a specific tag name. @param tagName <lowercase str> - A lowercase string of the tag name. @param root <AdvancedTag/'root'> - Search starting at a specific node, if provided. if string 'root', the root of the p...
Below is the the instruction that describes the task: ### Input: getElementsByTagName - Searches and returns all elements with a specific tag name. @param tagName <lowercase str> - A lowercase string of the tag name. @param root <AdvancedTag/'root'> - Search starting...
def with_(self, *relations): """ Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder """ if not relations: return self eagers = self._parse_relations(list(relations)) self._eager_load.upda...
Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder
Below is the the instruction that describes the task: ### Input: Set the relationships that should be eager loaded. :return: The current Builder instance :rtype: Builder ### Response: def with_(self, *relations): """ Set the relationships that should be eager loaded. :retu...
def slim_frame_data(frames, frame_allowance=25): """ Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``. """ frames_len = 0 app_frames = [] system_frames = [] for frame in frames: frames_len += 1 if frame.get('i...
Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``.
Below is the the instruction that describes the task: ### Input: Removes various excess metadata from middle frames which go beyond ``frame_allowance``. Returns ``frames``. ### Response: def slim_frame_data(frames, frame_allowance=25): """ Removes various excess metadata from middle frames which g...
def get_min_sec_from_morning(self): """Get the first second from midnight where a timerange is effective :return: smallest amount of second from midnight of all timerange :rtype: int """ mins = [] for timerange in self.timeranges: mins.append(timerange.get_se...
Get the first second from midnight where a timerange is effective :return: smallest amount of second from midnight of all timerange :rtype: int
Below is the the instruction that describes the task: ### Input: Get the first second from midnight where a timerange is effective :return: smallest amount of second from midnight of all timerange :rtype: int ### Response: def get_min_sec_from_morning(self): """Get the first second from mi...
def init_logging(log_level): """ Init logging settings with default set to INFO """ log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name)s:%(lineno)s - %(message)s" if log_level in os.environ else "%(levelname)s - %(message)s" logging_conf = { "version":...
Init logging settings with default set to INFO
Below is the the instruction that describes the task: ### Input: Init logging settings with default set to INFO ### Response: def init_logging(log_level): """ Init logging settings with default set to INFO """ log_level = log_level_to_string_map[min(log_level, 5)] msg = "%(levelname)s - %(name...
def parse(cls, resource, parent=None, _with_children=False): """ Parse a resource :param resource: Element rerpresenting a work :param type: basestring, etree._Element :param parent: Parent of the object :type parent: XmlCtsTextgroupMetadata :param _cls_dict: Dictionary ...
Parse a resource :param resource: Element rerpresenting a work :param type: basestring, etree._Element :param parent: Parent of the object :type parent: XmlCtsTextgroupMetadata :param _cls_dict: Dictionary of classes to generate subclasses
Below is the the instruction that describes the task: ### Input: Parse a resource :param resource: Element rerpresenting a work :param type: basestring, etree._Element :param parent: Parent of the object :type parent: XmlCtsTextgroupMetadata :param _cls_dict: Dictionary of c...
def create_meta_data(cls, options, args, parser): """ Override in subclass if required. """ meta_data = [] meta_data.append(('spiff_version', cls.get_version())) if options.target_engine: meta_data.append(('target_engine', options.target_engine)) if op...
Override in subclass if required.
Below is the the instruction that describes the task: ### Input: Override in subclass if required. ### Response: def create_meta_data(cls, options, args, parser): """ Override in subclass if required. """ meta_data = [] meta_data.append(('spiff_version', cls.get_version())) ...
def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ''' adapters = _parse_interfaces() if iface in adapters: try: if iface == 'source': template = JINJA.get_t...
Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0
Below is the the instruction that describes the task: ### Input: Return the contents of an interface script CLI Example: .. code-block:: bash salt '*' ip.get_interface eth0 ### Response: def get_interface(iface): ''' Return the contents of an interface script CLI Example: .. co...
def fmt_type(data_type): """ Returns a JSDoc annotation for a data type. May contain a union of enumerated subtypes. """ if is_struct_type(data_type) and data_type.has_enumerated_subtypes(): possible_types = [] possible_subtypes = data_type.get_all_subtypes_with_tags() for _,...
Returns a JSDoc annotation for a data type. May contain a union of enumerated subtypes.
Below is the the instruction that describes the task: ### Input: Returns a JSDoc annotation for a data type. May contain a union of enumerated subtypes. ### Response: def fmt_type(data_type): """ Returns a JSDoc annotation for a data type. May contain a union of enumerated subtypes. """ if ...
def edit_encoding(cls, parent): """ Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise """ dlg = cls(par...
Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise
Below is the the instruction that describes the task: ### Input: Static helper method that shows the encoding editor dialog If the dialog was accepted the new encodings are added to the settings. :param parent: parent widget :return: True in case of succes, False otherwise ### Response: de...
def get_area_url(location, distance): """Generate URL for downloading OSM data within a region. This function defines a boundary box where the edges touch a circle of ``distance`` kilometres in radius. It is important to note that the box is neither a square, nor bounded within the circle. The bo...
Generate URL for downloading OSM data within a region. This function defines a boundary box where the edges touch a circle of ``distance`` kilometres in radius. It is important to note that the box is neither a square, nor bounded within the circle. The bounding box is strictly a trapezoid whose nort...
Below is the the instruction that describes the task: ### Input: Generate URL for downloading OSM data within a region. This function defines a boundary box where the edges touch a circle of ``distance`` kilometres in radius. It is important to note that the box is neither a square, nor bounded within...
def _handle_next_export_subtask(self, export_state=None): """ Process the next export sub-task, if there is one. :param ExportState export_state: If provided, this is used instead of the database queue, in effect directing the exporter to process the previous export agai...
Process the next export sub-task, if there is one. :param ExportState export_state: If provided, this is used instead of the database queue, in effect directing the exporter to process the previous export again. This is used to avoid having to query the database when we know already wha...
Below is the the instruction that describes the task: ### Input: Process the next export sub-task, if there is one. :param ExportState export_state: If provided, this is used instead of the database queue, in effect directing the exporter to process the previous export again. This i...
def create(dataset, target, feature=None, model = 'resnet-50', l2_penalty=0.01, l1_penalty=0.0, solver='auto', feature_rescaling=True, convergence_threshold = _DEFAULT_SOLVER_OPTIONS['convergence_threshold'], step_size = _DEFAULT_SOLVER_OPTIONS['step_size'], lbfgs_memory_level = _DEFAULT_SOLVER...
Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the column containing the target variable. The values in this column m...
Below is the the instruction that describes the task: ### Input: Create a :class:`ImageClassifier` model. Parameters ---------- dataset : SFrame Input data. The column named by the 'feature' parameter will be extracted for modeling. target : string, or int Name of the colum...
def check_output_format(fmt, nfiles): """Validate file format string. Parameters ---------- fmt : `str` File format string. nfiles : `int` Number of files. Raises ------ ValueError If nfiles < 0 or format string is invalid. """ if nfiles < 0: rai...
Validate file format string. Parameters ---------- fmt : `str` File format string. nfiles : `int` Number of files. Raises ------ ValueError If nfiles < 0 or format string is invalid.
Below is the the instruction that describes the task: ### Input: Validate file format string. Parameters ---------- fmt : `str` File format string. nfiles : `int` Number of files. Raises ------ ValueError If nfiles < 0 or format string is invalid. ### Response: ...
def _get_x(self, kwargs): ''' Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' if 'x' in kwargs: return round(float(kwargs['x']), 6) elif self._element_x in kwargs: return round(float(kwargs[self._element_x]), 6) ...
Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError.
Below is the the instruction that describes the task: ### Input: Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ### Response: def _get_x(self, kwargs): ''' Returns x if it is explicitly defined in kwargs. Otherwise, raises TypeError. ''' ...
def GetUcsPropertyMetaAttributeList(classId): """ Methods returns the class meta. """ if classId in _ManagedObjectMeta: attrList = _ManagedObjectMeta[classId].keys() attrList.remove("Meta") return attrList if classId in _MethodFactoryMeta: attrList = _MethodFactoryMeta[classId].keys() attrList.remo...
Methods returns the class meta.
Below is the the instruction that describes the task: ### Input: Methods returns the class meta. ### Response: def GetUcsPropertyMetaAttributeList(classId): """ Methods returns the class meta. """ if classId in _ManagedObjectMeta: attrList = _ManagedObjectMeta[classId].keys() attrList.remove("Meta") r...
def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None): """1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevali...
1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib - MIT License, Copyright (c) 2018 Guillaume Chevalier
Below is the the instruction that describes the task: ### Input: 1D Iterable to get every convolution window per loop iteration. For more information, refer to: - https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py - https://github.com/guillaume-chevalier/python-conv-lib ...
def content(): """Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message """ message = m.Message() ...
Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.message.Message
Below is the the instruction that describes the task: ### Input: Helper method that returns just the content. This method was added so that the text could be reused in the dock_help module. .. versionadded:: 3.2.2 :returns: A message object without brand element. :rtype: safe.messaging.messag...
def write_block_data(self, cmd, block): """ Writes a block of bytes to the bus using I2C format to the specified command register """ self.bus.write_i2c_block_data(self.address, cmd, block) self.log.debug( "write_block_data: Wrote [%s] to command register 0x%0...
Writes a block of bytes to the bus using I2C format to the specified command register
Below is the the instruction that describes the task: ### Input: Writes a block of bytes to the bus using I2C format to the specified command register ### Response: def write_block_data(self, cmd, block): """ Writes a block of bytes to the bus using I2C format to the specified comma...
def restart(self, offset: int): '''Send restart command. Coroutine. ''' yield from self._control_stream.write_command(Command('REST', str(offset))) reply = yield from self._control_stream.read_reply() self.raise_if_not_match('Restart', ReplyCodes.requested_file_action_...
Send restart command. Coroutine.
Below is the the instruction that describes the task: ### Input: Send restart command. Coroutine. ### Response: def restart(self, offset: int): '''Send restart command. Coroutine. ''' yield from self._control_stream.write_command(Command('REST', str(offset))) repl...
def move_group_in_parent(self, group = None, index = None): """Move group to another position in group's parent. index must be a valid index of group.parent.groups """ if group is None or index is None: raise KPError("group and index must be set") e...
Move group to another position in group's parent. index must be a valid index of group.parent.groups
Below is the the instruction that describes the task: ### Input: Move group to another position in group's parent. index must be a valid index of group.parent.groups ### Response: def move_group_in_parent(self, group = None, index = None): """Move group to another position in group's paren...
def is_blackout(self) -> bool: """Does this alert match a blackout period?""" if not current_app.config['NOTIFICATION_BLACKOUT']: if self.severity in current_app.config['BLACKOUT_ACCEPT']: return False return db.is_blackout_period(self)
Does this alert match a blackout period?
Below is the the instruction that describes the task: ### Input: Does this alert match a blackout period? ### Response: def is_blackout(self) -> bool: """Does this alert match a blackout period?""" if not current_app.config['NOTIFICATION_BLACKOUT']: if self.severity in current_app.confi...
def authenticate(self, auth_token, auth_info, service_name): """Authenticates the current auth token. Args: auth_token: the auth token. auth_info: the auth configurations of the API method being called. service_name: the name of this service. Returns: A ...
Authenticates the current auth token. Args: auth_token: the auth token. auth_info: the auth configurations of the API method being called. service_name: the name of this service. Returns: A constructed UserInfo object representing the identity of the caller. ...
Below is the the instruction that describes the task: ### Input: Authenticates the current auth token. Args: auth_token: the auth token. auth_info: the auth configurations of the API method being called. service_name: the name of this service. Returns: A con...
def BLE(self, params): """ BLE label Branch to the instruction at label if the Z flag is set or if the N flag is not the same as the V flag """ label = self.get_one_parameter(self.ONE_PARAMETER, params) self.check_arguments(label_exists=(label,)) # BLE label ...
BLE label Branch to the instruction at label if the Z flag is set or if the N flag is not the same as the V flag
Below is the the instruction that describes the task: ### Input: BLE label Branch to the instruction at label if the Z flag is set or if the N flag is not the same as the V flag ### Response: def BLE(self, params): """ BLE label Branch to the instruction at label if the Z flag is ...
def _function_magic_marker(magic_kind): """Decorator factory for standalone functions. """ validate_type(magic_kind) # This is a closure to capture the magic_kind. We could also use a class, # but it's overkill for just that one bit of state. def magic_deco(arg): call = lambda f, *...
Decorator factory for standalone functions.
Below is the the instruction that describes the task: ### Input: Decorator factory for standalone functions. ### Response: def _function_magic_marker(magic_kind): """Decorator factory for standalone functions. """ validate_type(magic_kind) # This is a closure to capture the magic_kind. We cou...
def flatten_group(group_to_flatten, root, recursive=True, group_filter=lambda x: True, path_filter=lambda x: True, path_conversions=CONVERSIONS, group_search_xpath=SVG_GROUP_TAG): """Flatten all the paths in a specific group. The paths will be flattened int...
Flatten all the paths in a specific group. The paths will be flattened into the 'root' frame. Note that root needs to be an ancestor of the group that is being flattened. Otherwise, no paths will be returned.
Below is the the instruction that describes the task: ### Input: Flatten all the paths in a specific group. The paths will be flattened into the 'root' frame. Note that root needs to be an ancestor of the group that is being flattened. Otherwise, no paths will be returned. ### Response: def flatten_gr...
def refresh(self): ''' Refresh the list and the screen ''' self._screen.force_update() self._screen.refresh() self._update(1)
Refresh the list and the screen
Below is the the instruction that describes the task: ### Input: Refresh the list and the screen ### Response: def refresh(self): ''' Refresh the list and the screen ''' self._screen.force_update() self._screen.refresh() self._update(1)
def get_current_target(module, module_parameter=None, action_parameter=None): ''' Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter...
Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional params passed to the 'show' action CLI Example (current target of...
Below is the the instruction that describes the task: ### Input: Get the currently selected target for the given module. module name of the module to be queried for its current target module_parameter additional params passed to the defined module action_parameter additional p...
def write_entries(self, entries, logger_name=None, resource=None, labels=None): """API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default l...
API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log the entries; individual entries may overr...
Below is the the instruction that describes the task: ### Input: API call: log an entry resource via a POST request :type entries: sequence of mapping :param entries: the log entry resources to log. :type logger_name: str :param logger_name: name of default logger to which to log ...
def preprocess(self, dt): """ Preprocess the `dt` with `localize()` and `astz()` """ # Process try: # this block should not raise errors, and if it does -- they should not be wrapped with `Invalid` # localize if self.localize and dt.tzinfo is None: dt = s...
Preprocess the `dt` with `localize()` and `astz()`
Below is the the instruction that describes the task: ### Input: Preprocess the `dt` with `localize()` and `astz()` ### Response: def preprocess(self, dt): """ Preprocess the `dt` with `localize()` and `astz()` """ # Process try: # this block should not raise errors, and if it does -- they...
def remote_styles(family_metadata): """Get a dictionary of TTFont objects of all font files of a given family as currently hosted at Google Fonts. """ def download_family_from_Google_Fonts(family_name): """Return a zipfile containing a font family hosted on fonts.google.com""" from zipfile import Zi...
Get a dictionary of TTFont objects of all font files of a given family as currently hosted at Google Fonts.
Below is the the instruction that describes the task: ### Input: Get a dictionary of TTFont objects of all font files of a given family as currently hosted at Google Fonts. ### Response: def remote_styles(family_metadata): """Get a dictionary of TTFont objects of all font files of a given family as cur...
def get_cv_idxs(n, cv_idx=0, val_pct=0.2, seed=42): """ Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), validation set...
Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), validation set percentage seed : seed value for RandomState ...
Below is the the instruction that describes the task: ### Input: Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), valid...
def main(): """ generates a random world, sets terrain and runs agents in it TODO - need to change pieces in multiple places (see worlds.py, cls_grid, world_generator) (takes about 5 minutes to make 500x400 grid with 8% blockages) """ width = 20 # grid width height = 10 #...
generates a random world, sets terrain and runs agents in it TODO - need to change pieces in multiple places (see worlds.py, cls_grid, world_generator) (takes about 5 minutes to make 500x400 grid with 8% blockages)
Below is the the instruction that describes the task: ### Input: generates a random world, sets terrain and runs agents in it TODO - need to change pieces in multiple places (see worlds.py, cls_grid, world_generator) (takes about 5 minutes to make 500x400 grid with 8% blockages) ### Response: def main():...
def com_google_fonts_check_metadata_regular_is_400(family_metadata): """METADATA.pb: Regular should be 400.""" badfonts = [] for f in family_metadata.fonts: if f.full_name.endswith("Regular") and f.weight != 400: badfonts.append(f"{f.filename} (weight: {f.weight})") if len(badfonts) > 0: yield FAI...
METADATA.pb: Regular should be 400.
Below is the the instruction that describes the task: ### Input: METADATA.pb: Regular should be 400. ### Response: def com_google_fonts_check_metadata_regular_is_400(family_metadata): """METADATA.pb: Regular should be 400.""" badfonts = [] for f in family_metadata.fonts: if f.full_name.endswith("Regular"...
def _galaxy_association_cuts( self, matchedObjects, catalogueName, magnitudeLimitFilter, upperMagnitudeLimit, lowerMagnitudeLimit): """*perform a bright star match on the crossmatch results if required by the catalogue search* **Ke...
*perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- the name of the catalogue the crossmatch results from - ``m...
Below is the the instruction that describes the task: ### Input: *perform a bright star match on the crossmatch results if required by the catalogue search* **Key Arguments:** - ``matchedObjects`` -- the list of matched sources from the catalogue crossmatch - ``catalogueName`` -- th...
def do_help(self, arg): """Help command. Usage: help [command] Parameters: command: Optional - command name to display detailed help """ cmds = arg.split() if cmds: func = getattr(self, 'do_{}'.format(cmds[0])) if func: ...
Help command. Usage: help [command] Parameters: command: Optional - command name to display detailed help
Below is the the instruction that describes the task: ### Input: Help command. Usage: help [command] Parameters: command: Optional - command name to display detailed help ### Response: def do_help(self, arg): """Help command. Usage: help [comman...
def read_chunk(stream): """Ignore whitespace outside of strings. If we hit a string, read it in its entirety. """ chunk = stream.read(1) while chunk in SKIP: chunk = stream.read(1) if chunk == "\"": chunk += stream.read(1) while not chunk.endswith("\""): if ch...
Ignore whitespace outside of strings. If we hit a string, read it in its entirety.
Below is the the instruction that describes the task: ### Input: Ignore whitespace outside of strings. If we hit a string, read it in its entirety. ### Response: def read_chunk(stream): """Ignore whitespace outside of strings. If we hit a string, read it in its entirety. """ chunk = stream.read...
def _str_extract_frame(arr, pat, flags=0): """ For each subject string in the Series, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True), and always returns a DataFrame. """ from pandas import DataFrame regex = re.compile(pa...
For each subject string in the Series, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True), and always returns a DataFrame.
Below is the the instruction that describes the task: ### Input: For each subject string in the Series, extract groups from the first match of regular expression pat. This function is called from str_extract(expand=True), and always returns a DataFrame. ### Response: def _str_extract_frame(arr, pat, flags=...
def _HasTable(self, table_name): """Determines if a specific table exists. Args: table_name (str): name of the table. Returns: bool: True if the table exists, false otherwise. """ query = self._HAS_TABLE_QUERY.format(table_name) self._cursor.execute(query) return bool(self._cu...
Determines if a specific table exists. Args: table_name (str): name of the table. Returns: bool: True if the table exists, false otherwise.
Below is the the instruction that describes the task: ### Input: Determines if a specific table exists. Args: table_name (str): name of the table. Returns: bool: True if the table exists, false otherwise. ### Response: def _HasTable(self, table_name): """Determines if a specific table exi...
def surface_density(segmentation, voxelsize_mm, aoi=None, sond_raster_mm=None): """ :segmentation: is ndarray with 0 and 1 :voxelsize_mm: is array of three numbers specifiing size of voxel for each axis :aoi: is specify area of interest. It is ndarray with 0 and 1 :sond_raster_mm: unimplemen...
:segmentation: is ndarray with 0 and 1 :voxelsize_mm: is array of three numbers specifiing size of voxel for each axis :aoi: is specify area of interest. It is ndarray with 0 and 1 :sond_raster_mm: unimplemented. It is parametr of sonds design
Below is the the instruction that describes the task: ### Input: :segmentation: is ndarray with 0 and 1 :voxelsize_mm: is array of three numbers specifiing size of voxel for each axis :aoi: is specify area of interest. It is ndarray with 0 and 1 :sond_raster_mm: unimplemented. It is parametr of ...
def write_bus_data(self, file): """ Writes bus data in MATPOWER format. """ # I, 'NAME', BASKV, IDE, GL, BL, AREA, ZONE, VM, VA, OWNER bus_attrs = ["_i", "name", "v_base", "type", "g_shunt", "b_shunt", "area", "zone", "v_magnitude", "v_angl...
Writes bus data in MATPOWER format.
Below is the the instruction that describes the task: ### Input: Writes bus data in MATPOWER format. ### Response: def write_bus_data(self, file): """ Writes bus data in MATPOWER format. """ # I, 'NAME', BASKV, IDE, GL, BL, AREA, ZONE, VM, VA, OWNER bus_attrs = ["_i", "name", "v...
def trace_toolchain(toolchain): """ Trace the versions of the involved packages for the provided toolchain instance. """ pkgs = [] for cls in getmro(type(toolchain)): if not issubclass(cls, Toolchain): continue dist = _cls_lookup_dist(cls) value = { ...
Trace the versions of the involved packages for the provided toolchain instance.
Below is the the instruction that describes the task: ### Input: Trace the versions of the involved packages for the provided toolchain instance. ### Response: def trace_toolchain(toolchain): """ Trace the versions of the involved packages for the provided toolchain instance. """ pkgs = []...
def fullmatch(self, string, *args, **kwargs): """Apply `fullmatch`.""" return self._pattern.fullmatch(string, *args, **kwargs)
Apply `fullmatch`.
Below is the the instruction that describes the task: ### Input: Apply `fullmatch`. ### Response: def fullmatch(self, string, *args, **kwargs): """Apply `fullmatch`.""" return self._pattern.fullmatch(string, *args, **kwargs)
def write_iocs(self, directory=None, source=None): """ Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not...
Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not normally modifed by a user for this class. :return:
Below is the the instruction that describes the task: ### Input: Serializes IOCs to a directory. :param directory: Directory to write IOCs to. If not provided, the current working directory is used. :param source: Dictionary contianing iocid -> IOC mapping. Defaults to self.iocs_10. This is not n...
def getAdministrator(self, email, returned_properties=None): """Get the :class:`rtcclient.models.Administrator` object by the email address :param email: the email address (e.g. somebody@gmail.com) :param returned_properties: the returned properties that you want. Refer to :...
Get the :class:`rtcclient.models.Administrator` object by the email address :param email: the email address (e.g. somebody@gmail.com) :param returned_properties: the returned properties that you want. Refer to :class:`rtcclient.client.RTCClient` for more explanations :return...
Below is the the instruction that describes the task: ### Input: Get the :class:`rtcclient.models.Administrator` object by the email address :param email: the email address (e.g. somebody@gmail.com) :param returned_properties: the returned properties that you want. Refer to :cla...
def check(text): """Suggest the preferred forms.""" err = "redundancy.wallace" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ ["rectangular", ["rectangular in shape"]], ["audible", ["audible to the ear"]], ] return preferred_forms_check(text, re...
Suggest the preferred forms.
Below is the the instruction that describes the task: ### Input: Suggest the preferred forms. ### Response: def check(text): """Suggest the preferred forms.""" err = "redundancy.wallace" msg = "Redundancy. Use '{}' instead of '{}'." redundancies = [ ["rectangular", ["rectangular in ...
def Friedel(m, x, rhol, rhog, mul, mug, sigma, D, roughness=0, L=1): r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \...
r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \left(\frac{\rho_l}{\rho_g}\right)^{0.91}\left(\frac{\mu_g}{\mu_l} ...
Below is the the instruction that describes the task: ### Input: r'''Calculates two-phase pressure drop with the Friedel correlation. .. math:: \Delta P_{friction} = \Delta P_{lo} \phi_{lo}^2 .. math:: \phi_{lo}^2 = E + \frac{3.24FH}{Fr^{0.0454} We^{0.035}} .. math:: H = \left...
def import_parms(self, args): """Import external dict to internal dict""" for key, val in args.items(): self.set_parm(key, val)
Import external dict to internal dict
Below is the the instruction that describes the task: ### Input: Import external dict to internal dict ### Response: def import_parms(self, args): """Import external dict to internal dict""" for key, val in args.items(): self.set_parm(key, val)
def daemonize(redirect_out=True): ''' Daemonize a process ''' # Avoid circular import import salt.utils.crypt try: pid = os.fork() if pid > 0: # exit first parent salt.utils.crypt.reinit_crypto() os._exit(salt.defaults.exitcodes.EX_OK) exce...
Daemonize a process
Below is the the instruction that describes the task: ### Input: Daemonize a process ### Response: def daemonize(redirect_out=True): ''' Daemonize a process ''' # Avoid circular import import salt.utils.crypt try: pid = os.fork() if pid > 0: # exit first parent ...
def powerlaw(f, log10_A=-16, gamma=5): """Power-law PSD. :param f: Sampling frequencies :param log10_A: log10 of red noise Amplitude [GW units] :param gamma: Spectral index of red noise process """ fyr = 1 / 3.16e7 return (10**log10_A)**2 / 12.0 / np.pi**2 * fyr**(gamma-3) * f**(-gamma)
Power-law PSD. :param f: Sampling frequencies :param log10_A: log10 of red noise Amplitude [GW units] :param gamma: Spectral index of red noise process
Below is the the instruction that describes the task: ### Input: Power-law PSD. :param f: Sampling frequencies :param log10_A: log10 of red noise Amplitude [GW units] :param gamma: Spectral index of red noise process ### Response: def powerlaw(f, log10_A=-16, gamma=5): """Power-law PSD. :para...
def over(self, name='usd'): '''Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency).''' name = name.upper() if self.ccy1.code == name.upper(): return ccy_pair(self.ccy2, self.ccy1) else: return self
Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency).
Below is the the instruction that describes the task: ### Input: Returns a new currency pair with the *over* currency as second part of the pair (Foreign currency). ### Response: def over(self, name='usd'): '''Returns a new currency pair with the *over* currency as second part of the pair (...
def configure_roles_on_host(api, host): """ Go through all the roles on this host, and configure them if they match the role types that we care about. """ for role_ref in host.roleRefs: # Mgmt service/role has no cluster name. Skip over those. if role_ref.get('clusterName') is None: continue ...
Go through all the roles on this host, and configure them if they match the role types that we care about.
Below is the the instruction that describes the task: ### Input: Go through all the roles on this host, and configure them if they match the role types that we care about. ### Response: def configure_roles_on_host(api, host): """ Go through all the roles on this host, and configure them if they match the r...
def get(sub_array_id): """Sub array detail resource. This method will list scheduling blocks and processing blocks in the specified sub-array. """ if not re.match(r'^subarray-0[0-9]|subarray-1[0-5]$', sub_array_id): response = dict(error='Invalid sub-array ID specified "{}" does not ' ...
Sub array detail resource. This method will list scheduling blocks and processing blocks in the specified sub-array.
Below is the the instruction that describes the task: ### Input: Sub array detail resource. This method will list scheduling blocks and processing blocks in the specified sub-array. ### Response: def get(sub_array_id): """Sub array detail resource. This method will list scheduling blocks and proc...
def run(self): """Launch filtering, sorting and paging to output results.""" query = self.query # count before filtering self.cardinality = query.add_columns(self.columns[0].sqla_expr).count() self._set_column_filter_expressions() self._set_global_filter_expression() ...
Launch filtering, sorting and paging to output results.
Below is the the instruction that describes the task: ### Input: Launch filtering, sorting and paging to output results. ### Response: def run(self): """Launch filtering, sorting and paging to output results.""" query = self.query # count before filtering self.cardinality = query.a...
def clear(self): """Resets Bloch sphere data sets to empty. """ self.points = [] self.vectors = [] self.point_style = [] self.annotations = []
Resets Bloch sphere data sets to empty.
Below is the the instruction that describes the task: ### Input: Resets Bloch sphere data sets to empty. ### Response: def clear(self): """Resets Bloch sphere data sets to empty. """ self.points = [] self.vectors = [] self.point_style = [] self.annotations = []
def accept(self): """ Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`. """ AutosaveErrorDialog.show_errors = not self.dismiss_box.isChecked() return QDialog.accept(self)
Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`.
Below is the the instruction that describes the task: ### Input: Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`. ### Response: def accept(self): """ Update `show_errors` and hide dialog box. Overrides method of `QDialogBox`. """ Autosave...
def eni_present( name, subnet_id=None, subnet_name=None, private_ip_address=None, description=None, groups=None, source_dest_check=True, allocate_eip=None, arecords=None, region=None, key=None, keyid=None, profile=No...
Ensure the EC2 ENI exists. .. versionadded:: 2016.3.0 name Name tag associated with the ENI. subnet_id The VPC subnet ID the ENI will exist within. subnet_name The VPC subnet name the ENI will exist within. private_ip_address The private ip address to use for thi...
Below is the the instruction that describes the task: ### Input: Ensure the EC2 ENI exists. .. versionadded:: 2016.3.0 name Name tag associated with the ENI. subnet_id The VPC subnet ID the ENI will exist within. subnet_name The VPC subnet name the ENI will exist within. ...
def smooth_angle_channels(self, channels): """Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.""" for vertex in self.vertices: for col in vertex.meta['rot_ind']: if col: ...
Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions.
Below is the the instruction that describes the task: ### Input: Remove discontinuities in angle channels so that they don't cause artifacts in algorithms that rely on the smoothness of the functions. ### Response: def smooth_angle_channels(self, channels): """Remove discontinuities in angle channels so th...
def normalize_flags(self, flags): """normalize the flags to make sure needed values are there after this method is called self.flags is available :param flags: the flags that will be normalized """ flags['type'] = flags.get('type', None) paction = flags.get('action', 's...
normalize the flags to make sure needed values are there after this method is called self.flags is available :param flags: the flags that will be normalized
Below is the the instruction that describes the task: ### Input: normalize the flags to make sure needed values are there after this method is called self.flags is available :param flags: the flags that will be normalized ### Response: def normalize_flags(self, flags): """normalize the fl...
def redirect_stderr(self, enabled=True, log_level=logging.ERROR): """ Redirect sys.stderr to file-like object. """ if enabled: if self.__stderr_wrapper: self.__stderr_wrapper.update_log_level(log_level=log_level) else: self.__stderr...
Redirect sys.stderr to file-like object.
Below is the the instruction that describes the task: ### Input: Redirect sys.stderr to file-like object. ### Response: def redirect_stderr(self, enabled=True, log_level=logging.ERROR): """ Redirect sys.stderr to file-like object. """ if enabled: if self.__stderr_wrapper...
def get_hubs(self): """Get a list of hubs names. Returns ------- hubs : list List of hub names """ # Use helm to get a list of hubs. output = helm( 'list', '-q' ) # Check if an error occurred. if...
Get a list of hubs names. Returns ------- hubs : list List of hub names
Below is the the instruction that describes the task: ### Input: Get a list of hubs names. Returns ------- hubs : list List of hub names ### Response: def get_hubs(self): """Get a list of hubs names. Returns ------- hubs : list ...
def parse_nodes_coords(osm_response): """ Parse node coordinates from OSM response. Some nodes are standalone points of interest, others are vertices in polygonal (areal) POIs. Parameters ---------- osm_response : string OSM response JSON string Returns ------- ...
Parse node coordinates from OSM response. Some nodes are standalone points of interest, others are vertices in polygonal (areal) POIs. Parameters ---------- osm_response : string OSM response JSON string Returns ------- coords : dict dict of node IDs and their ...
Below is the the instruction that describes the task: ### Input: Parse node coordinates from OSM response. Some nodes are standalone points of interest, others are vertices in polygonal (areal) POIs. Parameters ---------- osm_response : string OSM response JSON string Retu...
def parent(self): """Return a Key constructed from all but the last (kind, id) pairs. If there is only one (kind, id) pair, return None. """ pairs = self.__pairs if len(pairs) <= 1: return None return Key(pairs=pairs[:-1], app=self.__app, namespace=self.__namespace)
Return a Key constructed from all but the last (kind, id) pairs. If there is only one (kind, id) pair, return None.
Below is the the instruction that describes the task: ### Input: Return a Key constructed from all but the last (kind, id) pairs. If there is only one (kind, id) pair, return None. ### Response: def parent(self): """Return a Key constructed from all but the last (kind, id) pairs. If there is only one...
def register_watchers(self, type_callback_dict, register_timeout=None): """ Register multiple callback/event type pairs, expressed as a dict. """ for event_type, callback in type_callback_dict.items(): self._push_watchers[event_type].add(callback) self.wait_for_respon...
Register multiple callback/event type pairs, expressed as a dict.
Below is the the instruction that describes the task: ### Input: Register multiple callback/event type pairs, expressed as a dict. ### Response: def register_watchers(self, type_callback_dict, register_timeout=None): """ Register multiple callback/event type pairs, expressed as a dict. """ ...
def index(self, value, floating=False): """Return the index of a value in the domain. Parameters ---------- value : ``self.set`` element Point whose index to find. floating : bool, optional If True, then the index should also give the position inside the ...
Return the index of a value in the domain. Parameters ---------- value : ``self.set`` element Point whose index to find. floating : bool, optional If True, then the index should also give the position inside the voxel. This is given by returning the i...
Below is the the instruction that describes the task: ### Input: Return the index of a value in the domain. Parameters ---------- value : ``self.set`` element Point whose index to find. floating : bool, optional If True, then the index should also give the po...
def parse(self, lines): ''' Parse signature file lines. @lines - A list of lines from a signature file. Returns None. ''' signature = None for line in lines: # Split at the first comment delimiter (if any) and strip the # result ...
Parse signature file lines. @lines - A list of lines from a signature file. Returns None.
Below is the the instruction that describes the task: ### Input: Parse signature file lines. @lines - A list of lines from a signature file. Returns None. ### Response: def parse(self, lines): ''' Parse signature file lines. @lines - A list of lines from a signature file....
def expose_finish(self, *args): """Finish drawing process """ # Obtain a reference to the OpenGL drawable # and rendering context. gldrawable = self.get_gl_drawable() # glcontext = self.get_gl_context() if not gldrawable: return # Put the buf...
Finish drawing process
Below is the the instruction that describes the task: ### Input: Finish drawing process ### Response: def expose_finish(self, *args): """Finish drawing process """ # Obtain a reference to the OpenGL drawable # and rendering context. gldrawable = self.get_gl_drawable() ...
def torus(script, major_radius=3.0, minor_radius=1.0, inner_diameter=None, outer_diameter=None, major_segments=48, minor_segments=12, color=None): """Create a torus mesh Args: major_radius (float, (optional)): radius from the origin to the center of the cross sections ...
Create a torus mesh Args: major_radius (float, (optional)): radius from the origin to the center of the cross sections minor_radius (float, (optional)): radius of the torus cross section inner_diameter (float, (optional)): inner diameter of torus. If both...
Below is the the instruction that describes the task: ### Input: Create a torus mesh Args: major_radius (float, (optional)): radius from the origin to the center of the cross sections minor_radius (float, (optional)): radius of the torus cross section inner_diame...
def safejoin(base, *elements): """Safely joins paths together. The result will always be a subdirectory under `base`, otherwise ValueError is raised. Args: base (str): base path elements (list of strings): path elements to join to base Returns: elements joined to base ...
Safely joins paths together. The result will always be a subdirectory under `base`, otherwise ValueError is raised. Args: base (str): base path elements (list of strings): path elements to join to base Returns: elements joined to base
Below is the the instruction that describes the task: ### Input: Safely joins paths together. The result will always be a subdirectory under `base`, otherwise ValueError is raised. Args: base (str): base path elements (list of strings): path elements to join to base Returns: ...
def ellipsis(text, length, symbol="..."): """Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis. """ if len(text) > length: pos = text.rfind(" ", 0, length) if pos < 0: ...
Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis.
Below is the the instruction that describes the task: ### Input: Present a block of text of given length. If the length of available text exceeds the requested length, truncate and intelligently append an ellipsis. ### Response: def ellipsis(text, length, symbol="..."): """Present a block of text ...
def install(feature, recurse=False, restart=False, source=None, exclude=None): r''' Install a feature .. note:: Some features require reboot after un/installation, if so until the server is restarted other features can not be installed! .. note:: Some features take a long time ...
r''' Install a feature .. note:: Some features require reboot after un/installation, if so until the server is restarted other features can not be installed! .. note:: Some features take a long time to complete un/installation, set -t with a long timeout Args: ...
Below is the the instruction that describes the task: ### Input: r''' Install a feature .. note:: Some features require reboot after un/installation, if so until the server is restarted other features can not be installed! .. note:: Some features take a long time to complete un...
def run_callbacks(obj, log=None): """Run callbacks.""" def run_callback(callback, args): return callback(*args) return walk_callbacks(obj, run_callback, log)
Run callbacks.
Below is the the instruction that describes the task: ### Input: Run callbacks. ### Response: def run_callbacks(obj, log=None): """Run callbacks.""" def run_callback(callback, args): return callback(*args) return walk_callbacks(obj, run_callback, log)
def get_properties_by_type(self, type, recursive=True, parent_path=""): """ Returns a sorted list of fields that match the type. :param type the type of the field "string","integer" or a list of types :param recursive recurse to sub object :returns a sorted list of fields the ma...
Returns a sorted list of fields that match the type. :param type the type of the field "string","integer" or a list of types :param recursive recurse to sub object :returns a sorted list of fields the match the type
Below is the the instruction that describes the task: ### Input: Returns a sorted list of fields that match the type. :param type the type of the field "string","integer" or a list of types :param recursive recurse to sub object :returns a sorted list of fields the match the type ### Respon...
def header(self): ''' This returns the first header in the data file ''' if self._header is None: self._header = self._read_half_frame_header(self.data) return self._header
This returns the first header in the data file
Below is the the instruction that describes the task: ### Input: This returns the first header in the data file ### Response: def header(self): ''' This returns the first header in the data file ''' if self._header is None: self._header = self._read_half_frame_header(self.data) return s...
def transform_audio(self, y): '''Compute the HCQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) CQT magnitude ...
Compute the HCQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) CQT magnitude data['dphase'] : np.ndarray, sha...
Below is the the instruction that describes the task: ### Input: Compute the HCQT with unwrapped phase Parameters ---------- y : np.ndarray The audio buffer Returns ------- data : dict data['mag'] : np.ndarray, shape=(n_frames, n_bins) ...
def environments(self): """ Access the environments :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList """ if self._environments is None: self._environments = Environme...
Access the environments :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList
Below is the the instruction that describes the task: ### Input: Access the environments :returns: twilio.rest.serverless.v1.service.environment.EnvironmentList :rtype: twilio.rest.serverless.v1.service.environment.EnvironmentList ### Response: def environments(self): """ Access th...
def groupBy(groups_in, classifier, fun_desc='?', keep_uniques=False, *args, **kwargs): """Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of pat...
Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of paths by some attribute. :type classifier: ``function(list, *args, **kwargs) -> str`` :param fun_des...
Below is the the instruction that describes the task: ### Input: Subdivide groups of paths according to a function. :param groups_in: Grouped sets of paths. :type groups_in: :class:`~__builtins__.dict` of iterables :param classifier: Function to group a list of paths by some attribute. :type class...
def _find_highest_supported_command(self, *segment_classes, **kwargs): """Search the BPD for the highest supported version of a segment.""" return_parameter_segment = kwargs.get("return_parameter_segment", False) parameter_segment_name = "{}I{}S".format(segment_classes[0].TYPE[0], segment_class...
Search the BPD for the highest supported version of a segment.
Below is the the instruction that describes the task: ### Input: Search the BPD for the highest supported version of a segment. ### Response: def _find_highest_supported_command(self, *segment_classes, **kwargs): """Search the BPD for the highest supported version of a segment.""" return_parameter_...
def set_main_video_stream_type(self, streamtype, callback=None): ''' Set the stream type of main stream ''' params = {'streamType': streamtype} return self.execute_command('setMainVideoStreamType', params, callback=callback)
Set the stream type of main stream
Below is the the instruction that describes the task: ### Input: Set the stream type of main stream ### Response: def set_main_video_stream_type(self, streamtype, callback=None): ''' Set the stream type of main stream ''' params = {'streamType': streamtype} return self.execu...
def system_describe_projects(input_params={}, always_retry=True, **kwargs): """ Invokes the /system/describeProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/System-Methods#API-method:-/system/describeProjects """ return DXHTTPRequest('/system/describeProje...
Invokes the /system/describeProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/System-Methods#API-method:-/system/describeProjects
Below is the the instruction that describes the task: ### Input: Invokes the /system/describeProjects API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/System-Methods#API-method:-/system/describeProjects ### Response: def system_describe_projects(input_params={}, always_retry=...
def launch(self): """Launch and synchronously write metadata. This is possible due to watchman's built-in async server startup - no double-forking required. """ cmd = self._construct_cmd((self._watchman_path, 'get-pid'), state_file=self._state_file, ...
Launch and synchronously write metadata. This is possible due to watchman's built-in async server startup - no double-forking required.
Below is the the instruction that describes the task: ### Input: Launch and synchronously write metadata. This is possible due to watchman's built-in async server startup - no double-forking required. ### Response: def launch(self): """Launch and synchronously write metadata. This is possible due to ...
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". Note that HFC-245fa was mistakenly labelled as HFC-245ca in MAGI...
Below is the the instruction that describes the task: ### Input: Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
def backfill_history(self, num_days, available_table_names): """ Backfill historical data for days that are missing. :param num_days: number of days of historical data to backfill, if missing :type num_days: int :param available_table_names: names of available per-date...
Backfill historical data for days that are missing. :param num_days: number of days of historical data to backfill, if missing :type num_days: int :param available_table_names: names of available per-date tables :type available_table_names: ``list``
Below is the the instruction that describes the task: ### Input: Backfill historical data for days that are missing. :param num_days: number of days of historical data to backfill, if missing :type num_days: int :param available_table_names: names of available per-date tables ...
def read_chunks(stream, block_size=2**10): """ Given a byte stream with reader, yield chunks of block_size until the stream is consusmed. """ while True: chunk = stream.read(block_size) if not chunk: break yield chunk
Given a byte stream with reader, yield chunks of block_size until the stream is consusmed.
Below is the the instruction that describes the task: ### Input: Given a byte stream with reader, yield chunks of block_size until the stream is consusmed. ### Response: def read_chunks(stream, block_size=2**10): """ Given a byte stream with reader, yield chunks of block_size until the stream is co...
def resolve_class(class_path): """ Load a class by a fully qualified class_path, eg. myapp.models.ModelName """ modulepath, classname = class_path.rsplit('.', 1) module = __import__(modulepath, fromlist=[classname]) return getattr(module, classname)
Load a class by a fully qualified class_path, eg. myapp.models.ModelName
Below is the the instruction that describes the task: ### Input: Load a class by a fully qualified class_path, eg. myapp.models.ModelName ### Response: def resolve_class(class_path): """ Load a class by a fully qualified class_path, eg. myapp.models.ModelName """ modulepath, classname = cl...
def generate_ansible_command(self): """ Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object to start the p...
Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object to start the process
Below is the the instruction that describes the task: ### Input: Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object t...
def process_file(self): """ process_file: Writes base64 encoding to file Args: None Returns: filename """ self.filename = self.convert_base64_to_file() config.LOGGER.info("\t--- Converted base64 image to {}".format(self.filename)) return self.filename
process_file: Writes base64 encoding to file Args: None Returns: filename
Below is the the instruction that describes the task: ### Input: process_file: Writes base64 encoding to file Args: None Returns: filename ### Response: def process_file(self): """ process_file: Writes base64 encoding to file Args: None Returns: filename ...
def get_property_names(obj): """ Gets names of all properties implemented in specified object. :param obj: an objec to introspect. :return: a list with property names. """ property_names = [] for property_name in dir(obj): property = getatt...
Gets names of all properties implemented in specified object. :param obj: an objec to introspect. :return: a list with property names.
Below is the the instruction that describes the task: ### Input: Gets names of all properties implemented in specified object. :param obj: an objec to introspect. :return: a list with property names. ### Response: def get_property_names(obj): """ Gets names of all properties imple...
def process_core(self): """ The method deals with a core found previously in :func:`get_core`. Clause selectors ``self.core_sels`` and sum assumptions involved in the core are treated separately of each other. This is handled by calling methods :func:`...
The method deals with a core found previously in :func:`get_core`. Clause selectors ``self.core_sels`` and sum assumptions involved in the core are treated separately of each other. This is handled by calling methods :func:`process_sels` and :func:`process_sums`, ...
Below is the the instruction that describes the task: ### Input: The method deals with a core found previously in :func:`get_core`. Clause selectors ``self.core_sels`` and sum assumptions involved in the core are treated separately of each other. This is handled by calling ...
def init_argparser(self, argparser): """ Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. """ super(ToolchainRuntime, self).init_argparser(argparser) # it is possible for subclasses to...
Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand.
Below is the the instruction that describes the task: ### Input: Other runtimes (or users of ArgumentParser) can pass their subparser into here to collect the arguments here for a subcommand. ### Response: def init_argparser(self, argparser): """ Other runtimes (or users of Argument...
def _get_equivalent_distances_east(wid, lng, mag, repi, focal_depth=10., ab06=False): """ Computes equivalent values of Joyner-Boore and closest distance to the rupture given epoicentral distance. The procedure is described in Atkinson (2012) - Appendix A (page 32). ...
Computes equivalent values of Joyner-Boore and closest distance to the rupture given epoicentral distance. The procedure is described in Atkinson (2012) - Appendix A (page 32). :param float wid: Width of rectangular rupture :param float lng: Length of rectangular rupture :param floa...
Below is the the instruction that describes the task: ### Input: Computes equivalent values of Joyner-Boore and closest distance to the rupture given epoicentral distance. The procedure is described in Atkinson (2012) - Appendix A (page 32). :param float wid: Width of rectangular rupture :p...