code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
async def _expect_command(cls, reader, name): """ Expect a command. :param reader: The reader to use. :returns: The command data. """ size_type = struct.unpack('B', await reader.readexactly(1))[0] if size_type == 0x04: size = struct.unpack('!B', awai...
Expect a command. :param reader: The reader to use. :returns: The command data.
Below is the the instruction that describes the task: ### Input: Expect a command. :param reader: The reader to use. :returns: The command data. ### Response: async def _expect_command(cls, reader, name): """ Expect a command. :param reader: The reader to use. :ret...
def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400): """ Make a light-weight loc figure """ fields = ['l1', 'm1', 'sizes', 'colors', 'snrs', 'key'] if not circleinds: circl...
Make a light-weight loc figure
Below is the the instruction that describes the task: ### Input: Make a light-weight loc figure ### Response: def plotloc(data, circleinds=[], crossinds=[], edgeinds=[], url_path=None, fileroot=None, tools="hover,tap,pan,box_select,wheel_zoom,reset", plot_width=450, plot_height=400): """ Make a lig...
def close(self): """ Closes the device. """ try: self._running = False self._read_thread.stop() self._device.close() except Exception: pass self.on_close()
Closes the device.
Below is the the instruction that describes the task: ### Input: Closes the device. ### Response: def close(self): """ Closes the device. """ try: self._running = False self._read_thread.stop() self._device.close() except Exception: ...
def check(self, uid=None, usage_limits_count=None, cryptographic_usage_mask=None, lease_time=None): """ Check the constraints for a managed object. Args: uid (string): The unique ID of the managed object to check. ...
Check the constraints for a managed object. Args: uid (string): The unique ID of the managed object to check. Optional, defaults to None. usage_limits_count (int): The number of items that can be secured with the specified managed object. Optional, defaul...
Below is the the instruction that describes the task: ### Input: Check the constraints for a managed object. Args: uid (string): The unique ID of the managed object to check. Optional, defaults to None. usage_limits_count (int): The number of items that can be secure...
def rad_latitude(self): """ Lazy conversion degrees latitude to radians. """ if self._rad_latitude is None: self._rad_latitude = math.radians(self.latitude) return self._rad_latitude
Lazy conversion degrees latitude to radians.
Below is the the instruction that describes the task: ### Input: Lazy conversion degrees latitude to radians. ### Response: def rad_latitude(self): """ Lazy conversion degrees latitude to radians. """ if self._rad_latitude is None: self._rad_latitude = math.radians(self....
def size(self): """Returns the size of the cache in bytes.""" total_size = 0 for dir_path, dir_names, filenames in os.walk(self.dir): for f in filenames: fp = os.path.join(dir_path, f) total_size += os.path.getsize(fp) return total_size
Returns the size of the cache in bytes.
Below is the the instruction that describes the task: ### Input: Returns the size of the cache in bytes. ### Response: def size(self): """Returns the size of the cache in bytes.""" total_size = 0 for dir_path, dir_names, filenames in os.walk(self.dir): for f in filenames: ...
def autostrip(cls): """ strip text fields before validation example: @autostrip class PersonForm(forms.Form): name = forms.CharField(min_length=2, max_length=10) email = forms.EmailField() Author: nail.xx """ warnings.warn( "django-annoying autostrip is deprecat...
strip text fields before validation example: @autostrip class PersonForm(forms.Form): name = forms.CharField(min_length=2, max_length=10) email = forms.EmailField() Author: nail.xx
Below is the the instruction that describes the task: ### Input: strip text fields before validation example: @autostrip class PersonForm(forms.Form): name = forms.CharField(min_length=2, max_length=10) email = forms.EmailField() Author: nail.xx ### Response: def autostrip(cls): ...
def run_tutorial(plot=False, multiplex=True, return_streams=False, cores=4, verbose=False): """ Run the tutorial. :return: detections """ client = Client("GEONET", debug=verbose) cat = client.get_events( minlatitude=-40.98, maxlatitude=-40.85, minlongitude=175.4, ...
Run the tutorial. :return: detections
Below is the the instruction that describes the task: ### Input: Run the tutorial. :return: detections ### Response: def run_tutorial(plot=False, multiplex=True, return_streams=False, cores=4, verbose=False): """ Run the tutorial. :return: detections """ client = Client("...
def _get_bokeh_chart(self, x_field, y_field, chart_type, label, opts, style, options={}, **kwargs): """ Get a Bokeh chart object """ if isinstance(x_field, list): kdims = x_field else: kdims = [x_field] if isinstance(y_fiel...
Get a Bokeh chart object
Below is the the instruction that describes the task: ### Input: Get a Bokeh chart object ### Response: def _get_bokeh_chart(self, x_field, y_field, chart_type, label, opts, style, options={}, **kwargs): """ Get a Bokeh chart object """ if isinstance(x_field...
def remove(self, item): """Remove an item from the list :param item: The item to remove from the list. :raises ValueError: If the item is not present in the list. """ if item not in self: raise ValueError('objectlist.remove(item) failed, item not in list') it...
Remove an item from the list :param item: The item to remove from the list. :raises ValueError: If the item is not present in the list.
Below is the the instruction that describes the task: ### Input: Remove an item from the list :param item: The item to remove from the list. :raises ValueError: If the item is not present in the list. ### Response: def remove(self, item): """Remove an item from the list :param ite...
def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """ cmd = ['iperf', '-c', host, '-p', str(port), '-t', str(timeout)] if not (protocol, 'UDP'): cmd.append('-u') if parall...
iperf -D -c host -t 60
Below is the the instruction that describes the task: ### Input: iperf -D -c host -t 60 ### Response: def start_client(self, host, port=5001, protocol='TCP', timeout=5, parallel=None, bandwidth=None): """iperf -D -c host -t 60 """ cmd = ['iperf', '-c', host, '-p', str(...
def _sdk_tools(self): """ Microsoft Windows SDK Tools paths generator """ if self.vc_ver < 15.0: bin_dir = 'Bin' if self.vc_ver <= 11.0 else r'Bin\x86' yield os.path.join(self.si.WindowsSdkDir, bin_dir) if not self.pi.current_is_x86(): arch_su...
Microsoft Windows SDK Tools paths generator
Below is the the instruction that describes the task: ### Input: Microsoft Windows SDK Tools paths generator ### Response: def _sdk_tools(self): """ Microsoft Windows SDK Tools paths generator """ if self.vc_ver < 15.0: bin_dir = 'Bin' if self.vc_ver <= 11.0 else r'Bin\x...
def AddTimeZoneOption(self, argument_group): """Adds the time zone option to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ # Note the default here is None so we can determine if the time zone # option was set. argument_group.add_argument(...
Adds the time zone option to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
Below is the the instruction that describes the task: ### Input: Adds the time zone option to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. ### Response: def AddTimeZoneOption(self, argument_group): """Adds the time zone option to the argument group. ...
def _load_report(infile): '''Loads report file into a dictionary. Key=reference name. Value = list of report lines for that reference''' report_dict = {} f = pyfastaq.utils.open_file_read(infile) first_line = True for line in f: line = line.rstrip() ...
Loads report file into a dictionary. Key=reference name. Value = list of report lines for that reference
Below is the the instruction that describes the task: ### Input: Loads report file into a dictionary. Key=reference name. Value = list of report lines for that reference ### Response: def _load_report(infile): '''Loads report file into a dictionary. Key=reference name. Value = list of repor...
def set_position(self, key, latlon, layer=None, rotation=0): '''move an object on the map''' self.object_queue.put(SlipPosition(key, latlon, layer, rotation))
move an object on the map
Below is the the instruction that describes the task: ### Input: move an object on the map ### Response: def set_position(self, key, latlon, layer=None, rotation=0): '''move an object on the map''' self.object_queue.put(SlipPosition(key, latlon, layer, rotation))
def from_path(self, request, path, lang): """ Resolve a request to an alias. returns a :class:`PageAlias <pages.models.PageAlias>` if the url matches no page at all. The aliasing system supports plain aliases (``/foo/bar``) as well as aliases containing GET parameters (li...
Resolve a request to an alias. returns a :class:`PageAlias <pages.models.PageAlias>` if the url matches no page at all. The aliasing system supports plain aliases (``/foo/bar``) as well as aliases containing GET parameters (like ``index.php?page=foo``). :param request: the reque...
Below is the the instruction that describes the task: ### Input: Resolve a request to an alias. returns a :class:`PageAlias <pages.models.PageAlias>` if the url matches no page at all. The aliasing system supports plain aliases (``/foo/bar``) as well as aliases containing GET parameters ...
def get_event_buffer(self, dag_ids=None): """ Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns all ...
Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns all :return: a dict of events
Below is the the instruction that describes the task: ### Input: Returns and flush the event buffer. In case dag_ids is specified it will only return and flush events for the given dag_ids. Otherwise it returns and flushes all :param dag_ids: to dag_ids to return events for, if None returns...
def _debug_check(self): """ Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort """ # old_start = 0 old_end = 0 old_sort = "" for segment in self._list: if segment.star...
Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort
Below is the the instruction that describes the task: ### Input: Iterates over list checking segments with same sort do not overlap :raise: Exception: if segments overlap space with same sort ### Response: def _debug_check(self): """ Iterates over list checking segments with same sort do n...
def exportData(self, datfile): """ Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). """ def ampl_set(name, values): def format_entry(e): ...
Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute).
Below is the the instruction that describes the task: ### Input: Create a .dat file with the data that has been loaded. Args: datfile: Path to the file (Relative to the current working directory or absolute). ### Response: def exportData(self, datfile): """ Create a...
def add(self, key, value): """add header value""" if key not in self.headers: self.headers[key] = [] self.headers[key].append(value) if self.sent_time: self.modified_since_sent = True
add header value
Below is the the instruction that describes the task: ### Input: add header value ### Response: def add(self, key, value): """add header value""" if key not in self.headers: self.headers[key] = [] self.headers[key].append(value) if self.sent_time: self.modif...
def _items_to_resources(self, body): """ Takes a List body and return a dictionary with the following structure: { 'api_version': str, 'kind': str, 'items': [{ 'resource': Resource, 'name': str, ...
Takes a List body and return a dictionary with the following structure: { 'api_version': str, 'kind': str, 'items': [{ 'resource': Resource, 'name': str, 'namespace': str, }] ...
Below is the the instruction that describes the task: ### Input: Takes a List body and return a dictionary with the following structure: { 'api_version': str, 'kind': str, 'items': [{ 'resource': Resource, 'name': st...
def print_information(handler, label): """ Prints latest tag's information """ click.echo('=> Latest stable: {tag}'.format( tag=click.style(str(handler.latest_stable or 'N/A'), fg='yellow' if handler.latest_stable else 'magenta') )) if label is not None: ...
Prints latest tag's information
Below is the the instruction that describes the task: ### Input: Prints latest tag's information ### Response: def print_information(handler, label): """ Prints latest tag's information """ click.echo('=> Latest stable: {tag}'.format( tag=click.style(str(handler.latest_stable or 'N/A'), fg=...
def get_label_set(self, type_str=None): """Get a set of label_str for the tree rooted at this node. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: set: The label...
Get a set of label_str for the tree rooted at this node. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: set: The labels of the nodes leading up to this node from the roo...
Below is the the instruction that describes the task: ### Input: Get a set of label_str for the tree rooted at this node. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: ...
def t_WSIGNORE_comment(self, token): r'[#][^\n]*\n+' token.lexer.lineno += token.value.count('\n') newline_token = _create_token('NEWLINE', '\n', token.lineno, token.lexpos + len(token.value) - 1) newline_token.lexer = token.lexer self._check_for_indent(newline_token)
r'[#][^\n]*\n+
Below is the the instruction that describes the task: ### Input: r'[#][^\n]*\n+ ### Response: def t_WSIGNORE_comment(self, token): r'[#][^\n]*\n+' token.lexer.lineno += token.value.count('\n') newline_token = _create_token('NEWLINE', '\n', token.lineno, token.lexpos + len(token....
def _wrap_sessions(sessions, request): """ Returns a list of session keys for the given lists of sessions and/or the session key of the current logged in user, if the list contains the magic item SELF. """ result = set() for s in sessions: if s is SELF and request: result.add...
Returns a list of session keys for the given lists of sessions and/or the session key of the current logged in user, if the list contains the magic item SELF.
Below is the the instruction that describes the task: ### Input: Returns a list of session keys for the given lists of sessions and/or the session key of the current logged in user, if the list contains the magic item SELF. ### Response: def _wrap_sessions(sessions, request): """ Returns a list of sess...
def _find_immediately(self, locator, search_object=None): ''' Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwra...
Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwrapper.WebElementWrapper @param search_object: Optional WebElement to ...
Below is the the instruction that describes the task: ### Input: Attempts to immediately find elements on the page without waiting @type locator: webdriverwrapper.support.locator.Locator @param locator: Locator object describing @type search_object: webdriverwrapper.WebE...
def is_within(self, query, subject): """Accessory function to check if a range is fully within another range""" if self.pt_within(query[0], subject) and self.pt_within(query[1], subject): return True return False
Accessory function to check if a range is fully within another range
Below is the the instruction that describes the task: ### Input: Accessory function to check if a range is fully within another range ### Response: def is_within(self, query, subject): """Accessory function to check if a range is fully within another range""" if self.pt_within(query[0], subject) an...
def __EncodedAttribute_decode_rgb32(self, da, extract_as=ExtractAs.Numpy): """Decode a color image (JPEG_RGB or RGB24) and returns a 32 bits RGB image. :param da: :class:`DeviceAttribute` that contains the image :type da: :class:`DeviceAttribute` :param extract_as: defaults to ExtractAs.Num...
Decode a color image (JPEG_RGB or RGB24) and returns a 32 bits RGB image. :param da: :class:`DeviceAttribute` that contains the image :type da: :class:`DeviceAttribute` :param extract_as: defaults to ExtractAs.Numpy :type extract_as: ExtractAs :return: the decoded data ...
Below is the the instruction that describes the task: ### Input: Decode a color image (JPEG_RGB or RGB24) and returns a 32 bits RGB image. :param da: :class:`DeviceAttribute` that contains the image :type da: :class:`DeviceAttribute` :param extract_as: defaults to ExtractAs.Numpy :t...
def _samples_dicts_to_array(samples_dicts, labels): """Convert an iterable of samples where each sample is a dict to a numpy 2d array. Also determines the labels is they are None. """ itersamples = iter(samples_dicts) first_sample = next(itersamples) if labels is None: labels = list(fi...
Convert an iterable of samples where each sample is a dict to a numpy 2d array. Also determines the labels is they are None.
Below is the the instruction that describes the task: ### Input: Convert an iterable of samples where each sample is a dict to a numpy 2d array. Also determines the labels is they are None. ### Response: def _samples_dicts_to_array(samples_dicts, labels): """Convert an iterable of samples where each sample...
def dict_intersection(dict1, dict2, combine=False, combine_op=op.add): r""" Args: dict1 (dict): dict2 (dict): combine (bool): Combines keys only if the values are equal if False else values are combined using combine_op (default = False) combine_op (func): (default = ...
r""" Args: dict1 (dict): dict2 (dict): combine (bool): Combines keys only if the values are equal if False else values are combined using combine_op (default = False) combine_op (func): (default = op.add) Returns: dict: mergedict_ CommandLine: py...
Below is the the instruction that describes the task: ### Input: r""" Args: dict1 (dict): dict2 (dict): combine (bool): Combines keys only if the values are equal if False else values are combined using combine_op (default = False) combine_op (func): (default = op.add...
def list( self, root: str, patterns: List[str], exclude: Optional[List[str]] = None ) -> List[str]: """ Return the list of files that match any of the patterns within root. If exclude is provided, files that match an exclude pattern are omitted. Note: The `find` ...
Return the list of files that match any of the patterns within root. If exclude is provided, files that match an exclude pattern are omitted. Note: The `find` command does not understand globs properly. e.g. 'a/*.py' will match 'a/b/c.py' For this reason, avoid calli...
Below is the the instruction that describes the task: ### Input: Return the list of files that match any of the patterns within root. If exclude is provided, files that match an exclude pattern are omitted. Note: The `find` command does not understand globs properly. e.g. 'a...
def set_tuning(self, tuning): """Set the tuning attribute on both the Track and its instrument (when available). Tuning should be a StringTuning or derivative object. """ if self.instrument: self.instrument.tuning = tuning self.tuning = tuning return ...
Set the tuning attribute on both the Track and its instrument (when available). Tuning should be a StringTuning or derivative object.
Below is the the instruction that describes the task: ### Input: Set the tuning attribute on both the Track and its instrument (when available). Tuning should be a StringTuning or derivative object. ### Response: def set_tuning(self, tuning): """Set the tuning attribute on both the Track a...
def domagicmag(file, Recs): """ converts a magic record back into the SIO mag format """ for rec in Recs: type = ".0" meths = [] tmp = rec["magic_method_codes"].split(':') for meth in tmp: meths.append(meth.strip()) if 'LT-T-I' in meths: ty...
converts a magic record back into the SIO mag format
Below is the the instruction that describes the task: ### Input: converts a magic record back into the SIO mag format ### Response: def domagicmag(file, Recs): """ converts a magic record back into the SIO mag format """ for rec in Recs: type = ".0" meths = [] tmp = rec["mag...
def toDom(self, node): """node -- node representing message""" wsdl = self.getWSDL() ep = ElementProxy(None, node) epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.version), 'part') epc.setAttributeNS(None, 'name', self.name) if self.element is not None: ns,n...
node -- node representing message
Below is the the instruction that describes the task: ### Input: node -- node representing message ### Response: def toDom(self, node): """node -- node representing message""" wsdl = self.getWSDL() ep = ElementProxy(None, node) epc = ep.createAppendElement(DOM.GetWSDLUri(wsdl.versio...
def get_executions(self, **kwargs): """ Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions a...
Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions associated to the current service.
Below is the the instruction that describes the task: ### Input: Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of Servic...
def render_to_response(template, object, params=None, mimetype='text/html'): """ ``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml will be transformed using ``template``. The result will be a :class:`~django.http.HttpResponse` object, containing the transformed ...
``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml will be transformed using ``template``. The result will be a :class:`~django.http.HttpResponse` object, containing the transformed xml as the body. :param template: an xslt template name. :param object: an o...
Below is the the instruction that describes the task: ### Input: ``object`` will be converted to xml using :func:`easymode.tree.xml`. The resulting xml will be transformed using ``template``. The result will be a :class:`~django.http.HttpResponse` object, containing the transformed xml as the body. ...
def truncate_table(self, table_name, database=None): """ Delete all rows from, but do not drop, an existing table Parameters ---------- table_name : string database : string, default None (optional) """ statement = ddl.TruncateTable(table_name, database=d...
Delete all rows from, but do not drop, an existing table Parameters ---------- table_name : string database : string, default None (optional)
Below is the the instruction that describes the task: ### Input: Delete all rows from, but do not drop, an existing table Parameters ---------- table_name : string database : string, default None (optional) ### Response: def truncate_table(self, table_name, database=None): ...
def drop(self): """Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases...
Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. .. warning:: For most use cases, the only reason to drop a...
Below is the the instruction that describes the task: ### Input: Release the message from lease management. This informs the policy to no longer hold on to the lease for this message. Pub/Sub will re-deliver the message if it is not acknowledged before the existing lease expires. ....
def get_connection_id_by_endpoint(self, endpoint): """Returns the connection id associated with a publically reachable endpoint or raises KeyError if the endpoint is not found. Args: endpoint (str): A zmq-style uri which identifies a publically reachable endp...
Returns the connection id associated with a publically reachable endpoint or raises KeyError if the endpoint is not found. Args: endpoint (str): A zmq-style uri which identifies a publically reachable endpoint.
Below is the the instruction that describes the task: ### Input: Returns the connection id associated with a publically reachable endpoint or raises KeyError if the endpoint is not found. Args: endpoint (str): A zmq-style uri which identifies a publically reachab...
def mixer(yaw, throttle, max_power=100): """ Mix a pair of joystick axes, returning a pair of wheel speeds. This is where the mapping from joystick positions to wheel powers is defined, so any changes to how the robot drives should be made here, everything else is really just plumbing. :param y...
Mix a pair of joystick axes, returning a pair of wheel speeds. This is where the mapping from joystick positions to wheel powers is defined, so any changes to how the robot drives should be made here, everything else is really just plumbing. :param yaw: Yaw axis value, ranges from -1.0 to 1.0 ...
Below is the the instruction that describes the task: ### Input: Mix a pair of joystick axes, returning a pair of wheel speeds. This is where the mapping from joystick positions to wheel powers is defined, so any changes to how the robot drives should be made here, everything else is really just plumbing. ...
def from_json(cls, data): """Create a data type from a dictionary. Args: data: Data as a dictionary. { "name": data type name of the data type as a string "data_type": the class name of the data type as a string "ba...
Create a data type from a dictionary. Args: data: Data as a dictionary. { "name": data type name of the data type as a string "data_type": the class name of the data type as a string "base_unit": the base unit of the data t...
Below is the the instruction that describes the task: ### Input: Create a data type from a dictionary. Args: data: Data as a dictionary. { "name": data type name of the data type as a string "data_type": the class name of the data type as ...
def _get_definitions(source): # type: (str) -> Tuple[Dict[str, str], int] """Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments ...
Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments and definitions as well as the length of the longest argument.
Below is the the instruction that describes the task: ### Input: Extract a dictionary of arguments and definitions. Args: source: The source for a section of a usage string that contains definitions. Returns: A two-tuple containing a dictionary of all arguments and definitions ...
def iter(self, match="*", count=1000): """ Iterates the set of keys in :prop:key_prefix in :prop:_client @match: #str pattern to match after the :prop:key_prefix @count: the user specified the amount of work that should be done at every call in order to retrieve elements ...
Iterates the set of keys in :prop:key_prefix in :prop:_client @match: #str pattern to match after the :prop:key_prefix @count: the user specified the amount of work that should be done at every call in order to retrieve elements from the collection -> yields redis ke...
Below is the the instruction that describes the task: ### Input: Iterates the set of keys in :prop:key_prefix in :prop:_client @match: #str pattern to match after the :prop:key_prefix @count: the user specified the amount of work that should be done at every call in order to ...
def visit_continue(self, node, parent): """visit a Continue node by returning a fresh instance of it""" return nodes.Continue( getattr(node, "lineno", None), getattr(node, "col_offset", None), parent )
visit a Continue node by returning a fresh instance of it
Below is the the instruction that describes the task: ### Input: visit a Continue node by returning a fresh instance of it ### Response: def visit_continue(self, node, parent): """visit a Continue node by returning a fresh instance of it""" return nodes.Continue( getattr(node, "lineno",...
def k_partitions(collection, k): """Generate all ``k``-partitions of a collection. Example: >>> list(k_partitions(range(3), 2)) [[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]] """ collection = list(collection) n = len(collection) # Special cases if n == 0 or k < 1: re...
Generate all ``k``-partitions of a collection. Example: >>> list(k_partitions(range(3), 2)) [[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]]
Below is the the instruction that describes the task: ### Input: Generate all ``k``-partitions of a collection. Example: >>> list(k_partitions(range(3), 2)) [[[0, 1], [2]], [[0], [1, 2]], [[0, 2], [1]]] ### Response: def k_partitions(collection, k): """Generate all ``k``-partitions of a co...
def from_set(self, fileset, check_if_dicoms=True): """Overwrites self.items with the given set of files. Will filter the fileset and keep only Dicom files. Parameters ---------- fileset: iterable of str Paths to files check_if_dicoms: bool Whether to che...
Overwrites self.items with the given set of files. Will filter the fileset and keep only Dicom files. Parameters ---------- fileset: iterable of str Paths to files check_if_dicoms: bool Whether to check if the items in fileset are dicom file paths
Below is the the instruction that describes the task: ### Input: Overwrites self.items with the given set of files. Will filter the fileset and keep only Dicom files. Parameters ---------- fileset: iterable of str Paths to files check_if_dicoms: bool Whether...
def add_extension(self, klass, extension): """Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type) """ klass = self._get_class_path(klass) # TODO: Take order into account. self._extensio...
Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type)
Below is the the instruction that describes the task: ### Input: Register an extension for a class. :param klass: Class to register an extension for :param extension: Extension (arbitrary type) ### Response: def add_extension(self, klass, extension): """Register an extension for a class. ...
def dimensions(self, *dimensions): """ Add a list of Dimension ingredients to the query. These can either be Dimension objects or strings representing dimensions on the shelf. The Dimension expression will be added to the query's select statement and to the group_by. :param dim...
Add a list of Dimension ingredients to the query. These can either be Dimension objects or strings representing dimensions on the shelf. The Dimension expression will be added to the query's select statement and to the group_by. :param dimensions: Dimensions to add to the recipe. Dimen...
Below is the the instruction that describes the task: ### Input: Add a list of Dimension ingredients to the query. These can either be Dimension objects or strings representing dimensions on the shelf. The Dimension expression will be added to the query's select statement and to the group_b...
def get_page_args(): """ Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER> """ pages = {} for arg in request.args: re_match = re.findall("page_(.*)", arg) if re_match: pages[re_...
Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER>
Below is the the instruction that describes the task: ### Input: Get page arguments, returns a dictionary { <VIEW_NAME>: PAGE_NUMBER } Arguments are passed: page_<VIEW_NAME>=<PAGE_NUMBER> ### Response: def get_page_args(): """ Get page arguments, returns a dictionary { <VIEW_NA...
def _resolve_indirect_inner(maybe_idict): """Resolve the contents an indirect dictionary (containing promises) to produce a dictionary actual values, including merging multiple sources into a single input. """ if isinstance(maybe_idict, IndirectDict): result = {} for key, value in l...
Resolve the contents an indirect dictionary (containing promises) to produce a dictionary actual values, including merging multiple sources into a single input.
Below is the the instruction that describes the task: ### Input: Resolve the contents an indirect dictionary (containing promises) to produce a dictionary actual values, including merging multiple sources into a single input. ### Response: def _resolve_indirect_inner(maybe_idict): """Resolve the conten...
def handle_inform(self, connection, msg): """Dispatch an inform message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The inform message to process. ...
Dispatch an inform message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The inform message to process.
Below is the the instruction that describes the task: ### Input: Dispatch an inform message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The inform messa...
def sample(self, n_to_sample, **kwargs): """Sample a sequence of items from the pool Parameters ---------- n_to_sample : int number of items to sample """ n_to_sample = verify_positive(int(n_to_sample)) n_remaining = self._max_iter - self.t_ ...
Sample a sequence of items from the pool Parameters ---------- n_to_sample : int number of items to sample
Below is the the instruction that describes the task: ### Input: Sample a sequence of items from the pool Parameters ---------- n_to_sample : int number of items to sample ### Response: def sample(self, n_to_sample, **kwargs): """Sample a sequence of items from the pool...
def init(url=None, ip=None, port=None, name=None, https=None, insecure=None, username=None, password=None, cookies=None, proxy=None, start_h2o=True, nthreads=-1, ice_root=None, log_dir=None, log_level=None, enable_assertions=True, max_mem_size=None, min_mem_size=None, strict_version_check=None, ignore...
Attempt to connect to a local server, or if not successful start a new server and connect to it. :param url: Full URL of the server to connect to (can be used instead of `ip` + `port` + `https`). :param ip: The ip address (or host name) of the server where H2O is running. :param port: Port number that H2O ...
Below is the the instruction that describes the task: ### Input: Attempt to connect to a local server, or if not successful start a new server and connect to it. :param url: Full URL of the server to connect to (can be used instead of `ip` + `port` + `https`). :param ip: The ip address (or host name) of th...
def run(self, raw_args=None): """ Parses the given arguments (if these are None, then argparse's parser defaults to parsing sys.argv), inits a Core instance, calls its lint method with the respective arguments, and then exits. """ args = self.parser.parse_args(raw_args) core = Core() try: report = ...
Parses the given arguments (if these are None, then argparse's parser defaults to parsing sys.argv), inits a Core instance, calls its lint method with the respective arguments, and then exits.
Below is the the instruction that describes the task: ### Input: Parses the given arguments (if these are None, then argparse's parser defaults to parsing sys.argv), inits a Core instance, calls its lint method with the respective arguments, and then exits. ### Response: def run(self, raw_args=None): """ P...
def from_args(cls, **kwargs): """ Generates one or more VSGSuite instances from command line arguments. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method. """ # Create a VSGSuite for each fil...
Generates one or more VSGSuite instances from command line arguments. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method.
Below is the the instruction that describes the task: ### Input: Generates one or more VSGSuite instances from command line arguments. :param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method. ### Response: def from_args(cls,...
def _read(self, entry): """Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. Returns: Entry content as string. """ start_time = time.time() content = self._zip.read(entry.filename) ctx = context.get() if ctx: operation.counters.Increment(COUNTER_IO_R...
Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. Returns: Entry content as string.
Below is the the instruction that describes the task: ### Input: Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. Returns: Entry content as string. ### Response: def _read(self, entry): """Read entry content. Args: entry: zip file entry as zipfile.ZipInfo. ...
def getHeaders(self): ''' 从字符串中格式化出字典形式的Headers ''' items = self.data headers = {} for item in items: if len(item) > 0 and self._judeNOtIn(item, ['curl', 'GET', 'Cookie', 'cookie']): sp = item.split(':') headers[sp[0]] = sp[1] ...
从字符串中格式化出字典形式的Headers
Below is the the instruction that describes the task: ### Input: 从字符串中格式化出字典形式的Headers ### Response: def getHeaders(self): ''' 从字符串中格式化出字典形式的Headers ''' items = self.data headers = {} for item in items: if len(item) > 0 and self._judeNOtIn(item, ['curl', ...
def in6_iseui64(x): """ Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format. """ eui64 = inet_pton(socket.AF_INET6, '::ff:fe00:0') ...
Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format.
Below is the the instruction that describes the task: ### Input: Return True if provided address has an interface identifier part created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*). Otherwise, False is returned. Address must be passed in printable format. ### Response: def in6_iseui6...
def _get_current_output(self): """ Get child modules output. """ output = [] for item in self.items: out = self.py3.get_output(item) if out and "separator" not in out[-1]: out[-1]["separator"] = True output += out return...
Get child modules output.
Below is the the instruction that describes the task: ### Input: Get child modules output. ### Response: def _get_current_output(self): """ Get child modules output. """ output = [] for item in self.items: out = self.py3.get_output(item) if out and "s...
def parse_output(a1_text, a2_text, sentence_segmentations): """Parses the output of the TEES reader and returns a networkx graph with the event information. Parameters ---------- a1_text : str Contents of the TEES a1 output, specifying the entities a1_text : str Contents of the ...
Parses the output of the TEES reader and returns a networkx graph with the event information. Parameters ---------- a1_text : str Contents of the TEES a1 output, specifying the entities a1_text : str Contents of the TEES a2 output, specifying the event graph sentence_segmentatio...
Below is the the instruction that describes the task: ### Input: Parses the output of the TEES reader and returns a networkx graph with the event information. Parameters ---------- a1_text : str Contents of the TEES a1 output, specifying the entities a1_text : str Contents of th...
def one_phase_dP_acceleration(m, D, rho_o, rho_i): r'''This function handles calculation of one-phase fluid pressure drop due to acceleration for flow inside channels. This is a discrete calculation, providing the total differential in pressure for a given length and should be called as part of a seg...
r'''This function handles calculation of one-phase fluid pressure drop due to acceleration for flow inside channels. This is a discrete calculation, providing the total differential in pressure for a given length and should be called as part of a segment solver routine. .. math:: - \left...
Below is the the instruction that describes the task: ### Input: r'''This function handles calculation of one-phase fluid pressure drop due to acceleration for flow inside channels. This is a discrete calculation, providing the total differential in pressure for a given length and should be called as...
def get_splits(self, id_num, unit='mi'): """Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or 'km'. """ url = self._build_url('my', 'activities', id_num, 'splits', unit) return self._json(u...
Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or 'km'.
Below is the the instruction that describes the task: ### Input: Return the splits of the activity with the given id. :param unit: The unit to use for splits. May be one of 'mi' or 'km'. ### Response: def get_splits(self, id_num, unit='mi'): """Return the splits of the activi...
def eq(self, o): """ Equal :param o: The ohter operand :return: TrueResult(), FalseResult(), or MaybeResult() """ if (self.is_integer and o.is_integer ): # Two integers if self.lower_bound == o.lower_bound: ...
Equal :param o: The ohter operand :return: TrueResult(), FalseResult(), or MaybeResult()
Below is the the instruction that describes the task: ### Input: Equal :param o: The ohter operand :return: TrueResult(), FalseResult(), or MaybeResult() ### Response: def eq(self, o): """ Equal :param o: The ohter operand :return: TrueResult(), FalseResult(), or M...
def clear_learning_objectives(self): """Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.lea...
Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.*
Below is the the instruction that describes the task: ### Input: Clears the learning objectives. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* ### Response: def clear_learning_object...
def EncodeMessages(self, message_list, result, destination=None, timestamp=None, api_version=3): """Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload...
Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue which will be filled in. destination: The CN of the remote system...
Below is the the instruction that describes the task: ### Input: Accepts a list of messages and encodes for transmission. This function signs and then encrypts the payload. Args: message_list: A MessageList rdfvalue containing a list of GrrMessages. result: A ClientCommunication rdfvalue whi...
def get_TGS(self, spn_user, override_etype = None): """ Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerberoasting, ...
Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerberoasting, will override the AP_REQ supported etype values (which is de...
Below is the the instruction that describes the task: ### Input: Requests a TGS ticket for the specified user. Retruns the TGS ticket, end the decrpyted encTGSRepPart. spn_user: KerberosTarget: the service user you want to get TGS for. override_etype: None or list of etype values (int) Used mostly for kerber...
def _sql_params(sql): """ Identify `sql` as either SQL string or 2-tuple of SQL and params. Same format as supported by Django's RunSQL operation for sql/reverse_sql. """ params = None if isinstance(sql, (list, tuple)): elements = len(sql) if elements == 2: sql, param...
Identify `sql` as either SQL string or 2-tuple of SQL and params. Same format as supported by Django's RunSQL operation for sql/reverse_sql.
Below is the the instruction that describes the task: ### Input: Identify `sql` as either SQL string or 2-tuple of SQL and params. Same format as supported by Django's RunSQL operation for sql/reverse_sql. ### Response: def _sql_params(sql): """ Identify `sql` as either SQL string or 2-tuple of SQL and...
def any(self, func): """ :param func: :type func: (K, T) -> bool :rtype: bool Usage: >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2) True >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3) False """ return any...
:param func: :type func: (K, T) -> bool :rtype: bool Usage: >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2) True >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3) False
Below is the the instruction that describes the task: ### Input: :param func: :type func: (K, T) -> bool :rtype: bool Usage: >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 2) True >>> TDict(k1=1, k2=2, k3=3).any(lambda k, v: v > 3) False ##...
def shutdown(self, channel=Channel.CHANNEL_ALL, shutdown_hardware=True): """ Shuts down all CAN interfaces and/or the hardware interface. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ALL`)...
Shuts down all CAN interfaces and/or the hardware interface. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ALL`) :param bool shutdown_hardware: If true then the hardware interface will be closed to...
Below is the the instruction that describes the task: ### Input: Shuts down all CAN interfaces and/or the hardware interface. :param int channel: CAN channel, to be used (:data:`Channel.CHANNEL_CH0`, :data:`Channel.CHANNEL_CH1` or :data:`Channel.CHANNEL_ALL`) :param bool shu...
def link(self): """Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark that running update persists the summary f...
Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark that running update persists the summary frames instead (or e...
Below is the the instruction that describes the task: ### Input: Ensure that an appropriate link to the cellpy-files exists for each cell. The experiment will then contain a CellpyData object for each cell (in the cell_data_frames attribute) with only the step-table stored. Remark ...
def sites_at_edges( self ): """ Finds the six sites with the maximum and minimum coordinates along x, y, and z. Args: None Returns: (List(List)): In the order [ +x, -x, +y, -y, +z, -z ] """ min_x = min( [ s.r[0] for s in self.sites ] ) m...
Finds the six sites with the maximum and minimum coordinates along x, y, and z. Args: None Returns: (List(List)): In the order [ +x, -x, +y, -y, +z, -z ]
Below is the the instruction that describes the task: ### Input: Finds the six sites with the maximum and minimum coordinates along x, y, and z. Args: None Returns: (List(List)): In the order [ +x, -x, +y, -y, +z, -z ] ### Response: def sites_at_edges( self ): """...
def send_ip_route_add( self, prefix, nexthops=None, safi=packet_safi.UNICAST, flags=zebra.ZEBRA_FLAG_INTERNAL, distance=None, metric=None, mtu=None, tag=None): """ Sends ZEBRA_IPV4/v6_ROUTE_ADD message to Zebra daemon. :param prefix: IPv4/v6 Prefix to adverti...
Sends ZEBRA_IPV4/v6_ROUTE_ADD message to Zebra daemon. :param prefix: IPv4/v6 Prefix to advertise. :param nexthops: List of nexthop addresses. :param safi: SAFI to advertise. :param flags: Message flags to advertise. See "ZEBRA_FLAG_*". :param distance: (Optional) Distance to ad...
Below is the the instruction that describes the task: ### Input: Sends ZEBRA_IPV4/v6_ROUTE_ADD message to Zebra daemon. :param prefix: IPv4/v6 Prefix to advertise. :param nexthops: List of nexthop addresses. :param safi: SAFI to advertise. :param flags: Message flags to advertise. S...
def list_formats(self, node, path=(), formats=None): """ Lists the object formats in sorted order. :param node: Root node to start listing the formats from. :type node: AbstractCompositeNode :param path: Walked paths. :type path: tuple :param formats: Formats. ...
Lists the object formats in sorted order. :param node: Root node to start listing the formats from. :type node: AbstractCompositeNode :param path: Walked paths. :type path: tuple :param formats: Formats. :type formats: list :return: Formats. :rtype: list
Below is the the instruction that describes the task: ### Input: Lists the object formats in sorted order. :param node: Root node to start listing the formats from. :type node: AbstractCompositeNode :param path: Walked paths. :type path: tuple :param formats: Formats. ...
def linkify_h_by_h(self): """Link hosts with their parents :return: None """ for host in self: # The new member list new_parents = [] for parent in getattr(host, 'parents', []): parent = parent.strip() o_parent = self.f...
Link hosts with their parents :return: None
Below is the the instruction that describes the task: ### Input: Link hosts with their parents :return: None ### Response: def linkify_h_by_h(self): """Link hosts with their parents :return: None """ for host in self: # The new member list new_paren...
def sortlevel(self, level=0, ascending=True, sort_remaining=True): """ Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters ---------- level : list-like, int or str, default 0 ...
Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters ---------- level : list-like, int or str, default 0 If a string is given, must be a name of the level If list-like must be nam...
Below is the the instruction that describes the task: ### Input: Sort MultiIndex at the requested level. The result will respect the original ordering of the associated factor at that level. Parameters ---------- level : list-like, int or str, default 0 If a string is gi...
def zlines(f = None, sep = "\0", osep = None, size = 8192): # {{{1 """File iterator that uses alternative line terminators.""" if f is None: f = sys.stdin if osep is None: osep = sep buf = "" while True: chars = f.read(size) if not chars: break buf += chars; lines = buf.split(sep); buf = lines...
File iterator that uses alternative line terminators.
Below is the the instruction that describes the task: ### Input: File iterator that uses alternative line terminators. ### Response: def zlines(f = None, sep = "\0", osep = None, size = 8192): # {{{1 """File iterator that uses alternative line terminators.""" if f is None: f = sys.stdin if osep is None: ...
def _format_data(self, name=None): """ Return the formatted data as a unicode string. """ # do we want to justify (only do so for non-objects) is_justify = not (self.inferred_type in ('string', 'unicode') or (self.inferred_type == 'categorical' and ...
Return the formatted data as a unicode string.
Below is the the instruction that describes the task: ### Input: Return the formatted data as a unicode string. ### Response: def _format_data(self, name=None): """ Return the formatted data as a unicode string. """ # do we want to justify (only do so for non-objects) is_ju...
def desc(self, table): '''Returns table description >>> yql.desc('geo.countries') >>> ''' query = "desc {0}".format(table) response = self.raw_query(query) return response
Returns table description >>> yql.desc('geo.countries') >>>
Below is the the instruction that describes the task: ### Input: Returns table description >>> yql.desc('geo.countries') >>> ### Response: def desc(self, table): '''Returns table description >>> yql.desc('geo.countries') >>> ''' query = "desc {0}".format(tabl...
def add_model_name_to_payload(cls, payload): """ Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the ...
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoi...
Below is the the instruction that describes the task: ### Input: Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include ...
def _parse_config(self, requires_cfg=True): """Parse the configuration file, if one is configured, and add it to the `Bison` state. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True) """ ...
Parse the configuration file, if one is configured, and add it to the `Bison` state. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True)
Below is the the instruction that describes the task: ### Input: Parse the configuration file, if one is configured, and add it to the `Bison` state. Args: requires_cfg (bool): Specify whether or not parsing should fail if a config file is not found. (default: True) ### ...
def cbox(i, gray=False, spectrum="alternate", reverse=False, **kwargs): """ Access a modular list of colors for plotting. Defines colours using rgb. :param i: (int), index to access color :param gray: (bool), if true then color is return as grayscale value :param spectrum: (str), choice of spec...
Access a modular list of colors for plotting. Defines colours using rgb. :param i: (int), index to access color :param gray: (bool), if true then color is return as grayscale value :param spectrum: (str), choice of spectrum to use :param reverse: (bool), reverses the color order :param kwargs: ...
Below is the the instruction that describes the task: ### Input: Access a modular list of colors for plotting. Defines colours using rgb. :param i: (int), index to access color :param gray: (bool), if true then color is return as grayscale value :param spectrum: (str), choice of spectrum to use ...
def get_github_cache(self, kind, key_): """ Get cache data for items of _type using key_ as the cache dict key """ cache = {} res_size = 100 # best size? from_ = 0 index_github = "github/" + kind url = self.elastic.url + "/" + index_github url += "/_search" + ...
Get cache data for items of _type using key_ as the cache dict key
Below is the the instruction that describes the task: ### Input: Get cache data for items of _type using key_ as the cache dict key ### Response: def get_github_cache(self, kind, key_): """ Get cache data for items of _type using key_ as the cache dict key """ cache = {} res_size = 100 # ...
def match_config(regex): ''' Display the current values of all configuration variables whose names match the given regular expression. .. versionadded:: 2016.11.0 .. code-block:: bash salt '*' trafficserver.match_config regex ''' if _TRAFFICCTL: cmd = _traffic_ctl('config'...
Display the current values of all configuration variables whose names match the given regular expression. .. versionadded:: 2016.11.0 .. code-block:: bash salt '*' trafficserver.match_config regex
Below is the the instruction that describes the task: ### Input: Display the current values of all configuration variables whose names match the given regular expression. .. versionadded:: 2016.11.0 .. code-block:: bash salt '*' trafficserver.match_config regex ### Response: def match_config...
def main(): """ NAME k15_magic.py DESCRIPTION converts .k15 format data to magic_measurements format. assums Jelinek Kappabridge measurement scheme SYNTAX k15_magic.py [-h] [command line options] OPTIONS -h prints help message and quits -DM DATA_MO...
NAME k15_magic.py DESCRIPTION converts .k15 format data to magic_measurements format. assums Jelinek Kappabridge measurement scheme SYNTAX k15_magic.py [-h] [command line options] OPTIONS -h prints help message and quits -DM DATA_MODEL: specify data model ...
Below is the the instruction that describes the task: ### Input: NAME k15_magic.py DESCRIPTION converts .k15 format data to magic_measurements format. assums Jelinek Kappabridge measurement scheme SYNTAX k15_magic.py [-h] [command line options] OPTIONS -h prin...
def send(r, stream=False): """Just sends the request using its send method and returns its response. """ r.send(stream=stream) return r.response
Just sends the request using its send method and returns its response.
Below is the the instruction that describes the task: ### Input: Just sends the request using its send method and returns its response. ### Response: def send(r, stream=False): """Just sends the request using its send method and returns its response. """ r.send(stream=stream) return r.response
def read(fname, fail_silently=False): """ Read the content of the given file. The path is evaluated from the directory containing this file. """ try: filepath = os.path.join(os.path.dirname(__file__), fname) with io.open(filepath, 'rt', encoding='utf8') as...
Read the content of the given file. The path is evaluated from the directory containing this file.
Below is the the instruction that describes the task: ### Input: Read the content of the given file. The path is evaluated from the directory containing this file. ### Response: def read(fname, fail_silently=False): """ Read the content of the given file. The path is evaluated from the ...
def get_text_style(text): """Return the text style dict for a text instance""" style = {} style['alpha'] = text.get_alpha() if style['alpha'] is None: style['alpha'] = 1 style['fontsize'] = text.get_size() style['color'] = color_to_hex(text.get_color()) style['halign'] = text.get_hor...
Return the text style dict for a text instance
Below is the the instruction that describes the task: ### Input: Return the text style dict for a text instance ### Response: def get_text_style(text): """Return the text style dict for a text instance""" style = {} style['alpha'] = text.get_alpha() if style['alpha'] is None: style['alpha']...
def register(self, plugin): """ Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins....
Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of samtranslator.plugins.BasePlugin or if it is already regis...
Below is the the instruction that describes the task: ### Input: Register a plugin. New plugins are added to the end of the plugins list. :param samtranslator.plugins.BasePlugin plugin: Instance/subclass of BasePlugin class that implements hooks :raises ValueError: If plugin is not an instance of s...
def scramble_itemdata(self, oid, value): """If metadata provided, use it to scramble the value based on data type""" if self.metadata is not None: path = ".//{0}[@{1}='{2}']".format(E_ODM.ITEM_DEF.value, A_ODM.OID.value, oid) elem = self.metadata.find(path) # for elem...
If metadata provided, use it to scramble the value based on data type
Below is the the instruction that describes the task: ### Input: If metadata provided, use it to scramble the value based on data type ### Response: def scramble_itemdata(self, oid, value): """If metadata provided, use it to scramble the value based on data type""" if self.metadata is not None: ...
def _indexes(self): """Instantiate the indexes only when asked Returns ------- list An empty list if the field is not indexable, else a list of all indexes tied to the field. If no indexes where passed when creating the field, the default indexes ...
Instantiate the indexes only when asked Returns ------- list An empty list if the field is not indexable, else a list of all indexes tied to the field. If no indexes where passed when creating the field, the default indexes from the field/model/da...
Below is the the instruction that describes the task: ### Input: Instantiate the indexes only when asked Returns ------- list An empty list if the field is not indexable, else a list of all indexes tied to the field. If no indexes where passed when creati...
def _ParseCommentRecord(self, structure): """Parse a comment and store appropriate attributes. Args: structure (pyparsing.ParseResults): parsed log line. """ comment = structure[1] if comment.startswith('Version'): _, _, self._version = comment.partition(':') elif comment.startswith...
Parse a comment and store appropriate attributes. Args: structure (pyparsing.ParseResults): parsed log line.
Below is the the instruction that describes the task: ### Input: Parse a comment and store appropriate attributes. Args: structure (pyparsing.ParseResults): parsed log line. ### Response: def _ParseCommentRecord(self, structure): """Parse a comment and store appropriate attributes. Args: ...
def get_comments(self): """ :calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment` """ return github.PaginatedList.PaginatedList( gi...
:calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment`
Below is the the instruction that describes the task: ### Input: :calls: `GET /repos/:owner/:repo/comments <http://developer.github.com/v3/repos/comments>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.CommitComment.CommitComment` ### Response: def get_comments(self): """ ...
def is_first_root(self): """Return ``True`` if this page is the first root pages.""" if self.parent: return False if self._is_first_root is not None: return self._is_first_root first_root_id = cache.get('PAGE_FIRST_ROOT_ID') if first_root_id is not None: ...
Return ``True`` if this page is the first root pages.
Below is the the instruction that describes the task: ### Input: Return ``True`` if this page is the first root pages. ### Response: def is_first_root(self): """Return ``True`` if this page is the first root pages.""" if self.parent: return False if self._is_first_root is not No...
def model_to_dict(model, exclude=None): """ Extract a SQLAlchemy model instance to a dictionary :param model: the model to be extracted :param exclude: Any keys to be excluded :return: New dictionary consisting of property-values """ exclude = exclude or [] exclude.append('_sa_instance_s...
Extract a SQLAlchemy model instance to a dictionary :param model: the model to be extracted :param exclude: Any keys to be excluded :return: New dictionary consisting of property-values
Below is the the instruction that describes the task: ### Input: Extract a SQLAlchemy model instance to a dictionary :param model: the model to be extracted :param exclude: Any keys to be excluded :return: New dictionary consisting of property-values ### Response: def model_to_dict(model, exclude=None)...
def save(self, models_dir, model_names_to_write=None, write_metadata=True): """ Serialize the predictor to a directory on disk. If the directory does not exist it will be created. The serialization format consists of a file called "manifest.csv" with the configurations o...
Serialize the predictor to a directory on disk. If the directory does not exist it will be created. The serialization format consists of a file called "manifest.csv" with the configurations of each Class1NeuralNetwork, along with per-network files giving the model weights. If th...
Below is the the instruction that describes the task: ### Input: Serialize the predictor to a directory on disk. If the directory does not exist it will be created. The serialization format consists of a file called "manifest.csv" with the configurations of each Class1NeuralNetwork,...
def str_get(x, i): """Extract a character from each sample at the specified position from a string column. Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan. :param int i: The index location, at which to extract the character. :re...
Extract a character from each sample at the specified position from a string column. Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan. :param int i: The index location, at which to extract the character. :returns: an expression conta...
Below is the the instruction that describes the task: ### Input: Extract a character from each sample at the specified position from a string column. Note that if the specified position is out of bound of the string sample, this method returns '', while pandas retunrs nan. :param int i: The index location,...
def MoveWindow(self, x: int, y: int, width: int, height: int, repaint: bool = True) -> bool: """ Call native MoveWindow if control has a valid native handle. x: int. y: int. width: int. height: int. repaint: bool. Return bool, True if succeed otherwise Fal...
Call native MoveWindow if control has a valid native handle. x: int. y: int. width: int. height: int. repaint: bool. Return bool, True if succeed otherwise False.
Below is the the instruction that describes the task: ### Input: Call native MoveWindow if control has a valid native handle. x: int. y: int. width: int. height: int. repaint: bool. Return bool, True if succeed otherwise False. ### Response: def MoveWindow(self, x: i...
def plots(data, **kwargs): """ simple wrapper plot with labels and skip x :param yonly_or_xy: :param kwargs: :return: """ labels = kwargs.pop('labels', '') loc = kwargs.pop('loc', 1) # if len(yonly_or_xy) == 1: # x = range(len(yonly_or_xy)) # y = yonly_or_xy # el...
simple wrapper plot with labels and skip x :param yonly_or_xy: :param kwargs: :return:
Below is the the instruction that describes the task: ### Input: simple wrapper plot with labels and skip x :param yonly_or_xy: :param kwargs: :return: ### Response: def plots(data, **kwargs): """ simple wrapper plot with labels and skip x :param yonly_or_xy: :param kwargs: :return:...
def encodeIntoArray(self, inputData, output): """ See `nupic.encoders.base.Encoder` for more information. :param: inputData (tuple) Contains speed (float), longitude (float), latitude (float), altitude (float) :param: output (numpy.array) Stores encoded SDR in this numpy ar...
See `nupic.encoders.base.Encoder` for more information. :param: inputData (tuple) Contains speed (float), longitude (float), latitude (float), altitude (float) :param: output (numpy.array) Stores encoded SDR in this numpy array
Below is the the instruction that describes the task: ### Input: See `nupic.encoders.base.Encoder` for more information. :param: inputData (tuple) Contains speed (float), longitude (float), latitude (float), altitude (float) :param: output (numpy.array) Stores encoded SDR in th...
def setPoint(self, i, p): """ Set specific `i-th` point coordinates in mesh. Actor transformation is reset to its original mesh position/orientation. :param int i: index of vertex point. :param list p: new coordinates of mesh point. .. warning:: if used in a loop this c...
Set specific `i-th` point coordinates in mesh. Actor transformation is reset to its original mesh position/orientation. :param int i: index of vertex point. :param list p: new coordinates of mesh point. .. warning:: if used in a loop this can slow down the execution by a lot. ...
Below is the the instruction that describes the task: ### Input: Set specific `i-th` point coordinates in mesh. Actor transformation is reset to its original mesh position/orientation. :param int i: index of vertex point. :param list p: new coordinates of mesh point. .. warning:: i...