code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_outfilename(url, domain=None):
"""Construct the output filename from domain and end of path."""
if domain is None:
domain = get_domain(url)
path = '{url.path}'.format(url=urlparse(url))
if '.' in path:
tail_url = path.split('.')[-2]
else:
tail_url = path
if tail... | Construct the output filename from domain and end of path. | Below is the the instruction that describes the task:
### Input:
Construct the output filename from domain and end of path.
### Response:
def get_outfilename(url, domain=None):
"""Construct the output filename from domain and end of path."""
if domain is None:
domain = get_domain(url)
path = '... |
def _ParseRecordString(
self, record_strings_data, record_strings_data_offset, string_offset):
"""Parses a record string.
Args:
record_strings_data (bytes): record strings data.
record_strings_data_offset (int): offset of the record strings data
relative to the start of the file.
... | Parses a record string.
Args:
record_strings_data (bytes): record strings data.
record_strings_data_offset (int): offset of the record strings data
relative to the start of the file.
string_offset (int): offset of the string relative to the start of
the file.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Parses a record string.
Args:
record_strings_data (bytes): record strings data.
record_strings_data_offset (int): offset of the record strings data
relative to the start of the file.
string_offset (int): offset of the ... |
def save(self, **kwargs):
"""
Create the organization, then get the user, then make the owner.
"""
is_active = True
try:
user = get_user_model().objects.get(email=self.cleaned_data["email"])
except get_user_model().DoesNotExist:
user = invitation_b... | Create the organization, then get the user, then make the owner. | Below is the the instruction that describes the task:
### Input:
Create the organization, then get the user, then make the owner.
### Response:
def save(self, **kwargs):
"""
Create the organization, then get the user, then make the owner.
"""
is_active = True
try:
... |
def open_ftp(self, url):
"""Use FTP protocol."""
if not isinstance(url, str):
raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
import mimetypes
host, path = splithost(url)
if not host: raise URLError('ftp error: no host given')
... | Use FTP protocol. | Below is the the instruction that describes the task:
### Input:
Use FTP protocol.
### Response:
def open_ftp(self, url):
"""Use FTP protocol."""
if not isinstance(url, str):
raise URLError('ftp error: proxy support for ftp protocol currently not implemented')
import mimetypes
... |
def applies_to(self, transition, from_state=None):
"""Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to... | Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook apply to the related transition, given a
valid source ... | Below is the the instruction that describes the task:
### Input:
Whether this hook applies to the given transition/state.
Args:
transition (Transition): the transition to check
from_state (State or None): the state to check. If absent, the check
is 'might this hook a... |
def profile(fn=None, skip=0, filename=None, immediate=False, dirs=False,
sort=None, entries=40,
profiler=('cProfile', 'profile', 'hotshot')):
"""Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results wi... | Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after each call.
If `dirs` is False only the name of the file will be pri... | Below is the the instruction that describes the task:
### Input:
Mark `fn` for profiling.
If `skip` is > 0, first `skip` calls to `fn` will not be profiled.
If `immediate` is False, profiling results will be printed to
sys.stdout on program termination. Otherwise results will be printed
after eac... |
def enroll(self):
"""Enrollment function"""
self.verify_integrity()
if session.get('u2f_enroll_authorized', False):
if request.method == 'GET':
return jsonify(self.get_enroll()), 200
elif request.method == 'POST':
response = self.verify_e... | Enrollment function | Below is the the instruction that describes the task:
### Input:
Enrollment function
### Response:
def enroll(self):
"""Enrollment function"""
self.verify_integrity()
if session.get('u2f_enroll_authorized', False):
if request.method == 'GET':
return jsonify(self... |
def generate_tokens(self):
"""Tokenize the file, run physical line checks and yield tokens."""
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
tokengen = tokenize.generate_tokens(self.readline)
try:
for token in tokengen:
... | Tokenize the file, run physical line checks and yield tokens. | Below is the the instruction that describes the task:
### Input:
Tokenize the file, run physical line checks and yield tokens.
### Response:
def generate_tokens(self):
"""Tokenize the file, run physical line checks and yield tokens."""
if self._io_error:
self.report_error(1, 0, 'E902 %s... |
def _collapse_fastq(in_fn):
"""
collapse reads into unique sequences
"""
args = argparse.Namespace()
args.fastq = in_fn
args.minimum = 1
args.out = op.dirname(in_fn)
return collapse_fastq(args) | collapse reads into unique sequences | Below is the the instruction that describes the task:
### Input:
collapse reads into unique sequences
### Response:
def _collapse_fastq(in_fn):
"""
collapse reads into unique sequences
"""
args = argparse.Namespace()
args.fastq = in_fn
args.minimum = 1
args.out = op.dirname(in_fn)
r... |
def find_articulation_vertices(graph):
"""Finds all of the articulation vertices within a graph.
Returns a list of all articulation vertices within the graph.
Returns an empty list for an empty graph.
"""
articulation_vertices = []
all_nodes = graph.get_all_node_ids()
if len(all_nodes) == ... | Finds all of the articulation vertices within a graph.
Returns a list of all articulation vertices within the graph.
Returns an empty list for an empty graph. | Below is the the instruction that describes the task:
### Input:
Finds all of the articulation vertices within a graph.
Returns a list of all articulation vertices within the graph.
Returns an empty list for an empty graph.
### Response:
def find_articulation_vertices(graph):
"""Finds all of the articu... |
def read_model(self):
""" Read the model and the couplings from the model file.
"""
if self.verbosity > 0:
settings.m(0,'reading model',self.model)
# read model
boolRules = []
for line in open(self.model):
if line.startswith('#') and 'modelType =' ... | Read the model and the couplings from the model file. | Below is the the instruction that describes the task:
### Input:
Read the model and the couplings from the model file.
### Response:
def read_model(self):
""" Read the model and the couplings from the model file.
"""
if self.verbosity > 0:
settings.m(0,'reading model',self.model... |
def draw_on_image(self,
image,
color=(0, 255, 0), color_face=None,
color_lines=None, color_points=None,
alpha=1.0, alpha_face=None,
alpha_lines=None, alpha_points=None,
size=1, size_lines=... | Draw all polygons onto a given image.
Parameters
----------
image : (H,W,C) ndarray
The image onto which to draw the bounding boxes.
This image should usually have the same shape as set in
``PolygonsOnImage.shape``.
color : iterable of int, optional
... | Below is the the instruction that describes the task:
### Input:
Draw all polygons onto a given image.
Parameters
----------
image : (H,W,C) ndarray
The image onto which to draw the bounding boxes.
This image should usually have the same shape as set in
`... |
def stylify_files(text):
"""Stylify many files."""
for filename in text:
text[filename] = stylify_code(text[filename])
return text | Stylify many files. | Below is the the instruction that describes the task:
### Input:
Stylify many files.
### Response:
def stylify_files(text):
"""Stylify many files."""
for filename in text:
text[filename] = stylify_code(text[filename])
return text |
def assertFileSizeGreater(self, filename, size, msg=None):
'''Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provide... | Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided, the :mod:`marbles.mixins` or
:mod:`unittest` standard m... | Below is the the instruction that describes the task:
### Input:
Fail if ``filename``'s size is not greater than ``size`` as
determined by the '>' operator.
Parameters
----------
filename : str, bytes, file-like
size : int, float
msg : str
If not provided... |
def serve_forever(self):
"""Wrapper to the serve_forever function."""
loop = True
while loop:
loop = self.__serve_forever()
self.end() | Wrapper to the serve_forever function. | Below is the the instruction that describes the task:
### Input:
Wrapper to the serve_forever function.
### Response:
def serve_forever(self):
"""Wrapper to the serve_forever function."""
loop = True
while loop:
loop = self.__serve_forever()
self.end() |
def rollback(self):
"""Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able ... | Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutations from the
buffer, but won't be able to rollback already committ... | Below is the the instruction that describes the task:
### Input:
Rolls back pending mutations.
Keep in mind that NoTransactionBatch splits all mutations into smaller
batches and commit them as soon as mutation buffer reaches maximum length.
That's why rollback method will only roll back pending mutatio... |
def get_ref_bedtool(ref_file, config, chrom=None):
"""Retrieve a pybedtool BedTool object with reference sizes from input reference.
"""
broad_runner = broad.runner_from_path("picard", config)
ref_dict = broad_runner.run_fn("picard_index_ref", ref_file)
ref_lines = []
with pysam.Samfile(ref_dict... | Retrieve a pybedtool BedTool object with reference sizes from input reference. | Below is the the instruction that describes the task:
### Input:
Retrieve a pybedtool BedTool object with reference sizes from input reference.
### Response:
def get_ref_bedtool(ref_file, config, chrom=None):
"""Retrieve a pybedtool BedTool object with reference sizes from input reference.
"""
broad_ru... |
def tick_all(self, times):
"""
Tick all the EWMAs for the given number of times
"""
for i in range(times):
for avg in (self.m1, self.m5, self.m15, self.day):
avg.tick() | Tick all the EWMAs for the given number of times | Below is the the instruction that describes the task:
### Input:
Tick all the EWMAs for the given number of times
### Response:
def tick_all(self, times):
"""
Tick all the EWMAs for the given number of times
"""
for i in range(times):
for avg in (self.m1, self.m5, self.... |
def protocols(self):
"""
:rtype: dict[int, list of ProtocolAnalyzer]
"""
result = {}
for i, group in enumerate(self.rootItem.children):
result[i] = [child.protocol for child in group.children]
return result | :rtype: dict[int, list of ProtocolAnalyzer] | Below is the the instruction that describes the task:
### Input:
:rtype: dict[int, list of ProtocolAnalyzer]
### Response:
def protocols(self):
"""
:rtype: dict[int, list of ProtocolAnalyzer]
"""
result = {}
for i, group in enumerate(self.rootItem.children):
resu... |
def _printClassDomain(self, hrlinetop=True, print_inferred=False):
"""
print(more informative stats about the object)
2016-06-14: added inferred option
"""
if not self.currentEntity: # ==> ontology level
return
x = self.currentEntity['object']
if self... | print(more informative stats about the object)
2016-06-14: added inferred option | Below is the the instruction that describes the task:
### Input:
print(more informative stats about the object)
2016-06-14: added inferred option
### Response:
def _printClassDomain(self, hrlinetop=True, print_inferred=False):
"""
print(more informative stats about the object)
2016-... |
def get_ar(self):
"""Create a temporary AR to fetch the fields from
"""
if not self.tmp_ar:
logger.info("*** CREATING TEMPORARY AR ***")
self.tmp_ar = self.context.restrictedTraverse(
"portal_factory/AnalysisRequest/Request new analyses")
return se... | Create a temporary AR to fetch the fields from | Below is the the instruction that describes the task:
### Input:
Create a temporary AR to fetch the fields from
### Response:
def get_ar(self):
"""Create a temporary AR to fetch the fields from
"""
if not self.tmp_ar:
logger.info("*** CREATING TEMPORARY AR ***")
self... |
def calc_particle_group_region_size(s, region_size=40, max_mem=1e9, **kwargs):
"""
Finds the biggest region size for LM particle optimization with a
given memory constraint.
Input Parameters
----------------
s : :class:`peri.states.ImageState`
The state with the particles
... | Finds the biggest region size for LM particle optimization with a
given memory constraint.
Input Parameters
----------------
s : :class:`peri.states.ImageState`
The state with the particles
region_size : Int or 3-element list-like of ints, optional.
The initial guess... | Below is the the instruction that describes the task:
### Input:
Finds the biggest region size for LM particle optimization with a
given memory constraint.
Input Parameters
----------------
s : :class:`peri.states.ImageState`
The state with the particles
region_size : Int or... |
def get_broadcast_transaction_hashes(coin_symbol='btc', api_key=None, limit=10):
'''
Warning, slow!
'''
transactions = get_broadcast_transactions(
coin_symbol=coin_symbol,
api_key=api_key,
limit=limit,
)
return [tx['hash'] for tx in transactions] | Warning, slow! | Below is the the instruction that describes the task:
### Input:
Warning, slow!
### Response:
def get_broadcast_transaction_hashes(coin_symbol='btc', api_key=None, limit=10):
'''
Warning, slow!
'''
transactions = get_broadcast_transactions(
coin_symbol=coin_symbol,
api_key=a... |
def genome_info(genome, info):
"""
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
"""
try:
scg = info['#SCG... | return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome | Below is the the instruction that describes the task:
### Input:
return genome info for choosing representative
if ggKbase table provided - choose rep based on SCGs and genome length
- priority for most SCGs - extra SCGs, then largest genome
otherwise, based on largest genome
### Response:
def ge... |
def inc_nbrs(self, node):
"""
List of nodes connected by incoming edges
"""
l = map(self.head, self.inc_edges(node))
#l.sort()
return l | List of nodes connected by incoming edges | Below is the the instruction that describes the task:
### Input:
List of nodes connected by incoming edges
### Response:
def inc_nbrs(self, node):
"""
List of nodes connected by incoming edges
"""
l = map(self.head, self.inc_edges(node))
#l.sort()
return l |
def delete_log(
self,
log_name,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Deletes all the log entries in a log.
The log reappears if it receives new entries.
Log entrie... | Deletes all the log entries in a log.
The log reappears if it receives new entries.
Log entries written shortly before the delete operation might not be
deleted.
Example:
>>> from google.cloud import logging_v2
>>>
>>> client = logging_v2.LoggingServi... | Below is the the instruction that describes the task:
### Input:
Deletes all the log entries in a log.
The log reappears if it receives new entries.
Log entries written shortly before the delete operation might not be
deleted.
Example:
>>> from google.cloud import loggin... |
def set_reaction(self, reaction_id, reaction):
"""Set the reaction ID to a reaction given by a
:class:`Reaction <psamm.reaction.Reaction>`
If an existing reaction exists with the given reaction ID it will be
overwritten.
"""
# Overwrite previous reaction if the same id ... | Set the reaction ID to a reaction given by a
:class:`Reaction <psamm.reaction.Reaction>`
If an existing reaction exists with the given reaction ID it will be
overwritten. | Below is the the instruction that describes the task:
### Input:
Set the reaction ID to a reaction given by a
:class:`Reaction <psamm.reaction.Reaction>`
If an existing reaction exists with the given reaction ID it will be
overwritten.
### Response:
def set_reaction(self, reaction_id, reac... |
def lookup_values_from_error_table(scores, err_df):
""" Find matching q-value for each score in 'scores' """
ix = find_nearest_matches(np.float32(err_df.cutoff.values), np.float32(scores))
return err_df.pvalue.iloc[ix].values, err_df.svalue.iloc[ix].values, err_df.pep.iloc[ix].values, err_df.qvalue.iloc[ix]... | Find matching q-value for each score in 'scores' | Below is the the instruction that describes the task:
### Input:
Find matching q-value for each score in 'scores'
### Response:
def lookup_values_from_error_table(scores, err_df):
""" Find matching q-value for each score in 'scores' """
ix = find_nearest_matches(np.float32(err_df.cutoff.values), np.float32... |
def _process_merge_request_change(self, payload, event, codebase=None):
"""
Consumes the merge_request JSON as a python object and turn it into a buildbot change.
:arguments:
payload
Python Object that represents the JSON sent by GitLab Service
Hook.
... | Consumes the merge_request JSON as a python object and turn it into a buildbot change.
:arguments:
payload
Python Object that represents the JSON sent by GitLab Service
Hook. | Below is the the instruction that describes the task:
### Input:
Consumes the merge_request JSON as a python object and turn it into a buildbot change.
:arguments:
payload
Python Object that represents the JSON sent by GitLab Service
Hook.
### Response:
def _pro... |
def firmware_download_output_fwdl_cmd_status(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
config = firmware_download
output = ET.SubElement(firmware_download, "output")
fwdl_cmd_statu... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def firmware_download_output_fwdl_cmd_status(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
firmware_download = ET.Element("firmware_download")
confi... |
def bwar_pitch(return_all=False):
"""
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True.
"""
url = "http://www.baseball-reference.com/data/war_daily_pitch.txt"
s = requests.get(url... | Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True. | Below is the the instruction that describes the task:
### Input:
Get data from war_daily_pitch table. Returns WAR, its components, and a few other useful stats.
To get all fields from this table, supply argument return_all=True.
### Response:
def bwar_pitch(return_all=False):
"""
Get data from war_dai... |
def measure_put_attachment(self, key, value):
"""Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last value will be ke... | Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last value will be kept. | Below is the the instruction that describes the task:
### Input:
Associate the contextual information of an Exemplar to this MeasureMap
Contextual information is represented as key - value string pairs.
If this method is called multiple times with the same key,
only the last valu... |
def __get_git_bin():
"""
Get git binary location.
:return: Check git location
"""
git = 'git'
alternatives = [
'/usr/bin/git'
]
for alt in alternatives:
if os.path.exists(alt):
git = alt
break
return git | Get git binary location.
:return: Check git location | Below is the the instruction that describes the task:
### Input:
Get git binary location.
:return: Check git location
### Response:
def __get_git_bin():
"""
Get git binary location.
:return: Check git location
"""
git = 'git'
alternatives = [
'/usr/bin/git'
]
for alt i... |
def batch_annotate_files(
self,
requests,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
):
"""
Service that performs image detection and annotation for a batch of files.
Now only "applica... | Service that performs image detection and annotation for a batch of files.
Now only "application/pdf", "image/tiff" and "image/gif" are supported.
This service will extract at most the first 10 frames (gif) or pages
(pdf or tiff) from each file provided and perform detection and annotation
... | Below is the the instruction that describes the task:
### Input:
Service that performs image detection and annotation for a batch of files.
Now only "application/pdf", "image/tiff" and "image/gif" are supported.
This service will extract at most the first 10 frames (gif) or pages
(pdf or ti... |
def pagingRequestType3():
"""PAGING REQUEST TYPE 3 Section 9.1.24"""
# This message has a L2 Pseudo Length of 19
a = L2PseudoLength(l2pLength=0x13)
b = TpPd(pd=0x6)
c = MessageType(mesType=0x24) # 00100100
d = PageModeAndChannelNeeded()
e = TmsiPTmsi()
f = TmsiPTmsi()
g = TmsiPTmsi()
... | PAGING REQUEST TYPE 3 Section 9.1.24 | Below is the the instruction that describes the task:
### Input:
PAGING REQUEST TYPE 3 Section 9.1.24
### Response:
def pagingRequestType3():
"""PAGING REQUEST TYPE 3 Section 9.1.24"""
# This message has a L2 Pseudo Length of 19
a = L2PseudoLength(l2pLength=0x13)
b = TpPd(pd=0x6)
c = MessageType(me... |
def parse_database_url(url):
"""Parses a database URL."""
if url == 'sqlite://:memory:':
# this is a special case, because if we pass this URL into
# urlparse, urlparse will choke trying to interpret "memory"
# as a port number
return {
'ENGINE': DATABASE_SCHEMES['sq... | Parses a database URL. | Below is the the instruction that describes the task:
### Input:
Parses a database URL.
### Response:
def parse_database_url(url):
"""Parses a database URL."""
if url == 'sqlite://:memory:':
# this is a special case, because if we pass this URL into
# urlparse, urlparse will choke trying t... |
def get_star(self, node):
"""Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's star.
:ra... | Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
in the node's star.
:raises: ValueError -- No such node exis... | Below is the the instruction that describes the task:
### Input:
Given a node, get a copy of that node's star, that is, the set of
hyperedges that the node belongs to.
:param node: node to retrieve the star of.
:returns: set -- set of hyperedge_ids for the hyperedges
... |
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
'''
ret = {}
name = None
attrs = {}
attr = None
for line in salt.utils.itertools.split(out, '\n'):
if line ... | Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'. | Below is the the instruction that describes the task:
### Input:
Helper function for info_installed()
Processes stdout output from a single invocation of
'opkg status'.
### Response:
def _process_info_installed_output(out, filter_attrs):
'''
Helper function for info_installed()
Processes stdo... |
def _position():
"""Returns the current xy coordinates of the mouse cursor as a two-integer
tuple by calling the GetCursorPos() win32 function.
Returns:
(x, y) tuple of the current xy coordinates of the mouse cursor.
"""
cursor = POINT()
ctypes.windll.user32.GetCursorPos(ctypes.byref(cur... | Returns the current xy coordinates of the mouse cursor as a two-integer
tuple by calling the GetCursorPos() win32 function.
Returns:
(x, y) tuple of the current xy coordinates of the mouse cursor. | Below is the the instruction that describes the task:
### Input:
Returns the current xy coordinates of the mouse cursor as a two-integer
tuple by calling the GetCursorPos() win32 function.
Returns:
(x, y) tuple of the current xy coordinates of the mouse cursor.
### Response:
def _position():
"""... |
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4,
output_stream=sys.stdout):
"""this function prints the components of a configobj ini file. It is
recursive for outputing the nested sections of the ini file."""
options = [
value
... | this function prints the components of a configobj ini file. It is
recursive for outputing the nested sections of the ini file. | Below is the the instruction that describes the task:
### Input:
this function prints the components of a configobj ini file. It is
recursive for outputing the nested sections of the ini file.
### Response:
def _write_ini(source_dict, namespace_name=None, level=0, indent_size=4,
output_... |
def update(self, i):
"""D.update(E) -> None. Update D from iterable E with pre-existing
items being overwritten.
Elements in E are assumed to be dicts containing the primary key to
allow the equivelent of:
for k in E: D[k.primary_key] = k
"""
key_list = ... | D.update(E) -> None. Update D from iterable E with pre-existing
items being overwritten.
Elements in E are assumed to be dicts containing the primary key to
allow the equivelent of:
for k in E: D[k.primary_key] = k | Below is the the instruction that describes the task:
### Input:
D.update(E) -> None. Update D from iterable E with pre-existing
items being overwritten.
Elements in E are assumed to be dicts containing the primary key to
allow the equivelent of:
for k in E: D[k.primary_key... |
def parse(fmt, stri):
"""Parse keys and corresponding values from *stri* using format described in *fmt* string."""
convdef = get_convert_dict(fmt)
keyvals = regex_formatter.extract_values(fmt, stri)
for key in convdef.keys():
keyvals[key] = _convert(convdef[key], keyvals[key])
return keyva... | Parse keys and corresponding values from *stri* using format described in *fmt* string. | Below is the the instruction that describes the task:
### Input:
Parse keys and corresponding values from *stri* using format described in *fmt* string.
### Response:
def parse(fmt, stri):
"""Parse keys and corresponding values from *stri* using format described in *fmt* string."""
convdef = get_convert_di... |
def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_config.get_field('format', filename)
if formatter not in self._formatters:
formatter = self._defau... | Returns a formatted log line | Below is the the instruction that describes the task:
### Input:
Returns a formatted log line
### Response:
def format(self, filename, line, timestamp, **kwargs):
"""Returns a formatted log line"""
line = unicode(line.encode("utf-8"), "utf-8", errors="ignore")
formatter = self._beaver_confi... |
def _preprocess_chars(self, chars):
'''
Performs string preprocessing before the main conversion algorithm
is used. Simple string replacements (for example, fullwidth rōmaji
to regular rōmaji) are performed at this point.
'''
chars = self._normalize_dakuten(chars)
... | Performs string preprocessing before the main conversion algorithm
is used. Simple string replacements (for example, fullwidth rōmaji
to regular rōmaji) are performed at this point. | Below is the the instruction that describes the task:
### Input:
Performs string preprocessing before the main conversion algorithm
is used. Simple string replacements (for example, fullwidth rōmaji
to regular rōmaji) are performed at this point.
### Response:
def _preprocess_chars(self, chars):
... |
def solution_violations(solution, events, slots):
"""Take a solution and return a list of violated constraints
Parameters
----------
solution: list or tuple
a schedule in solution form
events : list or tuple
of resources.Event instances
slots : list or tuple
... | Take a solution and return a list of violated constraints
Parameters
----------
solution: list or tuple
a schedule in solution form
events : list or tuple
of resources.Event instances
slots : list or tuple
of resources.Slot instances
Returns
... | Below is the the instruction that describes the task:
### Input:
Take a solution and return a list of violated constraints
Parameters
----------
solution: list or tuple
a schedule in solution form
events : list or tuple
of resources.Event instances
slots : li... |
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
''' use bet to strip skull from given anatomy '''
# should add options to use betsurf and T1/T2 in the future
# Since BET fails on weirdly distributed datasets, I added 3dUnifize in... I realize this makes this dependent on AFNI. Sorry, :)
if ... | use bet to strip skull from given anatomy | Below is the the instruction that describes the task:
### Input:
use bet to strip skull from given anatomy
### Response:
def skull_strip(dset,suffix='_ns',prefix=None,unifize=True):
''' use bet to strip skull from given anatomy '''
# should add options to use betsurf and T1/T2 in the future
# Since BET... |
def partition_read(
self,
session,
table,
key_set,
transaction=None,
index=None,
columns=None,
partition_options=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None,
... | Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session and read-only transaction must be used by the
PartitionReadR... | Below is the the instruction that describes the task:
### Input:
Creates a set of partition tokens that can be used to execute a read
operation in parallel. Each of the returned partition tokens can be used
by ``StreamingRead`` to specify a subset of the read result to read. The
same session... |
def help_center_section_translations(self, section_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#list-translations"
api_path = "/api/v2/help_center/sections/{section_id}/translations.json"
api_path = api_path.format(section_id=section_id)
return sel... | https://developer.zendesk.com/rest_api/docs/help_center/translations#list-translations | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/help_center/translations#list-translations
### Response:
def help_center_section_translations(self, section_id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/translations#list-... |
def value_change(self, model, name, info):
"""The model is changed and the view must be updated"""
msg = self.model.get_message(info.new)
self.view.set_msg(msg)
return | The model is changed and the view must be updated | Below is the the instruction that describes the task:
### Input:
The model is changed and the view must be updated
### Response:
def value_change(self, model, name, info):
"""The model is changed and the view must be updated"""
msg = self.model.get_message(info.new)
self.view.set_msg(msg)
... |
def _collect(self, section=None):
"""
Collect HAProxy Stats
"""
if self.config['method'] == 'http':
csv_data = self.http_get_csv_data(section)
elif self.config['method'] == 'unix':
csv_data = self.unix_get_csv_data()
else:
self.log.erro... | Collect HAProxy Stats | Below is the the instruction that describes the task:
### Input:
Collect HAProxy Stats
### Response:
def _collect(self, section=None):
"""
Collect HAProxy Stats
"""
if self.config['method'] == 'http':
csv_data = self.http_get_csv_data(section)
elif self.config['m... |
def add_tags(self, item, *tags):
"""
Add one or more tags to a retrieved item,
then update it on the server
Accepts a dict, and one or more tags to add to it
Returns the updated item from the server
"""
# Make sure there's a tags field, or add one
try:
... | Add one or more tags to a retrieved item,
then update it on the server
Accepts a dict, and one or more tags to add to it
Returns the updated item from the server | Below is the the instruction that describes the task:
### Input:
Add one or more tags to a retrieved item,
then update it on the server
Accepts a dict, and one or more tags to add to it
Returns the updated item from the server
### Response:
def add_tags(self, item, *tags):
"""
... |
def compare_outputs(expected, output, **kwargs):
"""
Compares expected values and output.
Returns None if no error, an exception message otherwise.
"""
SkipDim1 = kwargs.pop("SkipDim1", False)
NoProb = kwargs.pop("NoProb", False)
Dec4 = kwargs.pop("Dec4", False)
Dec3 = kwargs.pop("Dec3",... | Compares expected values and output.
Returns None if no error, an exception message otherwise. | Below is the the instruction that describes the task:
### Input:
Compares expected values and output.
Returns None if no error, an exception message otherwise.
### Response:
def compare_outputs(expected, output, **kwargs):
"""
Compares expected values and output.
Returns None if no error, an except... |
def _process_cache(self, d, path=()):
"""Recusively walk a nested recon cache dict to obtain path/values"""
for k, v in d.iteritems():
if not isinstance(v, dict):
self.metrics.append((path + (k,), v))
else:
self._process_cache(v, path + (k,)) | Recusively walk a nested recon cache dict to obtain path/values | Below is the the instruction that describes the task:
### Input:
Recusively walk a nested recon cache dict to obtain path/values
### Response:
def _process_cache(self, d, path=()):
"""Recusively walk a nested recon cache dict to obtain path/values"""
for k, v in d.iteritems():
if not is... |
def authenticate(self, req, resp, resource):
"""
Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
"""
payload = self._decod... | Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception` | Below is the the instruction that describes the task:
### Input:
Extract auth token from request `authorization` header, decode jwt token,
verify configured claims and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
### Response:
def authenticate(self,... |
def read_data(self, **kwargs):
"""
get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
... | get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
:param kwargs: contain keyword args : trigger_id at le... | Below is the the instruction that describes the task:
### Input:
get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be foun... |
def get(self, key, default=None):
"""Retrieve the first value for a marker or None."""
for k, v in self:
if k == key:
return v
return default | Retrieve the first value for a marker or None. | Below is the the instruction that describes the task:
### Input:
Retrieve the first value for a marker or None.
### Response:
def get(self, key, default=None):
"""Retrieve the first value for a marker or None."""
for k, v in self:
if k == key:
return v
return def... |
def load(cls, v):
"""Load the action from configuration"""
if v is None:
return []
if isinstance(v, list):
return [ Action(s) for s in v ]
elif isinstance(v, str):
return [Action(v)]
else:
raise ParseError("Couldn't parse action: %r... | Load the action from configuration | Below is the the instruction that describes the task:
### Input:
Load the action from configuration
### Response:
def load(cls, v):
"""Load the action from configuration"""
if v is None:
return []
if isinstance(v, list):
return [ Action(s) for s in v ]
elif i... |
def _build_error_report(
self, message, report_location=None, http_context=None, user=None
):
"""Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
... | Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was reported or logged by the
service.
:type rep... | Below is the the instruction that describes the task:
### Input:
Builds the Error Reporting object to report.
This builds the object according to
https://cloud.google.com/error-reporting/docs/formatting-error-messages
:type message: str
:param message: The stack trace that was rep... |
def parse_transcript_number(effect):
"""
Try to parse the number at the end of a transcript name associated with
an effect.
e.g. TP53-001 returns the integer 1.
Parameters
----------
effect : subclass of MutationEffect
Returns int
"""
name = name_of_associated_transcript(effec... | Try to parse the number at the end of a transcript name associated with
an effect.
e.g. TP53-001 returns the integer 1.
Parameters
----------
effect : subclass of MutationEffect
Returns int | Below is the the instruction that describes the task:
### Input:
Try to parse the number at the end of a transcript name associated with
an effect.
e.g. TP53-001 returns the integer 1.
Parameters
----------
effect : subclass of MutationEffect
Returns int
### Response:
def parse_transcrip... |
def resolve_symbols(self, tree, database, link_resolver):
"""
When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class.
"""
self.typed_symbols = self.__get_empty_typed_symbols()
a... | When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class. | Below is the the instruction that describes the task:
### Input:
When this method is called, the page's symbol names are queried
from `database`, and added to lists of actual symbols, sorted
by symbol class.
### Response:
def resolve_symbols(self, tree, database, link_resolver):
"""
... |
def getPeersByClassName(self, className):
'''
getPeersByClassName - Gets peers (elements on same level) with a given class name
@param className - classname must contain this name
@return - None if no parent element (error condition), otherwise a TagCollection of peers that... | getPeersByClassName - Gets peers (elements on same level) with a given class name
@param className - classname must contain this name
@return - None if no parent element (error condition), otherwise a TagCollection of peers that matched. | Below is the the instruction that describes the task:
### Input:
getPeersByClassName - Gets peers (elements on same level) with a given class name
@param className - classname must contain this name
@return - None if no parent element (error condition), otherwise a TagCollection of peers t... |
def status(self, reference_id, **params):
"""
Retrieves the current status of the message.
See https://developer.telesign.com/docs/messaging-api for detailed API documentation.
"""
return self.get(MESSAGING_STATUS_RESOURCE.format(reference_id=reference_id),
... | Retrieves the current status of the message.
See https://developer.telesign.com/docs/messaging-api for detailed API documentation. | Below is the the instruction that describes the task:
### Input:
Retrieves the current status of the message.
See https://developer.telesign.com/docs/messaging-api for detailed API documentation.
### Response:
def status(self, reference_id, **params):
"""
Retrieves the current status of th... |
def _validate(cls, options, items, warnfn):
"Validation of edge cases and incompatible options"
if 'html' in Store.display_formats:
pass
elif 'fig' in items and items['fig'] not in Store.display_formats:
msg = ("Requesting output figure format %r " % items['fig']
... | Validation of edge cases and incompatible options | Below is the the instruction that describes the task:
### Input:
Validation of edge cases and incompatible options
### Response:
def _validate(cls, options, items, warnfn):
"Validation of edge cases and incompatible options"
if 'html' in Store.display_formats:
pass
elif 'fig' i... |
def asarray(self):
"""
Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document.
"""
# most codes don't use this feature, this is the only place
# numpy is used here, and importing numpy can be
... | Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document. | Below is the the instruction that describes the task:
### Input:
Construct a numpy array from this column. Note that this
creates a copy of the data, so modifications made to the
array will *not* be recorded in the original document.
### Response:
def asarray(self):
"""
Construct a numpy array from this c... |
def process_set_priority(process, priority):
"""
Changes the priority of a process
:param process: The name or PID of the process to check.
:param priority:A flag which determines what priority to set
0 - Idle/Low
1 - Below Normal (Not supported on Windows 95/98/ME)
2 - Normal
... | Changes the priority of a process
:param process: The name or PID of the process to check.
:param priority:A flag which determines what priority to set
0 - Idle/Low
1 - Below Normal (Not supported on Windows 95/98/ME)
2 - Normal
3 - Above Normal (Not supported on Windows 95/98/ME... | Below is the the instruction that describes the task:
### Input:
Changes the priority of a process
:param process: The name or PID of the process to check.
:param priority:A flag which determines what priority to set
0 - Idle/Low
1 - Below Normal (Not supported on Windows 95/98/ME)
2... |
def spkw15(handle, body, center, inframe, first, last, segid, epoch, tp, pa, p,
ecc, j2flg, pv, gm, j2, radius):
"""
Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle of an SPK file open f... | Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: Body code for ephemeris object.
:type body: int
:param center: Body code for ... | Below is the the instruction that describes the task:
### Input:
Write an SPK segment of type 15 given a type 15 data record.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw15_c.html
:param handle: Handle of an SPK file open for writing.
:type handle: int
:param body: Body code for ep... |
def remove_droplets(self, droplet_ids):
"""
Unassign a LoadBalancer.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs
"""
return self.get_data(
"load_balancers/%s/droplets/" % self.id,
type=DELETE,
params={"droplet_id... | Unassign a LoadBalancer.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs | Below is the the instruction that describes the task:
### Input:
Unassign a LoadBalancer.
Args:
droplet_ids (obj:`list` of `int`): A list of Droplet IDs
### Response:
def remove_droplets(self, droplet_ids):
"""
Unassign a LoadBalancer.
Args:
droplet_ids (ob... |
def _preFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND'):
"""This function will process attributtes for all -find* commands."""
if hasattr(WHAT, '_modified'):
self._addDBParam('RECORDID', WHAT.RECORDID)
elif type(WHAT)==dict:
for key in WHAT:
self._addDBParam(key, WHAT[key])
else:
rais... | This function will process attributtes for all -find* commands. | Below is the the instruction that describes the task:
### Input:
This function will process attributtes for all -find* commands.
### Response:
def _preFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND'):
"""This function will process attributtes for all -find* commands."""
if hasattr(WHAT, '_modified... |
def pad(self, minibatch):
"""Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
... | Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not None. Returns a tuple of the
padded list and a list containing... | Below is the the instruction that describes the task:
### Input:
Pad a batch of examples using this field.
Pads to self.fix_length if provided, otherwise pads to the length of
the longest example in the batch. Prepends self.init_token and appends
self.eos_token if those attributes are not N... |
def main(to_dir, from_dir):
"""Copy CWL files."""
num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir)
if num > 0:
click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
else:
msg = 'No CWL files found in "{}". Copied 0 files'.format(from_dir)
click.echo(msg) | Copy CWL files. | Below is the the instruction that describes the task:
### Input:
Copy CWL files.
### Response:
def main(to_dir, from_dir):
"""Copy CWL files."""
num = copy_cwl_files(from_dir=from_dir, to_dir=to_dir)
if num > 0:
click.echo('Copied {} CWL files to "{}".'.format(num, to_dir))
else:
ms... |
def parse_obj(obj):
"""
>>> parse_obj('bucket/key')
('bucket', 'key')
>>> parse_obj('my-bucket/path/to/file.txt')
('my-bucket', 'path/to/file.txt')
>>> parse_obj('s3://this_bucket/some/path.txt')
('this_bucket', 'some/path.txt')
>>> parse_obj('https://s3.amazonaws.com/bucket/file.txt')
... | >>> parse_obj('bucket/key')
('bucket', 'key')
>>> parse_obj('my-bucket/path/to/file.txt')
('my-bucket', 'path/to/file.txt')
>>> parse_obj('s3://this_bucket/some/path.txt')
('this_bucket', 'some/path.txt')
>>> parse_obj('https://s3.amazonaws.com/bucket/file.txt')
('bucket', 'file.txt')
>>... | Below is the the instruction that describes the task:
### Input:
>>> parse_obj('bucket/key')
('bucket', 'key')
>>> parse_obj('my-bucket/path/to/file.txt')
('my-bucket', 'path/to/file.txt')
>>> parse_obj('s3://this_bucket/some/path.txt')
('this_bucket', 'some/path.txt')
>>> parse_obj('https:/... |
def DeleteRecords(cls, ids, token):
"""Delete records identified by ids.
Args:
ids: A list of ids provided by ClaimRecords.
token: The database access token to delete with.
Raises:
LockError: If the queue is not locked.
"""
with data_store.DB.GetMutationPool() as mutation_pool:
... | Delete records identified by ids.
Args:
ids: A list of ids provided by ClaimRecords.
token: The database access token to delete with.
Raises:
LockError: If the queue is not locked. | Below is the the instruction that describes the task:
### Input:
Delete records identified by ids.
Args:
ids: A list of ids provided by ClaimRecords.
token: The database access token to delete with.
Raises:
LockError: If the queue is not locked.
### Response:
def DeleteRecords(cls, ids,... |
def get_location_observation(lat, lng, token):
"""Lookup observations by geo coordinates."""
req = requests.get(
API_ENDPOINT_GEO % (lat, lng),
params={
'token': token
})
if req.status_code == 200 and req.json()["status"] == "ok":
return parse_observation_respons... | Lookup observations by geo coordinates. | Below is the the instruction that describes the task:
### Input:
Lookup observations by geo coordinates.
### Response:
def get_location_observation(lat, lng, token):
"""Lookup observations by geo coordinates."""
req = requests.get(
API_ENDPOINT_GEO % (lat, lng),
params={
'token'... |
def get_file_from_iso_fp(self, outfp, **kwargs):
# type: (BinaryIO, Any) -> None
'''
A method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each ... | A method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
iso_path - The absolute ISO9660 path to lookup on the ISO (exclusive
w... | Below is the the instruction that describes the task:
### Input:
A method to fetch a single file from the ISO and write it out
to the file object.
Parameters:
outfp - The file object to write data to.
blocksize - The number of bytes in each transfer.
iso_path - The absolu... |
def _fix_mappings(self):
""" Add computed stuff to mappings.
"""
self._mapping.update((key+'=', val+'=') for key, val in self._mapping.items() if not key.endswith('='))
if config.debug:
self.LOG.debug("CMD MAPPINGS ARE: %r" % (self._mapping,)) | Add computed stuff to mappings. | Below is the the instruction that describes the task:
### Input:
Add computed stuff to mappings.
### Response:
def _fix_mappings(self):
""" Add computed stuff to mappings.
"""
self._mapping.update((key+'=', val+'=') for key, val in self._mapping.items() if not key.endswith('='))
if... |
def version(self):
"""What's the version of this database? Found in metadata attached
by datacache when creating this database."""
query = "SELECT version FROM %s" % METADATA_TABLE_NAME
cursor = self.connection.execute(query)
version = cursor.fetchone()
if not version:
... | What's the version of this database? Found in metadata attached
by datacache when creating this database. | Below is the the instruction that describes the task:
### Input:
What's the version of this database? Found in metadata attached
by datacache when creating this database.
### Response:
def version(self):
"""What's the version of this database? Found in metadata attached
by datacache when cr... |
def set_phases(self, literals=[]):
"""
Sets polarities of a given list of variables.
"""
if self.minicard:
pysolvers.minicard_setphases(self.minicard, literals) | Sets polarities of a given list of variables. | Below is the the instruction that describes the task:
### Input:
Sets polarities of a given list of variables.
### Response:
def set_phases(self, literals=[]):
"""
Sets polarities of a given list of variables.
"""
if self.minicard:
pysolvers.minicard_setphases(self.... |
def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
"""
return EnclavePermissions(id=enclave.id,
name=enclave.name,... | Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object | Below is the the instruction that describes the task:
### Input:
Create an |EnclavePermissions| object from an |Enclave| object.
:param enclave: the Enclave object
:return: an EnclavePermissions object
### Response:
def from_enclave(cls, enclave):
"""
Create an |EnclavePermissions|... |
def create(model_config, model, vec_env, storage, fps=30.0, sample_args=None):
""" Vel factory function """
return EnjoyCommand(
model_config, model, vec_env, storage, float(fps), sample_args
) | Vel factory function | Below is the the instruction that describes the task:
### Input:
Vel factory function
### Response:
def create(model_config, model, vec_env, storage, fps=30.0, sample_args=None):
""" Vel factory function """
return EnjoyCommand(
model_config, model, vec_env, storage, float(fps), sample_args
) |
def pressure_tendency(code: str, unit: str = 'mb') -> str:
"""
Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing
"""
width, precision = int(code[2:4]), code[4]
return ('3-hour pressure difference: +/- '
f'{width}.{precision} {unit} - {PRESS... | Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing | Below is the the instruction that describes the task:
### Input:
Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 mb: Increasing, then decreasing
### Response:
def pressure_tendency(code: str, unit: str = 'mb') -> str:
"""
Translates a 5-digit pressure outlook code
Ex: 50123 -> 12.3 m... |
def help(self):
'''
Generates formatted help output.
Returns the help string.
'''
modules = {}
help_string = "\n"
help_string += "Binwalk v%s\n" % binwalk.__version__
help_string += "Craig Heffner, ReFirmLabs\n"
help_string += "https://github.com/... | Generates formatted help output.
Returns the help string. | Below is the the instruction that describes the task:
### Input:
Generates formatted help output.
Returns the help string.
### Response:
def help(self):
'''
Generates formatted help output.
Returns the help string.
'''
modules = {}
help_string = "\n"
... |
def tags_in_string(msg):
"""
Return the set of tags in a message string.
Tags includes HTML tags, data placeholders, etc.
Skips tags that might change due to translations: HTML entities, <abbr>,
and so on.
"""
def is_linguistic_tag(tag):
"""Is this tag one that can change with the... | Return the set of tags in a message string.
Tags includes HTML tags, data placeholders, etc.
Skips tags that might change due to translations: HTML entities, <abbr>,
and so on. | Below is the the instruction that describes the task:
### Input:
Return the set of tags in a message string.
Tags includes HTML tags, data placeholders, etc.
Skips tags that might change due to translations: HTML entities, <abbr>,
and so on.
### Response:
def tags_in_string(msg):
"""
Return t... |
def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned
"""
obj = None
content = self.service_instance.RetrieveContent()
if folder is None:
folder = content.rootFolder
co... | Return an object by name, if name is None the
first found object is returned | Below is the the instruction that describes the task:
### Input:
Return an object by name, if name is None the
first found object is returned
### Response:
def get_obj(self, vimtype, name, folder=None):
"""
Return an object by name, if name is None the
first found object is returned... |
def open(self, access_mode=constants.AccessModes.no_lock, open_timeout=5000):
"""Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milli... | Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milliseconds before the open operation times out.
:type open_timeout: int | Below is the the instruction that describes the task:
### Input:
Opens a session to the specified resource.
:param access_mode: Specifies the mode by which the resource is to be accessed.
:type access_mode: :class:`pyvisa.constants.AccessModes`
:param open_timeout: Milliseconds before the o... |
def _analytical_fit_adjacent(self, ref_dists):
"""
Fit coords (x,y,[z]) so that distances from reference coordinates
match closest to reference distances
"""
dists = ref_dists**2
rot_dists = self._rotate_rows(dists)
b = dists - rot_dists + self._partial_b
... | Fit coords (x,y,[z]) so that distances from reference coordinates
match closest to reference distances | Below is the the instruction that describes the task:
### Input:
Fit coords (x,y,[z]) so that distances from reference coordinates
match closest to reference distances
### Response:
def _analytical_fit_adjacent(self, ref_dists):
"""
Fit coords (x,y,[z]) so that distances from reference coor... |
def getImageCode(self, appKey):
"""
获取图片验证码方法 方法
@param appKey:应用Id
@return code:返回码,200 为正常。
@return url:返回的图片验证码 URL 地址。
@return verifyId:返回图片验证标识 Id。
@return errorMessage:错误信息。
"""
desc = {
"name": "SMSImageCodeReslut",
... | 获取图片验证码方法 方法
@param appKey:应用Id
@return code:返回码,200 为正常。
@return url:返回的图片验证码 URL 地址。
@return verifyId:返回图片验证标识 Id。
@return errorMessage:错误信息。 | Below is the the instruction that describes the task:
### Input:
获取图片验证码方法 方法
@param appKey:应用Id
@return code:返回码,200 为正常。
@return url:返回的图片验证码 URL 地址。
@return verifyId:返回图片验证标识 Id。
@return errorMessage:错误信息。
### Response:
def getImageCode(self, appKey):
"""
... |
def get_version(path) -> str:
"""
Reads the version field from a package file
:param path: the path to a valid package.json file
:return: the version string or "unknown"
"""
if path and os.path.exists(path):
with open(path) as pkg:
package_dict = json.load(pkg)
v... | Reads the version field from a package file
:param path: the path to a valid package.json file
:return: the version string or "unknown" | Below is the the instruction that describes the task:
### Input:
Reads the version field from a package file
:param path: the path to a valid package.json file
:return: the version string or "unknown"
### Response:
def get_version(path) -> str:
"""
Reads the version field from a package file
... |
def add_subtract_locally(st, region_depth=3, filter_size=5, sigma_cutoff=8,
**kwargs):
"""
Automatically adds and subtracts missing particles based on local
regions of poor fit.
Calls identify_misfeatured_regions to identify regions, then
add_subtract_misfeatured_tile on th... | Automatically adds and subtracts missing particles based on local
regions of poor fit.
Calls identify_misfeatured_regions to identify regions, then
add_subtract_misfeatured_tile on the tiles in order of size until
region_depth tiles have been checked without adding any particles.
Parameters
--... | Below is the the instruction that describes the task:
### Input:
Automatically adds and subtracts missing particles based on local
regions of poor fit.
Calls identify_misfeatured_regions to identify regions, then
add_subtract_misfeatured_tile on the tiles in order of size until
region_depth tiles h... |
def create_dscp_marking_rule(self, policy, body=None):
"""Creates a new DSCP marking rule."""
return self.post(self.qos_dscp_marking_rules_path % policy,
body=body) | Creates a new DSCP marking rule. | Below is the the instruction that describes the task:
### Input:
Creates a new DSCP marking rule.
### Response:
def create_dscp_marking_rule(self, policy, body=None):
"""Creates a new DSCP marking rule."""
return self.post(self.qos_dscp_marking_rules_path % policy,
body=bod... |
def configure_tty(self):
"""We don't want \n to be replaced with \r\n, and we disable the echo"""
attr = termios.tcgetattr(self.fd)
attr[1] &= ~termios.ONLCR # oflag
attr[3] &= ~termios.ECHO # lflag
termios.tcsetattr(self.fd, termios.TCSANOW, attr)
# unsetopt zle preven... | We don't want \n to be replaced with \r\n, and we disable the echo | Below is the the instruction that describes the task:
### Input:
We don't want \n to be replaced with \r\n, and we disable the echo
### Response:
def configure_tty(self):
"""We don't want \n to be replaced with \r\n, and we disable the echo"""
attr = termios.tcgetattr(self.fd)
attr[1] &= ~t... |
def transChicane(bend_length=None, bend_field=None, drift_length=None, gamma=None):
""" Transport matrix of chicane
composed of four rbends and three drifts between them
:param bend_length: rbend width in [m]
:param bend_field: rbend magnetic field in [T]
:param drift_length: drift length, list... | Transport matrix of chicane
composed of four rbends and three drifts between them
:param bend_length: rbend width in [m]
:param bend_field: rbend magnetic field in [T]
:param drift_length: drift length, list or tuple of three elements, in [m]
single float number stands for same length for t... | Below is the the instruction that describes the task:
### Input:
Transport matrix of chicane
composed of four rbends and three drifts between them
:param bend_length: rbend width in [m]
:param bend_field: rbend magnetic field in [T]
:param drift_length: drift length, list or tuple of three elem... |
def wait_mprocess(process, timeout):
"""Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached.
"""
if PY3:
try:
return process.wait(timeout=timeout)
except subprocess.TimeoutExpired as exc:
raise TimeoutEr... | Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached. | Below is the the instruction that describes the task:
### Input:
Compatibility function for waiting on a process with a timeout.
Raises TimeoutError when the timeout is reached.
### Response:
def wait_mprocess(process, timeout):
"""Compatibility function for waiting on a process with a timeout.
Raise... |
def isothermal_gas(rho, fd, P1=None, P2=None, L=None, D=None, m=None):
r'''Calculation function for dealing with flow of a compressible gas in a
pipeline for the complete isothermal flow equation. Can calculate any of
the following, given all other inputs:
* Mass flow rate
* Upstream pressure (nume... | r'''Calculation function for dealing with flow of a compressible gas in a
pipeline for the complete isothermal flow equation. Can calculate any of
the following, given all other inputs:
* Mass flow rate
* Upstream pressure (numerical)
* Downstream pressure (analytical or numerical if an overflow oc... | Below is the the instruction that describes the task:
### Input:
r'''Calculation function for dealing with flow of a compressible gas in a
pipeline for the complete isothermal flow equation. Can calculate any of
the following, given all other inputs:
* Mass flow rate
* Upstream pressure (numerical)... |
def apply(self, fn, dtype=None, skip_na=True, seed=None):
"""
apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be ... | apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be cast into the type specified by
``dtype``. If ``dtype`` is not specifi... | Below is the the instruction that describes the task:
### Input:
apply(fn, dtype=None, skip_na=True, seed=None)
Transform each element of the SArray by a given function. The result
SArray is of type ``dtype``. ``fn`` should be a function that returns
exactly one value which can be cast into... |
def insert_optimization_option_group(parser):
"""
Adds the options used to specify optimization-specific options.
Parameters
----------
parser : object
OptionParser instance
"""
optimization_group = parser.add_argument_group("Options for selecting "
... | Adds the options used to specify optimization-specific options.
Parameters
----------
parser : object
OptionParser instance | Below is the the instruction that describes the task:
### Input:
Adds the options used to specify optimization-specific options.
Parameters
----------
parser : object
OptionParser instance
### Response:
def insert_optimization_option_group(parser):
"""
Adds the options used to specify ... |
def get_method_docstring(cls, method_name):
"""
return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype:
"""
method = getattr(cls, method_name, None)
if method is None:
return
docstrign = inspect... | return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype: | Below is the the instruction that describes the task:
### Input:
return method docstring
if method docstring is empty we get docstring from parent
:param method:
:type method:
:return:
:rtype:
### Response:
def get_method_docstring(cls, method_name):
"""
return method docstring
i... |
def align_image_with_openpnm(im):
r"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im : ND-array
The image t... | r"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im : ND-array
The image to be rotated. Can be the Boolean imag... | Below is the the instruction that describes the task:
### Input:
r"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im... |
def _make_exe(linklibs, identifier, verbose):
"""Generates the script to run the compiling."""
linktxt = "$(LIBS) " if linklibs else ""
redirect = "" if verbose else " > /dev/null"
base = """
$(EXENAME): $(OBJSF90)
-rm $(EXENAME) 2> /dev/null
echo -n "Linking... "{2}
-$(F90) $(LDFLAGS) -o $(EXENAME) ... | Generates the script to run the compiling. | Below is the the instruction that describes the task:
### Input:
Generates the script to run the compiling.
### Response:
def _make_exe(linklibs, identifier, verbose):
"""Generates the script to run the compiling."""
linktxt = "$(LIBS) " if linklibs else ""
redirect = "" if verbose else " > /dev/null"
... |
def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False):
"""retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w"""
a = semimajor(P,M1+M2)
if sec:
b = a*AU*np.cos(inc*np.pi/180)/(R1*RSUN) * (1-ecc**2)/(1 - ecc*np.sin(w*np.pi/180))
#aR = a*AU/(R2*RSUN) #I feel like this was to correct a bug, but thi... | retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w | Below is the the instruction that describes the task:
### Input:
retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w
### Response:
def eclipse_pars(P,M1,M2,R1,R2,ecc=0,inc=90,w=0,sec=False):
"""retuns p,b,aR from P,M1,M2,R1,R2,ecc,inc,w"""
a = semimajor(P,M1+M2)
if sec:
b = a*AU*np.cos(inc*np.pi/180)/(R... |
def log_y_cb(self, w, val):
"""Toggle linear/log scale for Y-axis."""
self.tab_plot.logy = val
self.plot_two_columns() | Toggle linear/log scale for Y-axis. | Below is the the instruction that describes the task:
### Input:
Toggle linear/log scale for Y-axis.
### Response:
def log_y_cb(self, w, val):
"""Toggle linear/log scale for Y-axis."""
self.tab_plot.logy = val
self.plot_two_columns() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.