code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
text
stringlengths
164
112k
def listFileArray(self): """ API to list files in DBS. Either non-wildcarded logical_file_name, non-wildcarded dataset, non-wildcarded block_name or non-wildcarded lfn list is required. The combination of a non-wildcarded dataset or block_name with an wildcarded logical_file_name is supported....
API to list files in DBS. Either non-wildcarded logical_file_name, non-wildcarded dataset, non-wildcarded block_name or non-wildcarded lfn list is required. The combination of a non-wildcarded dataset or block_name with an wildcarded logical_file_name is supported. * For lumi_list the followi...
Below is the the instruction that describes the task: ### Input: API to list files in DBS. Either non-wildcarded logical_file_name, non-wildcarded dataset, non-wildcarded block_name or non-wildcarded lfn list is required. The combination of a non-wildcarded dataset or block_name with an wildcarded logical...
def _publish_message(self, exchange, routing_key, message, properties): """Publish the message to RabbitMQ :param str exchange: The exchange to publish to :param str routing_key: The routing key to publish with :param str message: The message body :param pika.BasicProperties: Th...
Publish the message to RabbitMQ :param str exchange: The exchange to publish to :param str routing_key: The routing key to publish with :param str message: The message body :param pika.BasicProperties: The message properties
Below is the the instruction that describes the task: ### Input: Publish the message to RabbitMQ :param str exchange: The exchange to publish to :param str routing_key: The routing key to publish with :param str message: The message body :param pika.BasicProperties: The message prop...
def deleteEdge(self, networkId, edgeId, verbose=None): """ Deletes the edge specified by the `edgeId` and `networkId` parameters. :param networkId: SUID of the network containing the edge. :param edgeId: SUID of the edge :param verbose: print more :returns: default: suc...
Deletes the edge specified by the `edgeId` and `networkId` parameters. :param networkId: SUID of the network containing the edge. :param edgeId: SUID of the edge :param verbose: print more :returns: default: successful operation
Below is the the instruction that describes the task: ### Input: Deletes the edge specified by the `edgeId` and `networkId` parameters. :param networkId: SUID of the network containing the edge. :param edgeId: SUID of the edge :param verbose: print more :returns: default: successfu...
def expand_source_files(filenames, cwd=None): """Expand a list of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. Any files tha...
Expand a list of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. Any files that do not end with ".py" will be dropped. Args: ...
Below is the the instruction that describes the task: ### Input: Expand a list of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. ...
def known_context_patterns(self, val): ''' val must be an ArticleContextPattern, a dictionary, or list of \ dictionaries e.g., {'attr': 'class', 'value': 'my-article-class'} or [{'attr': 'class', 'value': 'my-article-class'}, {'attr': 'id', 'value': 'm...
val must be an ArticleContextPattern, a dictionary, or list of \ dictionaries e.g., {'attr': 'class', 'value': 'my-article-class'} or [{'attr': 'class', 'value': 'my-article-class'}, {'attr': 'id', 'value': 'my-article-id'}]
Below is the the instruction that describes the task: ### Input: val must be an ArticleContextPattern, a dictionary, or list of \ dictionaries e.g., {'attr': 'class', 'value': 'my-article-class'} or [{'attr': 'class', 'value': 'my-article-class'}, {'attr':...
def load_segment(self, f, is_irom_segment=False): """ Load the next segment from the image file """ file_offs = f.tell() (offset, size) = struct.unpack('<II', f.read(8)) self.warn_if_unusual_segment(offset, size, is_irom_segment) segment_data = f.read(size) if len(segment...
Load the next segment from the image file
Below is the the instruction that describes the task: ### Input: Load the next segment from the image file ### Response: def load_segment(self, f, is_irom_segment=False): """ Load the next segment from the image file """ file_offs = f.tell() (offset, size) = struct.unpack('<II', f.read(8)) ...
def is_valid(self): """ Tests if the dependency is in a valid state """ return super(SimpleDependency, self).is_valid() or ( self.requirement.immediate_rebind and self._pending_ref is not None )
Tests if the dependency is in a valid state
Below is the the instruction that describes the task: ### Input: Tests if the dependency is in a valid state ### Response: def is_valid(self): """ Tests if the dependency is in a valid state """ return super(SimpleDependency, self).is_valid() or ( self.requirement.immedi...
def sanitize_loginurl (self): """Make login configuration consistent.""" url = self["loginurl"] disable = False if not self["loginpasswordfield"]: log.warn(LOG_CHECK, _("no CGI password fieldname given for login URL.")) disable = True if not se...
Make login configuration consistent.
Below is the the instruction that describes the task: ### Input: Make login configuration consistent. ### Response: def sanitize_loginurl (self): """Make login configuration consistent.""" url = self["loginurl"] disable = False if not self["loginpasswordfield"]: log.warn...
def as_minimized(values: List[float], maximized: List[bool]) -> List[float]: """ Return vector values as minimized """ return [v * -1. if m else v for v, m in zip(values, maximized)]
Return vector values as minimized
Below is the the instruction that describes the task: ### Input: Return vector values as minimized ### Response: def as_minimized(values: List[float], maximized: List[bool]) -> List[float]: """ Return vector values as minimized """ return [v * -1. if m else v for v, m in zip(values, maximized)]
def set_project_status(project_id, status, **kwargs): """ Set the status of a project to 'X' """ user_id = kwargs.get('user_id') #check_perm(user_id, 'delete_project') project = _get_project(project_id) project.check_write_permission(user_id) project.status = status db.DBSession....
Set the status of a project to 'X'
Below is the the instruction that describes the task: ### Input: Set the status of a project to 'X' ### Response: def set_project_status(project_id, status, **kwargs): """ Set the status of a project to 'X' """ user_id = kwargs.get('user_id') #check_perm(user_id, 'delete_project') proje...
def multi_post(self, urls, query_params=None, data=None, to_json=True, send_as_file=False): """Issue multiple POST requests. Args: urls - A string URL or list of string URLs query_params - None, a dict, or a list of dicts representing the query params data - None, a ...
Issue multiple POST requests. Args: urls - A string URL or list of string URLs query_params - None, a dict, or a list of dicts representing the query params data - None, a dict or string, or a list of dicts and strings representing the data body. to_json - A bool...
Below is the the instruction that describes the task: ### Input: Issue multiple POST requests. Args: urls - A string URL or list of string URLs query_params - None, a dict, or a list of dicts representing the query params data - None, a dict or string, or a list of dicts...
def getdrawings(): """Get all the drawings.""" infos = Info.query.all() sketches = [json.loads(info.contents) for info in infos] return jsonify(drawings=sketches)
Get all the drawings.
Below is the the instruction that describes the task: ### Input: Get all the drawings. ### Response: def getdrawings(): """Get all the drawings.""" infos = Info.query.all() sketches = [json.loads(info.contents) for info in infos] return jsonify(drawings=sketches)
async def _on_trace_notification(self, trace_event): """Callback function called when a trace chunk is received. Args: trace_chunk (dict): The received trace chunk information """ conn_string = trace_event.get('connection_string') payload = trace_event.get('payload'...
Callback function called when a trace chunk is received. Args: trace_chunk (dict): The received trace chunk information
Below is the the instruction that describes the task: ### Input: Callback function called when a trace chunk is received. Args: trace_chunk (dict): The received trace chunk information ### Response: async def _on_trace_notification(self, trace_event): """Callback function called when a...
def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. """ click.echo("Resetting OpenPGP data, don't remove your YubiKey...") ctx.obj['controller'].reset() click.echo('Success! All data has been cleared and defaul...
Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values.
Below is the the instruction that describes the task: ### Input: Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. ### Response: def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs t...
def fetch_existing_token_of_user(self, client_id, grant_type, user_id): """ Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The ident...
Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the access token has been issued to. :ret...
Below is the the instruction that describes the task: ### Input: Retrieve an access token issued to a client and user for a specific grant. :param client_id: The identifier of a client as a `str`. :param grant_type: The type of grant. :param user_id: The identifier of the user the a...
def load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """ o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) if not schema_only: a._filename = filename o.close() return a
Load an ARFF File from a file.
Below is the the instruction that describes the task: ### Input: Load an ARFF File from a file. ### Response: def load(cls, filename, schema_only=False): """ Load an ARFF File from a file. """ o = open(filename) s = o.read() a = cls.parse(s, schema_only=schema_only) ...
def del_repo(repo, **kwargs): ''' Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo passed in must be a fully fo...
Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo passed in must be a fully formed repository definition string. ...
Below is the the instruction that describes the task: ### Input: Delete a repo from the sources.list / sources.list.d If the .list file is in the sources.list.d directory and the file that the repo exists in does not contain any other repo configuration, the file itself will be deleted. The repo p...
def _squeeze(self, var_tbl: dict) -> dict: """ Makes sure no extra dimensions are floating around in the input arrays Returns inferred dict of variable: val pairs """ var_names = var_tbl.copy() # squeeze any numpy arrays for v in var_tbl: val = var_tbl...
Makes sure no extra dimensions are floating around in the input arrays Returns inferred dict of variable: val pairs
Below is the the instruction that describes the task: ### Input: Makes sure no extra dimensions are floating around in the input arrays Returns inferred dict of variable: val pairs ### Response: def _squeeze(self, var_tbl: dict) -> dict: """ Makes sure no extra dimensions are floating aroun...
def _get_ns(self, reply): '''_get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap. ''' def get_prefix(...
_get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap.
Below is the the instruction that describes the task: ### Input: _get_ns Low-level api: Return a dict of nsmap. Parameters ---------- reply : `Element` rpc-reply as an instance of Element. Returns ------- dict A dict of nsmap. ### ...
def SCISetStylingEx(self, line: int, col: int, style: bytearray): """ Pythonic wrapper for the SCI_SETSTYLINGEX command. For example, the following code will fetch the styling for the first five characters applies it verbatim to the next five characters. text, style = SCIGe...
Pythonic wrapper for the SCI_SETSTYLINGEX command. For example, the following code will fetch the styling for the first five characters applies it verbatim to the next five characters. text, style = SCIGetStyledText((0, 0, 0, 5)) SCISetStylingEx((0, 5), style) |Args| ...
Below is the the instruction that describes the task: ### Input: Pythonic wrapper for the SCI_SETSTYLINGEX command. For example, the following code will fetch the styling for the first five characters applies it verbatim to the next five characters. text, style = SCIGetStyledText((0, 0...
def update_parser(self, parser): """Update config dictionary with declared arguments in an argparse.parser New variables will be created, and existing ones overridden. Args: parser (argparse.ArgumentParser): parser to read variables from """ self._parser = parser ...
Update config dictionary with declared arguments in an argparse.parser New variables will be created, and existing ones overridden. Args: parser (argparse.ArgumentParser): parser to read variables from
Below is the the instruction that describes the task: ### Input: Update config dictionary with declared arguments in an argparse.parser New variables will be created, and existing ones overridden. Args: parser (argparse.ArgumentParser): parser to read variables from ### Response: def u...
def _decode_value(self, value): """ Decodes the value by turning any binary data back into Python objects. The method searches for ObjectId values, loads the associated binary data from GridFS and returns the decoded Python object. Args: value (object): The value that shoul...
Decodes the value by turning any binary data back into Python objects. The method searches for ObjectId values, loads the associated binary data from GridFS and returns the decoded Python object. Args: value (object): The value that should be decoded. Raises: D...
Below is the the instruction that describes the task: ### Input: Decodes the value by turning any binary data back into Python objects. The method searches for ObjectId values, loads the associated binary data from GridFS and returns the decoded Python object. Args: value (obje...
def deserialize(self): """Turns a sequence of bytes into a message dictionary.""" if self.msgbytes is None: raise LLRPError('No message bytes to deserialize.') data = self.msgbytes msgtype, length, msgid = struct.unpack(self.full_hdr_fmt, ...
Turns a sequence of bytes into a message dictionary.
Below is the the instruction that describes the task: ### Input: Turns a sequence of bytes into a message dictionary. ### Response: def deserialize(self): """Turns a sequence of bytes into a message dictionary.""" if self.msgbytes is None: raise LLRPError('No message bytes to deserializ...
def set_index(self, index): """Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None """ item = index.internalPointer() note = item.internal_data() se...
Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None
Below is the the instruction that describes the task: ### Input: Display the data of the given index :param index: the index to paint :type index: QtCore.QModelIndex :returns: None :rtype: None :raises: None ### Response: def set_index(self, index): """Display the d...
def format_general_name(name): """Format a single general name. >>> import ipaddress >>> format_general_name(x509.DNSName('example.com')) 'DNS:example.com' >>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1'))) 'IP:127.0.0.1' """ if isinstance(name, x509.DirectoryN...
Format a single general name. >>> import ipaddress >>> format_general_name(x509.DNSName('example.com')) 'DNS:example.com' >>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1'))) 'IP:127.0.0.1'
Below is the the instruction that describes the task: ### Input: Format a single general name. >>> import ipaddress >>> format_general_name(x509.DNSName('example.com')) 'DNS:example.com' >>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1'))) 'IP:127.0.0.1' ### Response: de...
def refresh_existing_encodings(self, encodings_from_file): """ Refresh existing encodings for messages, when encoding was changed by user in dialog :return: """ update = False for msg in self.table_model.protocol.messages: i = next((i for i, d in enumerate(e...
Refresh existing encodings for messages, when encoding was changed by user in dialog :return:
Below is the the instruction that describes the task: ### Input: Refresh existing encodings for messages, when encoding was changed by user in dialog :return: ### Response: def refresh_existing_encodings(self, encodings_from_file): """ Refresh existing encodings for messages, when encoding...
def _convert_type(self, data_type): ''' CDF data types to python struct data types ''' if (data_type == 1) or (data_type == 41): dt_string = 'b' elif data_type == 2: dt_string = 'h' elif data_type == 4: dt_string = 'i' elif (dat...
CDF data types to python struct data types
Below is the the instruction that describes the task: ### Input: CDF data types to python struct data types ### Response: def _convert_type(self, data_type): ''' CDF data types to python struct data types ''' if (data_type == 1) or (data_type == 41): dt_string = 'b' ...
def add_tab_stop(self, position, alignment=WD_TAB_ALIGNMENT.LEFT, leader=WD_TAB_LEADER.SPACES): """ Add a new tab stop at *position*, a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative *position* value is valid and ap...
Add a new tab stop at *position*, a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative *position* value is valid and appears in hanging indentation. Tab alignment defaults to left, but may be specified by passing a member of the :ref:`WdTab...
Below is the the instruction that describes the task: ### Input: Add a new tab stop at *position*, a |Length| object specifying the location of the tab stop relative to the paragraph edge. A negative *position* value is valid and appears in hanging indentation. Tab alignment defaults to left...
def execute_query(self, payload): '''Execute the query and returns and response''' if vars(self).get('oauth'): if not self.oauth.token_is_valid(): # Refresh token if token has expired self.oauth.refresh_token() response = self.oauth.session.get(self.PRIVATE_URL, p...
Execute the query and returns and response
Below is the the instruction that describes the task: ### Input: Execute the query and returns and response ### Response: def execute_query(self, payload): '''Execute the query and returns and response''' if vars(self).get('oauth'): if not self.oauth.token_is_valid(): # Refresh token if...
def delete_network(self, name, tenant_id, subnet_id, net_id): """Delete the openstack subnet and network. """ try: self.neutronclient.delete_subnet(subnet_id) except Exception as exc: LOG.error("Failed to delete subnet %(sub)s exc %(exc)s", {'sub': s...
Delete the openstack subnet and network.
Below is the the instruction that describes the task: ### Input: Delete the openstack subnet and network. ### Response: def delete_network(self, name, tenant_id, subnet_id, net_id): """Delete the openstack subnet and network. """ try: self.neutronclient.delete_subnet(subnet_id) ...
def off(self, dev_id): """Turn OFF all features of the device. schedules, weather intelligence, water budget, etc. """ path = 'device/off' payload = {'id': dev_id} return self.rachio.put(path, payload)
Turn OFF all features of the device. schedules, weather intelligence, water budget, etc.
Below is the the instruction that describes the task: ### Input: Turn OFF all features of the device. schedules, weather intelligence, water budget, etc. ### Response: def off(self, dev_id): """Turn OFF all features of the device. schedules, weather intelligence, water budget, etc. ...
def get_level_fmt(self, level): """Get format for log level.""" key = None if level == logging.DEBUG: key = 'debug' elif level == logging.INFO: key = 'info' elif level == logging.WARNING: key = 'warning' elif level == logging.ERROR: ...
Get format for log level.
Below is the the instruction that describes the task: ### Input: Get format for log level. ### Response: def get_level_fmt(self, level): """Get format for log level.""" key = None if level == logging.DEBUG: key = 'debug' elif level == logging.INFO: key = 'inf...
def _set_properties(self, api_response): """Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call """ job_id_present = ( "jobReference" in api_response and "jobId" in a...
Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call
Below is the the instruction that describes the task: ### Input: Update properties from resource in body of ``api_response`` :type api_response: dict :param api_response: response returned from an API call ### Response: def _set_properties(self, api_response): """Update properties from res...
def AddForwardedIp(self, address, interface): """Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. """ for ip in list(netaddr.IPNetwork(address)): self._RunIfconfig(args=[interface, 'al...
Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use.
Below is the the instruction that describes the task: ### Input: Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. ### Response: def AddForwardedIp(self, address, interface): """Configure a new ...
def get_changeform_initial_data(self, request): '''Copy initial data from parent''' initial = super(PageAdmin, self).get_changeform_initial_data(request) if ('translation_of' in request.GET): original = self.model._tree_manager.get( pk=request.GET.get('translation_of'...
Copy initial data from parent
Below is the the instruction that describes the task: ### Input: Copy initial data from parent ### Response: def get_changeform_initial_data(self, request): '''Copy initial data from parent''' initial = super(PageAdmin, self).get_changeform_initial_data(request) if ('translation_of' in requ...
def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debug', log_callback=None, runas=None, group=None, shell=DEFAULT_SHELL, python_shell=False, ...
Do the DRY thing and only call subprocess.Popen() once
Below is the the instruction that describes the task: ### Input: Do the DRY thing and only call subprocess.Popen() once ### Response: def _run(cmd, cwd=None, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE, output_encoding=None, output_loglevel='debu...
def cli(env, name, public): """List images.""" image_mgr = SoftLayer.ImageManager(env.client) images = [] if public in [False, None]: for image in image_mgr.list_private_images(name=name, mask=image_mod.MASK): images.append(image) ...
List images.
Below is the the instruction that describes the task: ### Input: List images. ### Response: def cli(env, name, public): """List images.""" image_mgr = SoftLayer.ImageManager(env.client) images = [] if public in [False, None]: for image in image_mgr.list_private_images(name=name, ...
def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): row[i] = row[i].isoformat() return tuple(row)
Receives a row, converts datetimes to strings.
Below is the the instruction that describes the task: ### Input: Receives a row, converts datetimes to strings. ### Response: def _reduce_datetimes(row): """Receives a row, converts datetimes to strings.""" row = list(row) for i in range(len(row)): if hasattr(row[i], 'isoformat'): ...
def qn(tag): """ Stands for "qualified name", a utility function to turn a namespace prefixed tag name into a Clark-notation qualified tag name for lxml. For example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``. """ prefix, tagroot = tag.split(':') uri = nsmap[prefix] ret...
Stands for "qualified name", a utility function to turn a namespace prefixed tag name into a Clark-notation qualified tag name for lxml. For example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``.
Below is the the instruction that describes the task: ### Input: Stands for "qualified name", a utility function to turn a namespace prefixed tag name into a Clark-notation qualified tag name for lxml. For example, ``qn('p:cSld')`` returns ``'{http://schemas.../main}cSld'``. ### Response: def qn(tag): ...
def get_by_name(self, name, clip_to_valid = False): """ Retrieve the active segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. All segmentlist objects within it will be copies of the contents of this object, modifications will not affect the contents of this object....
Retrieve the active segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. All segmentlist objects within it will be copies of the contents of this object, modifications will not affect the contents of this object. If clip_to_valid is True then the segmentlists will be i...
Below is the the instruction that describes the task: ### Input: Retrieve the active segmentlists whose name equals name. The result is a segmentlistdict indexed by instrument. All segmentlist objects within it will be copies of the contents of this object, modifications will not affect the contents of thi...
def validate_dict(in_dict, **kwargs): """ Returns Boolean of whether given dict conforms to type specifications given in kwargs. """ if not isinstance(in_dict, dict): raise ValueError('requires a dictionary') for key, value in kwargs.iteritems(): if key == 'required': for ...
Returns Boolean of whether given dict conforms to type specifications given in kwargs.
Below is the the instruction that describes the task: ### Input: Returns Boolean of whether given dict conforms to type specifications given in kwargs. ### Response: def validate_dict(in_dict, **kwargs): """ Returns Boolean of whether given dict conforms to type specifications given in kwargs. """ ...
def add_bias(self, name, b, input_name, output_name, shape_bias = [1]): """ Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The...
Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The input blob name of this layer. output_name: str The output blob name of...
Below is the the instruction that describes the task: ### Input: Add bias layer to the model. Parameters ---------- name: str The name of this layer. b: int | numpy.array Bias to add to the input. input_name: str The input blob name of thi...
def sh(self, *command, **kwargs): """Run a shell command with the given arguments.""" self.log.debug('shell: %s', ' '.join(command)) return subprocess.check_call(' '.join(command), stdout=sys.stdout, stderr=sys.stderr, ...
Run a shell command with the given arguments.
Below is the the instruction that describes the task: ### Input: Run a shell command with the given arguments. ### Response: def sh(self, *command, **kwargs): """Run a shell command with the given arguments.""" self.log.debug('shell: %s', ' '.join(command)) return subprocess.check_call(' '....
def getLogger(name=None, **kwargs): """Build a logger with the given name. :param name: The name for the logger. This is usually the module name, ``__name__``. :type name: string """ adapter = _LOGGERS.get(name) if not adapter: # NOTE(jd) Keep using the `adapter' variab...
Build a logger with the given name. :param name: The name for the logger. This is usually the module name, ``__name__``. :type name: string
Below is the the instruction that describes the task: ### Input: Build a logger with the given name. :param name: The name for the logger. This is usually the module name, ``__name__``. :type name: string ### Response: def getLogger(name=None, **kwargs): """Build a logger with the giv...
def release_client(self, cb): """ Return a Connection object to the pool :param Connection cb: the client to release """ if cb: self._q.put(cb, True) self._clients_in_use -= 1
Return a Connection object to the pool :param Connection cb: the client to release
Below is the the instruction that describes the task: ### Input: Return a Connection object to the pool :param Connection cb: the client to release ### Response: def release_client(self, cb): """ Return a Connection object to the pool :param Connection cb: the client to release ...
def wrap_lines(content, length=80): """Wraps long lines to a maximum length of 80. :param content: the content to wrap. :param legnth: the maximum length to wrap the content. :type content: str :type length: int :returns: a string containing the wrapped content. :rtype: str """ r...
Wraps long lines to a maximum length of 80. :param content: the content to wrap. :param legnth: the maximum length to wrap the content. :type content: str :type length: int :returns: a string containing the wrapped content. :rtype: str
Below is the the instruction that describes the task: ### Input: Wraps long lines to a maximum length of 80. :param content: the content to wrap. :param legnth: the maximum length to wrap the content. :type content: str :type length: int :returns: a string containing the wrapped content. ...
def write(self, default: bool=False): """Restore B6/M8 entry to original format Args: default (bool): output entry in default BLAST+ B6 format Returns: str: properly formatted string containing the B6/M8 entry """ none_type = type(None) if def...
Restore B6/M8 entry to original format Args: default (bool): output entry in default BLAST+ B6 format Returns: str: properly formatted string containing the B6/M8 entry
Below is the the instruction that describes the task: ### Input: Restore B6/M8 entry to original format Args: default (bool): output entry in default BLAST+ B6 format Returns: str: properly formatted string containing the B6/M8 entry ### Response: def write(self, default:...
def write_uint64(self, value, little_endian=True): """ Pack the value as an unsigned integer and write 8 bytes to the stream. Args: value: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes writte...
Pack the value as an unsigned integer and write 8 bytes to the stream. Args: value: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes written.
Below is the the instruction that describes the task: ### Input: Pack the value as an unsigned integer and write 8 bytes to the stream. Args: value: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes written....
def get_teams_of_org(self): """ Retrieves the number of teams of the organization. """ print 'Getting teams.' counter = 0 for team in self.org_retrieved.iter_teams(): self.teams_json[team.id] = team.to_json() counter += 1 return counter
Retrieves the number of teams of the organization.
Below is the the instruction that describes the task: ### Input: Retrieves the number of teams of the organization. ### Response: def get_teams_of_org(self): """ Retrieves the number of teams of the organization. """ print 'Getting teams.' counter = 0 for team in sel...
def load(self, config, file_object, prefer=None): """ An abstract method that loads from a given file object. :param class config: The config class to load into :param file file_object: The file object to load from :param str prefer: The preferred serialization module name :retu...
An abstract method that loads from a given file object. :param class config: The config class to load into :param file file_object: The file object to load from :param str prefer: The preferred serialization module name :returns: A dictionary converted from the content of the given file...
Below is the the instruction that describes the task: ### Input: An abstract method that loads from a given file object. :param class config: The config class to load into :param file file_object: The file object to load from :param str prefer: The preferred serialization module name ...
def show(): """ Show the modifiers and colors """ # modifiers sys.stdout.write(colorful.bold('bold') + ' ') sys.stdout.write(colorful.dimmed('dimmed') + ' ') sys.stdout.write(colorful.italic('italic') + ' ') sys.stdout.write(colorful.underlined('underlined') + ' ') sys.stdout.write(c...
Show the modifiers and colors
Below is the the instruction that describes the task: ### Input: Show the modifiers and colors ### Response: def show(): """ Show the modifiers and colors """ # modifiers sys.stdout.write(colorful.bold('bold') + ' ') sys.stdout.write(colorful.dimmed('dimmed') + ' ') sys.stdout.write(col...
def save_json(self, frames): """ Saves frames data into a json file at the specified json_path, named with the widget uuid. """ if self.json_save_path is None: return path = os.path.join(self.json_save_path, '%s.json' % self.id) if not os.path.isdir(self.json_save...
Saves frames data into a json file at the specified json_path, named with the widget uuid.
Below is the the instruction that describes the task: ### Input: Saves frames data into a json file at the specified json_path, named with the widget uuid. ### Response: def save_json(self, frames): """ Saves frames data into a json file at the specified json_path, named with the wi...
def _send_command(self, command): """ Send a command to the Chromecast on media channel. """ if self.status is None or self.status.media_session_id is None: self.logger.warning( "%s command requested but no session is active.", command[MESSAGE_TYPE]) ...
Send a command to the Chromecast on media channel.
Below is the the instruction that describes the task: ### Input: Send a command to the Chromecast on media channel. ### Response: def _send_command(self, command): """ Send a command to the Chromecast on media channel. """ if self.status is None or self.status.media_session_id is None: ...
def namedtuple_row_strategy(column_names): """ Namedtuple row strategy, rows returned as named tuples Column names that are not valid Python identifiers will be replaced with col<number>_ """ import collections # replace empty column names with placeholders column_names = [name if is_valid_...
Namedtuple row strategy, rows returned as named tuples Column names that are not valid Python identifiers will be replaced with col<number>_
Below is the the instruction that describes the task: ### Input: Namedtuple row strategy, rows returned as named tuples Column names that are not valid Python identifiers will be replaced with col<number>_ ### Response: def namedtuple_row_strategy(column_names): """ Namedtuple row strategy, rows retur...
def validate(self, value): """Validate field value.""" if value is not None and not isinstance(value, bool): raise ValidationError("field must be a boolean") super().validate(value)
Validate field value.
Below is the the instruction that describes the task: ### Input: Validate field value. ### Response: def validate(self, value): """Validate field value.""" if value is not None and not isinstance(value, bool): raise ValidationError("field must be a boolean") super().validate(va...
def get_file_type(self, abs_real_path_and_basename, _cache_file_type=_CACHE_FILE_TYPE): ''' :param abs_real_path_and_basename: The result from get_abs_path_real_path_and_base_from_file or get_abs_path_real_path_and_base_from_frame. :return _pydevd_bundle.pyde...
:param abs_real_path_and_basename: The result from get_abs_path_real_path_and_base_from_file or get_abs_path_real_path_and_base_from_frame. :return _pydevd_bundle.pydevd_dont_trace_files.PYDEV_FILE: If it's a file internal to the debugger which shouldn't be ...
Below is the the instruction that describes the task: ### Input: :param abs_real_path_and_basename: The result from get_abs_path_real_path_and_base_from_file or get_abs_path_real_path_and_base_from_frame. :return _pydevd_bundle.pydevd_dont_trace_files.PYDEV_FILE: ...
def _updateFrame(self): """ Updates the frame for the given sender. """ for col, mov in self._movies.items(): self.setIcon(col, QtGui.QIcon(mov.currentPixmap()))
Updates the frame for the given sender.
Below is the the instruction that describes the task: ### Input: Updates the frame for the given sender. ### Response: def _updateFrame(self): """ Updates the frame for the given sender. """ for col, mov in self._movies.items(): self.setIcon(col, QtGui.QIcon(mov.cur...
def max_date(self, symbol): """ Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item """ res = self._collection.find_one({SYMBOL: symbol}, projection={ID: 0, END: 1}, ...
Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item
Below is the the instruction that describes the task: ### Input: Return the maximum datetime stored for a particular symbol Parameters ---------- symbol : `str` symbol name for the item ### Response: def max_date(self, symbol): """ Return the maximum datetime st...
def start_blocking(self): """ Start the advertiser in the background, but wait until it is ready """ self._cav_started.clear() self.start() self._cav_started.wait()
Start the advertiser in the background, but wait until it is ready
Below is the the instruction that describes the task: ### Input: Start the advertiser in the background, but wait until it is ready ### Response: def start_blocking(self): """ Start the advertiser in the background, but wait until it is ready """ self._cav_started.clear() self.start() ...
def genome_coverage(genomes, scaffold_coverage, total_bases): """ coverage = (number of bases / length of genome) * 100 """ coverage = {} custom = {} std = {} for genome in genomes: for sequence in parse_fasta(genome): scaffold = sequence[0].split('>')[1].split()[0] coverage, std = sum_coverage(coverage,...
coverage = (number of bases / length of genome) * 100
Below is the the instruction that describes the task: ### Input: coverage = (number of bases / length of genome) * 100 ### Response: def genome_coverage(genomes, scaffold_coverage, total_bases): """ coverage = (number of bases / length of genome) * 100 """ coverage = {} custom = {} std = {} for genome in ge...
def get_hardware(self, hardware_id, **kwargs): """Get details about a hardware device. :param integer id: the hardware ID :returns: A dictionary containing a large amount of information about the specified server. Example:: object_mask = "mask[id,networkV...
Get details about a hardware device. :param integer id: the hardware ID :returns: A dictionary containing a large amount of information about the specified server. Example:: object_mask = "mask[id,networkVlans[vlanNumber]]" # Object masks are optional...
Below is the the instruction that describes the task: ### Input: Get details about a hardware device. :param integer id: the hardware ID :returns: A dictionary containing a large amount of information about the specified server. Example:: object_mask = "mask[...
def get_redirect_url(self, url, encrypt_code, card_id): """ 获取卡券跳转外链 """ from wechatpy.utils import WeChatSigner code = self.decrypt_code(encrypt_code) signer = WeChatSigner() signer.add_data(self.secret) signer.add_data(code) signer.add_data(car...
获取卡券跳转外链
Below is the the instruction that describes the task: ### Input: 获取卡券跳转外链 ### Response: def get_redirect_url(self, url, encrypt_code, card_id): """ 获取卡券跳转外链 """ from wechatpy.utils import WeChatSigner code = self.decrypt_code(encrypt_code) signer = WeChatSigner() ...
def process_tomography_set(meas_qubits, meas_basis='Pauli', prep_qubits=None, prep_basis='SIC'): """ Generate a dictionary of process tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state and process t...
Generate a dictionary of process tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state and process tomography circuits, and extract tomography data from results after execution on a backend. A quantum process tomography set is c...
Below is the the instruction that describes the task: ### Input: Generate a dictionary of process tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state and process tomography circuits, and extract tomography data from results af...
def connect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None: '''Connect to a device via TCP/IP directly.''' self.device_sn = f'{host}:{port}' if not is_connectable(host, port): raise ConnectionError(f'Cannot connect to {self.device_sn}.') self._execute(...
Connect to a device via TCP/IP directly.
Below is the the instruction that describes the task: ### Input: Connect to a device via TCP/IP directly. ### Response: def connect(self, host: str = '192.168.0.3', port: Union[int, str] = 5555) -> None: '''Connect to a device via TCP/IP directly.''' self.device_sn = f'{host}:{port}' if not...
def simplex(x, rho): """ Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf """ # sort the elements in descending order u = np.flipud(np.sort(x.ravel())) lambdas = (1 - np.cumsum(u)) / (1. + np.arange(u.size)) ix = np.where(u + lambdas > 0)[0].max() return...
Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf
Below is the the instruction that describes the task: ### Input: Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf ### Response: def simplex(x, rho): """ Projection onto the probability simplex http://arxiv.org/pdf/1309.1541v1.pdf """ # sort the elements in des...
def read_coils(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 01: Read Coils. :param slave_id: Number of slave. :return: Byte array with ADU. """ function = ReadCoils() function.starting_address = starting_address function.quantity = quantity return _cre...
Return ADU for Modbus function code 01: Read Coils. :param slave_id: Number of slave. :return: Byte array with ADU.
Below is the the instruction that describes the task: ### Input: Return ADU for Modbus function code 01: Read Coils. :param slave_id: Number of slave. :return: Byte array with ADU. ### Response: def read_coils(slave_id, starting_address, quantity): """ Return ADU for Modbus function code 01: Read Coil...
def parse_output(host, output): """Parse the output of the dump tool and print warnings or error messages accordingly. :param host: the source :type host: str :param output: the output of the script on host :type output: list of str """ current_file = None for line in output.readlin...
Parse the output of the dump tool and print warnings or error messages accordingly. :param host: the source :type host: str :param output: the output of the script on host :type output: list of str
Below is the the instruction that describes the task: ### Input: Parse the output of the dump tool and print warnings or error messages accordingly. :param host: the source :type host: str :param output: the output of the script on host :type output: list of str ### Response: def parse_output(...
def send_to_back(self): """adjusts sprite's z-order so that the sprite is behind it's siblings""" if not self.parent: return self.z_order = self.parent._z_ordered_sprites[0].z_order - 1
adjusts sprite's z-order so that the sprite is behind it's siblings
Below is the the instruction that describes the task: ### Input: adjusts sprite's z-order so that the sprite is behind it's siblings ### Response: def send_to_back(self): """adjusts sprite's z-order so that the sprite is behind it's siblings""" if not self.parent: return...
def merge_extinfo(host, extinfo): """Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None ...
Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo :return: None
Below is the the instruction that describes the task: ### Input: Merge extended host information into a host :param host: the host to edit :type host: alignak.objects.host.Host :param extinfo: the external info we get data from :type extinfo: alignak.objects.hostextinfo.HostExtInfo ...
def get_log_tag(process_name): """method returns tag that all messages will be preceded with""" process_obj = context.process_context[process_name] if isinstance(process_obj, FreerunProcessEntry): return str(process_obj.token) elif isinstance(process_obj, ManagedProcessEntry): return str...
method returns tag that all messages will be preceded with
Below is the the instruction that describes the task: ### Input: method returns tag that all messages will be preceded with ### Response: def get_log_tag(process_name): """method returns tag that all messages will be preceded with""" process_obj = context.process_context[process_name] if isinstance(pro...
def get_normalized_elevation_array(world): ''' Convert raw elevation into normalized values between 0 and 255, and return a numpy array of these values ''' e = world.layers['elevation'].data ocean = world.layers['ocean'].data mask = numpy.ma.array(e, mask=ocean) # only land min_elev_land ...
Convert raw elevation into normalized values between 0 and 255, and return a numpy array of these values
Below is the the instruction that describes the task: ### Input: Convert raw elevation into normalized values between 0 and 255, and return a numpy array of these values ### Response: def get_normalized_elevation_array(world): ''' Convert raw elevation into normalized values between 0 and 255, ...
def load_graphdef(model_url, reset_device=True): """Load GraphDef from a binary proto file.""" graph_def = load(model_url) if reset_device: for n in graph_def.node: n.device = "" return graph_def
Load GraphDef from a binary proto file.
Below is the the instruction that describes the task: ### Input: Load GraphDef from a binary proto file. ### Response: def load_graphdef(model_url, reset_device=True): """Load GraphDef from a binary proto file.""" graph_def = load(model_url) if reset_device: for n in graph_def.node: n.device = "" ...
def get_header(self, service_id, version_number, name): """Retrieves a Header object by name.""" content = self._fetch("/service/%s/version/%d/header/%s" % (service_id, version_number, name)) return FastlyHeader(self, content)
Retrieves a Header object by name.
Below is the the instruction that describes the task: ### Input: Retrieves a Header object by name. ### Response: def get_header(self, service_id, version_number, name): """Retrieves a Header object by name.""" content = self._fetch("/service/%s/version/%d/header/%s" % (service_id, version_number, name)) ret...
def _write_newick_internal_label(out, node_id, node, otu_group, label_key, needs_quotes_pattern): """`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list...
`label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. The list will hold the order encountered, and the dict...
Below is the the instruction that describes the task: ### Input: `label_key` is a string (a key in the otu object) or a callable that takes two arguments: the node, and the otu (which may be None for an internal node) If `leaf_labels` is not None, it shoulr be a (list, dict) pair which will be filled. T...
def ohlcDF(symbol, token='', version=''): '''Returns the official open and close for a give symbol. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: ...
Returns the official open and close for a give symbol. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version Returns: DataFrame: result
Below is the the instruction that describes the task: ### Input: Returns the official open and close for a give symbol. https://iexcloud.io/docs/api/#news 9:30am-5pm ET Mon-Fri Args: symbol (string); Ticker to request token (string); Access token version (string); API version ...
def energy_minimize(dirname='em', mdp=config.templates['em.mdp'], struct='solvate/ionized.gro', top='top/system.top', output='em.pdb', deffnm="em", mdrunner=None, mdrun_args=None, **kwargs): """Energy minimize the system. This sets...
Energy minimize the system. This sets up the system (creates run input files) and also runs ``mdrun_d``. Thus it can take a while. Additional itp files should be in the same directory as the top file. Many of the keyword arguments below already have sensible values. :Keywords: *dirname* ...
Below is the the instruction that describes the task: ### Input: Energy minimize the system. This sets up the system (creates run input files) and also runs ``mdrun_d``. Thus it can take a while. Additional itp files should be in the same directory as the top file. Many of the keyword arguments b...
def main(args=None): """Script body.""" if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() fasta_file = args.fasta_file species = args.species chrom_pat = args.chromosome_pattern output_file = args.output_file ...
Script body.
Below is the the instruction that describes the task: ### Input: Script body. ### Response: def main(args=None): """Script body.""" if args is None: # parse command-line arguments parser = get_argument_parser() args = parser.parse_args() fasta_file = args.fasta_file speci...
def auth_view(name, **kwargs): """ Shows an authorization group's content. """ ctx = Context(**kwargs) ctx.execute_action('auth:group:view', **{ 'storage': ctx.repo.create_secure_service('storage'), 'name': name, })
Shows an authorization group's content.
Below is the the instruction that describes the task: ### Input: Shows an authorization group's content. ### Response: def auth_view(name, **kwargs): """ Shows an authorization group's content. """ ctx = Context(**kwargs) ctx.execute_action('auth:group:view', **{ 'storage': ctx.repo.cre...
def merge_or_link(self, input_args, raw_folder, local_base="sample"): """ This function standardizes various input possibilities by converting either .bam, .fastq, or .fastq.gz files into a local file; merging those if multiple files given. :param list input_args: This is a list...
This function standardizes various input possibilities by converting either .bam, .fastq, or .fastq.gz files into a local file; merging those if multiple files given. :param list input_args: This is a list of arguments, each one is a class of inputs (which can in turn be a string or...
Below is the the instruction that describes the task: ### Input: This function standardizes various input possibilities by converting either .bam, .fastq, or .fastq.gz files into a local file; merging those if multiple files given. :param list input_args: This is a list of arguments, each o...
def s_find_first(pred, first, lst): """Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element ...
Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :return: the first element for which predicate is true.
Below is the the instruction that describes the task: ### Input: Evaluate `first`; if predicate `pred` succeeds on the result of `first`, return the result; otherwise recur on the first element of `lst`. :param pred: a predicate. :param first: a promise. :param lst: a list of quoted promises. :...
def medium_integer(self, column, auto_increment=False, unsigned=False): """ Create a new medium integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent """ return s...
Create a new medium integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent
Below is the the instruction that describes the task: ### Input: Create a new medium integer column on the table. :param column: The column :type column: str :type auto_increment: bool :type unsigned: bool :rtype: Fluent ### Response: def medium_integer(self, column, aut...
def Uniform(cls, low: 'TensorFluent', high: 'TensorFluent', batch_size: Optional[int] = None) -> Tuple[Distribution, 'TensorFluent']: '''Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform...
Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform distribution. high: The high parameter of the Uniform distribution. batch_size: The size of the batch (optional). Returns: ...
Below is the the instruction that describes the task: ### Input: Returns a TensorFluent for the Uniform sampling op with given low and high parameters. Args: low: The low parameter of the Uniform distribution. high: The high parameter of the Uniform distribution. batch_s...
def log(logger, level, message): """Logs message to stderr if logging isn't initialized.""" if logger.parent.name != 'root': logger.log(level, message) else: print(message, file=sys.stderr)
Logs message to stderr if logging isn't initialized.
Below is the the instruction that describes the task: ### Input: Logs message to stderr if logging isn't initialized. ### Response: def log(logger, level, message): """Logs message to stderr if logging isn't initialized.""" if logger.parent.name != 'root': logger.log(level, message) else: ...
def _add_vxr_levels_r(self, f, vxrhead, numVXRs): ''' Build a new level of VXRs... make VXRs more tree-like From: VXR1 -> VXR2 -> VXR3 -> VXR4 -> ... -> VXRn To: new VXR1 / | \ VXR2 VXR3 VXR4 ...
Build a new level of VXRs... make VXRs more tree-like From: VXR1 -> VXR2 -> VXR3 -> VXR4 -> ... -> VXRn To: new VXR1 / | \ VXR2 VXR3 VXR4 / | \ ... ...
Below is the the instruction that describes the task: ### Input: Build a new level of VXRs... make VXRs more tree-like From: VXR1 -> VXR2 -> VXR3 -> VXR4 -> ... -> VXRn To: new VXR1 / | \ VXR2 VXR3 VXR4 ...
def track(cls, obj, ptr): """ Track an object which needs destruction when it is garbage collected. """ cls._objects.add(cls(obj, ptr))
Track an object which needs destruction when it is garbage collected.
Below is the the instruction that describes the task: ### Input: Track an object which needs destruction when it is garbage collected. ### Response: def track(cls, obj, ptr): """ Track an object which needs destruction when it is garbage collected. """ cls._objects.add(cls(obj, ptr)...
def cli(env, prop): """Find details about this machine.""" try: if prop == 'network': env.fout(get_network()) return meta_prop = META_MAPPING.get(prop) or prop env.fout(SoftLayer.MetadataManager().get(meta_prop)) except SoftLayer.TransportError: rais...
Find details about this machine.
Below is the the instruction that describes the task: ### Input: Find details about this machine. ### Response: def cli(env, prop): """Find details about this machine.""" try: if prop == 'network': env.fout(get_network()) return meta_prop = META_MAPPING.get(prop) o...
def last_modified_version(self, **kwargs): """ Get the last modified version """ self.items(**kwargs) return int(self.request.headers.get("last-modified-version", 0))
Get the last modified version
Below is the the instruction that describes the task: ### Input: Get the last modified version ### Response: def last_modified_version(self, **kwargs): """ Get the last modified version """ self.items(**kwargs) return int(self.request.headers.get("last-modified-version", 0))
def create_physical_relationship(manager, physical_handle_id, other_handle_id, rel_type): """ Makes relationship between the two nodes and returns the relationship. If a relationship is not possible NoRelationshipPossible exception is raised. """ other_meta_type = get_node_meta_type(manager, oth...
Makes relationship between the two nodes and returns the relationship. If a relationship is not possible NoRelationshipPossible exception is raised.
Below is the the instruction that describes the task: ### Input: Makes relationship between the two nodes and returns the relationship. If a relationship is not possible NoRelationshipPossible exception is raised. ### Response: def create_physical_relationship(manager, physical_handle_id, other_handle_id, ...
def getApplicationSupportedMimeTypes(self, pchAppKey, pchMimeTypesBuffer, unMimeTypesBuffer): """Get the list of supported mime types for this application, comma-delimited""" fn = self.function_table.getApplicationSupportedMimeTypes result = fn(pchAppKey, pchMimeTypesBuffer, unMimeTypesBuffer) ...
Get the list of supported mime types for this application, comma-delimited
Below is the the instruction that describes the task: ### Input: Get the list of supported mime types for this application, comma-delimited ### Response: def getApplicationSupportedMimeTypes(self, pchAppKey, pchMimeTypesBuffer, unMimeTypesBuffer): """Get the list of supported mime types for this applicatio...
def value_counts(self, dropna=True): """ Returns a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaN, even if NaN is in sp_values. Returns ------- counts : Series ...
Returns a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaN, even if NaN is in sp_values. Returns ------- counts : Series
Below is the the instruction that describes the task: ### Input: Returns a Series containing counts of unique values. Parameters ---------- dropna : boolean, default True Don't include counts of NaN, even if NaN is in sp_values. Returns ------- counts : ...
def render_diagram(root_task, out_base, max_param_len=20, horizontal=False, colored=False): """Render a diagram of the ETL pipeline All upstream tasks (i.e. requirements) of :attr:`root_task` are rendered. Nodes are, by default, styled as simple rects. This style is augmented by any :attr:`diagram_sty...
Render a diagram of the ETL pipeline All upstream tasks (i.e. requirements) of :attr:`root_task` are rendered. Nodes are, by default, styled as simple rects. This style is augmented by any :attr:`diagram_style` attributes of the tasks. .. note:: This function requires the 'dot' executable from the Gr...
Below is the the instruction that describes the task: ### Input: Render a diagram of the ETL pipeline All upstream tasks (i.e. requirements) of :attr:`root_task` are rendered. Nodes are, by default, styled as simple rects. This style is augmented by any :attr:`diagram_style` attributes of the tasks. ...
def run(self): """ Runs the simulation. """ self.init_run() if self.debug: self.dump("AfterInit: ") #print("++++++++++++++++ Time: %f"%self.current_time) while self.step(): #self.dump("Time: %f"%self.current_time) #print("++++++++++++++++ ...
Runs the simulation.
Below is the the instruction that describes the task: ### Input: Runs the simulation. ### Response: def run(self): """ Runs the simulation. """ self.init_run() if self.debug: self.dump("AfterInit: ") #print("++++++++++++++++ Time: %f"%self.current_time) whil...
def handle_items(repo, **kwargs): """:return: repo.files()""" log.info('items: %s %s' %(repo, kwargs)) if not hasattr(repo, 'items'): return [] return [i.serialize() for i in repo.items(**kwargs)]
:return: repo.files()
Below is the the instruction that describes the task: ### Input: :return: repo.files() ### Response: def handle_items(repo, **kwargs): """:return: repo.files()""" log.info('items: %s %s' %(repo, kwargs)) if not hasattr(repo, 'items'): return [] return [i.serialize() for i in repo.items(**kw...
def _get_err_msg(row, col, fld, val, prt_flds): """Return an informative message with details of xlsx write attempt.""" import traceback traceback.print_exc() err_msg = ( "ROW({R}) COL({C}) FIELD({F}) VAL({V})\n".format(R=row, C=col, F=fld, V=val), "PRINT FIELDS({...
Return an informative message with details of xlsx write attempt.
Below is the the instruction that describes the task: ### Input: Return an informative message with details of xlsx write attempt. ### Response: def _get_err_msg(row, col, fld, val, prt_flds): """Return an informative message with details of xlsx write attempt.""" import traceback traceback...
def _resolve_periods_in_year(scale, frame): """ Convert the scale to an annualzation factor. If scale is None then attempt to resolve from frame. If scale is a scalar then use it. If scale is a string then use it to lookup the annual factor """ if scale is None: return periodicity(frame) ...
Convert the scale to an annualzation factor. If scale is None then attempt to resolve from frame. If scale is a scalar then use it. If scale is a string then use it to lookup the annual factor
Below is the the instruction that describes the task: ### Input: Convert the scale to an annualzation factor. If scale is None then attempt to resolve from frame. If scale is a scalar then use it. If scale is a string then use it to lookup the annual factor ### Response: def _resolve_periods_in_year(scale...
def handle_msg(self, msg): """handle the message *msg*. """ addr_ = msg.data["URI"] status = msg.data.get('status', True) if status: service = msg.data.get('service') for service in self.services: if not service or service in service: ...
handle the message *msg*.
Below is the the instruction that describes the task: ### Input: handle the message *msg*. ### Response: def handle_msg(self, msg): """handle the message *msg*. """ addr_ = msg.data["URI"] status = msg.data.get('status', True) if status: service = msg.data.get('s...
def _ensure_worker(self): """Ensure there are enough workers available""" while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_workers: worker = threading.Thread( target=self._execute_futures, name=self.identifie...
Ensure there are enough workers available
Below is the the instruction that describes the task: ### Input: Ensure there are enough workers available ### Response: def _ensure_worker(self): """Ensure there are enough workers available""" while len(self._workers) < self._min_workers or len(self._workers) < self._queue.qsize() < self._max_wor...
def wallet_representative(self, wallet): """ Returns the default representative for **wallet** :param wallet: Wallet to get default representative account for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_representative( ... wall...
Returns the default representative for **wallet** :param wallet: Wallet to get default representative account for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_representative( ... wallet="000D1BAEC8EC208142C99059B393051BAC8380F9B5A2E6B2489A277D8...
Below is the the instruction that describes the task: ### Input: Returns the default representative for **wallet** :param wallet: Wallet to get default representative account for :type wallet: str :raises: :py:exc:`nano.rpc.RPCException` >>> rpc.wallet_representative( ... ...
def set_missing_value_policy(self, policy, target_attr_name=None): """ Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist. """ assert policy in MISSING_VALUE_POLICIES, \ ...
Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist.
Below is the the instruction that describes the task: ### Input: Sets the behavior for one or all attributes to use when traversing the tree using a query vector and it encounters a branch that does not exist. ### Response: def set_missing_value_policy(self, policy, target_attr_name=None): ...
def write(self): """Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry """ none_type = type(None) # Format attributes for writing attrs = self.attribute_string() # Place holder if field value is ...
Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry
Below is the the instruction that describes the task: ### Input: Restore GFF3 entry to original format Returns: str: properly formatted string containing the GFF3 entry ### Response: def write(self): """Restore GFF3 entry to original format Returns: str: properly f...