code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def _update_params(self, constants):
"""Update the params."""
constants = np.max(np.min(constants, 1))
self.params['r']['value'] = max([self.params['r']['value'],
constants])
epsilon = constants / self.params['r']['value']
influence = self... | Update the params. | Below is the the instruction that describes the task:
### Input:
Update the params.
### Response:
def _update_params(self, constants):
"""Update the params."""
constants = np.max(np.min(constants, 1))
self.params['r']['value'] = max([self.params['r']['value'],
... |
def _load_template(dev_path):
"""
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
"""
# See https://bitbucket.org/pypa/setuptools/issue/134 for info
# on script file naming and downstream issues with SVR4
... | There are a couple of template scripts in the package. This
function loads one of them and prepares it for use. | Below is the the instruction that describes the task:
### Input:
There are a couple of template scripts in the package. This
function loads one of them and prepares it for use.
### Response:
def _load_template(dev_path):
"""
There are a couple of template scripts in the package. This
... |
def _setup_program(self):
"""
Create a temporary file containing the program code. The code is
fetched via :meth:`_get_program`.
"""
filename = self._get_program_filename()
path = os.path.join(self.get_temp_dir(), filename)
self.program_fp = open(path, 'wb')
... | Create a temporary file containing the program code. The code is
fetched via :meth:`_get_program`. | Below is the the instruction that describes the task:
### Input:
Create a temporary file containing the program code. The code is
fetched via :meth:`_get_program`.
### Response:
def _setup_program(self):
"""
Create a temporary file containing the program code. The code is
fetched vi... |
def _read_header(self):
'''
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
'''
self._fh.seek(0)
buf = self._fh.read(4*2)
fc, dc = struct.unpack("<II", buf)
retur... | Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count | | Below is the the instruction that describes the task:
### Input:
Little-endian
|... 4 bytes unsigned int ...|... 4 bytes unsigned int ...|
| frames count | dimensions count |
### Response:
def _read_header(self):
'''
Little-endian
|... 4 bytes unsigne... |
def create_track(self, href=None, media_url=None, label=None,
audio_channel=None):
"""Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not... | Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not be None.
'media_url' public URL to media file. May not be None.
'label' short name for the track. ... | Below is the the instruction that describes the task:
### Input:
Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not be None.
'media_url' public URL to me... |
def _hash(self, hash_name):
""" Returns a hash object for the file at the current path.
`hash_name` should be a hash algo name (such as ``'md5'``
or ``'sha1'``) that's available in the :mod:`hashlib` module.
"""
m = hashlib.new(hash_name)
for chunk in self.chunks(8192, m... | Returns a hash object for the file at the current path.
`hash_name` should be a hash algo name (such as ``'md5'``
or ``'sha1'``) that's available in the :mod:`hashlib` module. | Below is the the instruction that describes the task:
### Input:
Returns a hash object for the file at the current path.
`hash_name` should be a hash algo name (such as ``'md5'``
or ``'sha1'``) that's available in the :mod:`hashlib` module.
### Response:
def _hash(self, hash_name):
""" Ret... |
async def _download_text(url, session):
"""Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
content : `str`
... | Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
content : `str`
Content downloaded from the URL. | Below is the the instruction that describes the task:
### Input:
Asynchronously request a URL and get the encoded text content of the
body.
Parameters
----------
url : `str`
URL to download.
session : `aiohttp.ClientSession`
An open aiohttp session.
Returns
-------
... |
def _reset_kvstore(self):
"""Reset kvstore."""
if self._kvstore and 'dist' in self._kvstore.type:
raise RuntimeError("Cannot reset distributed KVStore.")
self._kv_initialized = False
self._kvstore = None
self._distributed = None
self._update_on_kvstore = None
... | Reset kvstore. | Below is the the instruction that describes the task:
### Input:
Reset kvstore.
### Response:
def _reset_kvstore(self):
"""Reset kvstore."""
if self._kvstore and 'dist' in self._kvstore.type:
raise RuntimeError("Cannot reset distributed KVStore.")
self._kv_initialized = False
... |
def create_module(sym, data_shapes, label_shapes, label_names, gpus=''):
"""Creates a new MXNet module.
Parameters
----------
sym : Symbol
An MXNet symbol.
input_shape: tuple
The shape of the input data in the form of (batch_size, channels, height, width)
files: list of string... | Creates a new MXNet module.
Parameters
----------
sym : Symbol
An MXNet symbol.
input_shape: tuple
The shape of the input data in the form of (batch_size, channels, height, width)
files: list of strings
List of URLs pertaining to files that need to be downloaded in order t... | Below is the the instruction that describes the task:
### Input:
Creates a new MXNet module.
Parameters
----------
sym : Symbol
An MXNet symbol.
input_shape: tuple
The shape of the input data in the form of (batch_size, channels, height, width)
files: list of strings
L... |
def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent,
timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls,
async_mode=True, get_object=False, no_input=False):
"""
Run Fetcher.
"""
g = ctx.obj
Fetcher = load_cls(None, None, f... | Run Fetcher. | Below is the the instruction that describes the task:
### Input:
Run Fetcher.
### Response:
def fetcher(ctx, xmlrpc, xmlrpc_host, xmlrpc_port, poolsize, proxy, user_agent,
timeout, phantomjs_endpoint, puppeteer_endpoint, splash_endpoint, fetcher_cls,
async_mode=True, get_object=False, no_in... |
def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device."""
return self.any_raspberry_pi or self.any_beaglebone or \
self.any_orange_pi or self.any_giant_board or self.any_jetson_board | Check whether the current board is any embedded Linux device. | Below is the the instruction that describes the task:
### Input:
Check whether the current board is any embedded Linux device.
### Response:
def any_embedded_linux(self):
"""Check whether the current board is any embedded Linux device."""
return self.any_raspberry_pi or self.any_beaglebone or \
... |
def prependsitedir(projdir, *args):
"""
like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. If its a
... | like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. If its a
a file, the parent directory will be added
... | Below is the the instruction that describes the task:
### Input:
like sys.addsitedir() but gives the added directory preference
over system directories. The paths will be normalized for dots and
slash direction before being added to the path.
projdir: the path you want to add to sys.path. ... |
def endswith(self, suffix, start=None, end=None):
"""Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
"""
suffix... | Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len. | Below is the the instruction that describes the task:
### Input:
Return whether the current bitstring ends with suffix.
suffix -- The bitstring to search for.
start -- The bit position to start from. Defaults to 0.
end -- The bit position to end at. Defaults to self.len.
### Response:
def ... |
def __get_query_filters(cls, filters={}, inverse=False):
"""
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filte... | Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filters to be applied
:param inverse: if True include all the inverse filt... | Below is the the instruction that describes the task:
### Input:
Convert a dict with the filters to be applied ({"name1":"value1", "name2":"value2"})
to a list of query objects which can be used together in a query using boolean
combination logic.
:param filters: dict with the filters to be... |
def generate_cdef():
"""Generate the cdef output file"""
include_libc_path = path.join(HERE, 'fake_libc_include')
include_vulkan_path = path.join(HERE, 'vulkan_include')
out_file = path.join(HERE, path.pardir, 'vulkan', 'vulkan.cdef.h')
header = path.join(include_vulkan_path, 'vulkan.h')
comman... | Generate the cdef output file | Below is the the instruction that describes the task:
### Input:
Generate the cdef output file
### Response:
def generate_cdef():
"""Generate the cdef output file"""
include_libc_path = path.join(HERE, 'fake_libc_include')
include_vulkan_path = path.join(HERE, 'vulkan_include')
out_file = path.join... |
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name):
""" Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body... | Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message body in plain text. | Below is the the instruction that describes the task:
### Input:
Send email message via Flask-Sendmail.
Args:
recipient: Email address or tuple of (Name, Email-address).
subject: Subject line.
html_message: The message body in HTML.
text_message: The message ... |
def estimate_duration(self):
"""
Estimate duration (timedelta) for this task.
Estimate the average length of time we expect between this task's
start and end times.
:returns: deferred that when fired returns a timedelta object for the
estimated timedelta, or t... | Estimate duration (timedelta) for this task.
Estimate the average length of time we expect between this task's
start and end times.
:returns: deferred that when fired returns a timedelta object for the
estimated timedelta, or the actual timedelta, or None if we
... | Below is the the instruction that describes the task:
### Input:
Estimate duration (timedelta) for this task.
Estimate the average length of time we expect between this task's
start and end times.
:returns: deferred that when fired returns a timedelta object for the
estim... |
def _parse_conference(self, stats):
"""
Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
... | Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery object
A PyQuery object containing the HTML from the pla... | Below is the the instruction that describes the task:
### Input:
Parse the conference abbreviation for the player's team.
The conference abbreviation is embedded within the conference name tag
and should be special-parsed to extract it.
Parameters
----------
stats : PyQuery... |
def serialize(self, sw, **kw):
'''
sw -- SoapWriter instance, add WS-Address header.
'''
for pyobj in self.header_pyobjs:
if hasattr(pyobj, 'typecode') is False:
raise RuntimeError, 'all header pyobjs must have a typecode attribute'
sw.serialize_h... | sw -- SoapWriter instance, add WS-Address header. | Below is the the instruction that describes the task:
### Input:
sw -- SoapWriter instance, add WS-Address header.
### Response:
def serialize(self, sw, **kw):
'''
sw -- SoapWriter instance, add WS-Address header.
'''
for pyobj in self.header_pyobjs:
if hasattr(pyobj, 't... |
def flexifunction_read_req_encode(self, target_system, target_component, read_req_type, data_index):
'''
Reqest reading of flexifunction data
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
... | Reqest reading of flexifunction data
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
read_req_type : Type of flexifunction data requested (int16_t)
data_index : index into data ... | Below is the the instruction that describes the task:
### Input:
Reqest reading of flexifunction data
target_system : System ID (uint8_t)
target_component : Component ID (uint8_t)
read_req_type : Type of flexifunction data requested (... |
def load_gene_exp_to_df(inst_path):
'''
Loads gene expression data from 10x in sparse matrix format and returns a
Pandas dataframe
'''
import pandas as pd
from scipy import io
from scipy import sparse
from ast import literal_eval as make_tuple
# matrix
Matrix = io.mmread( inst_... | Loads gene expression data from 10x in sparse matrix format and returns a
Pandas dataframe | Below is the the instruction that describes the task:
### Input:
Loads gene expression data from 10x in sparse matrix format and returns a
Pandas dataframe
### Response:
def load_gene_exp_to_df(inst_path):
'''
Loads gene expression data from 10x in sparse matrix format and returns a
Pandas datafram... |
def is_tone(char, strict=True):
"""
Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[1]: http://www.unicode.org/char... | Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[1]: http://www.unicode.org/charts/PDF/UA700.pdf | Below is the the instruction that describes the task:
### Input:
Check whether the character is a tone or word accent symbol. In strict mode
return True only for the symbols listed in the last group of the chart. If
strict=False, also accept symbols that belong to the Modifier Tone Letters
Unicode block [1].
[... |
def rename(self, new_name):
"""
Renames this NIO
:param new_name: new NIO name
"""
yield from self._hypervisor.send("nio rename {name} {new_name}".format(name=self._name, new_name=new_name))
log.info("NIO {name} renamed to {new_name}".format(name=self._name, new_name=n... | Renames this NIO
:param new_name: new NIO name | Below is the the instruction that describes the task:
### Input:
Renames this NIO
:param new_name: new NIO name
### Response:
def rename(self, new_name):
"""
Renames this NIO
:param new_name: new NIO name
"""
yield from self._hypervisor.send("nio rename {name} {ne... |
def _extract_word(self, source, position):
"""
Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word
"... | Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word | Below is the the instruction that describes the task:
### Input:
Extracts the word that falls at or around a specific position
:param source:
The template source as a unicode string
:param position:
The position where the word falls
:return:
The word
###... |
def visit(self, url=''):
"""Visit the url, checking for rr errors in the response
@param url: URL
@return: Visit result
"""
result = super(CoyoteDriver, self).visit(url)
source = self.page_source()
return result | Visit the url, checking for rr errors in the response
@param url: URL
@return: Visit result | Below is the the instruction that describes the task:
### Input:
Visit the url, checking for rr errors in the response
@param url: URL
@return: Visit result
### Response:
def visit(self, url=''):
"""Visit the url, checking for rr errors in the response
@param url: URL
@ret... |
def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
"""
u = 0
y = 0
result = []
for idx, val in enumerate(list_of_numbers):
y += list_of_numbers[idx]
while y >=... | find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]] | Below is the the instruction that describes the task:
### Input:
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022, 580, 930, 898], 285) ->
[[4, 5],[5, 6]]
### Response:
def find_cumulative_indices(list_of_numbers, search_sum):
"""
find_cumulative_indices([70, 58, 81, 909, 70, 215, 70, 1022,... |
def MakeSelfExtractingZip(self, payload_data, output_path):
"""Repack the installer into the payload.
Args:
payload_data: data payload for zip file
output_path: filename for the zip output
Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
... | Repack the installer into the payload.
Args:
payload_data: data payload for zip file
output_path: filename for the zip output
Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
output_path: filename string of zip output file | Below is the the instruction that describes the task:
### Input:
Repack the installer into the payload.
Args:
payload_data: data payload for zip file
output_path: filename for the zip output
Raises:
RuntimeError: if the ClientBuilder.unzipsfx_stub doesn't require admin.
Returns:
... |
def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is_category(dt):
obj_cols.append(df.columns.values[idx])
return obj_cols | Returns names of 'object' columns in the DataFrame. | Below is the the instruction that describes the task:
### Input:
Returns names of 'object' columns in the DataFrame.
### Response:
def get_obj_cols(df):
"""
Returns names of 'object' columns in the DataFrame.
"""
obj_cols = []
for idx, dt in enumerate(df.dtypes):
if dt == 'object' or is... |
def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not self.onOffset(dt):
dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds)
return dt | Roll provided date forward to next offset only if not on offset. | Below is the the instruction that describes the task:
### Input:
Roll provided date forward to next offset only if not on offset.
### Response:
def rollforward(self, dt):
"""
Roll provided date forward to next offset only if not on offset.
"""
dt = as_timestamp(dt)
if not se... |
def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... | Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it. | Below is the the instruction that describes the task:
### Input:
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
### Response:
def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is s... |
def config_get(args):
""" Retrieve a method config from a workspace, send stdout """
r = fapi.get_workspace_config(args.project, args.workspace,
args.namespace, args.config)
fapi._check_response_code(r, 200)
# Setting ensure_ascii to False ensures unicode string r... | Retrieve a method config from a workspace, send stdout | Below is the the instruction that describes the task:
### Input:
Retrieve a method config from a workspace, send stdout
### Response:
def config_get(args):
""" Retrieve a method config from a workspace, send stdout """
r = fapi.get_workspace_config(args.project, args.workspace,
... |
def trace_requirements(requirements):
"""given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements.
"""
requirements = tuple(pretty_req(r) for r in requirements)
working_set = fresh_working_set()
# breadth-first traversal:
from co... | given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements. | Below is the the instruction that describes the task:
### Input:
given an iterable of pip InstallRequirements,
return the set of required packages, given their transitive requirements.
### Response:
def trace_requirements(requirements):
"""given an iterable of pip InstallRequirements,
return the set of... |
def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
'''
v_ind, f_ind = self.vertex_indices_in_segments(segments_to_k... | Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed. | Below is the the instruction that describes the task:
### Input:
Keep the faces and vertices for given segments, discarding all others.
When preserve_segmentation is false self.segm is discarded for speed.
### Response:
def keep_segments(self, segments_to_keep, preserve_segmentation=True):
'''
... |
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None:
"""Write this graph to GraphML XML file using :func:`networkx.write_graphml`.
The .graphml file extension is suggested so Cytoscape can recognize it.
"""
rv = nx.MultiDiGraph()
for node in graph:
rv.add_node(node.as_bel()... | Write this graph to GraphML XML file using :func:`networkx.write_graphml`.
The .graphml file extension is suggested so Cytoscape can recognize it. | Below is the the instruction that describes the task:
### Input:
Write this graph to GraphML XML file using :func:`networkx.write_graphml`.
The .graphml file extension is suggested so Cytoscape can recognize it.
### Response:
def to_graphml(graph: BELGraph, path: Union[str, BinaryIO]) -> None:
"""Write th... |
def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets the Virtual Media drive status and allows the
boot options for booting from the virtual media.
"""
return self._call_method('set_vm_status', device, boot_option,
... | Sets the Virtual Media drive status and allows the
boot options for booting from the virtual media. | Below is the the instruction that describes the task:
### Input:
Sets the Virtual Media drive status and allows the
boot options for booting from the virtual media.
### Response:
def set_vm_status(self, device='FLOPPY',
boot_option='BOOT_ONCE', write_protect='YES'):
"""Sets t... |
def bulk_write(self, requests, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent.
... | See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempotent. | Below is the the instruction that describes the task:
### Input:
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.bulk_write
Warning: this is wrapped in mongo_retry, and is therefore potentially unsafe if the write you want to execute
isn't idempot... |
def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
"""
if PyFunceble.CONFIGURATION["debug"] and PyFunceble.CONFIGURATION["logs"]:
# The debug and the logs subsystem are activated.
if... | Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str | Below is the the instruction that describes the task:
### Input:
Logs the WHOIS record if needed.
:param record: The record to log.
:type record: str
### Response:
def whois(self, record):
"""
Logs the WHOIS record if needed.
:param record: The record to log.
:type... |
def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
url, dsid)
if self.pch is None:
self.pch = build_opener(HTTPCookieProcessor(self... | Make the request | Below is the the instruction that describes the task:
### Input:
Make the request
### Response:
def request(self, url, post=None, method="GET"):
""" Make the request"""
dsid = self.get_dsid()
baseurl = "https://auth.api.swedbank.se/TDE_DAP_Portal_REST_WEB/api/v1/%s?dsid=%s" % (
... |
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover
"""Returns an image of a pyquil circuit.
See circuit_to_latex() for more details.
"""
circ = pyquil_to_circuit(program)
latex = circuit_to_latex(circ)
img = render_latex(latex)
return img | Returns an image of a pyquil circuit.
See circuit_to_latex() for more details. | Below is the the instruction that describes the task:
### Input:
Returns an image of a pyquil circuit.
See circuit_to_latex() for more details.
### Response:
def pyquil_to_image(program: pyquil.Program) -> PIL.Image: # pragma: no cover
"""Returns an image of a pyquil circuit.
See circuit_to_latex() ... |
def check_exists(name, path):
'''
Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path
'''
cmd = [_get_cmd(), '--display', name]
out = __salt__['cmd.run_all'](cmd, pytho... | Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path | Below is the the instruction that describes the task:
### Input:
Check if the given path is an alternative for a name.
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' alternatives.check_exists name path
### Response:
def check_exists(name, path):
'''
Check if t... |
def get_templates(self):
"""
Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding mustache file is added to th... | Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding mustache file is added to the sub-dictionary. | Below is the the instruction that describes the task:
### Input:
Return a list of template_dicts based on the config.yaml in
$self.base_path. Keys correspond to templates and values represent
further settings regarding each template. A pystache object containing
the parsed corresponding must... |
def select(self):
'''If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot'''
if not hasattr(self._gdbframe, 'select'):
print ('Unabl... | If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot | Below is the the instruction that describes the task:
### Input:
If supported, select this frame and return True; return False if unsupported
Not all builds have a gdb.Frame.select method; seems to be present on Fedora 12
onwards, but absent on Ubuntu buildbot
### Response:
def select(self):
... |
def describe_training_job_with_log(self, job_name, positions, stream_names,
instance_count, state, last_description,
last_describe_job_call):
"""
Return the training job info associated with job_name and print CloudWatch logs
... | Return the training job info associated with job_name and print CloudWatch logs | Below is the the instruction that describes the task:
### Input:
Return the training job info associated with job_name and print CloudWatch logs
### Response:
def describe_training_job_with_log(self, job_name, positions, stream_names,
instance_count, state, last_description,
... |
def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
__pillar__.update(kwargs.get('pillar', {}))
opts = salt.utils.state.get_sls_opts(__opts__, **kwargs)
st_ = salt.c... | Create the seed file for a state.sls run | Below is the the instruction that describes the task:
### Input:
Create the seed file for a state.sls run
### Response:
def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
'''
Create the seed file for a state.sls run
'''
st_kwargs = __salt__.kwargs
__opts__['grains'] = __grains__
... |
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = ... | master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead. | Below is the the instruction that describes the task:
### Input:
master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead.
### Response:
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pt... |
def binary(self, new_binary):
"""Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
"""
if not isinstance(new_binary, FirefoxBinary):
new_binary = FirefoxBinary(new_binary)
self._binary = new_binary | Sets location of the browser binary, either by string or
``FirefoxBinary`` instance. | Below is the the instruction that describes the task:
### Input:
Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
### Response:
def binary(self, new_binary):
"""Sets location of the browser binary, either by string or
``FirefoxBinary`` instance.
... |
def show_description(self):
""" Prints the formatted response for the matching return type """
def printit(c, v):
underline = "-" * len(dr.get_name(c))
resp = self.responses[v["type"]]
name = "%s[%s] %s%s" % (resp.color, resp.label, dr.get_name(c), Style.RESET_ALL)
... | Prints the formatted response for the matching return type | Below is the the instruction that describes the task:
### Input:
Prints the formatted response for the matching return type
### Response:
def show_description(self):
""" Prints the formatted response for the matching return type """
def printit(c, v):
underline = "-" * len(dr.get_name(... |
def cmd_startstop(options):
"""Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object)... | Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
Args:
options (object): contains args and data from parse... | Below is the the instruction that describes the task:
### Input:
Start or Stop the specified instance.
Finds instances that match args and instance-state expected by the
command. Then, the target instance is determined, the action is
performed on the instance, and the eturn information is displayed.
... |
def __fetch_issues(self, from_date, to_date):
"""Fetch the issues"""
issues_groups = self.client.issues(from_date=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw_issues)
for issue in issues:
if str_to_datetime(issue['updated_at']) > ... | Fetch the issues | Below is the the instruction that describes the task:
### Input:
Fetch the issues
### Response:
def __fetch_issues(self, from_date, to_date):
"""Fetch the issues"""
issues_groups = self.client.issues(from_date=from_date)
for raw_issues in issues_groups:
issues = json.loads(raw... |
def _get_grouped_dicoms(dicom_input):
"""
Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data
"""
# if all dicoms have an instance number try sorting by instance number else by position
if [d for d in dicom_input if 'Instance... | Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data | Below is the the instruction that describes the task:
### Input:
Search all dicoms in the dicom directory, sort and validate them
fast_read = True will only read the headers not the data
### Response:
def _get_grouped_dicoms(dicom_input):
"""
Search all dicoms in the dicom directory, sort and validate... |
def generic_is_view_attribute(parents, attrs):
"""Generates is_X_attribute function for given parents and attrs."""
def is_attribute(node):
return _attribute_is_magic(node, attrs, parents)
return is_attribute | Generates is_X_attribute function for given parents and attrs. | Below is the the instruction that describes the task:
### Input:
Generates is_X_attribute function for given parents and attrs.
### Response:
def generic_is_view_attribute(parents, attrs):
"""Generates is_X_attribute function for given parents and attrs."""
def is_attribute(node):
return _attribute... |
def export_events(self, filename, evt_type):
"""Export events to CSV
Parameters
----------
filename : str
path of export file
evt_type : list of str
event types to export
"""
filename = splitext(filename)[0] + '.csv'
headin... | Export events to CSV
Parameters
----------
filename : str
path of export file
evt_type : list of str
event types to export | Below is the the instruction that describes the task:
### Input:
Export events to CSV
Parameters
----------
filename : str
path of export file
evt_type : list of str
event types to export
### Response:
def export_events(self, filename, evt_type):
... |
def query(self, sql: str, args: tuple = None):
"""Execute a SQL query with a return value."""
with self._cursor() as cursor:
log.debug('Running SQL: ' + str((sql, args)))
cursor.execute(sql, args)
return cursor.fetchall() | Execute a SQL query with a return value. | Below is the the instruction that describes the task:
### Input:
Execute a SQL query with a return value.
### Response:
def query(self, sql: str, args: tuple = None):
"""Execute a SQL query with a return value."""
with self._cursor() as cursor:
log.debug('Running SQL: ' + str((sql, arg... |
def Chisholm(m, x, rhol, rhog, mul, mug, D, roughness=0, L=1,
rough_correction=False):
r'''Calculates two-phase pressure drop with the Chisholm (1973) correlation
from [1]_, also in [2]_ and [3]_.
.. math::
\frac{\Delta P_{tp}}{\Delta P_{lo}} = \phi_{ch}^2
.. math::
\phi_{... | r'''Calculates two-phase pressure drop with the Chisholm (1973) correlation
from [1]_, also in [2]_ and [3]_.
.. math::
\frac{\Delta P_{tp}}{\Delta P_{lo}} = \phi_{ch}^2
.. math::
\phi_{ch}^2 = 1 + (\Gamma^2 -1)\left\{B x^{(2-n)/2} (1-x)^{(2-n)/2}
+ x^{2-n} \right\}
.. math::
... | Below is the the instruction that describes the task:
### Input:
r'''Calculates two-phase pressure drop with the Chisholm (1973) correlation
from [1]_, also in [2]_ and [3]_.
.. math::
\frac{\Delta P_{tp}}{\Delta P_{lo}} = \phi_{ch}^2
.. math::
\phi_{ch}^2 = 1 + (\Gamma^2 -1)\left\{B x... |
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'PPP' and self.ppp_fd != -1:
print("got ppp mavlink pkt len=%u" % m.length)
os.write(self.ppp_fd, m.data[:m.length]) | handle an incoming mavlink packet | Below is the the instruction that describes the task:
### Input:
handle an incoming mavlink packet
### Response:
def mavlink_packet(self, m):
'''handle an incoming mavlink packet'''
if m.get_type() == 'PPP' and self.ppp_fd != -1:
print("got ppp mavlink pkt len=%u" % m.length)
... |
def _prepare_axes(node, sort_key):
"""
Sort axes and combine those that point to the same target and go
in the same direction.
"""
links = node.links
o_links = node._overlapping_links
overlap = {ax2 for ax in links for ax2 in o_links.get(ax, [])}
axes = []
for axis in sorted(links.ke... | Sort axes and combine those that point to the same target and go
in the same direction. | Below is the the instruction that describes the task:
### Input:
Sort axes and combine those that point to the same target and go
in the same direction.
### Response:
def _prepare_axes(node, sort_key):
"""
Sort axes and combine those that point to the same target and go
in the same direction.
"... |
def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self.bulk_insert
cache_len = len(cache)
row = '(%s,%s,%s,%s,%s,%s)'
query = 'INSERT INTO gauged_cache ' \
'(n... | Add cached values for the specified date range and query | Below is the the instruction that describes the task:
### Input:
Add cached values for the specified date range and query
### Response:
def add_cache(self, namespace, key, query_hash, length, cache):
"""Add cached values for the specified date range and query"""
start = 0
bulk_insert = self... |
def PopAttributeContainer(self):
"""Pops a serialized attribute container from the list.
Returns:
bytes: serialized attribute container data.
"""
try:
serialized_data = self._list.pop(0)
self.data_size -= len(serialized_data)
return serialized_data
except IndexError:
... | Pops a serialized attribute container from the list.
Returns:
bytes: serialized attribute container data. | Below is the the instruction that describes the task:
### Input:
Pops a serialized attribute container from the list.
Returns:
bytes: serialized attribute container data.
### Response:
def PopAttributeContainer(self):
"""Pops a serialized attribute container from the list.
Returns:
bytes:... |
def commajoin_as_strings(iterable):
""" Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable)) | Join the given iterable with ',' | Below is the the instruction that describes the task:
### Input:
Join the given iterable with ','
### Response:
def commajoin_as_strings(iterable):
""" Join the given iterable with ',' """
return _(u',').join((six.text_type(i) for i in iterable)) |
def plate_exchanger_identifier(self):
'''Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places.
'''
s = ('L' + str(round(se... | Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places. | Below is the the instruction that describes the task:
### Input:
Method to create an identifying string in format 'L' + wavelength +
'A' + amplitude + 'B' + chevron angle-chevron angle. Wavelength and
amplitude are specified in units of mm and rounded to two decimal places.
### Response:
def plat... |
def can_be_executed_by(self, thread_id):
'''By default, it must be in the same thread to be executed
'''
return self.thread_id == thread_id or self.thread_id.endswith('|' + thread_id) | By default, it must be in the same thread to be executed | Below is the the instruction that describes the task:
### Input:
By default, it must be in the same thread to be executed
### Response:
def can_be_executed_by(self, thread_id):
'''By default, it must be in the same thread to be executed
'''
return self.thread_id == thread_id or self.thread_... |
def append(self, to_append, ignore_index=False, verify_integrity=False):
"""
Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, d... | Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, do not use the index labels.
.. versionadded:: 0.19.0
verify_integrity :... | Below is the the instruction that describes the task:
### Input:
Concatenate two or more Series.
Parameters
----------
to_append : Series or list/tuple of Series
Series to append with self.
ignore_index : bool, default False
If True, do not use the index labe... |
def _configure_iam_role(config):
"""Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create further gce instances and store it... | Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create further gce instances and store items
in google cloud storage.
TO... | Below is the the instruction that describes the task:
### Input:
Setup a gcp service account with IAM roles.
Creates a gcp service acconut and binds IAM roles which allow it to control
control storage/compute services. Specifically, the head node needs to have
an IAM role that allows it to create furth... |
def sanitize_resources(resource: dict):
"""Cleans up incoming scene data
:param resource: The dict with scene data to be sanitized.
:returns: Cleaned up scene dict.
"""
try:
for shade in resource[ATTR_SHADE_DATA]:
_name = shade.get(ATTR_NAME)
... | Cleans up incoming scene data
:param resource: The dict with scene data to be sanitized.
:returns: Cleaned up scene dict. | Below is the the instruction that describes the task:
### Input:
Cleans up incoming scene data
:param resource: The dict with scene data to be sanitized.
:returns: Cleaned up scene dict.
### Response:
def sanitize_resources(resource: dict):
"""Cleans up incoming scene data
:param ... |
def _get_prioritized_parameters(plugins_dict, is_using_default_value_map, prefer_default=True):
"""
:type plugins_dict: dict(plugin_name => plugin_params)
:param plugin_dict: mapping of plugin name to all plugin params
:type is_using_default_value_map: dict(str => bool)
:param is_using_default_valu... | :type plugins_dict: dict(plugin_name => plugin_params)
:param plugin_dict: mapping of plugin name to all plugin params
:type is_using_default_value_map: dict(str => bool)
:param is_using_default_value_map: mapping of parameter name to whether its value is derived
from a default value.
:param p... | Below is the the instruction that describes the task:
### Input:
:type plugins_dict: dict(plugin_name => plugin_params)
:param plugin_dict: mapping of plugin name to all plugin params
:type is_using_default_value_map: dict(str => bool)
:param is_using_default_value_map: mapping of parameter name to whe... |
def prepare_url(self, uri, kwargs):
"""Convert dict for URL params
"""
params = dict()
for key in kwargs:
if key in ('include', 'exclude', 'fields'):
params.update({
key: ','.join(kwargs.get(key))
})
elif key in ... | Convert dict for URL params | Below is the the instruction that describes the task:
### Input:
Convert dict for URL params
### Response:
def prepare_url(self, uri, kwargs):
"""Convert dict for URL params
"""
params = dict()
for key in kwargs:
if key in ('include', 'exclude', 'fields'):
... |
def correlation(self, x, y=None, binby=[], limits=None, shape=default_shape, sort=False, sort_key=np.abs, selection=False, delay=False, progress=None):
"""Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby.
Example:
>>> df.co... | Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby.
Example:
>>> df.correlation("x**2+y**2+z**2", "-log(-E+1)")
array(0.6366637382215669)
>>> df.correlation("x**2+y**2+z**2", "-log(-E+1)", binby="Lz", shape=4)
... | Below is the the instruction that describes the task:
### Input:
Calculate the correlation coefficient cov[x,y]/(std[x]*std[y]) between and x and y, possibly on a grid defined by binby.
Example:
>>> df.correlation("x**2+y**2+z**2", "-log(-E+1)")
array(0.6366637382215669)
>>> df.cor... |
def register_macro(name: str, func: Callable, allow_overwrite: bool = False) -> None:
"""Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the ... | Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
Otherwise, raise the ValueError.
Raises:
Val... | Below is the the instruction that describes the task:
### Input:
Register new macro to Circuit.
Args:
name (str): The name of macro.
func (callable): The function to be called.
allow_overwrite (bool, optional): If True, allow to overwrite the existing macro.
... |
def save(cls, network, phases=[], filename=''):
r"""
Write Network to a Mat file for exporting to Matlab.
Parameters
----------
network : OpenPNM Network Object
filename : string
Desired file name, defaults to network name if not given
phases : list... | r"""
Write Network to a Mat file for exporting to Matlab.
Parameters
----------
network : OpenPNM Network Object
filename : string
Desired file name, defaults to network name if not given
phases : list of phase objects ([])
Phases that have prop... | Below is the the instruction that describes the task:
### Input:
r"""
Write Network to a Mat file for exporting to Matlab.
Parameters
----------
network : OpenPNM Network Object
filename : string
Desired file name, defaults to network name if not given
... |
def handle_close(self, header, payload):
"""
Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame.
"""
if not payload:
self.close(1000, None)
... | Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame. | Below is the the instruction that describes the task:
### Input:
Called when a close frame has been decoded from the stream.
:param header: The decoded `Header`.
:param payload: The bytestring payload associated with the close frame.
### Response:
def handle_close(self, header, payload):
"... |
def on_tblFunctions1_itemSelectionChanged(self):
"""Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
"""
# Clear the selection on the 2nd matrix
self.parent.step_fc_functions2.tblFuncti... | Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes. | Below is the the instruction that describes the task:
### Input:
Choose selected hazard x exposure combination.
.. note:: This is an automatic Qt slot
executed when the category selection changes.
### Response:
def on_tblFunctions1_itemSelectionChanged(self):
"""Choose selected hazard x... |
def setRows(self, rows):
""" Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well) """
self._raster[0] = rows
if self._raster[1] == 0:
self._raster[1] = 1 | Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well) | Below is the the instruction that describes the task:
### Input:
Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well)
### Response:
def setRows(self, rows):
""" Sets the number of rows in the raster (if columns have not been initialized, set to 1 as well) """
... |
def get_network(ipv4addr=None, network=None, return_fields=None, **api_opts):
'''
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,e... | Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI Example:
.. code-block:: bash
salt-call infoblox.get_net... | Below is the the instruction that describes the task:
### Input:
Get list of all networks. This is helpful when looking up subnets to use
with func:nextavailableip
This call is offen slow and not cached!
some return_fields
comment,network,network_view,ddns_domainname,disable,enable_ddns
CLI E... |
def provideObjectsToLearn(self, learningConfig, plot=False):
"""
Returns the objects in a canonical format to be sent to an experiment.
The input, learningConfig, should have the following format. It is a
mapping from object to a list of features to sample locations from, and
the number of points t... | Returns the objects in a canonical format to be sent to an experiment.
The input, learningConfig, should have the following format. It is a
mapping from object to a list of features to sample locations from, and
the number of points to sample from each feature. Note that these objects
should be first a... | Below is the the instruction that describes the task:
### Input:
Returns the objects in a canonical format to be sent to an experiment.
The input, learningConfig, should have the following format. It is a
mapping from object to a list of features to sample locations from, and
the number of points to sa... |
def parametrize_peaks(self, intervals, max_peakwidth=50, min_peakwidth=25, symmetric_bounds=True):
"""
Computes and stores the intonation profile of an audio recording.
:param intervals: these will be the reference set of intervals to which peak positions
correspond to. For each interv... | Computes and stores the intonation profile of an audio recording.
:param intervals: these will be the reference set of intervals to which peak positions
correspond to. For each interval, the properties of corresponding peak, if exists,
will be computed and stored as intonation profile.
... | Below is the the instruction that describes the task:
### Input:
Computes and stores the intonation profile of an audio recording.
:param intervals: these will be the reference set of intervals to which peak positions
correspond to. For each interval, the properties of corresponding peak, if exist... |
def main(log_files):
""" Main executor of the trimmomatic_report template.
Parameters
----------
log_files : list
List of paths to the trimmomatic log files.
"""
log_storage = OrderedDict()
for log in log_files:
log_id = log.rstrip("_trimlog.txt")
# Populate stor... | Main executor of the trimmomatic_report template.
Parameters
----------
log_files : list
List of paths to the trimmomatic log files. | Below is the the instruction that describes the task:
### Input:
Main executor of the trimmomatic_report template.
Parameters
----------
log_files : list
List of paths to the trimmomatic log files.
### Response:
def main(log_files):
""" Main executor of the trimmomatic_report template.
... |
def main():
"""
NAME
umich_magic.py
DESCRIPTION
converts UMICH .mag format files to magic_measurements format files
SYNTAX
umich_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
... | NAME
umich_magic.py
DESCRIPTION
converts UMICH .mag format files to magic_measurements format files
SYNTAX
umich_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-usr USER: identify user, default is ""
-f FILE: specify .mag ... | Below is the the instruction that describes the task:
### Input:
NAME
umich_magic.py
DESCRIPTION
converts UMICH .mag format files to magic_measurements format files
SYNTAX
umich_magic.py [command line options]
OPTIONS
-h: prints the help message and quits.
-us... |
def has_no_title(self, title, **kwargs):
"""
Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whe... | Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
bool: Whether it doesn't match. | Below is the the instruction that describes the task:
### Input:
Checks if the page doesn't have the given title.
Args:
title (str | RegexObject): The string that the title should include.
**kwargs: Arbitrary keyword arguments for :class:`TitleQuery`.
Returns:
b... |
def __normalize_progress(self):
"""
Adjust the funding progress filter to be a factor of 10
"""
progress = self['funding_progress']
if progress % 10 != 0:
progress = round(float(progress) / 10)
progress = int(progress) * 10
self['funding_prog... | Adjust the funding progress filter to be a factor of 10 | Below is the the instruction that describes the task:
### Input:
Adjust the funding progress filter to be a factor of 10
### Response:
def __normalize_progress(self):
"""
Adjust the funding progress filter to be a factor of 10
"""
progress = self['funding_progress']
if prog... |
def process_incoming_tuples(self):
"""Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt.
"""
# back-pressure
if self.output_helper.is_out_queue_available():
self._read_tuples_and_exec... | Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt. | Below is the the instruction that describes the task:
### Input:
Should be called when tuple was buffered into in_stream
This method is equivalent to ``addBoltTasks()`` but
is designed for event-driven single-thread bolt.
### Response:
def process_incoming_tuples(self):
"""Should be called when tuple ... |
def share(self, name, item):
'''
Share an object via the telepath protocol.
Args:
name (str): Name of the shared object
item (object): The object to share over telepath.
'''
try:
if isinstance(item, s_telepath.Aware):
item.on... | Share an object via the telepath protocol.
Args:
name (str): Name of the shared object
item (object): The object to share over telepath. | Below is the the instruction that describes the task:
### Input:
Share an object via the telepath protocol.
Args:
name (str): Name of the shared object
item (object): The object to share over telepath.
### Response:
def share(self, name, item):
'''
Share an object v... |
def scencd(sc, sclkch, MXPART=None):
"""
Encode character representation of spacecraft clock time into a
double precision number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param sclkch: Character rep... | Encode character representation of spacecraft clock time into a
double precision number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param sclkch: Character representation of a spacecraft clock.
:type sclk... | Below is the the instruction that describes the task:
### Input:
Encode character representation of spacecraft clock time into a
double precision number.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/scencd_c.html
:param sc: NAIF spacecraft identification code.
:type sc: int
:param s... |
def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False):
"""
Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments.
"""
try:
handlers = get_magic_attr(coro)
except AttributeError:
... | Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments. | Below is the the instruction that describes the task:
### Input:
Return true if `coro` has been decorated with :func:`iq_handler` for the
given `type_` and `payload_cls` and the specified keyword arguments.
### Response:
def is_iq_handler(type_, payload_cls, coro, *, with_send_reply=False):
"""
Return ... |
def _add_chart_graphicFrame(self, rId, x, y, cx, cy):
"""Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and
refers to the chart part identified by *rId*.
"""
shape_id = self._next_shape_id
... | Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and
refers to the chart part identified by *rId*. | Below is the the instruction that describes the task:
### Input:
Return new `p:graphicFrame` element appended to this shape tree.
The `p:graphicFrame` element has the specified position and size and
refers to the chart part identified by *rId*.
### Response:
def _add_chart_graphicFrame(self, rId, ... |
def get_curie(self, uri):
'''Get a CURIE from a URI '''
prefix = self.get_curie_prefix(uri)
if prefix is not None:
key = self.curie_map[prefix]
return '%s:%s' % (prefix, uri[len(key):len(uri)])
return None | Get a CURIE from a URI | Below is the the instruction that describes the task:
### Input:
Get a CURIE from a URI
### Response:
def get_curie(self, uri):
'''Get a CURIE from a URI '''
prefix = self.get_curie_prefix(uri)
if prefix is not None:
key = self.curie_map[prefix]
return '%s:%s' % (pre... |
def notify(self, event_id):
"""Let the FlowControl system know that there is an event."""
self._event_buffer.extend([event_id])
self._event_count += 1
if self._event_count >= self.threshold:
logger.debug("Eventcount >= threshold")
self.make_callback(kind="event") | Let the FlowControl system know that there is an event. | Below is the the instruction that describes the task:
### Input:
Let the FlowControl system know that there is an event.
### Response:
def notify(self, event_id):
"""Let the FlowControl system know that there is an event."""
self._event_buffer.extend([event_id])
self._event_count += 1
... |
def obfn_dfd(self):
r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \right) \|_2^2`.
"""
Ef = sl.inner(self.Zf, self.obfn_fvarf(), axis=self.cri.axisM) \
- self.Sf
return (np.linalg.norm(self.W * sl.irfftn(Ef, sel... | r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \right) \|_2^2`. | Below is the the instruction that describes the task:
### Input:
r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{d}_m * \mathbf{x}_m - \mathbf{s} \right) \|_2^2`.
### Response:
def obfn_dfd(self):
r"""Compute data fidelity term :math:`(1/2) \| W \left( \sum_m
\mathbf{... |
def is_almost_full(self):
"""Return whether the activity is almost full (>90%)."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_up = self.eighthsignup_set.count()
return num_signed_up >= (0.9 * capacity)
return False | Return whether the activity is almost full (>90%). | Below is the the instruction that describes the task:
### Input:
Return whether the activity is almost full (>90%).
### Response:
def is_almost_full(self):
"""Return whether the activity is almost full (>90%)."""
capacity = self.get_true_capacity()
if capacity != -1:
num_signed_... |
def lemmatize(self, tokens):
"""define list of lemmas"""
entries = self.entries
forms_and_lemmas = self.forms_and_lemmas
lemma_list = [x[0] for x in entries]
"""Provide a lemma for each token"""
lemmatized = []
for token in tokens:
"""check for a matc... | define list of lemmas | Below is the the instruction that describes the task:
### Input:
define list of lemmas
### Response:
def lemmatize(self, tokens):
"""define list of lemmas"""
entries = self.entries
forms_and_lemmas = self.forms_and_lemmas
lemma_list = [x[0] for x in entries]
"""Provide a le... |
def update_resource(self, resource, filename, change=None):
"""Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModi... | Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModified from the GET response instead
but maybe warn if different ... | Below is the the instruction that describes the task:
### Input:
Update resource from uri to filename on local system.
Update means three things:
1. GET resources
2. set mtime in local time to be equal to timestamp in UTC (should perhaps
or at least warn if different from LastModifi... |
def bbox(self):
bbox = self._df[['id', 'x1', 'y1', 'x2', 'y2']].copy()
# TODO: Fix this to become x, y, w, h
if self.bbox_with_size:
bbox['y2'] -= bbox['y1']
bbox['x2'] -= bbox['x1']
"""Converts a dataframe to a list of arrays
:param df:
:param le... | Converts a dataframe to a list of arrays
:param df:
:param length:
:return: | Below is the the instruction that describes the task:
### Input:
Converts a dataframe to a list of arrays
:param df:
:param length:
:return:
### Response:
def bbox(self):
bbox = self._df[['id', 'x1', 'y1', 'x2', 'y2']].copy()
# TODO: Fix this to become x, y, w, h
if ... |
def available_repositories(self, **kwargs):
"""Lists available repositories for the repository set
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response... | Lists available repositories for the repository set
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the server's response otherwise.
:param kwargs: Arguments to pass to... | Below is the the instruction that describes the task:
### Input:
Lists available repositories for the repository set
:param synchronous: What should happen if the server returns an HTTP
202 (accepted) status code? Wait for the task to complete if
``True``. Immediately return the ser... |
def mps_device_name():
"""
Returns name of MPS device that will be used, else None.
"""
lib = _load_tcmps_lib()
if lib is None:
return None
n = 256
c_name = (_ctypes.c_char * n)()
ret = lib.TCMPSMetalDeviceName(_ctypes.byref(c_name), _ctypes.c_int32(n))
if ret == 0:
... | Returns name of MPS device that will be used, else None. | Below is the the instruction that describes the task:
### Input:
Returns name of MPS device that will be used, else None.
### Response:
def mps_device_name():
"""
Returns name of MPS device that will be used, else None.
"""
lib = _load_tcmps_lib()
if lib is None:
return None
n = 25... |
def MI_associators(self,
env,
objectName,
assocClassName,
resultClassName,
role,
resultRole,
propertyList):
# pylint: disable=invalid-name
"""R... | Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method. | Below is the the instruction that describes the task:
### Input:
Return instances associated to a given object.
Implements the WBEM operation Associators in terms
of the references method. A derived class will not normally
override this method.
### Response:
def MI_associators(self,
... |
def get_cipher(data):
"""http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string).
"""
legend = {0: 'Use group cipher suite', 1: 'WEP-40', 2: 'TKIP... | http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string). | Below is the the instruction that describes the task:
### Input:
http://git.kernel.org/cgit/linux/kernel/git/jberg/iw.git/tree/scan.c?id=v3.17#n336.
Positional arguments:
data -- bytearray data to read.
Returns:
WiFi stream cipher used by the access point (string).
### Response:
def get_cipher(da... |
def expand_env_variables(lines_enum):
# type: (ReqFileLines) -> ReqFileLines
"""Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that con... | Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't accidentally (partially) expanded.
2. Ensure consistency across pl... | Below is the the instruction that describes the task:
### Input:
Replace all environment variables that can be retrieved via `os.getenv`.
The only allowed format for environment variables defined in the
requirement file is `${MY_VARIABLE_1}` to ensure two things:
1. Strings that contain a `$` aren't a... |
def get(cls, whitelist_id, whitelist_result_id,
note_text_whitelist_result_id, monetary_account_id=None,
custom_headers=None):
"""
:type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type whitelist_id: int
:type... | :type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type whitelist_id: int
:type whitelist_result_id: int
:type note_text_whitelist_result_id: int
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseNoteTextWhitelist... | Below is the the instruction that describes the task:
### Input:
:type api_context: context.ApiContext
:type user_id: int
:type monetary_account_id: int
:type whitelist_id: int
:type whitelist_result_id: int
:type note_text_whitelist_result_id: int
:type custom_header... |
def parse_readme():
"""Parse contents of the README."""
# Get the long description from the relevant file
here = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(here, 'README.md')
with codecs.open(readme_path, encoding='utf-8') as handle:
long_description = handle.read(... | Parse contents of the README. | Below is the the instruction that describes the task:
### Input:
Parse contents of the README.
### Response:
def parse_readme():
"""Parse contents of the README."""
# Get the long description from the relevant file
here = os.path.abspath(os.path.dirname(__file__))
readme_path = os.path.join(here, '... |
def cached_tree(self, subject_ids=None, visit_ids=None, fill=False):
"""
Access the repository tree and caches it for subsequent
accesses
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None... | Access the repository tree and caches it for subsequent
accesses
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None all are returned
visit_ids : list(str)
List of visit IDs with which ... | Below is the the instruction that describes the task:
### Input:
Access the repository tree and caches it for subsequent
accesses
Parameters
----------
subject_ids : list(str)
List of subject IDs with which to filter the tree with. If
None all are returned
... |
def latex2png(snippet, outfile):
"""Compiles a LaTeX snippet to png"""
pngimage = os.path.join(IMAGEDIR, outfile + '.png')
texdocument = os.path.join(IMAGEDIR, 'tmp.tex')
with open(texdocument, 'w') as doc:
doc.write(LATEX_DOC % (snippet))
environment = os.environ
environment['shell_esca... | Compiles a LaTeX snippet to png | Below is the the instruction that describes the task:
### Input:
Compiles a LaTeX snippet to png
### Response:
def latex2png(snippet, outfile):
"""Compiles a LaTeX snippet to png"""
pngimage = os.path.join(IMAGEDIR, outfile + '.png')
texdocument = os.path.join(IMAGEDIR, 'tmp.tex')
with open(texdocu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.