code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def copy(self): """ Make a copy of the MemoryData. :return: A copy of the MemoryData instance. :rtype: MemoryData """ s = MemoryData(self.address, self.size, self.sort, pointer_addr=self.pointer_addr, max_size=self.max_size) s.content = self.content retu...
Make a copy of the MemoryData. :return: A copy of the MemoryData instance. :rtype: MemoryData
Below is the the instruction that describes the task: ### Input: Make a copy of the MemoryData. :return: A copy of the MemoryData instance. :rtype: MemoryData ### Response: def copy(self): """ Make a copy of the MemoryData. :return: A copy of the MemoryData instance. ...
def delete_indicator_from_whitelist(self, indicator): """ Delete an indicator from the user's company's whitelist. :param indicator: An |Indicator| object, representing the indicator to delete. """ params = indicator.to_dict() self._client.delete("whitelist", params=par...
Delete an indicator from the user's company's whitelist. :param indicator: An |Indicator| object, representing the indicator to delete.
Below is the the instruction that describes the task: ### Input: Delete an indicator from the user's company's whitelist. :param indicator: An |Indicator| object, representing the indicator to delete. ### Response: def delete_indicator_from_whitelist(self, indicator): """ Delete an indicat...
def analysisJWT(self, token): """ 解析token, 返回解码后的header、payload、signature等 """ _header, _payload, _signature = token.split(".") data = { "header": json.loads(base64.urlsafe_b64decode(str(_header))), "payload": json.loads(base64.urlsafe_b64decode(str(_payload))), ...
解析token, 返回解码后的header、payload、signature等
Below is the the instruction that describes the task: ### Input: 解析token, 返回解码后的header、payload、signature等 ### Response: def analysisJWT(self, token): """ 解析token, 返回解码后的header、payload、signature等 """ _header, _payload, _signature = token.split(".") data = { "header": json.loads(b...
def _set_alarm_falling_event_index(self, v, load=False): """ Setter method for alarm_falling_event_index, mapped from YANG variable /rmon/alarm_entry/alarm_falling_event_index (alarm-falling-event-index-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_falling_...
Setter method for alarm_falling_event_index, mapped from YANG variable /rmon/alarm_entry/alarm_falling_event_index (alarm-falling-event-index-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_falling_event_index is considered as a private method. Backends looking t...
Below is the the instruction that describes the task: ### Input: Setter method for alarm_falling_event_index, mapped from YANG variable /rmon/alarm_entry/alarm_falling_event_index (alarm-falling-event-index-type) If this variable is read-only (config: false) in the source YANG file, then _set_alarm_falling_...
def triggering_streams(streams): """ Temporarily declares the streams as being in a triggered state. Needed by DynamicMap to determine whether to memoize on a Callable, i.e. if a stream has memoization disabled and is in triggered state Callable should disable lookup in the memoization cache. This i...
Temporarily declares the streams as being in a triggered state. Needed by DynamicMap to determine whether to memoize on a Callable, i.e. if a stream has memoization disabled and is in triggered state Callable should disable lookup in the memoization cache. This is done by the dynamicmap_memoization cont...
Below is the the instruction that describes the task: ### Input: Temporarily declares the streams as being in a triggered state. Needed by DynamicMap to determine whether to memoize on a Callable, i.e. if a stream has memoization disabled and is in triggered state Callable should disable lookup in the m...
def bulk(iterable, index=INDEX_NAME, doc_type=DOC_TYPE, action='index'): """ Wrapper of elasticsearch's bulk method Converts an interable of models to document operations and submits them to Elasticsearch. Returns a count of operations when done. https://elasticsearch-py.readthedocs.io/en/master/...
Wrapper of elasticsearch's bulk method Converts an interable of models to document operations and submits them to Elasticsearch. Returns a count of operations when done. https://elasticsearch-py.readthedocs.io/en/master/api.html#elasticsearch.Elasticsearch.bulk https://www.elastic.co/guide/en/elastic...
Below is the the instruction that describes the task: ### Input: Wrapper of elasticsearch's bulk method Converts an interable of models to document operations and submits them to Elasticsearch. Returns a count of operations when done. https://elasticsearch-py.readthedocs.io/en/master/api.html#elastic...
def loadZone(self, zone, callback=None, errback=None): """ Load an existing zone into a high level Zone object. :param str zone: zone name, like 'example.com' :rtype: :py:class:`ns1.zones.Zone` """ import ns1.zones zone = ns1.zones.Zone(self.config, zone) ...
Load an existing zone into a high level Zone object. :param str zone: zone name, like 'example.com' :rtype: :py:class:`ns1.zones.Zone`
Below is the the instruction that describes the task: ### Input: Load an existing zone into a high level Zone object. :param str zone: zone name, like 'example.com' :rtype: :py:class:`ns1.zones.Zone` ### Response: def loadZone(self, zone, callback=None, errback=None): """ Load an e...
def add_edge(self, from_index, to_index, from_jimage=(0, 0, 0), to_jimage=None, weight=None, warn_duplicates=True, edge_properties=None): """ Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have ...
Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted so that from_index < to_index and from_jimage becomes (0, 0,...
Below is the the instruction that describes the task: ### Input: Add edge to graph. Since physically a 'bond' (or other connection between sites) doesn't have a direction, from_index, from_jimage can be swapped with to_index, to_jimage. However, images will always always be shifted...
def marker_tags(self, iid): """Generator for all the tags of a certain marker""" tags = self._markers[iid]["tags"] for tag in tags: yield tag
Generator for all the tags of a certain marker
Below is the the instruction that describes the task: ### Input: Generator for all the tags of a certain marker ### Response: def marker_tags(self, iid): """Generator for all the tags of a certain marker""" tags = self._markers[iid]["tags"] for tag in tags: yield tag
def _set_redistribute_connected(self, v, load=False): """ Setter method for redistribute_connected, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_connected (container) If this variable is read-only (config: false) in the source YANG file, then _set_redistribute_connect...
Setter method for redistribute_connected, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_connected (container) If this variable is read-only (config: false) in the source YANG file, then _set_redistribute_connected is considered as a private method. Backends looking to popu...
Below is the the instruction that describes the task: ### Input: Setter method for redistribute_connected, mapped from YANG variable /rbridge_id/ipv6/router/ospf/redistribute/redistribute_connected (container) If this variable is read-only (config: false) in the source YANG file, then _set_redistribute_conn...
def _read_data_handler(whence, ctx, complete, can_flush): """Creates a co-routine for retrieving data up to a requested size. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. complete (True|False): True i...
Creates a co-routine for retrieving data up to a requested size. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. complete (True|False): True if STREAM_END should be emitted if no bytes are read or ...
Below is the the instruction that describes the task: ### Input: Creates a co-routine for retrieving data up to a requested size. Args: whence (Coroutine): The co-routine to return to after the data is satisfied. ctx (_HandlerContext): The context for the read. complete (True|False): Tr...
def group_lines(lines): """Split a list of lines using empty lines as separators.""" groups = [] group = [] for line in lines: if line.strip() == "": groups.append(group[:]) group = [] continue group.append(line) if group: groups.append(g...
Split a list of lines using empty lines as separators.
Below is the the instruction that describes the task: ### Input: Split a list of lines using empty lines as separators. ### Response: def group_lines(lines): """Split a list of lines using empty lines as separators.""" groups = [] group = [] for line in lines: if line.strip() == "": ...
def weighted_axioms(self, x, y, xg): """ return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping between x and y. See kboom paper """ # TODO: allow additional weighting # weights are log odds w=log(p/(1-p))...
return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping between x and y. See kboom paper
Below is the the instruction that describes the task: ### Input: return a tuple (sub,sup,equiv,other) indicating estimated prior probabilities for an interpretation of a mapping between x and y. See kboom paper ### Response: def weighted_axioms(self, x, y, xg): """ return a tuple (...
def pow2_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_...
Pow2 Quantized Convolution. Pow2 Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j}, ...
Below is the the instruction that describes the task: ### Input: Pow2 Quantized Convolution. Pow2 Quantized Convolution is the convolution function, except the definition of the inner product is modified. The input-output relation of this function is as follows: .. math:: y_{n, a, b} = \s...
def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor.get_current_editorstack() stack.autosave.autosave_all() self.start_autosave_timer()
Instruct current editorstack to autosave files where necessary.
Below is the the instruction that describes the task: ### Input: Instruct current editorstack to autosave files where necessary. ### Response: def do_autosave(self): """Instruct current editorstack to autosave files where necessary.""" logger.debug('Autosave triggered') stack = self.editor....
def preprocess(net, image): ''' convert to Caffe input image layout ''' return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
convert to Caffe input image layout
Below is the the instruction that describes the task: ### Input: convert to Caffe input image layout ### Response: def preprocess(net, image): ''' convert to Caffe input image layout ''' return np.float32(np.rollaxis(image, 2)[::-1]) - net.transformer.mean["data"]
def validate(ref_time, ref_freqs, est_time, est_freqs): """Checks that the time and frequency inputs are well-formed. Parameters ---------- ref_time : np.ndarray reference time stamps in seconds ref_freqs : list of np.ndarray reference frequencies in Hz est_time : np.ndarray ...
Checks that the time and frequency inputs are well-formed. Parameters ---------- ref_time : np.ndarray reference time stamps in seconds ref_freqs : list of np.ndarray reference frequencies in Hz est_time : np.ndarray estimate time stamps in seconds est_freqs : list of np...
Below is the the instruction that describes the task: ### Input: Checks that the time and frequency inputs are well-formed. Parameters ---------- ref_time : np.ndarray reference time stamps in seconds ref_freqs : list of np.ndarray reference frequencies in Hz est_time : np.ndarr...
def get_permissions(FunctionName, Qualifier=None, region=None, key=None, keyid=None, profile=None): ''' Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba...
Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba.get_permissions my_function permissions: {...}
Below is the the instruction that describes the task: ### Input: Get resource permissions for the given lambda function Returns dictionary of permissions, by statement ID CLI Example: .. code-block:: bash salt myminion boto_lamba.get_permissions my_function permissions: {...} ### Re...
def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
sets camera viewup vector
Below is the the instruction that describes the task: ### Input: sets camera viewup vector ### Response: def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.Se...
def get_keyword_hierarchy(self, pattern="*"): """Returns all keywords that match a glob-style pattern The result is a list of dictionaries, sorted by collection name. The pattern matching is insensitive to case. The function returns a list of (library_name, keyword_name, ...
Returns all keywords that match a glob-style pattern The result is a list of dictionaries, sorted by collection name. The pattern matching is insensitive to case. The function returns a list of (library_name, keyword_name, keyword_synopsis tuples) sorted by keyword name
Below is the the instruction that describes the task: ### Input: Returns all keywords that match a glob-style pattern The result is a list of dictionaries, sorted by collection name. The pattern matching is insensitive to case. The function returns a list of (library_name, keyword_...
def mkp(*args, **kwargs): """ Generate a directory path, and create it if requested. .. code-block:: Python filepath = mkp('base', 'folder', 'file') dirpath = mkp('root', 'path', 'folder', mk=True) Args: \*args: File or directory path segments to be concatenated mk (bo...
Generate a directory path, and create it if requested. .. code-block:: Python filepath = mkp('base', 'folder', 'file') dirpath = mkp('root', 'path', 'folder', mk=True) Args: \*args: File or directory path segments to be concatenated mk (bool): Make the directory (if it doesn't...
Below is the the instruction that describes the task: ### Input: Generate a directory path, and create it if requested. .. code-block:: Python filepath = mkp('base', 'folder', 'file') dirpath = mkp('root', 'path', 'folder', mk=True) Args: \*args: File or directory path segments to...
def trade_history( self, from_=None, count=None, from_id=None, end_id=None, order=None, since=None, end=None, pair=None ): """ Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display s...
Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display starts (default 0) :param int or None count: the number of trades for display (default 1000) :param int or None from_id: trade ID, from which the di...
Below is the the instruction that describes the task: ### Input: Returns trade history. To use this method you need a privilege of the info key. :param int or None from_: trade ID, from which the display starts (default 0) :param int or None count: the number of trades for display (default ...
def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg
Execute Registered Filters
Below is the the instruction that describes the task: ### Input: Execute Registered Filters ### Response: def _execFilters(self, type, msg): """ Execute Registered Filters """ for filter in self.FILTERS: msg = filter(type, msg) return msg
def post_replicate(request): """MNReplication.replicate(session, sysmeta, sourceNode) → boolean.""" d1_gmn.app.views.assert_db.post_has_mime_parts( request, (('field', 'sourceNode'), ('file', 'sysmeta')) ) sysmeta_pyxb = d1_gmn.app.sysmeta.deserialize(request.FILES['sysmeta']) d1_gmn.app.loc...
MNReplication.replicate(session, sysmeta, sourceNode) → boolean.
Below is the the instruction that describes the task: ### Input: MNReplication.replicate(session, sysmeta, sourceNode) → boolean. ### Response: def post_replicate(request): """MNReplication.replicate(session, sysmeta, sourceNode) → boolean.""" d1_gmn.app.views.assert_db.post_has_mime_parts( request...
def maven_url(self): ''' Download-URL from Maven ''' return '{prefix}/{path}/{artifact}/{version}/{filename}'.format( prefix = MAVEN_PREFIX, path = '/'.join(self.group.split('.')), artifact = self.artifact, version = self.version, ...
Download-URL from Maven
Below is the the instruction that describes the task: ### Input: Download-URL from Maven ### Response: def maven_url(self): ''' Download-URL from Maven ''' return '{prefix}/{path}/{artifact}/{version}/{filename}'.format( prefix = MAVEN_PREFIX, path = '/...
def wait(self, task_id): """ Blocking method which wait end of task. It's prefered to use :class:`carotte.Task` object directly :param string task_id: Task ID :returns: Task dict :rtype: dict """ data = { 'action': 'wait', 'id': t...
Blocking method which wait end of task. It's prefered to use :class:`carotte.Task` object directly :param string task_id: Task ID :returns: Task dict :rtype: dict
Below is the the instruction that describes the task: ### Input: Blocking method which wait end of task. It's prefered to use :class:`carotte.Task` object directly :param string task_id: Task ID :returns: Task dict :rtype: dict ### Response: def wait(self, task_id): """ ...
async def async_get_sensor_log(self, index: int) -> Optional[SensorLogResponse]: """ Get an entry from the Special sensor log. :param index: Index for the sensor log entry to be obtained. :return: Response containing the sensor log entry, or None if not found. """ respo...
Get an entry from the Special sensor log. :param index: Index for the sensor log entry to be obtained. :return: Response containing the sensor log entry, or None if not found.
Below is the the instruction that describes the task: ### Input: Get an entry from the Special sensor log. :param index: Index for the sensor log entry to be obtained. :return: Response containing the sensor log entry, or None if not found. ### Response: async def async_get_sensor_log(self, index:...
def p_abbrev_rel_loc_path(p): 'AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step' p[0] = list(p[1]) p[0].append(_expand_double_slash()) p[0].append(p[3])
AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step
Below is the the instruction that describes the task: ### Input: AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step ### Response: def p_abbrev_rel_loc_path(p): 'AbbreviatedRelativeLocationPath : RelativeLocationPath DOUBLESLASH Step' p[0] = list(p[1]) p[0].append(_expand_double_sla...
def get_group_hierarchy_session(self, proxy): """Gets the group hierarchy traversal session for the given resource group. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinHierarchySession) - ``a GroupHierarchySession`` raise: NullArgument - ``proxy`` ...
Gets the group hierarchy traversal session for the given resource group. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinHierarchySession) - ``a GroupHierarchySession`` raise: NullArgument - ``proxy`` is ``null`` raise: OperationFailed - unable to c...
Below is the the instruction that describes the task: ### Input: Gets the group hierarchy traversal session for the given resource group. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.resource.BinHierarchySession) - ``a GroupHierarchySession`` raise: NullArgument ...
def to_csv(weekmatrices, filename, digits=5): """ Exports a list of week-matrices to a specified filename in the CSV format. Parameters ---------- weekmatrices : list The week-matrices to export. filename : string Path for the exported CSV file. """ with open(filename, ...
Exports a list of week-matrices to a specified filename in the CSV format. Parameters ---------- weekmatrices : list The week-matrices to export. filename : string Path for the exported CSV file.
Below is the the instruction that describes the task: ### Input: Exports a list of week-matrices to a specified filename in the CSV format. Parameters ---------- weekmatrices : list The week-matrices to export. filename : string Path for the exported CSV file. ### Response: def to_...
def create_data(self, extra=None): r""" Generate object for api. Example json: { "service_job_id": "1234567890", "service_name": "travis-ci", "source_files": [ { "name": "example.py", ...
r""" Generate object for api. Example json: { "service_job_id": "1234567890", "service_name": "travis-ci", "source_files": [ { "name": "example.py", "source": "def four\n 4\n...
Below is the the instruction that describes the task: ### Input: r""" Generate object for api. Example json: { "service_job_id": "1234567890", "service_name": "travis-ci", "source_files": [ { "na...
def check_conventions_are_cf_16(self, ds): ''' Check the global attribute conventions to contain CF-1.6 CF §2.6.1 the NUG defined global attribute Conventions to the string value "CF-1.6" :param netCDF4.Dataset ds: An open netCDF dataset :rtype: compliance_checker.base....
Check the global attribute conventions to contain CF-1.6 CF §2.6.1 the NUG defined global attribute Conventions to the string value "CF-1.6" :param netCDF4.Dataset ds: An open netCDF dataset :rtype: compliance_checker.base.Result
Below is the the instruction that describes the task: ### Input: Check the global attribute conventions to contain CF-1.6 CF §2.6.1 the NUG defined global attribute Conventions to the string value "CF-1.6" :param netCDF4.Dataset ds: An open netCDF dataset :rtype: compliance_checker...
def get_publisher(self, publisher_id): """GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>` """ route_values = {} if publisher_id is no...
GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>`
Below is the the instruction that describes the task: ### Input: GetPublisher. Get a specific service hooks publisher. :param str publisher_id: ID for a publisher. :rtype: :class:`<Publisher> <azure.devops.v5_0.service_hooks.models.Publisher>` ### Response: def get_publisher(self, publisher...
def delete_content_type_object(repo, content_type, uuid): """ Delete an object of a certain content type """ storage_manager = StorageManager(repo) model_class = load_model_class(repo, content_type) model = storage_manager.get(model_class, uuid) commit = storage_manager.delete(model, 'Delete...
Delete an object of a certain content type
Below is the the instruction that describes the task: ### Input: Delete an object of a certain content type ### Response: def delete_content_type_object(repo, content_type, uuid): """ Delete an object of a certain content type """ storage_manager = StorageManager(repo) model_class = load_model_...
def string_to_double_precision_float(s: str) -> float: """ Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float by Python ``float`` function, so I wrote this function to help conversion. For example, :param s: a string denoting a double prec...
Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float by Python ``float`` function, so I wrote this function to help conversion. For example, :param s: a string denoting a double precision number :return: a Python floating point number .. do...
Below is the the instruction that describes the task: ### Input: Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float by Python ``float`` function, so I wrote this function to help conversion. For example, :param s: a string denoting a double pr...
def cli_forms(self, *args): """List all available form definitions""" forms = [] missing = [] for key, item in schemastore.items(): if 'form' in item and len(item['form']) > 0: forms.append(key) else: missing.append(key) ...
List all available form definitions
Below is the the instruction that describes the task: ### Input: List all available form definitions ### Response: def cli_forms(self, *args): """List all available form definitions""" forms = [] missing = [] for key, item in schemastore.items(): if 'form' in item and ...
def accuracy(y_true, y_pred, round=True): """Classification accuracy """ y_true, y_pred = _mask_value_nan(y_true, y_pred) if round: y_true = np.round(y_true) y_pred = np.round(y_pred) return skm.accuracy_score(y_true, y_pred)
Classification accuracy
Below is the the instruction that describes the task: ### Input: Classification accuracy ### Response: def accuracy(y_true, y_pred, round=True): """Classification accuracy """ y_true, y_pred = _mask_value_nan(y_true, y_pred) if round: y_true = np.round(y_true) y_pred = np.round(y_pr...
def import_from_pandapower_net(network, net): """ Import network from pandapower net. This import function is not yet finished (see warning below). Parameters ---------- net : pandapower network Examples -------- >>> network.import_from_pandapower_net(net) """ logger.warni...
Import network from pandapower net. This import function is not yet finished (see warning below). Parameters ---------- net : pandapower network Examples -------- >>> network.import_from_pandapower_net(net)
Below is the the instruction that describes the task: ### Input: Import network from pandapower net. This import function is not yet finished (see warning below). Parameters ---------- net : pandapower network Examples -------- >>> network.import_from_pandapower_net(net) ### Response:...
def filter_missing_rna(s2bins, bins2s, rna_cov): """ remove any bins that don't have 16S """ for bin, scaffolds in list(bins2s.items()): c = 0 for s in scaffolds: if s in rna_cov: c += 1 if c == 0: del bins2s[bin] for scaffold, bin in l...
remove any bins that don't have 16S
Below is the the instruction that describes the task: ### Input: remove any bins that don't have 16S ### Response: def filter_missing_rna(s2bins, bins2s, rna_cov): """ remove any bins that don't have 16S """ for bin, scaffolds in list(bins2s.items()): c = 0 for s in scaffolds: ...
def update(self, current, values=[], exact=[], strict=[]): """ Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. ex...
Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. exact: List of tuples (name, value_for_last_step). The progress b...
Below is the the instruction that describes the task: ### Input: Updates the progress bar. # Arguments current: Index of current step. values: List of tuples (name, value_for_last_step). The progress bar will display averages for these values. exact: List ...
def _update_datasource(self, source, data): """ Update datasource with data for a new frame. """ if isinstance(source, ColumnDataSource): if self.handles['static_source']: source.trigger('data', source.data, data) else: source.data....
Update datasource with data for a new frame.
Below is the the instruction that describes the task: ### Input: Update datasource with data for a new frame. ### Response: def _update_datasource(self, source, data): """ Update datasource with data for a new frame. """ if isinstance(source, ColumnDataSource): if self.h...
def get_graph_tool_from_adjacency(adjacency, directed=None): """Get graph_tool graph from adjacency matrix.""" import graph_tool as gt adjacency_edge_list = adjacency if not directed: from scipy.sparse import tril adjacency_edge_list = tril(adjacency) g = gt.Graph(directed=directed) ...
Get graph_tool graph from adjacency matrix.
Below is the the instruction that describes the task: ### Input: Get graph_tool graph from adjacency matrix. ### Response: def get_graph_tool_from_adjacency(adjacency, directed=None): """Get graph_tool graph from adjacency matrix.""" import graph_tool as gt adjacency_edge_list = adjacency if not di...
def rpush_limit(self, queue, value, limit=100000): ''' Pushes an element to a list in an atomic way until it reaches certain size Once limit is reached, the function will lpop the oldest elements This operation runs in LUA, so is always atomic ''' lua = ''' ...
Pushes an element to a list in an atomic way until it reaches certain size Once limit is reached, the function will lpop the oldest elements This operation runs in LUA, so is always atomic
Below is the the instruction that describes the task: ### Input: Pushes an element to a list in an atomic way until it reaches certain size Once limit is reached, the function will lpop the oldest elements This operation runs in LUA, so is always atomic ### Response: def rpush_limit(self,...
def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('callback', None) if callback is None: content = func(*args, **kwargs) else: conte...
Wrap response in JSON or JSONP style
Below is the the instruction that describes the task: ### Input: Wrap response in JSON or JSONP style ### Response: def json_or_jsonp(func): """Wrap response in JSON or JSONP style""" @wraps(func) def _(*args, **kwargs): mimetype = 'application/javascript' callback = request.args.get('c...
def re(self, *parts): """Matches string values against a regular expression compiled of individual parts. Document.field.re(r'^', variable_part, r'\\.') Regex operator: {$regex: value} Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/ """ if self._combining: # We are ...
Matches string values against a regular expression compiled of individual parts. Document.field.re(r'^', variable_part, r'\\.') Regex operator: {$regex: value} Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/
Below is the the instruction that describes the task: ### Input: Matches string values against a regular expression compiled of individual parts. Document.field.re(r'^', variable_part, r'\\.') Regex operator: {$regex: value} Documentation: https://docs.mongodb.com/manual/reference/operator/query/regex/...
def convert(self, imtls, nsites, idx=0): """ Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index on the z...
Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index on the z-axis (default 0)
Below is the the instruction that describes the task: ### Input: Convert a probability map into a composite array of length `nsites` and dtype `imtls.dt`. :param imtls: DictArray instance :param nsites: the total number of sites :param idx: index ...
def find_include_file(self, t): """ Finds the #include file for a given preprocessor tuple. """ fname = t[2] for d in self.searchpath[t[1]]: if d == os.curdir: f = fname else: f = os.path.join(d, fname) if os.pat...
Finds the #include file for a given preprocessor tuple.
Below is the the instruction that describes the task: ### Input: Finds the #include file for a given preprocessor tuple. ### Response: def find_include_file(self, t): """ Finds the #include file for a given preprocessor tuple. """ fname = t[2] for d in self.searchpath[t[1]]:...
def is_inside_bounds(value, params): """Return ``True`` if ``value`` is contained in ``params``. This method supports broadcasting in the sense that for ``params.ndim >= 2``, if more than one value is given, the inputs are broadcast against each other. Parameters ---------- value : `array-...
Return ``True`` if ``value`` is contained in ``params``. This method supports broadcasting in the sense that for ``params.ndim >= 2``, if more than one value is given, the inputs are broadcast against each other. Parameters ---------- value : `array-like` Value(s) to be checked. For se...
Below is the the instruction that describes the task: ### Input: Return ``True`` if ``value`` is contained in ``params``. This method supports broadcasting in the sense that for ``params.ndim >= 2``, if more than one value is given, the inputs are broadcast against each other. Parameters -----...
def is_transaction_expired(transaction, block_number): """ True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. I...
True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is over. If the current block is higher than any of these expirations...
Below is the the instruction that describes the task: ### Input: True if transaction cannot be mined because it has expired. Some transactions are time dependent, e.g. the secret registration must be done before the lock expiration, and the update transfer must be done before the settlement window is o...
def cancel(self, campaign_id): """ Cancel a Regular or Plain-Text Campaign after you send, before all of your recipients receive it. This feature is included with MailChimp Pro. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str` ...
Cancel a Regular or Plain-Text Campaign after you send, before all of your recipients receive it. This feature is included with MailChimp Pro. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:class:`str`
Below is the the instruction that describes the task: ### Input: Cancel a Regular or Plain-Text Campaign after you send, before all of your recipients receive it. This feature is included with MailChimp Pro. :param campaign_id: The unique id for the campaign. :type campaign_id: :py:...
def register_field(cls, field): """ Handles registering the fields with the FieldRegistry and creating a post-save signal for the model. """ FieldRegistry.add_field(cls, field) signals.post_save.connect(handle_save_embeds, sender=cls, dispatch_uid='%s.%s.%s' % \ (cl...
Handles registering the fields with the FieldRegistry and creating a post-save signal for the model.
Below is the the instruction that describes the task: ### Input: Handles registering the fields with the FieldRegistry and creating a post-save signal for the model. ### Response: def register_field(cls, field): """ Handles registering the fields with the FieldRegistry and creating a post-save si...
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_logo(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_interface") config = fcoe_get_interface output = ET.SubElement(fcoe_get_interface, "output") ...
Auto Generated Code
Below is the the instruction that describes the task: ### Input: Auto Generated Code ### Response: def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_rx_logo(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") fcoe_get_interface = ET.Element("fcoe_get_inter...
def add_event(self, name, subfolder, session): """ Add an event """ if self._similar_event_exists(subfolder): subfolder += "_{0}".format(self.next_id(subfolder)) new_event = ProjectFileEvent(name=name, subfolder=subfolder) session.add(new_event) self.e...
Add an event
Below is the the instruction that describes the task: ### Input: Add an event ### Response: def add_event(self, name, subfolder, session): """ Add an event """ if self._similar_event_exists(subfolder): subfolder += "_{0}".format(self.next_id(subfolder)) new_event...
def delete_token(self): """ Deletes the token file :return bool: Success / Failure """ if self.token_path.exists(): self.token_path.unlink() return True return False
Deletes the token file :return bool: Success / Failure
Below is the the instruction that describes the task: ### Input: Deletes the token file :return bool: Success / Failure ### Response: def delete_token(self): """ Deletes the token file :return bool: Success / Failure """ if self.token_path.exists(): self....
def _handle_func_call(self, node, scope, ctxt, stream): """Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO """ self._dlog("handling function call to '{}'".format(node.name.name)) if node.args is None: ...
Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO
Below is the the instruction that describes the task: ### Input: Handle FuncCall nodes :node: TODO :scope: TODO :ctxt: TODO :stream: TODO :returns: TODO ### Response: def _handle_func_call(self, node, scope, ctxt, stream): """Handle FuncCall nodes :node: TO...
def generate_build(self, image, targetname, rebuilds=None, cache_repo='', cache_tag='', buildargs=None, **kwargs): """ Separate the build into a series of one or more intermediate steps. Each specified build directory gets its own step Args: image (str...
Separate the build into a series of one or more intermediate steps. Each specified build directory gets its own step Args: image (str): name of the image as defined in the dockermake.py file targetname (str): name to tag the final built image with rebuilds (List[str]...
Below is the the instruction that describes the task: ### Input: Separate the build into a series of one or more intermediate steps. Each specified build directory gets its own step Args: image (str): name of the image as defined in the dockermake.py file targetname (str): n...
def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) for cls, crd in zip(klass, is_crowd): clsname = cfg.DATA.CLASS_NAMES[cls] if cr...
Will not modify img
Below is the the instruction that describes the task: ### Input: Will not modify img ### Response: def draw_annotation(img, boxes, klass, is_crowd=None): """Will not modify img""" labels = [] assert len(boxes) == len(klass) if is_crowd is not None: assert len(boxes) == len(is_crowd) ...
def lookups(self, request, model_admin): """ Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar. ...
Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right sidebar.
Below is the the instruction that describes the task: ### Input: Returns a list of tuples. The first element in each tuple is the coded value for the option that will appear in the URL query. The second element is the human-readable name for the option that will appear in the right s...
def _checkTable(cls, field): """Split a field from _sqlFields into table, column. Registers the table in cls._tables, and returns a fully qualified table.column (default table: cls._sqlTable) """ # Get table part try: (table, field) = field.split('.') ...
Split a field from _sqlFields into table, column. Registers the table in cls._tables, and returns a fully qualified table.column (default table: cls._sqlTable)
Below is the the instruction that describes the task: ### Input: Split a field from _sqlFields into table, column. Registers the table in cls._tables, and returns a fully qualified table.column (default table: cls._sqlTable) ### Response: def _checkTable(cls, field): """Split a field from ...
def ram_sp_ar(clk, we, addr, di, do): ''' RAM: Single-Port, Asynchronous Read ''' memL = [Signal(intbv(0)[len(di):]) for _ in range(2**len(addr))] @always(clk.posedge) def write(): if we: memL[int(addr)].next = di @always_comb def read(): do.next = memL[int(addr)] ...
RAM: Single-Port, Asynchronous Read
Below is the the instruction that describes the task: ### Input: RAM: Single-Port, Asynchronous Read ### Response: def ram_sp_ar(clk, we, addr, di, do): ''' RAM: Single-Port, Asynchronous Read ''' memL = [Signal(intbv(0)[len(di):]) for _ in range(2**len(addr))] @always(clk.posedge) def write(): ...
def _set_query_data(self, action='query'): """ set attributes derived from MediaWiki (action=query) """ data = self._load_response(action) page = data['query']['pages'][0] self._handle_continuations(data, action) if action == 'query': self.data['rand...
set attributes derived from MediaWiki (action=query)
Below is the the instruction that describes the task: ### Input: set attributes derived from MediaWiki (action=query) ### Response: def _set_query_data(self, action='query'): """ set attributes derived from MediaWiki (action=query) """ data = self._load_response(action) page...
def attach_bp(self, bp, description=''): """Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` """ ...
Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint`
Below is the the instruction that describes the task: ### Input: Attaches a flask.Blueprint to the bundle :param bp: :class:`flask.Blueprint` object :param description: Optional description string :raises: - InvalidBlueprint if the Blueprint is not of type `flask.Blueprint` ### ...
def get_blob_content(self, repository_id, sha1, project=None, download=None, file_name=None, resolve_lfs=None, **kwargs): """GetBlobContent. [Preview API] Get a single blob. :param str repository_id: The name or ID of the repository. :param str sha1: SHA1 hash of the file. You can get th...
GetBlobContent. [Preview API] Get a single blob. :param str repository_id: The name or ID of the repository. :param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint. :param str project: Project ID or project name :param bool ...
Below is the the instruction that describes the task: ### Input: GetBlobContent. [Preview API] Get a single blob. :param str repository_id: The name or ID of the repository. :param str sha1: SHA1 hash of the file. You can get the SHA1 of a file using the "Git/Items/Get Item" endpoint. ...
def parse_coordinates(variant, category): """Find out the coordinates for a variant Args: variant(cyvcf2.Variant) Returns: coordinates(dict): A dictionary on the form: { 'position':<int>, 'end':<int>, 'end_chrom':<str>, 'length':<int>...
Find out the coordinates for a variant Args: variant(cyvcf2.Variant) Returns: coordinates(dict): A dictionary on the form: { 'position':<int>, 'end':<int>, 'end_chrom':<str>, 'length':<int>, 'sub_category':<str>, '...
Below is the the instruction that describes the task: ### Input: Find out the coordinates for a variant Args: variant(cyvcf2.Variant) Returns: coordinates(dict): A dictionary on the form: { 'position':<int>, 'end':<int>, 'end_chrom':<str>, ...
def _prep_sample_and_config(ldetail_group, fastq_dir, fastq_final_dir): """Prepare output fastq file and configuration for a single sample. Only passes non-empty files through for processing. """ files = [] print("->", ldetail_group[0]["name"], len(ldetail_group)) for read in ["R1", "R2"]: ...
Prepare output fastq file and configuration for a single sample. Only passes non-empty files through for processing.
Below is the the instruction that describes the task: ### Input: Prepare output fastq file and configuration for a single sample. Only passes non-empty files through for processing. ### Response: def _prep_sample_and_config(ldetail_group, fastq_dir, fastq_final_dir): """Prepare output fastq file and confi...
def _get_fieldcodes(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords) ...
Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords)
Below is the the instruction that describes the task: ### Input: Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of tuples with (fieldcodes, keywords)...
def _check_create_parameters(self, **kwargs): """Override method for one in resource.py to check partition The partition cannot be included as a parameter to create a guest. Raise an exception if a consumer gives the partition parameter. :raises: DisallowedCreationParameter """...
Override method for one in resource.py to check partition The partition cannot be included as a parameter to create a guest. Raise an exception if a consumer gives the partition parameter. :raises: DisallowedCreationParameter
Below is the the instruction that describes the task: ### Input: Override method for one in resource.py to check partition The partition cannot be included as a parameter to create a guest. Raise an exception if a consumer gives the partition parameter. :raises: DisallowedCreationParameter...
def delete_triple(self, subject, predicate, object): """ Triple of curied or full iris to add to graph. Subject should be an interlex""" def filter_ontid(ontid): if ontid.startswith('http://'): pass elif ontid.prefix == 'ILXTEMP': onti...
Triple of curied or full iris to add to graph. Subject should be an interlex
Below is the the instruction that describes the task: ### Input: Triple of curied or full iris to add to graph. Subject should be an interlex ### Response: def delete_triple(self, subject, predicate, object): """ Triple of curied or full iris to add to graph. Subject should be an in...
def _adjust_cell_attributes(self, insertion_point, no_to_insert, axis, tab=None, cell_attrs=None): """Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place ...
Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that shall be inserted axis: Integer in range(3) \tSpecif...
Below is the the instruction that describes the task: ### Input: Adjusts cell attributes on insertion/deletion Parameters ---------- insertion_point: Integer \tPont on axis, before which insertion takes place no_to_insert: Integer >= 0 \tNumber of rows/cols/tabs that...
def Page_setDocumentContent(self, frameId, html): """ Function path: Page.setDocumentContent Domain: Page Method name: setDocumentContent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'frameId' (type: FrameId) -> Frame id to set HTML for. 'html' (ty...
Function path: Page.setDocumentContent Domain: Page Method name: setDocumentContent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'frameId' (type: FrameId) -> Frame id to set HTML for. 'html' (type: string) -> HTML content to set. No return value. ...
Below is the the instruction that describes the task: ### Input: Function path: Page.setDocumentContent Domain: Page Method name: setDocumentContent WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'frameId' (type: FrameId) -> Frame id to set HTML for. ...
def get_event_data(self, read_number=None, time_in_seconds=False): """ Get event data for the specified (or only) read. :param read_number: The read number to grab event data for. If this is None, and there is only one read, it will grab event data for that read. ...
Get event data for the specified (or only) read. :param read_number: The read number to grab event data for. If this is None, and there is only one read, it will grab event data for that read. :param time_in_seconds: If True, this will convert (if necessary) the ...
Below is the the instruction that describes the task: ### Input: Get event data for the specified (or only) read. :param read_number: The read number to grab event data for. If this is None, and there is only one read, it will grab event data for that read. :param ti...
def filterAll(self, **kwargs): ''' filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or...
filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, use "filter" or "filterAnd" on a TagCollection For specia...
Below is the the instruction that describes the task: ### Input: filterAll aka filterAllAnd - Perform a filter operation on ALL nodes in this collection and all their children. Results must match ALL the filter criteria. for ANY, use the *Or methods For just the nodes in this collection, u...
def assignees(self): """List of assignees to the activity.""" if 'assignees' in self._json_data and self._json_data.get('assignees_ids') == list(): return [] elif 'assignees' in self._json_data and self._json_data.get('assignees_ids'): assignees_ids_str = ','.join([str(id...
List of assignees to the activity.
Below is the the instruction that describes the task: ### Input: List of assignees to the activity. ### Response: def assignees(self): """List of assignees to the activity.""" if 'assignees' in self._json_data and self._json_data.get('assignees_ids') == list(): return [] elif 'a...
def load_from_remote(remote_name, owner=None): """ Loads the data from a remote repository. :param remote_name: The name of the dataset in the remote repository :param owner: (optional) The owner of the dataset. If nothing is provided, the current user is used. For public datasets use 'pu...
Loads the data from a remote repository. :param remote_name: The name of the dataset in the remote repository :param owner: (optional) The owner of the dataset. If nothing is provided, the current user is used. For public datasets use 'public'. :return: A new GMQLDataset or a GDataframe
Below is the the instruction that describes the task: ### Input: Loads the data from a remote repository. :param remote_name: The name of the dataset in the remote repository :param owner: (optional) The owner of the dataset. If nothing is provided, the current user is used. For public da...
def on_error_close(logger): """ Decorator for callback methods that implement `IProtocol`. Any uncaught exception is logged and the connection is closed forcefully. Usage:: import logger logger = logging.getLogger(__name__) class MyProtocol(Protocol): ...
Decorator for callback methods that implement `IProtocol`. Any uncaught exception is logged and the connection is closed forcefully. Usage:: import logger logger = logging.getLogger(__name__) class MyProtocol(Protocol): @on_error_close(logger.error) ...
Below is the the instruction that describes the task: ### Input: Decorator for callback methods that implement `IProtocol`. Any uncaught exception is logged and the connection is closed forcefully. Usage:: import logger logger = logging.getLogger(__name__) cla...
def load_data_and_labels(filename, encoding='utf-8'): """Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For exam...
Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. For example: ``` EU B-ORG rejects O G...
Below is the the instruction that describes the task: ### Input: Loads data and label from a file. Args: filename (str): path to the file. encoding (str): file encoding format. The file format is tab-separated values. A blank line is required at the end of a sentence. ...
def setup_logging(fail_silently=False): """ Setup logging configuration Finds the most user-facing log config on disk and uses it """ config = None paths = list(get_config_paths(filename='logconfig.yml', reversed=True)) for path in paths: if not os.path.exists(path): co...
Setup logging configuration Finds the most user-facing log config on disk and uses it
Below is the the instruction that describes the task: ### Input: Setup logging configuration Finds the most user-facing log config on disk and uses it ### Response: def setup_logging(fail_silently=False): """ Setup logging configuration Finds the most user-facing log config on disk and uses it ...
async def update_firmware(request): """ This handler accepts a POST request with Content-Type: multipart/form-data and a file field in the body named "hex". The file should be a valid HEX image to be flashed to the LPC1769. The received file is flashed using lpc21isp, and then deleted and a success ...
This handler accepts a POST request with Content-Type: multipart/form-data and a file field in the body named "hex". The file should be a valid HEX image to be flashed to the LPC1769. The received file is flashed using lpc21isp, and then deleted and a success code is returned.
Below is the the instruction that describes the task: ### Input: This handler accepts a POST request with Content-Type: multipart/form-data and a file field in the body named "hex". The file should be a valid HEX image to be flashed to the LPC1769. The received file is flashed using lpc21isp, and then d...
def indented_script(self) -> bool: ''' check self._script and see if it is indented ''' # get all leading space, tab and newline leading = INDENTED.match(self._script) return 0 if leading is None else len(leading.group(2))
check self._script and see if it is indented
Below is the the instruction that describes the task: ### Input: check self._script and see if it is indented ### Response: def indented_script(self) -> bool: ''' check self._script and see if it is indented ''' # get all leading space, tab and newline leading = INDENTED.match(self._script)...
def glm(interactive=True, echo=True, testing=False): """GLM model demo.""" def demo_body(go): """ Demo of H2O's Generalized Linear Estimator. This demo uploads a dataset to h2o, parses it, and shows a description. Then it divides the dataset into training and test sets, builds ...
GLM model demo.
Below is the the instruction that describes the task: ### Input: GLM model demo. ### Response: def glm(interactive=True, echo=True, testing=False): """GLM model demo.""" def demo_body(go): """ Demo of H2O's Generalized Linear Estimator. This demo uploads a dataset to h2o, parses i...
def _set_name(self, name): """ Sets the name of this asset. :param name: The name of the asset :type name: str """ if self._is_identifier_quoted(name): self._quoted = True name = self._trim_quotes(name) if "." in name: parts =...
Sets the name of this asset. :param name: The name of the asset :type name: str
Below is the the instruction that describes the task: ### Input: Sets the name of this asset. :param name: The name of the asset :type name: str ### Response: def _set_name(self, name): """ Sets the name of this asset. :param name: The name of the asset :type name:...
def reset(ip: str = None, username: str = None) -> int: """ Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. """ attempts = AccessAttempt.objects.all() if ip: attempts = attempts....
Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API.
Below is the the instruction that describes the task: ### Input: Reset records that match IP or username, and return the count of removed attempts. This utility method is meant to be used from the CLI or via Python API. ### Response: def reset(ip: str = None, username: str = None) -> int: """ Reset re...
def _set_selinux_context(self): """ Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException if the command is not present on the system. :return: None """ chcon_command_exists() # FIXME: do this using python API if possible ...
Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException if the command is not present on the system. :return: None
Below is the the instruction that describes the task: ### Input: Set SELinux context or fields using chcon program. Raises CommandDoesNotExistException if the command is not present on the system. :return: None ### Response: def _set_selinux_context(self): """ Set SELinux context o...
def do_start_cluster(self, cluster): """ Start the cluster Usage: > start_cluster <cluster> """ try: cluster = api.get_cluster(cluster) cluster.start() print("Starting Cluster") except ApiException: print("Cluste...
Start the cluster Usage: > start_cluster <cluster>
Below is the the instruction that describes the task: ### Input: Start the cluster Usage: > start_cluster <cluster> ### Response: def do_start_cluster(self, cluster): """ Start the cluster Usage: > start_cluster <cluster> """ try: ...
def matches_factor_conditions(s, env): """"Returns True if py{33, 34} expanded is contained in env.name.""" env_labels = set(env.name.split('-')) labels = set(bash_expand(s)) return bool(labels & env_labels)
Returns True if py{33, 34} expanded is contained in env.name.
Below is the the instruction that describes the task: ### Input: Returns True if py{33, 34} expanded is contained in env.name. ### Response: def matches_factor_conditions(s, env): """"Returns True if py{33, 34} expanded is contained in env.name.""" env_labels = set(env.name.split('-')) labels = set(bas...
def cb(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__cb_url = self.__cb_url.format(ctime=int(time.time())) # 请求数据 rep = requests.get(self.__cb_url) # 获取返回的json字符串 fundjson = json.loads(rep.text) ...
以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元
Below is the the instruction that describes the task: ### Input: 以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 ### Response: def cb(self, min_volume=0): """以字典形式返回QDII数据 :param min_volume:最小交易量,单位万元 """ # 添加当前的ctime self.__cb_url = self.__cb_url.format(ctime=int(time.ti...
def find_records(self, check, keys=None): """Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optio...
Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: list of strs [optional] if specified, the subset of keys to ...
Below is the the instruction that describes the task: ### Input: Find records matching a query dict, optionally extracting subset of keys. Returns dict keyed by msg_id of matching records. Parameters ---------- check: dict mongodb-style query argument keys: lis...
def _apply_with_random_selector(x, func, num_cases): """Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the...
Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func receives the value of the selector as a python integer, but sel is...
Below is the the instruction that describes the task: ### Input: Computes func(x, sel), with sel sampled from [0...num_cases-1]. Args: x: input Tensor. func: Python function to apply. num_cases: Python int32, number of cases to sample sel from. Returns: The result of func(x, sel), where func r...
def add_tag(self, task, params={}, **options): """Adds a tag to a task. Returns an empty data block. Parameters ---------- task : {Id} The task to add a tag to. [data] : {Object} Data for the request - tag : {Id} The tag to add to the task. """ path = ...
Adds a tag to a task. Returns an empty data block. Parameters ---------- task : {Id} The task to add a tag to. [data] : {Object} Data for the request - tag : {Id} The tag to add to the task.
Below is the the instruction that describes the task: ### Input: Adds a tag to a task. Returns an empty data block. Parameters ---------- task : {Id} The task to add a tag to. [data] : {Object} Data for the request - tag : {Id} The tag to add to the task. ### Response: de...
def get_input_spec_patterns(): ''' Extract the inputSpec patterns, if they exist -- modifed from dx-upload-all-outputs Returns a dict of all patterns, with keys equal to the respective input parameter names. ''' input_spec = None if 'DX_JOB_ID' in environ: # works in the cloud, not loca...
Extract the inputSpec patterns, if they exist -- modifed from dx-upload-all-outputs Returns a dict of all patterns, with keys equal to the respective input parameter names.
Below is the the instruction that describes the task: ### Input: Extract the inputSpec patterns, if they exist -- modifed from dx-upload-all-outputs Returns a dict of all patterns, with keys equal to the respective input parameter names. ### Response: def get_input_spec_patterns(): ''' Extract the inp...
def get_url_directory_string(url): """ Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server """ domain = UrlExtractor.get_allowed_domain(url) splitted_url = url.split(...
Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server
Below is the the instruction that describes the task: ### Input: Determines the url's directory string. :param str url: the url to extract the directory string from :return str: the directory string on the server ### Response: def get_url_directory_string(url): """ Determines the u...
def new_pattern(self, id_, name, rows=None): """Create a new knitting pattern. If rows is :obj:`None` it is replaced with the :meth:`new_row_collection`. """ if rows is None: rows = self.new_row_collection() return self._spec.new_pattern(id_, name, rows, self...
Create a new knitting pattern. If rows is :obj:`None` it is replaced with the :meth:`new_row_collection`.
Below is the the instruction that describes the task: ### Input: Create a new knitting pattern. If rows is :obj:`None` it is replaced with the :meth:`new_row_collection`. ### Response: def new_pattern(self, id_, name, rows=None): """Create a new knitting pattern. If rows is :obj:`...
def _get_query_parts(self, query_str, search_options=None): """ Split a query string into its parts """ if search_options is None: search_options = {} if query_str is None: raise NipapValueError("'query_string' must not be None") # find query parts ...
Split a query string into its parts
Below is the the instruction that describes the task: ### Input: Split a query string into its parts ### Response: def _get_query_parts(self, query_str, search_options=None): """ Split a query string into its parts """ if search_options is None: search_options = {} if ...
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Packet(key) if key not in Packet._member_map_: extend_enum(Packet, key, default) return Packet[key]
Backport support for original codes.
Below is the the instruction that describes the task: ### Input: Backport support for original codes. ### Response: def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return Packet(key) if key not in Packet._member_map_: ext...
def initialize(self, *args, **kwargs): """ Call self._initialize with `self` made available to Zipline API functions. """ with ZiplineAPI(self): self._initialize(self, *args, **kwargs)
Call self._initialize with `self` made available to Zipline API functions.
Below is the the instruction that describes the task: ### Input: Call self._initialize with `self` made available to Zipline API functions. ### Response: def initialize(self, *args, **kwargs): """ Call self._initialize with `self` made available to Zipline API functions. """...
def ip_address_delete(session, ifname, ifaddr): """ Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. ...
Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of interface. :param ifaddr: IPv4 or IPv6 address. :return: Instanc...
Below is the the instruction that describes the task: ### Input: Deletes an IP address from interface record identified with the given "ifname". The arguments are similar to "ip address delete" command of iproute2. :param session: Session instance connecting to database. :param ifname: Name of int...
def notification_channel_descriptor_path(cls, project, channel_descriptor): """Return a fully-qualified notification_channel_descriptor string.""" return google.api_core.path_template.expand( "projects/{project}/notificationChannelDescriptors/{channel_descriptor}", project=projec...
Return a fully-qualified notification_channel_descriptor string.
Below is the the instruction that describes the task: ### Input: Return a fully-qualified notification_channel_descriptor string. ### Response: def notification_channel_descriptor_path(cls, project, channel_descriptor): """Return a fully-qualified notification_channel_descriptor string.""" return g...
def remove(self, name): """Remove a transform in the chain.""" cpu_transforms = self._remove_transform(self.cpu_transforms, name) gpu_transforms = self._remove_transform(self.gpu_transforms, name) return (TransformChain().add_on_cpu(cpu_transforms). add_on_gpu(gpu_transfo...
Remove a transform in the chain.
Below is the the instruction that describes the task: ### Input: Remove a transform in the chain. ### Response: def remove(self, name): """Remove a transform in the chain.""" cpu_transforms = self._remove_transform(self.cpu_transforms, name) gpu_transforms = self._remove_transform(self.gpu_...
def insert(self, identified): """ Inserts an already-created identified object of the expected class. """ if not isinstance(identified, self._class): raise self.Error("Passed instance is not of the needed class", self.Error.INVALID_INSTANCE_CLASS...
Inserts an already-created identified object of the expected class.
Below is the the instruction that describes the task: ### Input: Inserts an already-created identified object of the expected class. ### Response: def insert(self, identified): """ Inserts an already-created identified object of the expected class. """ if not isinstance(identified,...
def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. """ try: # get instance id and aws region instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', ...
Returns True if the current instance is the first instance in the ASG group, sorted by instance_id.
Below is the the instruction that describes the task: ### Input: Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. ### Response: def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by ...