code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def get_record(self, name, record_id): """Retrieve a record with a given type name and record id. Args: name (string): The name which the record is stored under. record_id (int): The id of the record requested. Returns: :class:`cinder_data.model.CinderModel`...
Retrieve a record with a given type name and record id. Args: name (string): The name which the record is stored under. record_id (int): The id of the record requested. Returns: :class:`cinder_data.model.CinderModel`: The cached model.
Below is the the instruction that describes the task: ### Input: Retrieve a record with a given type name and record id. Args: name (string): The name which the record is stored under. record_id (int): The id of the record requested. Returns: :class:`cinder_data...
def fit_model(ts, sc=None): """ Fits a GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a GARCH model as a Numpy array Returns a GARCH model """ assert sc != None, "Missing SparkContext" jvm = sc....
Fits a GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a GARCH model as a Numpy array Returns a GARCH model
Below is the the instruction that describes the task: ### Input: Fits a GARCH(1, 1) model to the given time series. Parameters ---------- ts: the time series to which we want to fit a GARCH model as a Numpy array Returns a GARCH model ### Response: def fit_model(ts, sc=None): ...
def set_version(self): """ compute and set our version """ version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: self.version = tuple(int(x) for x in version.split('.')) if len(self.version) == 2: self.version = ...
compute and set our version
Below is the the instruction that describes the task: ### Input: compute and set our version ### Response: def set_version(self): """ compute and set our version """ version = _ensure_decoded( getattr(self.group._v_attrs, 'pandas_version', None)) try: self.version = ...
def parse_multiple(s, f, values=None): """Parse multiple comma-separated elements, each of which is parsed using function f.""" if values is None: values = [] values.append(f(s)) if s.pos < len(s) and s.cur == ',': s.pos += 1 return parse_multiple(s, f, values) else: r...
Parse multiple comma-separated elements, each of which is parsed using function f.
Below is the the instruction that describes the task: ### Input: Parse multiple comma-separated elements, each of which is parsed using function f. ### Response: def parse_multiple(s, f, values=None): """Parse multiple comma-separated elements, each of which is parsed using function f.""" if ...
def publish(self): ''' Perform HTTP session to transmit defined weather values. ''' return self._publish( self.args, self.server, self.URI)
Perform HTTP session to transmit defined weather values.
Below is the the instruction that describes the task: ### Input: Perform HTTP session to transmit defined weather values. ### Response: def publish(self): ''' Perform HTTP session to transmit defined weather values. ''' return self._publish( self.args, self.server, self.URI)
def decipher(self,string,keep_punct=False): """Decipher string using Railfence cipher according to initialised key. Example:: plaintext = Railfence(3).decipher(ciphertext) :param string: The string to decipher. :param keep_punct: if true, punctuation and spaci...
Decipher string using Railfence cipher according to initialised key. Example:: plaintext = Railfence(3).decipher(ciphertext) :param string: The string to decipher. :param keep_punct: if true, punctuation and spacing are retained. If false, it is all removed. Default i...
Below is the the instruction that describes the task: ### Input: Decipher string using Railfence cipher according to initialised key. Example:: plaintext = Railfence(3).decipher(ciphertext) :param string: The string to decipher. :param keep_punct: if true, punctua...
def value(self, index, extra): """Returns ('Simple', #codewords) or ('Complex', HSKIP) """ if index==1: if extra>3: raise ValueError('value: extra out of range') return 'Simple', extra+1 if extra: raise ValueError('value: extra out of r...
Returns ('Simple', #codewords) or ('Complex', HSKIP)
Below is the the instruction that describes the task: ### Input: Returns ('Simple', #codewords) or ('Complex', HSKIP) ### Response: def value(self, index, extra): """Returns ('Simple', #codewords) or ('Complex', HSKIP) """ if index==1: if extra>3: raise ValueErro...
def get_schema(repo, content_type): """ Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict """ try: with open( os.path.join(repo.working_dir, '_schemas', ...
Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict
Below is the the instruction that describes the task: ### Input: Return a schema for a content type in a repository. :param Repo repo: The git repository. :returns: dict ### Response: def get_schema(repo, content_type): """ Return a schema for a content type in a repository. :param Re...
def diff(self, source_path='', target_path='', which=-1): """Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_pa...
Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_path: (Default value = '') :param target_path: (Default value...
Below is the the instruction that describes the task: ### Input: Build the diff between original docstring and proposed docstring. :type which: int -> -1 means all the dosctrings of the file -> >=0 means the index of the docstring to proceed (Default value = -1) :param source_pa...
def compute_metric(self, components): """Compute recall from `components`""" numerator = components[RECALL_RELEVANT_RETRIEVED] denominator = components[RECALL_RELEVANT] if denominator == 0.: if numerator == 0: return 1. else: raise ...
Compute recall from `components`
Below is the the instruction that describes the task: ### Input: Compute recall from `components` ### Response: def compute_metric(self, components): """Compute recall from `components`""" numerator = components[RECALL_RELEVANT_RETRIEVED] denominator = components[RECALL_RELEVANT] if...
def update_notification_list(self, apps=None, schema_editor=None, verbose=False): """Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notificatio...
Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notification class (not model) will automatically call this method if the named notifica...
Below is the the instruction that describes the task: ### Input: Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notification class (not mod...
def or_(cls, *queries): """ 根据传入的 Query 对象,构造一个新的 OR 查询。 :param queries: 需要构造的子查询列表 :rtype: Query """ if len(queries) < 2: raise ValueError('or_ need two queries at least') if not all(x._query_class._class_name == queries[0]._query_class._class_name f...
根据传入的 Query 对象,构造一个新的 OR 查询。 :param queries: 需要构造的子查询列表 :rtype: Query
Below is the the instruction that describes the task: ### Input: 根据传入的 Query 对象,构造一个新的 OR 查询。 :param queries: 需要构造的子查询列表 :rtype: Query ### Response: def or_(cls, *queries): """ 根据传入的 Query 对象,构造一个新的 OR 查询。 :param queries: 需要构造的子查询列表 :rtype: Query """ ...
def critical_section_lock(lock=None, blocking=True, timeout=None, raise_exception=True): """ An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object instead of a function that returns a lock with which a function protection will be made :param lock: lock with which a fun...
An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object instead of a function that returns a lock with which a function protection will be made :param lock: lock with which a function will be protected :param blocking: same as blocking in :func:`.critical_section_dynamic...
Below is the the instruction that describes the task: ### Input: An a wrapper for :func:`.critical_section_dynamic_lock` function call, but uses a static lock object instead of a function that returns a lock with which a function protection will be made :param lock: lock with which a function will be protected ...
def command(self, vehicle_id, name, data=None, wake_if_asleep=True): """Post name command to the vehicle_id. Parameters ---------- vehicle_id : string Identifier for the car on the owner-api endpoint. Confusingly it is not the vehicle_id field for identifying the...
Post name command to the vehicle_id. Parameters ---------- vehicle_id : string Identifier for the car on the owner-api endpoint. Confusingly it is not the vehicle_id field for identifying the car across different endpoints. https://tesla-api.timdo...
Below is the the instruction that describes the task: ### Input: Post name command to the vehicle_id. Parameters ---------- vehicle_id : string Identifier for the car on the owner-api endpoint. Confusingly it is not the vehicle_id field for identifying the car across...
def zip_clean_metaxml(zip_src, logger=None): """ Given a zipfile, cleans all *-meta.xml files in the zip for deployment by stripping all <packageVersions/> elements """ zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZIP_DEFLATED) changed = [] for name in zip_src.namelist(): co...
Given a zipfile, cleans all *-meta.xml files in the zip for deployment by stripping all <packageVersions/> elements
Below is the the instruction that describes the task: ### Input: Given a zipfile, cleans all *-meta.xml files in the zip for deployment by stripping all <packageVersions/> elements ### Response: def zip_clean_metaxml(zip_src, logger=None): """ Given a zipfile, cleans all *-meta.xml files in the zip for...
def visit_Method(self, method): """ Ensure method has the same signature matching method on parent interface. :param method: L{quarkc.ast.Method} instance. """ resolved_method = method.resolved.type def get_params(method, extra_bindings): # The Method should...
Ensure method has the same signature matching method on parent interface. :param method: L{quarkc.ast.Method} instance.
Below is the the instruction that describes the task: ### Input: Ensure method has the same signature matching method on parent interface. :param method: L{quarkc.ast.Method} instance. ### Response: def visit_Method(self, method): """ Ensure method has the same signature matching method on...
def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original code for this was the following. We've left it # visible for now in case the new implementation shows any problems down # th...
Import and return bar given the string foo.bar.
Below is the the instruction that describes the task: ### Input: Import and return bar given the string foo.bar. ### Response: def import_item(name): """Import and return bar given the string foo.bar.""" package = '.'.join(name.split('.')[0:-1]) obj = name.split('.')[-1] # Note: the original c...
def registerTrailingStop(self, tickerId, orderId=0, quantity=1, lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs): """ adds trailing stop to monitor list """ ticksize = self.contractDetails(tickerId)["m_minTick"] trailingStop = self.trailingStops[tickerId] = { ...
adds trailing stop to monitor list
Below is the the instruction that describes the task: ### Input: adds trailing stop to monitor list ### Response: def registerTrailingStop(self, tickerId, orderId=0, quantity=1, lastPrice=0, trailPercent=100., trailAmount=0., parentId=0, **kwargs): """ adds trailing stop to monitor list """ ...
def indexOf(self, url): """ Returns the index of the inputed url for this stack. If the url is \ not found, then -1 is returned. :param url | <str> :return <int> """ for i, (m_url, _) in enumerate(self._stack): if m_url ==...
Returns the index of the inputed url for this stack. If the url is \ not found, then -1 is returned. :param url | <str> :return <int>
Below is the the instruction that describes the task: ### Input: Returns the index of the inputed url for this stack. If the url is \ not found, then -1 is returned. :param url | <str> :return <int> ### Response: def indexOf(self, url): """ Return...
def _consolidate(self, inplace=False): """ Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing ob...
Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify existing object Returns ------- consolidated ...
Below is the the instruction that describes the task: ### Input: Compute NDFrame with "consolidated" internals (data of each dtype grouped together in a single ndarray). Parameters ---------- inplace : boolean, default False If False return new object, otherwise modify e...
def provision_vdp_overlay_networks(self, port_uuid, mac, net_uuid, segmentation_id, lvid, oui): """Provisions a overlay type network configured using VDP. :param port_uuid: the uuid of the VM port. :param mac: the MAC address of the VM. :param net_...
Provisions a overlay type network configured using VDP. :param port_uuid: the uuid of the VM port. :param mac: the MAC address of the VM. :param net_uuid: the uuid of the network associated with this vlan. :param segmentation_id: the VID for 'vlan' or tunnel ID for 'tunnel' :lvi...
Below is the the instruction that describes the task: ### Input: Provisions a overlay type network configured using VDP. :param port_uuid: the uuid of the VM port. :param mac: the MAC address of the VM. :param net_uuid: the uuid of the network associated with this vlan. :param segme...
def _pos(self, k): """ Description: Position k breaking Parameters: k: position k is used for the breaking """ if k < 2: raise ValueError("k smaller than 2") G = np.zeros((self.m, self.m)) for i in range(self.m): ...
Description: Position k breaking Parameters: k: position k is used for the breaking
Below is the the instruction that describes the task: ### Input: Description: Position k breaking Parameters: k: position k is used for the breaking ### Response: def _pos(self, k): """ Description: Position k breaking Parameters: ...
def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={}, style={}, options={}, **kwargs): """ Get Chartjs html """ try: xdata = list(self.df[xcol]) except Exception as e: self.err(e, self._get_chartjs_chart, ...
Get Chartjs html
Below is the the instruction that describes the task: ### Input: Get Chartjs html ### Response: def _get_chartjs_chart(self, xcol, ycol, chart_type, label=None, opts={}, style={}, options={}, **kwargs): """ Get Chartjs html """ try: xdata = lis...
def _enable_profiling(): """ Start profiling and register callback to print stats when the program exits. """ import cProfile import atexit global _profiler _profiler = cProfile.Profile() _profiler.enable() atexit.register(_profile_atexit)
Start profiling and register callback to print stats when the program exits.
Below is the the instruction that describes the task: ### Input: Start profiling and register callback to print stats when the program exits. ### Response: def _enable_profiling(): """ Start profiling and register callback to print stats when the program exits. """ import cProfile import at...
def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]): """ Attach list of media :param medias: """ for media in medias: self.attach(media)
Attach list of media :param medias:
Below is the the instruction that describes the task: ### Input: Attach list of media :param medias: ### Response: def attach_many(self, *medias: typing.Union[InputMedia, typing.Dict]): """ Attach list of media :param medias: """ for media in medias: se...
def conf_sets(self): '''The dictionary of configuration sets in this component, if any.''' with self._mutex: if not self._conf_sets: self._parse_configuration() return self._conf_sets
The dictionary of configuration sets in this component, if any.
Below is the the instruction that describes the task: ### Input: The dictionary of configuration sets in this component, if any. ### Response: def conf_sets(self): '''The dictionary of configuration sets in this component, if any.''' with self._mutex: if not self._conf_sets: ...
def convert_to_vertexlist(geometry, **kwargs): """ Try to convert various geometry objects to the constructor args for a pyglet indexed vertex list. Parameters ------------ obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float Object to render Returns ------------ args : tu...
Try to convert various geometry objects to the constructor args for a pyglet indexed vertex list. Parameters ------------ obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float Object to render Returns ------------ args : tuple Args to be passed to pyglet indexed vertex list ...
Below is the the instruction that describes the task: ### Input: Try to convert various geometry objects to the constructor args for a pyglet indexed vertex list. Parameters ------------ obj : Trimesh, Path2D, Path3D, (n,2) float, (n,3) float Object to render Returns ------------ ...
def add_condition(self, manager, condition_set, field_name, condition, exclude=False, commit=True): """ Adds a new condition and registers it in the global ``gargoyle`` switch manager. If ``commit`` is ``False``, the data will not be written to the database. >>> switch = gargoyle['my_s...
Adds a new condition and registers it in the global ``gargoyle`` switch manager. If ``commit`` is ``False``, the data will not be written to the database. >>> switch = gargoyle['my_switch'] #doctest: +SKIP >>> condition_set_id = condition_set.get_id() #doctest: +SKIP >>> switch.add_con...
Below is the the instruction that describes the task: ### Input: Adds a new condition and registers it in the global ``gargoyle`` switch manager. If ``commit`` is ``False``, the data will not be written to the database. >>> switch = gargoyle['my_switch'] #doctest: +SKIP >>> condition_set_i...
def read(cls, iprot): ''' Read a new object from the given input protocol and return the object. :type iprot: thryft.protocol._input_protocol._InputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage ''' i...
Read a new object from the given input protocol and return the object. :type iprot: thryft.protocol._input_protocol._InputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailImage
Below is the the instruction that describes the task: ### Input: Read a new object from the given input protocol and return the object. :type iprot: thryft.protocol._input_protocol._InputProtocol :rtype: pastpy.gen.database.impl.online.online_database_object_detail_image.OnlineDatabaseObjectDetailI...
def export_data(self, phases=[], filename=None, filetype='vtp'): r""" Export the pore and throat data from the given object(s) into the specified file and format. Parameters ---------- phases : list of OpenPNM Phase Objects The data on each supplied phase wil...
r""" Export the pore and throat data from the given object(s) into the specified file and format. Parameters ---------- phases : list of OpenPNM Phase Objects The data on each supplied phase will be added to file filename : string The file name t...
Below is the the instruction that describes the task: ### Input: r""" Export the pore and throat data from the given object(s) into the specified file and format. Parameters ---------- phases : list of OpenPNM Phase Objects The data on each supplied phase will be...
def on_raw_update( self=None, group: int = 0 ) -> callable: """Use this decorator to automatically register a function for handling raw updates. This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`. Args: group (``int``, *optional*)...
Use this decorator to automatically register a function for handling raw updates. This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`. Args: group (``int``, *optional*): The group identifier, defaults to 0.
Below is the the instruction that describes the task: ### Input: Use this decorator to automatically register a function for handling raw updates. This does the same thing as :meth:`add_handler` using the :class:`RawUpdateHandler`. Args: group (``int``, *optional*): The ...
def set(self, value, mode=None): """Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is...
Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is less that the current one. :rtype:...
Below is the the instruction that describes the task: ### Input: Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - S...
def deploy(self, args, **extra_args): """Deploy a docker container to a specific container ship (host) :param args: :type args: """ if not isinstance(args, argparse.Namespace): raise TypeError(logger.error("args should of an instance of argparse.Namespace")) ...
Deploy a docker container to a specific container ship (host) :param args: :type args:
Below is the the instruction that describes the task: ### Input: Deploy a docker container to a specific container ship (host) :param args: :type args: ### Response: def deploy(self, args, **extra_args): """Deploy a docker container to a specific container ship (host) :param args:...
def _parse(self, text, i): """Recursive function to parse a single dictionary, list, or value.""" m = self.start_dict_re.match(text, i) if m: parsed = m.group(0) i += len(parsed) return self._parse_dict(text, i) m = self.start_list_re.match(text, i) ...
Recursive function to parse a single dictionary, list, or value.
Below is the the instruction that describes the task: ### Input: Recursive function to parse a single dictionary, list, or value. ### Response: def _parse(self, text, i): """Recursive function to parse a single dictionary, list, or value.""" m = self.start_dict_re.match(text, i) if m: ...
def _createSegment(cls, connections, lastUsedIterationForSegment, cell, iteration, maxSegmentsPerCell): """ Create a segment on the connections, enforcing the maxSegmentsPerCell parameter. """ # Enforce maxSegmentsPerCell. while connections.numSegments(cell) >= maxSegmentsPe...
Create a segment on the connections, enforcing the maxSegmentsPerCell parameter.
Below is the the instruction that describes the task: ### Input: Create a segment on the connections, enforcing the maxSegmentsPerCell parameter. ### Response: def _createSegment(cls, connections, lastUsedIterationForSegment, cell, iteration, maxSegmentsPerCell): """ Create a segme...
def launch_app(app_path, params=[], time_before_kill_app=15): """ start an app """ import subprocess try: res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True) print('res = ', res) if res == 0: return True else: re...
start an app
Below is the the instruction that describes the task: ### Input: start an app ### Response: def launch_app(app_path, params=[], time_before_kill_app=15): """ start an app """ import subprocess try: res = subprocess.call([app_path, params], timeout=time_before_kill_app, shell=True) ...
def verify(self, subject, signature=None): """ Verify a subject with a signature using this key. :param subject: The subject to verify :type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID` :param signature: If the signature is de...
Verify a subject with a signature using this key. :param subject: The subject to verify :type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID` :param signature: If the signature is detached, it should be specified here. :type signature: :...
Below is the the instruction that describes the task: ### Input: Verify a subject with a signature using this key. :param subject: The subject to verify :type subject: ``str``, ``unicode``, ``None``, :py:obj:`PGPMessage`, :py:obj:`PGPKey`, :py:obj:`PGPUID` :param signature: If the signature...
def moves_from_games(self, start_game, end_game, moves, shuffle, column_family, column): """Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how man...
Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games. column_family: name of the column family containing move...
Below is the the instruction that describes the task: ### Input: Dataset of samples and/or shuffled moves from game range. Args: n: an integer indicating how many past games should be sourced. moves: an integer indicating how many moves should be sampled from those N games...
def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. """ # create a steppable iterator, so we can handle \-continuations lines = iter(yield_lines(strs)) def scan_list(ITEM, TERMINATOR, ...
Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof.
Below is the the instruction that describes the task: ### Input: Yield ``Requirement`` objects for each specification in `strs` `strs` must be a string, or a (possibly-nested) iterable thereof. ### Response: def parse_requirements(strs): """Yield ``Requirement`` objects for each specification in `strs` ...
def residual_histogram(df, col_true, col_pred=None): """ Compute histogram of residuals of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: s...
Compute histogram of residuals of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_true: str :param col_true: column name of predicted value, 'predicti...
Below is the the instruction that describes the task: ### Input: Compute histogram of residuals of a predicted DataFrame. Note that this method will trigger the defined flow to execute. :param df: predicted data frame :type df: DataFrame :param col_true: column name of true value :type col_tru...
def rrmdir(directory): """ Recursivly delete a directory :param directory: directory to remove """ for root, dirs, files in os.walk(directory, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root,...
Recursivly delete a directory :param directory: directory to remove
Below is the the instruction that describes the task: ### Input: Recursivly delete a directory :param directory: directory to remove ### Response: def rrmdir(directory): """ Recursivly delete a directory :param directory: directory to remove """ for root, dirs, files in os.walk(directory,...
def create_attach_volumes(name, kwargs, call=None): ''' .. versionadded:: 2017.7.0 Create and attach multiple volumes to a node. The 'volumes' and 'node' arguments are required, where 'node' is a libcloud node, and 'volumes' is a list of maps, where each map contains: size The size of ...
.. versionadded:: 2017.7.0 Create and attach multiple volumes to a node. The 'volumes' and 'node' arguments are required, where 'node' is a libcloud node, and 'volumes' is a list of maps, where each map contains: size The size of the new disk in GB. Required. type The disk type, e...
Below is the the instruction that describes the task: ### Input: .. versionadded:: 2017.7.0 Create and attach multiple volumes to a node. The 'volumes' and 'node' arguments are required, where 'node' is a libcloud node, and 'volumes' is a list of maps, where each map contains: size The siz...
def _get_class_repo(self, namespace): """ Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock reposi...
Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the mock repository. If the class repository does not contain th...
Below is the the instruction that describes the task: ### Input: Returns the class repository for the specified CIM namespace within the mock repository. This is the original instance variable, so any modifications will change the mock repository. Validates that the namespace exists in the ...
def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists: if row[-1] == '\n': print(row, end=' ') else: print(row) return None
Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None
Below is the the instruction that describes the task: ### Input: Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None ### Response: def pl (listoflists): """ Prints a list of lists, 1 list (row) at a time. Usage: pl(listoflists) Returns: None """ for row in listoflists...
def load_from_json(data): """ Load a :class:`Item` from a dictionary ot string (that will be parsed as json) """ if isinstance(data, str): data = json.loads(data) return Item(data['title'], data['uri'])
Load a :class:`Item` from a dictionary ot string (that will be parsed as json)
Below is the the instruction that describes the task: ### Input: Load a :class:`Item` from a dictionary ot string (that will be parsed as json) ### Response: def load_from_json(data): """ Load a :class:`Item` from a dictionary ot string (that will be parsed as json) """ ...
def make_fuzzy(word, max=1): """Naive neighborhoods algo.""" # inversions neighbors = [] for i in range(0, len(word) - 1): neighbor = list(word) neighbor[i], neighbor[i+1] = neighbor[i+1], neighbor[i] neighbors.append(''.join(neighbor)) # substitutions for letter in strin...
Naive neighborhoods algo.
Below is the the instruction that describes the task: ### Input: Naive neighborhoods algo. ### Response: def make_fuzzy(word, max=1): """Naive neighborhoods algo.""" # inversions neighbors = [] for i in range(0, len(word) - 1): neighbor = list(word) neighbor[i], neighbor[i+1] = neig...
def ParseFileObject(self, parser_mediator, file_object): """Parses a Windows Recycler INFO2 file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. R...
Parses a Windows Recycler INFO2 file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
Below is the the instruction that describes the task: ### Input: Parses a Windows Recycler INFO2 file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. ...
def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ftp.iana.org/tz. """ tmpdir = tempfile.mkdtemp() zonedir = os.path.join(tmpdir, "zoneinfo") moduledir = os....
Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ftp.iana.org/tz.
Below is the the instruction that describes the task: ### Input: Rebuild the internal timezone info in dateutil/zoneinfo/zoneinfo*tar* filename is the timezone tarball from ftp.iana.org/tz. ### Response: def rebuild(filename, tag=None, format="gz", zonegroups=[], metadata=None): """Rebuild the internal ti...
def ajRadical(self, i, r=None): """ Ajoute le radical r de numéro i à la map des radicaux du lemme. :param i: Index de radical :type i: int :param r: Radical à ajouter :type r: Radical """ if r: self._radicaux[i].append(r)
Ajoute le radical r de numéro i à la map des radicaux du lemme. :param i: Index de radical :type i: int :param r: Radical à ajouter :type r: Radical
Below is the the instruction that describes the task: ### Input: Ajoute le radical r de numéro i à la map des radicaux du lemme. :param i: Index de radical :type i: int :param r: Radical à ajouter :type r: Radical ### Response: def ajRadical(self, i, r=None): """ Ajoute le ...
def new(self, repo_type, name=None, make_default=False, repository_class=None, aggregate_class=None, configuration=None): """ Creates a new repository of the given type. If the root repository domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`) ...
Creates a new repository of the given type. If the root repository domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`) is passed as a repository name, the type string is used as the name; if no name is passed, a unique name is created automatically.
Below is the the instruction that describes the task: ### Input: Creates a new repository of the given type. If the root repository domain (see :class:`everest.repositories.constants.REPOSITORY_DOMAINS`) is passed as a repository name, the type string is used as the name; if no name is passe...
def CheckPermissions(self, username, subject): """Checks if a given user has access to a given subject.""" if subject in self.authorized_users: return ((username in self.authorized_users[subject]) or self.group_access_manager.MemberOfAuthorizedGroup( username, subject)) ...
Checks if a given user has access to a given subject.
Below is the the instruction that describes the task: ### Input: Checks if a given user has access to a given subject. ### Response: def CheckPermissions(self, username, subject): """Checks if a given user has access to a given subject.""" if subject in self.authorized_users: return ((username in se...
def fullmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.""" # Build a version of the pattern with a non-capturing group around it. # This is needed to get m.end() to correctly rep...
Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found.
Below is the the instruction that describes the task: ### Input: Try to apply the pattern at the start of the string, returning a match object if the whole string matches, or None if no match was found. ### Response: def fullmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the s...
def get_cube(self, cube, init=True, name=None, copy_config=True, **kwargs): '''wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of...
wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of the cube :param copy_config: apply config of calling cube to new? ...
Below is the the instruction that describes the task: ### Input: wrapper for :func:`metrique.utils.get_cube` Locates and loads a metrique cube :param cube: name of cube to load :param init: (bool) initialize cube before returning? :param name: override the name of the cube ...
def remove_rules_with_epsilon(grammar, inplace=False): # type: (Grammar, bool) -> Grammar """ Remove epsilon rules. :param grammar: Grammar where rules remove :param inplace: True if transformation should be performed in place, false otherwise. False by default. :return: Grammar without epsi...
Remove epsilon rules. :param grammar: Grammar where rules remove :param inplace: True if transformation should be performed in place, false otherwise. False by default. :return: Grammar without epsilon rules.
Below is the the instruction that describes the task: ### Input: Remove epsilon rules. :param grammar: Grammar where rules remove :param inplace: True if transformation should be performed in place, false otherwise. False by default. :return: Grammar without epsilon rules. ### Response: def remove_...
def ge(self, event_property, value): """A greater-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.ge('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).ge(elapsed_ms, 500) """ c = self...
A greater-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.ge('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).ge(elapsed_ms, 500)
Below is the the instruction that describes the task: ### Input: A greater-than-or-equal-to filter chain. >>> request_time = EventExpression('request', 'elapsed_ms') >>> filtered = request_time.ge('elapsed_ms', 500) >>> print(filtered) request(elapsed_ms).ge(elapsed_ms, 500) ### Res...
def _change_splitlevel(self, ttype, value): """Get the new split level (increase, decrease or remain equal)""" # parenthesis increase/decrease a level if ttype is T.Punctuation and value == '(': return 1 elif ttype is T.Punctuation and value == ')': return -1 ...
Get the new split level (increase, decrease or remain equal)
Below is the the instruction that describes the task: ### Input: Get the new split level (increase, decrease or remain equal) ### Response: def _change_splitlevel(self, ttype, value): """Get the new split level (increase, decrease or remain equal)""" # parenthesis increase/decrease a level ...
def to_phalf_from_pfull(arr, val_toa=0, val_sfc=0): """Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere. """ pha...
Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere.
Below is the the instruction that describes the task: ### Input: Compute data at half pressure levels from values at full levels. Could be the pressure array itself, but it could also be any other data defined at pressure levels. Requires specification of values at surface and top of atmosphere. ### R...
def killCells(self, percent = 0.05): """ Changes the percentage of cells that are now considered dead. The first time you call this method a permutation list is set up. Calls change the number of cells considered dead. """ if self.zombiePermutation is None: self.zombiePermutation = numpy....
Changes the percentage of cells that are now considered dead. The first time you call this method a permutation list is set up. Calls change the number of cells considered dead.
Below is the the instruction that describes the task: ### Input: Changes the percentage of cells that are now considered dead. The first time you call this method a permutation list is set up. Calls change the number of cells considered dead. ### Response: def killCells(self, percent = 0.05): """ C...
def locate(self, requirement, prereleases=False): """ Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``Tr...
Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``True``, allow pre-release versions to be loc...
Below is the the instruction that describes the task: ### Input: Find the most recent distribution which matches the given requirement. :param requirement: A requirement of the form 'foo (1.0)' or perhaps 'foo (>= 1.0, < 2.0, != 1.3)' :param prereleases: If ``Tru...
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: * Layer 0: a - a - sepm (self-a...
Below is the the instruction that describes the task: ### Input: Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a...
def _serve_file(self, path): """Call Paste's FileApp (a WSGI application) to serve the file at the specified path """ request = self._py_object.request request.environ['PATH_INFO'] = '/%s' % path return PkgResourcesParser('pylons', 'pylons')(request.environ, self.start_re...
Call Paste's FileApp (a WSGI application) to serve the file at the specified path
Below is the the instruction that describes the task: ### Input: Call Paste's FileApp (a WSGI application) to serve the file at the specified path ### Response: def _serve_file(self, path): """Call Paste's FileApp (a WSGI application) to serve the file at the specified path """ ...
def insert(self): """Insert this document""" from mongoframes.queries import to_refs # Send insert signal signal('insert').send(self.__class__, frames=[self]) # Prepare the document to be inserted document = to_refs(self._document) # Insert the document and upd...
Insert this document
Below is the the instruction that describes the task: ### Input: Insert this document ### Response: def insert(self): """Insert this document""" from mongoframes.queries import to_refs # Send insert signal signal('insert').send(self.__class__, frames=[self]) # Prepare the ...
def _data_format_resolver(data_format, resolver_dict): """Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. ...
Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. resolver_dict (dict): the resolving dict. Can hold any value ...
Below is the the instruction that describes the task: ### Input: Resolve a value from :attr:`resolver_dict` based on the :attr:`data_format`. Args: data_format (:class:`~.DataFormat` or str): The data format; must be a member of :class:`~.DataFormat` or a string equivalent. ...
def on_service_add(self, service): """ When a new service is added, a worker thread is launched to periodically run the checks for that service. """ self.launch_thread(service.name, self.check_loop, service)
When a new service is added, a worker thread is launched to periodically run the checks for that service.
Below is the the instruction that describes the task: ### Input: When a new service is added, a worker thread is launched to periodically run the checks for that service. ### Response: def on_service_add(self, service): """ When a new service is added, a worker thread is launched to ...
def _disable_encryption(self): # () -> None """Enable encryption methods for ciphers that support them.""" self.encrypt = self._disabled_encrypt self.decrypt = self._disabled_decrypt
Enable encryption methods for ciphers that support them.
Below is the the instruction that describes the task: ### Input: Enable encryption methods for ciphers that support them. ### Response: def _disable_encryption(self): # () -> None """Enable encryption methods for ciphers that support them.""" self.encrypt = self._disabled_encrypt se...
def roundrobin(*iterables): """roundrobin('ABC', 'D', 'EF') --> A D E B F C""" raise NotImplementedError('not sure if this implementation is correct') # http://stackoverflow.com/questions/11125212/interleaving-lists-in-python #sentinel = object() #return (x for x in chain(*zip_longest(fillvalue=sent...
roundrobin('ABC', 'D', 'EF') --> A D E B F C
Below is the the instruction that describes the task: ### Input: roundrobin('ABC', 'D', 'EF') --> A D E B F C ### Response: def roundrobin(*iterables): """roundrobin('ABC', 'D', 'EF') --> A D E B F C""" raise NotImplementedError('not sure if this implementation is correct') # http://stackoverflow.com/q...
def query(cls, offset=None, limit=None, api=None): """ Query (List) divisions. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: Collection object. """ api = api if api else cls._API return super(...
Query (List) divisions. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: Collection object.
Below is the the instruction that describes the task: ### Input: Query (List) divisions. :param offset: Pagination offset. :param limit: Pagination limit. :param api: Api instance. :return: Collection object. ### Response: def query(cls, offset=None, limit=None, api=None): ...
def _legacy_upload_archive(self, data_collected, duration): ''' Do an HTTPS upload of the archive ''' file_name = os.path.basename(data_collected) try: from insights.contrib import magic m = magic.open(magic.MAGIC_MIME) m.load() mim...
Do an HTTPS upload of the archive
Below is the the instruction that describes the task: ### Input: Do an HTTPS upload of the archive ### Response: def _legacy_upload_archive(self, data_collected, duration): ''' Do an HTTPS upload of the archive ''' file_name = os.path.basename(data_collected) try: ...
def beacon(config): ''' Read the last btmp file and return information on the failed logins ''' ret = [] users = {} groups = {} defaults = None for config_item in config: if 'users' in config_item: users = config_item['users'] if 'groups' in config_item: ...
Read the last btmp file and return information on the failed logins
Below is the the instruction that describes the task: ### Input: Read the last btmp file and return information on the failed logins ### Response: def beacon(config): ''' Read the last btmp file and return information on the failed logins ''' ret = [] users = {} groups = {} defaults = ...
def insertPDF(self, docsrc, from_page=-1, to_page=-1, start_at=-1, rotate=-1, links=1): """Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'.""" if self.isClosed or self.isEncrypted: raise ValueError("operation illegal for closed / encrypted doc") if id...
Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'.
Below is the the instruction that describes the task: ### Input: Copy page range ['from', 'to'] of source PDF, starting as page number 'start_at'. ### Response: def insertPDF(self, docsrc, from_page=-1, to_page=-1, start_at=-1, rotate=-1, links=1): """Copy page range ['from', 'to'] of source PDF, starting ...
def run(self): """Main thread for processing messages.""" self.OnStartup() try: while True: message = self._in_queue.get() # A message of None is our terminal message. if message is None: break try: self.HandleMessage(message) # Catch a...
Main thread for processing messages.
Below is the the instruction that describes the task: ### Input: Main thread for processing messages. ### Response: def run(self): """Main thread for processing messages.""" self.OnStartup() try: while True: message = self._in_queue.get() # A message of None is our terminal mes...
def _local_install(self, args, pkg_name=None): ''' Install a package from a file ''' if len(args) < 2: raise SPMInvocationError('A package file must be specified') self._install(args)
Install a package from a file
Below is the the instruction that describes the task: ### Input: Install a package from a file ### Response: def _local_install(self, args, pkg_name=None): ''' Install a package from a file ''' if len(args) < 2: raise SPMInvocationError('A package file must be specified'...
def rdfs_classes(rdf): """Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.""" # find out the subclass mappings upperclasses = {} # key: class val: set([superclass1, superclass2..]) for s, o in rdf.subject_objects(RDFS.subClassOf): upperclasses...
Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.
Below is the the instruction that describes the task: ### Input: Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class. ### Response: def rdfs_classes(rdf): """Perform RDFS subclass inference. Mark all resources with a subclass type with the upper class.""" ...
def get_extr_license_ident(self, extr_lic): """ Return an a license identifier from an ExtractedLicense or None. """ identifier_tripples = list(self.graph.triples((extr_lic, self.spdx_namespace['licenseId'], None))) if not identifier_tripples: self.error = True ...
Return an a license identifier from an ExtractedLicense or None.
Below is the the instruction that describes the task: ### Input: Return an a license identifier from an ExtractedLicense or None. ### Response: def get_extr_license_ident(self, extr_lic): """ Return an a license identifier from an ExtractedLicense or None. """ identifier_tripples = ...
def get_uri(self, key, is_list=False, is_optional=False, is_secret=False, is_local=False, default=None, options=None): """ Get a the value corresponding to the key and converts it to `UriSpec`...
Get a the value corresponding to the key and converts it to `UriSpec`. Args key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. is_secret: If the key is a secret. is_local: If ...
Below is the the instruction that describes the task: ### Input: Get a the value corresponding to the key and converts it to `UriSpec`. Args key: the dict key. is_list: If this is one element or a list of elements. is_optional: To raise an error if key was not found. ...
def flip(self, axis=HORIZONTAL): """Flips the layer, either HORIZONTAL or VERTICAL. """ if axis == HORIZONTAL: self.img = self.img.transpose(Image.FLIP_LEFT_RIGHT) if axis == VERTICAL: self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM)
Flips the layer, either HORIZONTAL or VERTICAL.
Below is the the instruction that describes the task: ### Input: Flips the layer, either HORIZONTAL or VERTICAL. ### Response: def flip(self, axis=HORIZONTAL): """Flips the layer, either HORIZONTAL or VERTICAL. """ if axis == HORIZONTAL: self.img = self.img.transpose(...
def render_formset(formset, **kwargs): """ Render a formset to a Bootstrap layout """ renderer_cls = get_formset_renderer(**kwargs) return renderer_cls(formset, **kwargs).render()
Render a formset to a Bootstrap layout
Below is the the instruction that describes the task: ### Input: Render a formset to a Bootstrap layout ### Response: def render_formset(formset, **kwargs): """ Render a formset to a Bootstrap layout """ renderer_cls = get_formset_renderer(**kwargs) return renderer_cls(formset, **kwargs).render...
def paschen_back_energies(fine_state, Bz): r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_state, Bz): ... ...
r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_state, Bz): ... print(f_group) [1.51284728917866e-24 3.8048...
Below is the the instruction that describes the task: ### Input: r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_stat...
def _schema_nodes(self): """parse self._ontology_file into a graph""" name, ext = os.path.splitext(self._ontology_file) if ext in ['.ttl']: self._ontology_parser_function = \ lambda s: rdflib.Graph().parse(s, format='n3') else: self._ontology_parse...
parse self._ontology_file into a graph
Below is the the instruction that describes the task: ### Input: parse self._ontology_file into a graph ### Response: def _schema_nodes(self): """parse self._ontology_file into a graph""" name, ext = os.path.splitext(self._ontology_file) if ext in ['.ttl']: self._ontology_parser...
def collect_analysis(using): """ generate the analysis settings from Python land """ python_analysis = defaultdict(dict) for index in registry.indexes_for_connection(using): python_analysis.update(index._doc_type.mapping._collect_analysis()) return stringer(python_analysis)
generate the analysis settings from Python land
Below is the the instruction that describes the task: ### Input: generate the analysis settings from Python land ### Response: def collect_analysis(using): """ generate the analysis settings from Python land """ python_analysis = defaultdict(dict) for index in registry.indexes_for_connection(us...
def run(self, pcap): """ Runs suricata against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts """ tmpdir = None try: tmpdir = tempfile.mkdtemp(prefix='tmpsuri') proc = Popen(self._s...
Runs suricata against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts
Below is the the instruction that describes the task: ### Input: Runs suricata against the supplied pcap. :param pcap: Filepath to pcap file to scan :returns: tuple of version, list of alerts ### Response: def run(self, pcap): """ Runs suricata against the supplied pcap. :...
def _allKeys(self, prefix): """ Private implementation method. Use keys() instead. """ global dictItemsIter result = [prefix + self.key] if self.key != None else [] for key, trie in dictItemsIter(self.slots): result.extend(trie._allKeys(prefix + key)) ...
Private implementation method. Use keys() instead.
Below is the the instruction that describes the task: ### Input: Private implementation method. Use keys() instead. ### Response: def _allKeys(self, prefix): """ Private implementation method. Use keys() instead. """ global dictItemsIter result = [prefix + self.key] if self.key != None else...
def check_commutation(pauli_list, pauli_two): """ Check if commuting a PauliTerm commutes with a list of other terms by natural calculation. Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the number of anti-coincidences (which must always be even for commuting Pau...
Check if commuting a PauliTerm commutes with a list of other terms by natural calculation. Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the number of anti-coincidences (which must always be even for commuting PauliTerms) instead of the no. of coincidences, as in the...
Below is the the instruction that describes the task: ### Input: Check if commuting a PauliTerm commutes with a list of other terms by natural calculation. Uses the result in Section 3 of arXiv:1405.5749v2, modified slightly here to check for the number of anti-coincidences (which must always be even for co...
def _add_admin(self, app, **kwargs): """Add a Flask Admin interface to an application. :param flask.Flask app: A Flask application :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin` :rtype: flask_admin.Admin """ from flask_admin import Admi...
Add a Flask Admin interface to an application. :param flask.Flask app: A Flask application :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin` :rtype: flask_admin.Admin
Below is the the instruction that describes the task: ### Input: Add a Flask Admin interface to an application. :param flask.Flask app: A Flask application :param kwargs: Keyword arguments are passed through to :class:`flask_admin.Admin` :rtype: flask_admin.Admin ### Response: def _add_adm...
def add_group(self, name, desc, status): """ Add a new group to a network. """ existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, ResourceGroup.network_id==self.id).first() if existing_group is not None: raise HydraError("A resou...
Add a new group to a network.
Below is the the instruction that describes the task: ### Input: Add a new group to a network. ### Response: def add_group(self, name, desc, status): """ Add a new group to a network. """ existing_group = get_session().query(ResourceGroup).filter(ResourceGroup.name==name, Resou...
def save(self, filename, fformat=None, fill_value=None, compute=True, keep_palette=False, cmap=None, **format_kwargs): """Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be ...
Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be one of many image formats supported by the `rasterio` or `PIL` libraries ('jpg', 'png', ...
Below is the the instruction that describes the task: ### Input: Save the image to the given *filename*. Args: filename (str): Output filename fformat (str): File format of output file (optional). Can be one of many image formats supported by the ...
def writeln(self, data): """ Write a line of text to the file :param data: The text to write """ self.f.write(" "*self.indent_level) self.f.write(data + "\n")
Write a line of text to the file :param data: The text to write
Below is the the instruction that describes the task: ### Input: Write a line of text to the file :param data: The text to write ### Response: def writeln(self, data): """ Write a line of text to the file :param data: The text to write """ self.f.write(" "*self.ind...
def set_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) """ key = self.key(term1, term2) self.keys.update([term1, term2]) self.pairs[key] = value
Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed)
Below is the the instruction that describes the task: ### Input: Set the value for a pair of terms. Args: term1 (str) term2 (str) value (mixed) ### Response: def set_pair(self, term1, term2, value, **kwargs): """ Set the value for a pair of terms. ...
def calculate_content_width(self): """ Calculate the width of inner content of the border. This will be the width of the menu borders, minus the left and right padding, and minus the two vertical border characters. For example, given a border width of 77, with left and right margins eac...
Calculate the width of inner content of the border. This will be the width of the menu borders, minus the left and right padding, and minus the two vertical border characters. For example, given a border width of 77, with left and right margins each set to 2, the content width would be 71 (77 -...
Below is the the instruction that describes the task: ### Input: Calculate the width of inner content of the border. This will be the width of the menu borders, minus the left and right padding, and minus the two vertical border characters. For example, given a border width of 77, with left and rig...
def deserialize(datagram, source): """ De-serialize a stream of byte to a message. :param datagram: the incoming udp message :param source: the source address and port (ip, port) :return: the message :rtype: Message """ try: fmt = "!BBH" ...
De-serialize a stream of byte to a message. :param datagram: the incoming udp message :param source: the source address and port (ip, port) :return: the message :rtype: Message
Below is the the instruction that describes the task: ### Input: De-serialize a stream of byte to a message. :param datagram: the incoming udp message :param source: the source address and port (ip, port) :return: the message :rtype: Message ### Response: def deserialize(datagram, ...
def vsubg(v1, v2, ndim): """ Compute the difference between two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html :param v1: First vector (minuend). :type v1: Array of floats :param v2: Second vector (subtrahend). :t...
Compute the difference between two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html :param v1: First vector (minuend). :type v1: Array of floats :param v2: Second vector (subtrahend). :type v2: Array of floats :param nd...
Below is the the instruction that describes the task: ### Input: Compute the difference between two double precision vectors of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vsubg_c.html :param v1: First vector (minuend). :type v1: Array of floats :param v2: Sec...
def remove_markables(self,list_mark_ids): """ Removes a list of markables from the layer @type list_term_ids: list @param list_term_ids: list of markable identifiers to be removed """ nodes_to_remove = set() for markable in self: if markable.get_id()...
Removes a list of markables from the layer @type list_term_ids: list @param list_term_ids: list of markable identifiers to be removed
Below is the the instruction that describes the task: ### Input: Removes a list of markables from the layer @type list_term_ids: list @param list_term_ids: list of markable identifiers to be removed ### Response: def remove_markables(self,list_mark_ids): """ Removes a list of markab...
def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if child.get('supported') == 'yes': enums = [_parse_caps_enum(node) for node in child.findall('enum')] result[child.tag] = {ite...
Parse the devices or features list of the domain capatilities
Below is the the instruction that describes the task: ### Input: Parse the devices or features list of the domain capatilities ### Response: def _parse_caps_devices_features(node): ''' Parse the devices or features list of the domain capatilities ''' result = {} for child in node: if ch...
def syd(c, s, l): """ This accountancy function computes sum of the years digits depreciation for an asset purchased for cash with a known life span and salvage value. The depreciation is returned as a list in python. c = historcal cost or price paid s = the expected salvage proceeds l =...
This accountancy function computes sum of the years digits depreciation for an asset purchased for cash with a known life span and salvage value. The depreciation is returned as a list in python. c = historcal cost or price paid s = the expected salvage proceeds l = expected useful life of the ...
Below is the the instruction that describes the task: ### Input: This accountancy function computes sum of the years digits depreciation for an asset purchased for cash with a known life span and salvage value. The depreciation is returned as a list in python. c = historcal cost or price paid s...
def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False): """Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre. Parameters ---------- shape: (int, int) The (y,x) shape of the mask in units of pixels. ...
Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre. Parameters ---------- shape: (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float The arc-second to pixel conversion factor of each pixel. ...
Below is the the instruction that describes the task: ### Input: Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre. Parameters ---------- shape: (int, int) The (y,x) shape of the mask in units of pixels. pixel_scale: float ...
def load_payload(self, payload, serializer=None): """Loads the encoded object. This function raises :class:`BadPayload` if the payload is not valid. The `serializer` parameter can be used to override the serializer stored on the class. The encoded payload is always byte based. ...
Loads the encoded object. This function raises :class:`BadPayload` if the payload is not valid. The `serializer` parameter can be used to override the serializer stored on the class. The encoded payload is always byte based.
Below is the the instruction that describes the task: ### Input: Loads the encoded object. This function raises :class:`BadPayload` if the payload is not valid. The `serializer` parameter can be used to override the serializer stored on the class. The encoded payload is always byte based....
def get_all_cache_subnet_groups(name=None, region=None, key=None, keyid=None, profile=None): ''' Return a list of all cache subnet groups with details CLI example:: salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1 ''' conn = _get_conn(re...
Return a list of all cache subnet groups with details CLI example:: salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1
Below is the the instruction that describes the task: ### Input: Return a list of all cache subnet groups with details CLI example:: salt myminion boto_elasticache.get_all_subnet_groups region=us-east-1 ### Response: def get_all_cache_subnet_groups(name=None, region=None, key=None, ...
def get_or_init_instance(self, instance_loader, row): """ Either fetches an already existing instance or initializes a new one. """ instance = self.get_instance(instance_loader, row) if instance: return (instance, False) else: return (self.init_ins...
Either fetches an already existing instance or initializes a new one.
Below is the the instruction that describes the task: ### Input: Either fetches an already existing instance or initializes a new one. ### Response: def get_or_init_instance(self, instance_loader, row): """ Either fetches an already existing instance or initializes a new one. """ in...
def dump(self, file, payload): """Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None. """ ...
Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: None.
Below is the the instruction that describes the task: ### Input: Dump json oject to open file output. Writes json with 2 spaces indentation. Args: file: Open file-like object. Must be open for writing. payload: The Json object to write to file. Returns: ...
def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True): """ Convert result from datetime_to_dtstr to datetime in timezone UTC0. """ try: dt = datetime.datetime.utcfromtimestamp(int(dtstr, 36) / 1e3) if to_tz: dt = timezone.make_aware(dt, timezone=pytz.UTC) i...
Convert result from datetime_to_dtstr to datetime in timezone UTC0.
Below is the the instruction that describes the task: ### Input: Convert result from datetime_to_dtstr to datetime in timezone UTC0. ### Response: def dtstr_to_datetime(dtstr, to_tz=None, fail_silently=True): """ Convert result from datetime_to_dtstr to datetime in timezone UTC0. """ try: d...