code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def calculate_check_digit(gtin):
'''Given a GTIN (8-14) or SSCC, calculate its appropriate check digit'''
reverse_gtin = gtin[::-1]
total = 0
count = 0
for char in reverse_gtin:
digit = int(char)
if count % 2 == 0:
digit = digit * 3
total = total + digit
c... | Given a GTIN (8-14) or SSCC, calculate its appropriate check digit | Below is the the instruction that describes the task:
### Input:
Given a GTIN (8-14) or SSCC, calculate its appropriate check digit
### Response:
def calculate_check_digit(gtin):
'''Given a GTIN (8-14) or SSCC, calculate its appropriate check digit'''
reverse_gtin = gtin[::-1]
total = 0
count = 0
... |
def _combined_regex(regexes, flags=re.IGNORECASE, use_re2=False, max_mem=None):
"""
Return a compiled regex combined (using OR) from a list of ``regexes``.
If there is nothing to combine, None is returned.
re2 library (https://github.com/axiak/pyre2) often can match and compile
large regexes much f... | Return a compiled regex combined (using OR) from a list of ``regexes``.
If there is nothing to combine, None is returned.
re2 library (https://github.com/axiak/pyre2) often can match and compile
large regexes much faster than stdlib re module (10x is not uncommon),
but there are some gotchas:
* in... | Below is the the instruction that describes the task:
### Input:
Return a compiled regex combined (using OR) from a list of ``regexes``.
If there is nothing to combine, None is returned.
re2 library (https://github.com/axiak/pyre2) often can match and compile
large regexes much faster than stdlib re mo... |
def validate_instance_size(self, size):
''' integer between 5-1024 (inclusive) '''
try:
int(size)
except ValueError:
return '*** Error: size must be a whole number between 5 and 1024.'
if int(size) < 5 or int(size) > 1024:
return '*** Error: size must ... | integer between 5-1024 (inclusive) | Below is the the instruction that describes the task:
### Input:
integer between 5-1024 (inclusive)
### Response:
def validate_instance_size(self, size):
''' integer between 5-1024 (inclusive) '''
try:
int(size)
except ValueError:
return '*** Error: size must be a wh... |
def get_gdb_response(
self, timeout_sec=DEFAULT_GDB_TIMEOUT_SEC, raise_error_on_timeout=True
):
"""Get response from GDB, and block while doing so. If GDB does not have any response ready to be read
by timeout_sec, an exception is raised.
Args:
timeout_sec (float): Maxim... | Get response from GDB, and block while doing so. If GDB does not have any response ready to be read
by timeout_sec, an exception is raised.
Args:
timeout_sec (float): Maximum time to wait for reponse. Must be >= 0. Will return after
raise_error_on_timeout (bool): Whether an exce... | Below is the the instruction that describes the task:
### Input:
Get response from GDB, and block while doing so. If GDB does not have any response ready to be read
by timeout_sec, an exception is raised.
Args:
timeout_sec (float): Maximum time to wait for reponse. Must be >= 0. Will re... |
def are_flags_valid(packet_type, flags):
"""True when flags comply with [MQTT-2.2.2-1] requirements based on
packet_type; False otherwise.
Parameters
----------
packet_type: MqttControlPacketType
flags: int
Integer representation of 4-bit MQTT header flags field.
Values outside ... | True when flags comply with [MQTT-2.2.2-1] requirements based on
packet_type; False otherwise.
Parameters
----------
packet_type: MqttControlPacketType
flags: int
Integer representation of 4-bit MQTT header flags field.
Values outside of the range [0, 15] will certainly cause the
... | Below is the the instruction that describes the task:
### Input:
True when flags comply with [MQTT-2.2.2-1] requirements based on
packet_type; False otherwise.
Parameters
----------
packet_type: MqttControlPacketType
flags: int
Integer representation of 4-bit MQTT header flags field.
... |
def parse_declaration_expressn_memberaccess(self, lhsAST, rhsAST, es):
"""
Instead of "Class.variablename", use "Class.rv('variablename')".
:param lhsAST:
:param rhsAST:
:param es:
:return:
"""
if isinstance(lhsAST, wdl_parser.Terminal):
es = ... | Instead of "Class.variablename", use "Class.rv('variablename')".
:param lhsAST:
:param rhsAST:
:param es:
:return: | Below is the the instruction that describes the task:
### Input:
Instead of "Class.variablename", use "Class.rv('variablename')".
:param lhsAST:
:param rhsAST:
:param es:
:return:
### Response:
def parse_declaration_expressn_memberaccess(self, lhsAST, rhsAST, es):
"""
... |
def envvar_constructor(loader, node):
"""Tag constructor to use environment variables in YAML files. Usage:
- !TAG VARIABLE
raise while loading the document if variable does not exists
- !TAG VARIABLE:=DEFAULT_VALUE
For instance:
credentials:
user: !env USER:=root
... | Tag constructor to use environment variables in YAML files. Usage:
- !TAG VARIABLE
raise while loading the document if variable does not exists
- !TAG VARIABLE:=DEFAULT_VALUE
For instance:
credentials:
user: !env USER:=root
group: !env GROUP:= root | Below is the the instruction that describes the task:
### Input:
Tag constructor to use environment variables in YAML files. Usage:
- !TAG VARIABLE
raise while loading the document if variable does not exists
- !TAG VARIABLE:=DEFAULT_VALUE
For instance:
credentials:
user: ... |
def on_close(self, stats, previous_stats):
"""Print the extended JSON report to reporter's output.
:param dict stats: Metrics for the current pylint run
:param dict previous_stats: Metrics for the previous pylint run
"""
reports = {
'messages': self._messages,
... | Print the extended JSON report to reporter's output.
:param dict stats: Metrics for the current pylint run
:param dict previous_stats: Metrics for the previous pylint run | Below is the the instruction that describes the task:
### Input:
Print the extended JSON report to reporter's output.
:param dict stats: Metrics for the current pylint run
:param dict previous_stats: Metrics for the previous pylint run
### Response:
def on_close(self, stats, previous_stats):
... |
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
"""
self.root.set("transform", "%s skewY(%f)" %
(self.root.get("transform") or '', y))
return ... | Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees | Below is the the instruction that describes the task:
### Input:
Skew element along the y-axis by the given angle.
Parameters
----------
y : float
y-axis skew angle in degrees
### Response:
def skew_y(self, y):
"""Skew element along the y-axis by the given angle.
... |
def update(self, id, **kwargs):
"""
Updates an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function... | Updates an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
... | Below is the the instruction that describes the task:
### Input:
Updates an existing License
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def ... |
def calc_nfalse(d):
""" Calculate the number of thermal-noise false positives per segment.
"""
dtfactor = n.sum([1./i for i in d['dtarr']]) # assumes dedisperse-all algorithm
ntrials = d['readints'] * dtfactor * len(d['dmarr']) * d['npixx'] * d['npixy']
qfrac = 1 - (erf(d['sigma_image1']/n.sqrt(... | Calculate the number of thermal-noise false positives per segment. | Below is the the instruction that describes the task:
### Input:
Calculate the number of thermal-noise false positives per segment.
### Response:
def calc_nfalse(d):
""" Calculate the number of thermal-noise false positives per segment.
"""
dtfactor = n.sum([1./i for i in d['dtarr']]) # assumes ded... |
def toDict(self):
"""
Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment.
"""
return {
'hsps': [hsp.toDict() for hsp in self.hsps],
'read': self.read.toDict(),
} | Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment. | Below is the the instruction that describes the task:
### Input:
Get information about a title alignment as a dictionary.
@return: A C{dict} representation of the title aligment.
### Response:
def toDict(self):
"""
Get information about a title alignment as a dictionary.
@return: ... |
def cluster_path(cls, project, instance, cluster):
"""Return a fully-qualified cluster string."""
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/clusters/{cluster}",
project=project,
instance=instance,
cluster=cluster... | Return a fully-qualified cluster string. | Below is the the instruction that describes the task:
### Input:
Return a fully-qualified cluster string.
### Response:
def cluster_path(cls, project, instance, cluster):
"""Return a fully-qualified cluster string."""
return google.api_core.path_template.expand(
"projects/{project}/inst... |
def listing(
source: list,
ordered: bool = False,
expand_full: bool = False
):
"""
An unordered or ordered list of the specified *source* iterable where
each element is converted to a string representation for display.
:param source:
The iterable to display as a list.
... | An unordered or ordered list of the specified *source* iterable where
each element is converted to a string representation for display.
:param source:
The iterable to display as a list.
:param ordered:
Whether or not the list should be ordered. If False, which is the
default, an uno... | Below is the the instruction that describes the task:
### Input:
An unordered or ordered list of the specified *source* iterable where
each element is converted to a string representation for display.
:param source:
The iterable to display as a list.
:param ordered:
Whether or not the l... |
def titled_box(self, titles, contents, tdir='h', cdir='h'):
"""
Helper function to build a box containing a list of elements,
with a title above and/or below, or left and/or right of the
box. (e.g. a class name on top, or brackets on both sides.)
The elements given must already ... | Helper function to build a box containing a list of elements,
with a title above and/or below, or left and/or right of the
box. (e.g. a class name on top, or brackets on both sides.)
The elements given must already have been transformed into
Tag instances.
Arguments:
... | Below is the the instruction that describes the task:
### Input:
Helper function to build a box containing a list of elements,
with a title above and/or below, or left and/or right of the
box. (e.g. a class name on top, or brackets on both sides.)
The elements given must already have been t... |
def speak(self, message):
""" Post a message.
Args:
message (:class:`Message` or string): Message
Returns:
bool. Success
"""
campfire = self.get_campfire()
if not isinstance(message, Message):
message = Message(campfire, message)
... | Post a message.
Args:
message (:class:`Message` or string): Message
Returns:
bool. Success | Below is the the instruction that describes the task:
### Input:
Post a message.
Args:
message (:class:`Message` or string): Message
Returns:
bool. Success
### Response:
def speak(self, message):
""" Post a message.
Args:
message (:class:`Messa... |
def showEvent(self, event):
"""When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible"""
selected = self.par... | When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible | Below is the the instruction that describes the task:
### Input:
When this widget is shown it has an effect of putting
other widgets in the parent widget into different editing modes, emits
signal to notify other widgets. Restores the previous selection the last
time this widget was visible
... |
def get_syslog(self, service_id, version_number, name):
"""Get the Syslog for a particular service and version."""
content = self._fetch("/service/%s/version/%d/syslog/%s" % (service_id, version_number, name))
return FastlySyslog(self, content) | Get the Syslog for a particular service and version. | Below is the the instruction that describes the task:
### Input:
Get the Syslog for a particular service and version.
### Response:
def get_syslog(self, service_id, version_number, name):
"""Get the Syslog for a particular service and version."""
content = self._fetch("/service/%s/version/%d/syslog/%s" % (serv... |
def Join(self):
"""Waits until all outstanding tasks are completed."""
for _ in range(self.JOIN_TIMEOUT_DECISECONDS):
if self._queue.empty() and not self.busy_threads:
return
time.sleep(0.1)
raise ValueError("Timeout during Join() for threadpool %s." % self.name) | Waits until all outstanding tasks are completed. | Below is the the instruction that describes the task:
### Input:
Waits until all outstanding tasks are completed.
### Response:
def Join(self):
"""Waits until all outstanding tasks are completed."""
for _ in range(self.JOIN_TIMEOUT_DECISECONDS):
if self._queue.empty() and not self.busy_threads:
... |
def select_seqs(ol,seqs):
'''
from elist.elist import *
ol = ['a','b','c','d']
select_seqs(ol,[1,2])
'''
rslt =copy.deepcopy(ol)
rslt = itemgetter(*seqs)(ol)
if(seqs.__len__()==0):
rslt = []
elif(seqs.__len__()==1):
rslt = [rslt]
else:
rslt = l... | from elist.elist import *
ol = ['a','b','c','d']
select_seqs(ol,[1,2]) | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
ol = ['a','b','c','d']
select_seqs(ol,[1,2])
### Response:
def select_seqs(ol,seqs):
'''
from elist.elist import *
ol = ['a','b','c','d']
select_seqs(ol,[1,2])
'''
rslt =co... |
def apply_customization(self, serializer, customization):
"""
Applies fields customization to a nested or embedded DocumentSerializer.
"""
# apply fields or exclude
if customization.fields is not None:
if len(customization.fields) == 0:
# customization... | Applies fields customization to a nested or embedded DocumentSerializer. | Below is the the instruction that describes the task:
### Input:
Applies fields customization to a nested or embedded DocumentSerializer.
### Response:
def apply_customization(self, serializer, customization):
"""
Applies fields customization to a nested or embedded DocumentSerializer.
"""
... |
def _match_dfs_expr(lo_meta, expr, tt):
"""
Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filename... | Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return list: All filenames that match the expression | Below is the the instruction that describes the task:
### Input:
Use the given expression to get all data frames that match the criteria (i.e. "paleo measurement tables")
:param dict lo_meta: Lipd object metadata
:param str expr: Search expression
:param str tt: Table type (chron or paleo)
:return l... |
def _serialize_lnk(lnk):
"""Serialize a predication lnk to surface form into the SimpleMRS
encoding."""
s = ""
if lnk is not None:
s = '<'
if lnk.type == Lnk.CHARSPAN:
cfrom, cto = lnk.data
s += ''.join([str(cfrom), ':', str(cto)])
elif lnk.type == Lnk.... | Serialize a predication lnk to surface form into the SimpleMRS
encoding. | Below is the the instruction that describes the task:
### Input:
Serialize a predication lnk to surface form into the SimpleMRS
encoding.
### Response:
def _serialize_lnk(lnk):
"""Serialize a predication lnk to surface form into the SimpleMRS
encoding."""
s = ""
if lnk is not None:
... |
def _set_pspf_timer(self, v, load=False):
"""
Setter method for pspf_timer, mapped from YANG variable /isis_state/router_isis_config/pspf_timer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_pspf_timer is considered as a private
method. Backends looking ... | Setter method for pspf_timer, mapped from YANG variable /isis_state/router_isis_config/pspf_timer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_pspf_timer is considered as a private
method. Backends looking to populate this variable should
do so via calling... | Below is the the instruction that describes the task:
### Input:
Setter method for pspf_timer, mapped from YANG variable /isis_state/router_isis_config/pspf_timer (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_pspf_timer is considered as a private
method. Ba... |
def process_sentence(sentence, start_word="<S>", end_word="</S>"):
"""Seperate a sentence string into a list of string words, add start_word and end_word,
see ``create_vocab()`` and ``tutorial_tfrecord3.py``.
Parameters
----------
sentence : str
A sentence.
start_word : str or None
... | Seperate a sentence string into a list of string words, add start_word and end_word,
see ``create_vocab()`` and ``tutorial_tfrecord3.py``.
Parameters
----------
sentence : str
A sentence.
start_word : str or None
The start word. If None, no start word will be appended.
end_word ... | Below is the the instruction that describes the task:
### Input:
Seperate a sentence string into a list of string words, add start_word and end_word,
see ``create_vocab()`` and ``tutorial_tfrecord3.py``.
Parameters
----------
sentence : str
A sentence.
start_word : str or None
T... |
def _recover_shape_information(self, inputs, outputs):
"""Recover output tensor shape value to enable shape inference.
The batch size of `inputs` isn't preserved by the convolution op. Calculate
what the proper output shape will be for `outputs`.
Args:
inputs: A Tensor of shape `data_format` and... | Recover output tensor shape value to enable shape inference.
The batch size of `inputs` isn't preserved by the convolution op. Calculate
what the proper output shape will be for `outputs`.
Args:
inputs: A Tensor of shape `data_format` and of type `tf.float16`,
`tf.bfloat16` or `tf.float32`... | Below is the the instruction that describes the task:
### Input:
Recover output tensor shape value to enable shape inference.
The batch size of `inputs` isn't preserved by the convolution op. Calculate
what the proper output shape will be for `outputs`.
Args:
inputs: A Tensor of shape `data_form... |
def status(self):
"""
Get server status. Uses GET to /status interface.
:Returns: (dict) Server status as described `here <https://cloud.knuverse.com/docs/api/#api-General-Status>`_.
"""
response = self._get(url.status)
self._check_response(response, 200)
return... | Get server status. Uses GET to /status interface.
:Returns: (dict) Server status as described `here <https://cloud.knuverse.com/docs/api/#api-General-Status>`_. | Below is the the instruction that describes the task:
### Input:
Get server status. Uses GET to /status interface.
:Returns: (dict) Server status as described `here <https://cloud.knuverse.com/docs/api/#api-General-Status>`_.
### Response:
def status(self):
"""
Get server status. Uses GE... |
def _fulfill(self, bits, ignore_nonpromised_bits=False):
"""Supply the promise with the bits from its associated primitive's execution.
The fulfillment process must walk the promise chain backwards
until it reaches the original promise and can supply the final
value.
The data t... | Supply the promise with the bits from its associated primitive's execution.
The fulfillment process must walk the promise chain backwards
until it reaches the original promise and can supply the final
value.
The data that comes in can either be all a bit read for every
bit writ... | Below is the the instruction that describes the task:
### Input:
Supply the promise with the bits from its associated primitive's execution.
The fulfillment process must walk the promise chain backwards
until it reaches the original promise and can supply the final
value.
The data ... |
def coupling(self, source_y, target_y, weight):
"""How to couple the output of one subsystem to the input of another.
This is a fallback default coupling function that should usually be
replaced with your own.
This example coupling function takes the mean of all variables of the
... | How to couple the output of one subsystem to the input of another.
This is a fallback default coupling function that should usually be
replaced with your own.
This example coupling function takes the mean of all variables of the
source subsystem and uses that value weighted by the conn... | Below is the the instruction that describes the task:
### Input:
How to couple the output of one subsystem to the input of another.
This is a fallback default coupling function that should usually be
replaced with your own.
This example coupling function takes the mean of all variables of ... |
def add_virtual_columns_cartesian_velocities_to_polar(self, x="x", y="y", vx="vx", radius_polar=None, vy="vy", vr_out="vr_polar", vazimuth_out="vphi_polar",
propagate_uncertainties=False,):
"""Convert cartesian to polar velocities.
:param x:
... | Convert cartesian to polar velocities.
:param x:
:param y:
:param vx:
:param radius_polar: Optional expression for the radius, may lead to a better performance when given.
:param vy:
:param vr_out:
:param vazimuth_out:
:param propagate_uncertainties: {pro... | Below is the the instruction that describes the task:
### Input:
Convert cartesian to polar velocities.
:param x:
:param y:
:param vx:
:param radius_polar: Optional expression for the radius, may lead to a better performance when given.
:param vy:
:param vr_out:
... |
def system(session, py):
"""Run the system test suite."""
# Sanity check: Only run system tests if the environment variable is set.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
session.skip('Credentials must be set via environment variable.')
# Run the system tests against late... | Run the system test suite. | Below is the the instruction that describes the task:
### Input:
Run the system test suite.
### Response:
def system(session, py):
"""Run the system test suite."""
# Sanity check: Only run system tests if the environment variable is set.
if not os.environ.get('GOOGLE_APPLICATION_CREDENTIALS', ''):
... |
def formatTime(self, record, datefmt=None):
"""Format the log timestamp."""
_seconds_fraction = record.created - int(record.created)
_datetime_utc = time.mktime(time.gmtime(record.created))
_datetime_utc += _seconds_fraction
_created = self.converter(_datetime_utc)
if da... | Format the log timestamp. | Below is the the instruction that describes the task:
### Input:
Format the log timestamp.
### Response:
def formatTime(self, record, datefmt=None):
"""Format the log timestamp."""
_seconds_fraction = record.created - int(record.created)
_datetime_utc = time.mktime(time.gmtime(record.create... |
def quadratic_forms(h1, h2):
r"""
Quadrativ forms metric.
Notes
-----
UNDER DEVELOPMENT
This distance measure shows very strange behaviour. The expression
transpose(h1-h2) * A * (h1-h2) yields egative values that can not be processed by the
square root. Some examples::
... | r"""
Quadrativ forms metric.
Notes
-----
UNDER DEVELOPMENT
This distance measure shows very strange behaviour. The expression
transpose(h1-h2) * A * (h1-h2) yields egative values that can not be processed by the
square root. Some examples::
h1 h2 ... | Below is the the instruction that describes the task:
### Input:
r"""
Quadrativ forms metric.
Notes
-----
UNDER DEVELOPMENT
This distance measure shows very strange behaviour. The expression
transpose(h1-h2) * A * (h1-h2) yields egative values that can not be processed by the
s... |
def get_all_instances(include_fastboot=False):
"""Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to ... | Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
attached to the computer. | Below is the the instruction that describes the task:
### Input:
Create AndroidDevice instances for all attached android devices.
Args:
include_fastboot: Whether to include devices in bootloader mode or not.
Returns:
A list of AndroidDevice objects each representing an android device
... |
def gist(self, id_num):
"""Gets the gist using the specified id number.
:param int id_num: (required), unique id of the gist
:returns: :class:`Gist <github3.gists.Gist>`
"""
url = self._build_url('gists', str(id_num))
json = self._json(self._get(url), 200)
return... | Gets the gist using the specified id number.
:param int id_num: (required), unique id of the gist
:returns: :class:`Gist <github3.gists.Gist>` | Below is the the instruction that describes the task:
### Input:
Gets the gist using the specified id number.
:param int id_num: (required), unique id of the gist
:returns: :class:`Gist <github3.gists.Gist>`
### Response:
def gist(self, id_num):
"""Gets the gist using the specified id numb... |
def _get_segmentation_id(self, netid, segid, source):
"""Allocate segmentation id. """
return self.seg_drvr.allocate_segmentation_id(netid, seg_id=segid,
source=source) | Allocate segmentation id. | Below is the the instruction that describes the task:
### Input:
Allocate segmentation id.
### Response:
def _get_segmentation_id(self, netid, segid, source):
"""Allocate segmentation id. """
return self.seg_drvr.allocate_segmentation_id(netid, seg_id=segid,
... |
def ack(self):
"""Acknowledge Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return:... | Acknowledge Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an error.
:return: | Below is the the instruction that describes the task:
### Input:
Acknowledge Message.
:raises AMQPInvalidArgument: Invalid Parameters
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
... |
def read_alignment(out_sam, loci, seqs, out_file):
"""read which seqs map to which loci and
return a tab separated file"""
hits = defaultdict(list)
with open(out_file, "w") as out_handle:
samfile = pysam.Samfile(out_sam, "r")
for a in samfile.fetch():
if not a.is_unmapped:
... | read which seqs map to which loci and
return a tab separated file | Below is the the instruction that describes the task:
### Input:
read which seqs map to which loci and
return a tab separated file
### Response:
def read_alignment(out_sam, loci, seqs, out_file):
"""read which seqs map to which loci and
return a tab separated file"""
hits = defaultdict(list)
wi... |
def take_screen_shot_to_array(self, screen_id, width, height, bitmap_format):
"""Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
... | Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
Desired image width.
in height of type int
Desired image height.... | Below is the the instruction that describes the task:
### Input:
Takes a guest screen shot of the requested size and format
and returns it as an array of bytes.
in screen_id of type int
The guest monitor to take screenshot from.
in width of type int
Desired image wi... |
def get_scene(self):
"""
- get_scene(): It return the x and y position, the smoothing length
of the particles and the index of the particles that are active in
the scene. In principle this is an internal function and you don't
need this data.
"""
return self._... | - get_scene(): It return the x and y position, the smoothing length
of the particles and the index of the particles that are active in
the scene. In principle this is an internal function and you don't
need this data. | Below is the the instruction that describes the task:
### Input:
- get_scene(): It return the x and y position, the smoothing length
of the particles and the index of the particles that are active in
the scene. In principle this is an internal function and you don't
need this data.
### Re... |
def fromxml(node):
"""Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element"""
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(Stri... | Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element | Below is the the instruction that describes the task:
### Input:
Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element
### Response:
def fromxml(node):
"""Create a Parameter instance (of any class derive... |
def cyclic(self):
"Returns True if the options cycle, otherwise False"
return any(isinstance(val, Cycle) for val in self.kwargs.values()) | Returns True if the options cycle, otherwise False | Below is the the instruction that describes the task:
### Input:
Returns True if the options cycle, otherwise False
### Response:
def cyclic(self):
"Returns True if the options cycle, otherwise False"
return any(isinstance(val, Cycle) for val in self.kwargs.values()) |
def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret is None:raise treeError('nodePop() failed')
return xmlNode(_obj=ret) | Pops the top element node from the node stack | Below is the the instruction that describes the task:
### Input:
Pops the top element node from the node stack
### Response:
def nodePop(ctxt):
"""Pops the top element node from the node stack """
if ctxt is None: ctxt__o = None
else: ctxt__o = ctxt._o
ret = libxml2mod.nodePop(ctxt__o)
if ret i... |
def json_loads(cls, s, **kwargs):
"""
A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict
"""
if 'cls' not in kwargs:
kwargs['cls'] = cls.json_decoder
return json.l... | A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict | Below is the the instruction that describes the task:
### Input:
A rewrap of json.loads done for one reason - to inject a custom `cls` kwarg
:param s:
:param kwargs:
:return:
:rtype: dict
### Response:
def json_loads(cls, s, **kwargs):
"""
A rewrap of json.loads don... |
def _get_nets_radb(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('ASNOrigin._get_nets_radb() has been deprecated and will be '
'removed. You should now use ASNOrigin.get_nets_radb().')
re... | Deprecated. This will be removed in a future release. | Below is the the instruction that describes the task:
### Input:
Deprecated. This will be removed in a future release.
### Response:
def _get_nets_radb(self, *args, **kwargs):
"""
Deprecated. This will be removed in a future release.
"""
from warnings import warn
warn('ASNO... |
def stSpectralEntropy(X, n_short_blocks=10):
"""Computes the spectral entropy"""
L = len(X) # number of frame samples
Eol = numpy.sum(X ** 2) # total spectral energy
sub_win_len = int(numpy.floor(L / n_short_blocks)) # length of sub-frame
if L != sub_win_len * n... | Computes the spectral entropy | Below is the the instruction that describes the task:
### Input:
Computes the spectral entropy
### Response:
def stSpectralEntropy(X, n_short_blocks=10):
"""Computes the spectral entropy"""
L = len(X) # number of frame samples
Eol = numpy.sum(X ** 2) # total spectral ... |
def _resolve_by_callback(request, url, urlconf=None):
"""
Finds a view function by urlconf. If the function has attribute
'navigation', it is used as breadcrumb title. Such title can be either a
callable or an object with `__unicode__` attribute. If it is callable, it
must follow the views API (i.e.... | Finds a view function by urlconf. If the function has attribute
'navigation', it is used as breadcrumb title. Such title can be either a
callable or an object with `__unicode__` attribute. If it is callable, it
must follow the views API (i.e. the only required argument is request
object). It is also exp... | Below is the the instruction that describes the task:
### Input:
Finds a view function by urlconf. If the function has attribute
'navigation', it is used as breadcrumb title. Such title can be either a
callable or an object with `__unicode__` attribute. If it is callable, it
must follow the views API (i... |
def correct_bounding_box_list_for_nonzero_origin(bbox_list, full_box_list):
"""The bounding box calculated from an image has coordinates relative to the
lower-left point in the PDF being at zero. Similarly, Ghostscript reports a
bounding box relative to a zero lower-left point. If the MediaBox (or full
... | The bounding box calculated from an image has coordinates relative to the
lower-left point in the PDF being at zero. Similarly, Ghostscript reports a
bounding box relative to a zero lower-left point. If the MediaBox (or full
page box) has been shifted, like when cropping a previously cropped
document,... | Below is the the instruction that describes the task:
### Input:
The bounding box calculated from an image has coordinates relative to the
lower-left point in the PDF being at zero. Similarly, Ghostscript reports a
bounding box relative to a zero lower-left point. If the MediaBox (or full
page box) ha... |
def config_to_string(config):
"""Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
"""
output = []
for secti... | Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config. | Below is the the instruction that describes the task:
### Input:
Nice output string for the config, which is a nested defaultdict.
Args:
config (defaultdict(defaultdict)): The configuration information.
Returns:
str: A human-readable output string detailing the contents of the config.
### R... |
def zthread_fork(ctx, func, *args, **kwargs):
"""
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
"""
a = ctx.socket(zmq.PAIR)
a.setsoc... | Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error. | Below is the the instruction that describes the task:
### Input:
Create an attached thread. An attached thread gets a ctx and a PAIR
pipe back to its parent. It must monitor its pipe, and exit if the
pipe becomes unreadable. Returns pipe, or NULL if there was an error.
### Response:
def zthread_fork(ctx, f... |
def set_header(self,header):
"""
Sets the header of the object
@type header: L{CHeader}
@param header: the header object
"""
self.header = header
self.root.insert(0,header.get_node()) | Sets the header of the object
@type header: L{CHeader}
@param header: the header object | Below is the the instruction that describes the task:
### Input:
Sets the header of the object
@type header: L{CHeader}
@param header: the header object
### Response:
def set_header(self,header):
"""
Sets the header of the object
@type header: L{CHeader}
@param heade... |
def requiv_to_pot_contact(requiv, q, sma, compno=1):
"""
:param requiv: user-provided equivalent radius
:param q: mass ratio
:param sma: semi-major axis (d = sma because we explicitly assume circular orbits for contacts)
:param compno: 1 for primary, 2 for secondary
:return: potential and fillou... | :param requiv: user-provided equivalent radius
:param q: mass ratio
:param sma: semi-major axis (d = sma because we explicitly assume circular orbits for contacts)
:param compno: 1 for primary, 2 for secondary
:return: potential and fillout factor | Below is the the instruction that describes the task:
### Input:
:param requiv: user-provided equivalent radius
:param q: mass ratio
:param sma: semi-major axis (d = sma because we explicitly assume circular orbits for contacts)
:param compno: 1 for primary, 2 for secondary
:return: potential and fi... |
def check_keepalive(self):
"""Send keepalive/PING if necessary."""
if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive:
if self.state == NC.CS_CONNECTED:
self.send_pingreq()
else:
self.socket_close() | Send keepalive/PING if necessary. | Below is the the instruction that describes the task:
### Input:
Send keepalive/PING if necessary.
### Response:
def check_keepalive(self):
"""Send keepalive/PING if necessary."""
if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive:
if self.state == ... |
def query_bypass(self, query, raw_output=True):
''' Bypass query meaning that field check and validation is skipped, then query object directly executed by pymongo.
:param raw_output: Skip OmMongo ORM layer (default: True)
'''
if not isinstance(query, dict):
rais... | Bypass query meaning that field check and validation is skipped, then query object directly executed by pymongo.
:param raw_output: Skip OmMongo ORM layer (default: True) | Below is the the instruction that describes the task:
### Input:
Bypass query meaning that field check and validation is skipped, then query object directly executed by pymongo.
:param raw_output: Skip OmMongo ORM layer (default: True)
### Response:
def query_bypass(self, query, raw_output=Tru... |
def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.requested_band_filename, 'r')
wvl = ncf.variables['wavelength'][:] * scale
resp = ncf.variables['response'][:]
... | Load the SLSTR relative spectral responses | Below is the the instruction that describes the task:
### Input:
Load the SLSTR relative spectral responses
### Response:
def _load(self, scale=1.0):
"""Load the SLSTR relative spectral responses
"""
LOG.debug("File: %s", str(self.requested_band_filename))
ncf = Dataset(self.reques... |
def proba2onehot(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> np.ndarray:
"""
Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given cla... | Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given classes
confident_threshold: boundary of probability to belong with a class
classes: array of classes' names
Re... | Below is the the instruction that describes the task:
### Input:
Convert vectors of probabilities to one-hot representations using confident threshold
Args:
proba: samples where each sample is a vector of probabilities to belong with given classes
confident_threshold: boundary of probability to... |
def update(self, ell, k):
"""Update the posterior and estimates after a label is sampled
Parameters
----------
ell : int
sampled label: 0 or 1
k : int
index of stratum where label was sampled
"""
self.alpha_[k] += ell
self.beta_[k... | Update the posterior and estimates after a label is sampled
Parameters
----------
ell : int
sampled label: 0 or 1
k : int
index of stratum where label was sampled | Below is the the instruction that describes the task:
### Input:
Update the posterior and estimates after a label is sampled
Parameters
----------
ell : int
sampled label: 0 or 1
k : int
index of stratum where label was sampled
### Response:
def update(self... |
def get_metric_group_definitions(self):
"""
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of its manag... | Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of its manager object that
are in that list, are included in the... | Below is the the instruction that describes the task:
### Input:
Get the faked metric group definitions for this context object
that are to be returned from its create operation.
If a 'metric-groups' property had been specified for this context,
only those faked metric group definitions of ... |
def restore_instances(self, instances):
"""Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file.
"""
instances = instances.encode()
if os.path.exists... | Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file. | Below is the the instruction that describes the task:
### Input:
Restore a set of instances into the CLIPS data base.
The Python equivalent of the CLIPS restore-instances command.
Instances can be passed as a set of strings or as a file.
### Response:
def restore_instances(self, instances):
... |
def sanitize_args(cmd: List[str]) -> List[str]:
""" Filter the command so that it no longer contains passwords
"""
sanitized = []
for idx, fieldname in enumerate(cmd):
def _is_password(cmdstr):
return 'wifi-sec.psk' in cmdstr\
or 'password' in cmdstr.lower()
i... | Filter the command so that it no longer contains passwords | Below is the the instruction that describes the task:
### Input:
Filter the command so that it no longer contains passwords
### Response:
def sanitize_args(cmd: List[str]) -> List[str]:
""" Filter the command so that it no longer contains passwords
"""
sanitized = []
for idx, fieldname in enumerate... |
def get_spectrum(self, nr_id=None, abmn=None, plot_filename=None):
"""Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response... | Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response`
Normal spectrum. None if no normal spectrum is available
... | Below is the the instruction that describes the task:
### Input:
Return a spectrum and its reciprocal counter part, if present in the
dataset. Optimally, refer to the spectrum by its normal-reciprocal id.
Returns
-------
spectrum_nor : :py:class:`reda.eis.plots.sip_response`
... |
def create_project(self, project_path):
"""
Create Trionyx project in given path
:param str path: path to create project in.
:raises FileExistsError:
"""
shutil.copytree(self.project_path, project_path)
self.update_file(project_path, 'requirements.txt', {
... | Create Trionyx project in given path
:param str path: path to create project in.
:raises FileExistsError: | Below is the the instruction that describes the task:
### Input:
Create Trionyx project in given path
:param str path: path to create project in.
:raises FileExistsError:
### Response:
def create_project(self, project_path):
"""
Create Trionyx project in given path
:param ... |
def query_one(self, *args, **kwargs):
"""Return first document from :meth:`query`, with same parameters.
"""
for r in self.query(*args, **kwargs):
return r
return None | Return first document from :meth:`query`, with same parameters. | Below is the the instruction that describes the task:
### Input:
Return first document from :meth:`query`, with same parameters.
### Response:
def query_one(self, *args, **kwargs):
"""Return first document from :meth:`query`, with same parameters.
"""
for r in self.query(*args, **kwargs):
... |
def recalculate_current_specimen_interpreatations(self):
"""
recalculates all interpretations on all specimens for all coordinate
systems. Does not display recalcuated data.
"""
self.initialize_CART_rot(self.s)
if str(self.s) in self.pmag_results_data['specimens']:
... | recalculates all interpretations on all specimens for all coordinate
systems. Does not display recalcuated data. | Below is the the instruction that describes the task:
### Input:
recalculates all interpretations on all specimens for all coordinate
systems. Does not display recalcuated data.
### Response:
def recalculate_current_specimen_interpreatations(self):
"""
recalculates all interpretations on al... |
def sync_entities_watching(instance):
"""
Syncs entities watching changes of a model instance.
"""
for entity_model, entity_model_getter in entity_registry.entity_watching[instance.__class__]:
model_objs = list(entity_model_getter(instance))
if model_objs:
sync_entities(*mode... | Syncs entities watching changes of a model instance. | Below is the the instruction that describes the task:
### Input:
Syncs entities watching changes of a model instance.
### Response:
def sync_entities_watching(instance):
"""
Syncs entities watching changes of a model instance.
"""
for entity_model, entity_model_getter in entity_registry.entity_watc... |
def _set_ipv6_interface(self, v, load=False):
"""
Setter method for ipv6_interface, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track/ipv6_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_interface is consi... | Setter method for ipv6_interface, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track/ipv6_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_interface is considered as a private
method. Backends looking to populat... | Below is the the instruction that describes the task:
### Input:
Setter method for ipv6_interface, mapped from YANG variable /rbridge_id/interface/ve/ipv6/ipv6_local_anycast_gateway/ipv6_track/ipv6_interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_ipv6_interfa... |
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
'''
ret = {'comment': '', 'success': False}
cmd = __execute_cmd('riak', 'stop')
if cmd['retcode'] != 0:
ret['comment'] = cmd['stderr']
else:
r... | Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop | Below is the the instruction that describes the task:
### Input:
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' riak.stop
### Response:
def stop():
'''
Stop Riak
.. versionchanged:: 2015.8.0
CLI Example:
.. code-block:: bash
... |
def user_admin_view(model, login_view="Login", template_dir=None):
"""
:param UserStruct: The User model structure containing other classes
:param login_view: The login view interface
:param template_dir: The directory containing the view pages
:return: UserAdmin
Doc:
User Admin is a view t... | :param UserStruct: The User model structure containing other classes
:param login_view: The login view interface
:param template_dir: The directory containing the view pages
:return: UserAdmin
Doc:
User Admin is a view that allows you to admin users.
You must create a Pylot view called `UserAdm... | Below is the the instruction that describes the task:
### Input:
:param UserStruct: The User model structure containing other classes
:param login_view: The login view interface
:param template_dir: The directory containing the view pages
:return: UserAdmin
Doc:
User Admin is a view that allows... |
def minimum_enclosing_circle(labels, indexes = None,
hull_and_point_count = None):
"""Find the location of the minimum enclosing circle and its radius
labels - a labels matrix
indexes - an array giving the label indexes to be processed
hull_and_point_count - convex_hul... | Find the location of the minimum enclosing circle and its radius
labels - a labels matrix
indexes - an array giving the label indexes to be processed
hull_and_point_count - convex_hull output if already done. None = calculate
returns an Nx3 array organized as i,j of the center and radius
A... | Below is the the instruction that describes the task:
### Input:
Find the location of the minimum enclosing circle and its radius
labels - a labels matrix
indexes - an array giving the label indexes to be processed
hull_and_point_count - convex_hull output if already done. None = calculate
... |
def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
in inspect.getmembers(self, predicate=inspect.ismethod)])
for message in global_callbacks:
global... | Remove the actor's methods from the callback registry. | Below is the the instruction that describes the task:
### Input:
Remove the actor's methods from the callback registry.
### Response:
def unplug(self):
'''Remove the actor's methods from the callback registry.'''
if not self.__plugged:
return
members = set([method for _, method
... |
def read_analogy_file(filename):
"""
Read the analogy task test set from a file.
"""
section = None
with open(filename, 'r') as questions_file:
for line in questions_file:
if line.startswith(':'):
section = line[2:].replace('\n', '')
continue... | Read the analogy task test set from a file. | Below is the the instruction that describes the task:
### Input:
Read the analogy task test set from a file.
### Response:
def read_analogy_file(filename):
"""
Read the analogy task test set from a file.
"""
section = None
with open(filename, 'r') as questions_file:
for line in qu... |
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs texture coordinates"""
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root... | dump vtkjs texture coordinates | Below is the the instruction that describes the task:
### Input:
dump vtkjs texture coordinates
### Response:
def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs texture coordinates"""
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords(... |
def versions(self):
"""Return all version changes."""
versions = []
for v, _ in self.restarts:
if len(versions) == 0 or v != versions[-1]:
versions.append(v)
return versions | Return all version changes. | Below is the the instruction that describes the task:
### Input:
Return all version changes.
### Response:
def versions(self):
"""Return all version changes."""
versions = []
for v, _ in self.restarts:
if len(versions) == 0 or v != versions[-1]:
versions.append(v... |
def get_ties(G):
"""
If you specify a target that shares a dependency with another target,
both targets need to be updated. This is because running one will resolve
the sha mismatch and sake will think that the other one doesn't have to
run. This is called a "tie". This function will find such ties.... | If you specify a target that shares a dependency with another target,
both targets need to be updated. This is because running one will resolve
the sha mismatch and sake will think that the other one doesn't have to
run. This is called a "tie". This function will find such ties. | Below is the the instruction that describes the task:
### Input:
If you specify a target that shares a dependency with another target,
both targets need to be updated. This is because running one will resolve
the sha mismatch and sake will think that the other one doesn't have to
run. This is called a "... |
def join(self, _id):
""" Join a room """
if not SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id] = set()
SockJSRoomHandler._room[self._gcls() + _id].add(self) | Join a room | Below is the the instruction that describes the task:
### Input:
Join a room
### Response:
def join(self, _id):
""" Join a room """
if not SockJSRoomHandler._room.has_key(self._gcls() + _id):
SockJSRoomHandler._room[self._gcls() + _id] = set()
SockJSRoomHandler._room[self._gcls(... |
def addDEX(self, filename, data, dx=None):
"""
Add a DEX file to the Session and run analysis.
:param filename: the (file)name of the DEX file
:param data: binary data of the dex file
:param dx: an existing Analysis Object (optional)
:return: A tuple of SHA256 Hash, Dalv... | Add a DEX file to the Session and run analysis.
:param filename: the (file)name of the DEX file
:param data: binary data of the dex file
:param dx: an existing Analysis Object (optional)
:return: A tuple of SHA256 Hash, DalvikVMFormat Object and Analysis object | Below is the the instruction that describes the task:
### Input:
Add a DEX file to the Session and run analysis.
:param filename: the (file)name of the DEX file
:param data: binary data of the dex file
:param dx: an existing Analysis Object (optional)
:return: A tuple of SHA256 Hash... |
def add(setname=None, entry=None, family='ipv4', **kwargs):
'''
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
'''
if not setname:
return 'Error:... | Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF | Below is the the instruction that describes the task:
### Input:
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
### Response:
def add(setname=None, entry=None, famil... |
def _create_binary_trigger(trigger):
"""Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger."""
ops = {
0: ">",
1: "<",
2: ">=",
3: "<=",
4: "==",
5: 'always'
}
op_codes = {y: x for x, y in ops.items()}
source = 0
if i... | Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger. | Below is the the instruction that describes the task:
### Input:
Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger.
### Response:
def _create_binary_trigger(trigger):
"""Create an 8-bit binary trigger from an InputTrigger, TrueTrigger, FalseTrigger."""
ops = {
0: ">",
... |
def build_dummy_request(newsitem):
"""
Construct a HttpRequest object that is, as far as possible,
representative of ones that would receive this page as a response. Used
for previewing / moderation and any other place where we want to
display a view of this page in the admin interface without going... | Construct a HttpRequest object that is, as far as possible,
representative of ones that would receive this page as a response. Used
for previewing / moderation and any other place where we want to
display a view of this page in the admin interface without going
through the regular page routing logic. | Below is the the instruction that describes the task:
### Input:
Construct a HttpRequest object that is, as far as possible,
representative of ones that would receive this page as a response. Used
for previewing / moderation and any other place where we want to
display a view of this page in the admin i... |
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2:
return True
elif tzinfo1 is None or tzinfo2 is None:
return False
def dt_test(dt):
if dt is None:
re... | Compare offsets and DST transitions from startYear to endYear. | Below is the the instruction that describes the task:
### Input:
Compare offsets and DST transitions from startYear to endYear.
### Response:
def tzinfo_eq(tzinfo1, tzinfo2, startYear = 2000, endYear=2020):
"""
Compare offsets and DST transitions from startYear to endYear.
"""
if tzinfo1 == tzinfo2... |
def resolve_metric_as_tuple(metric):
"""
Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric`
"""
if "." in metric:
_, metric = metric.split(".")
r = [
(operator, match) for operator, match in ALL_METRICS ... | Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric` | Below is the the instruction that describes the task:
### Input:
Resolve metric key to a given target.
:param metric: the metric name.
:type metric: ``str``
:rtype: :class:`Metric`
### Response:
def resolve_metric_as_tuple(metric):
"""
Resolve metric key to a given target.
:param metric... |
def versions_information(include_salt_cloud=False):
'''
Report the versions of dependent software.
'''
salt_info = list(salt_information())
lib_info = list(dependency_information(include_salt_cloud))
sys_info = list(system_information())
return {'Salt Version': dict(salt_info),
... | Report the versions of dependent software. | Below is the the instruction that describes the task:
### Input:
Report the versions of dependent software.
### Response:
def versions_information(include_salt_cloud=False):
'''
Report the versions of dependent software.
'''
salt_info = list(salt_information())
lib_info = list(dependency_inform... |
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb)) | Constructs a :class:`Colour` from an HSV tuple. | Below is the the instruction that describes the task:
### Input:
Constructs a :class:`Colour` from an HSV tuple.
### Response:
def from_hsv(cls, h, s, v):
"""Constructs a :class:`Colour` from an HSV tuple."""
rgb = colorsys.hsv_to_rgb(h, s, v)
return cls.from_rgb(*(int(x * 255) for x in rgb... |
def generate_name(length=15, not_in=None):
"""
Generates a random string of lowercase letters with the given length.
Parameters:
length (int): Length of the string to output.
not_in (list): Only return a string not in the given iterator.
Returns:
str: A new name thats not in th... | Generates a random string of lowercase letters with the given length.
Parameters:
length (int): Length of the string to output.
not_in (list): Only return a string not in the given iterator.
Returns:
str: A new name thats not in the given list. | Below is the the instruction that describes the task:
### Input:
Generates a random string of lowercase letters with the given length.
Parameters:
length (int): Length of the string to output.
not_in (list): Only return a string not in the given iterator.
Returns:
str: A new name t... |
def telemetry_client(self, value: BotTelemetryClient) -> None:
"""
Sets the telemetry client for logging events.
"""
if value is None:
self._telemetry_client = NullTelemetryClient()
else:
self._telemetry_client = value | Sets the telemetry client for logging events. | Below is the the instruction that describes the task:
### Input:
Sets the telemetry client for logging events.
### Response:
def telemetry_client(self, value: BotTelemetryClient) -> None:
"""
Sets the telemetry client for logging events.
"""
if value is None:
self._telem... |
def wrap_callable(cls, uri, methods, callable_obj):
"""Wraps function-based callable_obj into a `Route` instance, else
proxies a `bottle_neck.handlers.BaseHandler` subclass instance.
Args:
uri (str): The uri relative path.
methods (tuple): A tuple of valid method string... | Wraps function-based callable_obj into a `Route` instance, else
proxies a `bottle_neck.handlers.BaseHandler` subclass instance.
Args:
uri (str): The uri relative path.
methods (tuple): A tuple of valid method strings.
callable_obj (instance): The callable object.
... | Below is the the instruction that describes the task:
### Input:
Wraps function-based callable_obj into a `Route` instance, else
proxies a `bottle_neck.handlers.BaseHandler` subclass instance.
Args:
uri (str): The uri relative path.
methods (tuple): A tuple of valid method ... |
def modules_directory():
"""
Get the core modules directory.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") | Get the core modules directory. | Below is the the instruction that describes the task:
### Input:
Get the core modules directory.
### Response:
def modules_directory():
"""
Get the core modules directory.
"""
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules") |
def resource_path(relative_path=None, expect=None):
"""Return the absolute path to a resource in iotile-build.
This method finds the path to the `config` folder inside
iotile-build, appends `relative_path` to it and then
checks to make sure the desired file or directory exists.
You can specify exp... | Return the absolute path to a resource in iotile-build.
This method finds the path to the `config` folder inside
iotile-build, appends `relative_path` to it and then
checks to make sure the desired file or directory exists.
You can specify expect=(None, 'file', or 'folder') for
what you expect to ... | Below is the the instruction that describes the task:
### Input:
Return the absolute path to a resource in iotile-build.
This method finds the path to the `config` folder inside
iotile-build, appends `relative_path` to it and then
checks to make sure the desired file or directory exists.
You can s... |
def _get_not_annotated(func, annotations=None):
"""Return non-optional parameters that are not annotated."""
argspec = inspect.getfullargspec(func)
args = argspec.args
if argspec.defaults is not None:
args = args[:-len(argspec.defaults)]
if inspect.isclass(func) or inspect.ismethod(func):
... | Return non-optional parameters that are not annotated. | Below is the the instruction that describes the task:
### Input:
Return non-optional parameters that are not annotated.
### Response:
def _get_not_annotated(func, annotations=None):
"""Return non-optional parameters that are not annotated."""
argspec = inspect.getfullargspec(func)
args = argspec.args
... |
def parse_motion_state(val):
"""Convert motion state byte to seconds."""
number = val & 0b00111111
unit = (val & 0b11000000) >> 6
if unit == 1:
number *= 60 # minutes
elif unit == 2:
number *= 60 * 60 # hours
elif unit == 3 and number < 32:
... | Convert motion state byte to seconds. | Below is the the instruction that describes the task:
### Input:
Convert motion state byte to seconds.
### Response:
def parse_motion_state(val):
"""Convert motion state byte to seconds."""
number = val & 0b00111111
unit = (val & 0b11000000) >> 6
if unit == 1:
number *= ... |
def old(self):
"""Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes.
"""
value = getattr(self.fastaccess_old, self.n... | Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes. | Below is the the instruction that describes the task:
### Input:
Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes.
### Response:
def o... |
def parse(self, p_todo):
"""
Returns fully parsed string from 'format_string' attribute with all
placeholders properly substituted by content obtained from p_todo.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format) stored in 'format_list... | Returns fully parsed string from 'format_string' attribute with all
placeholders properly substituted by content obtained from p_todo.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format) stored in 'format_list'
attribute. | Below is the the instruction that describes the task:
### Input:
Returns fully parsed string from 'format_string' attribute with all
placeholders properly substituted by content obtained from p_todo.
It uses preprocessed form of 'format_string' (result of
ListFormatParser._preprocess_format... |
def session_info(consul_url=None, token=None, session=None, **kwargs):
'''
Information about a session
:param consul_url: The Consul server URL.
:param session: The ID of the session to return information about.
:param dc: By default, the datacenter of the agent is queried;
however, ... | Information about a session
:param consul_url: The Consul server URL.
:param session: The ID of the session to return information about.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be provided using the "dc" parameter.
:return: Boolean & message of ... | Below is the the instruction that describes the task:
### Input:
Information about a session
:param consul_url: The Consul server URL.
:param session: The ID of the session to return information about.
:param dc: By default, the datacenter of the agent is queried;
however, the dc can be ... |
def add_and_get(self, delta):
"""
Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
:raises C... | Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10.
:raises ConsistencyLostError: if the session guarantees hav... | Below is the the instruction that describes the task:
### Input:
Adds the given value to the current value and returns the updated value.
:raises NoDataMemberInClusterError: if the cluster does not contain any data members.
:raises UnsupportedOperationError: if the cluster version is less than 3.10... |
def getHeaders(self):
"""
Get common headers
:return:
"""
basicauth = base64.encodestring(b(self.user + ':' + self.password)).strip()
return {
"Depth": "1",
"Authorization": 'Basic ' + _decode_utf8(basicauth),
"Accept": "*/*"
} | Get common headers
:return: | Below is the the instruction that describes the task:
### Input:
Get common headers
:return:
### Response:
def getHeaders(self):
"""
Get common headers
:return:
"""
basicauth = base64.encodestring(b(self.user + ':' + self.password)).strip()
return {
... |
def place_instruction(order_type, selection_id, side, handicap=None, limit_order=None, limit_on_close_order=None,
market_on_close_order=None, customer_order_ref=None):
"""
Create order instructions to place an order at exchange.
:param str order_type: define type of order to place.
... | Create order instructions to place an order at exchange.
:param str order_type: define type of order to place.
:param int selection_id: selection on which to place order
:param float handicap: handicap if placing order on asianhandicap type market
:param str side: side of order
:param resources.Limi... | Below is the the instruction that describes the task:
### Input:
Create order instructions to place an order at exchange.
:param str order_type: define type of order to place.
:param int selection_id: selection on which to place order
:param float handicap: handicap if placing order on asianhandicap typ... |
def patch_custom_resource_definition_status(self, name, body, **kwargs): # noqa: E501
"""patch_custom_resource_definition_status # noqa: E501
partially update status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | patch_custom_resource_definition_status # noqa: E501
partially update status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_custom_r... | Below is the the instruction that describes the task:
### Input:
patch_custom_resource_definition_status # noqa: E501
partially update status of the specified CustomResourceDefinition # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reques... |
def parse_bismark_mbias(self, f):
""" Parse the Bismark M-Bias plot data """
s = f['s_name']
self.bismark_mbias_data['meth']['CpG_R1'][s] = {}
self.bismark_mbias_data['meth']['CHG_R1'][s] = {}
self.bismark_mbias_data['meth']['CHH_R1'][s] = {}
self.bismark_mbias_data['cov'... | Parse the Bismark M-Bias plot data | Below is the the instruction that describes the task:
### Input:
Parse the Bismark M-Bias plot data
### Response:
def parse_bismark_mbias(self, f):
""" Parse the Bismark M-Bias plot data """
s = f['s_name']
self.bismark_mbias_data['meth']['CpG_R1'][s] = {}
self.bismark_mbias_data['m... |
def wrap_http_for_jwt_access(credentials, http):
"""Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
... | Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the original request.
Args:
credentials: _JWTAccessCredentials, t... | Below is the the instruction that describes the task:
### Input:
Prepares an HTTP object's request method for JWT access.
Wraps HTTP requests with logic to catch auth failures (typically
identified via a 401 status code). In the event of failure, tries
to refresh the token used and then retry the origi... |
def pairwise_distances(x, y=None, **kwargs):
r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_like
An :math:... | r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_like
An :math:`n \times m` array of :math:`n` observations in
... | Below is the the instruction that describes the task:
### Input:
r"""
pairwise_distances(x, y=None, *, exponent=1)
Pairwise distance between points.
Return the pairwise distance between points in two sets, or
in the same set if only one set is passed.
Parameters
----------
x: array_li... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.