code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def addDataset(self, dataset):
"""
Adds the given data set to this chart widget.
:param dataSet | <XChartDataset>
"""
self._datasets.append(dataset)
self._dataChanged = True
self._addDatasetAction(dataset) | Adds the given data set to this chart widget.
:param dataSet | <XChartDataset> | Below is the the instruction that describes the task:
### Input:
Adds the given data set to this chart widget.
:param dataSet | <XChartDataset>
### Response:
def addDataset(self, dataset):
"""
Adds the given data set to this chart widget.
:param dat... |
def _GetCachedEntryDataTypeMap(
self, format_type, value_data, cached_entry_offset):
"""Determines the cached entry data type map.
Args:
format_type (int): format type.
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to... | Determines the cached entry data type map.
Args:
format_type (int): format type.
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.
Returns:
dtfabric.DataTypeMap: data type map which contai... | Below is the the instruction that describes the task:
### Input:
Determines the cached entry data type map.
Args:
format_type (int): format type.
value_data (bytes): value data.
cached_entry_offset (int): offset of the first cached entry data
relative to the start of the value data.... |
def check_gsims(self, gsims):
"""
:param gsims: a sequence of GSIM instances
"""
imts = set(from_string(imt).name for imt in self.imtls)
for gsim in gsims:
restrict_imts = gsim.DEFINED_FOR_INTENSITY_MEASURE_TYPES
if restrict_imts:
names = s... | :param gsims: a sequence of GSIM instances | Below is the the instruction that describes the task:
### Input:
:param gsims: a sequence of GSIM instances
### Response:
def check_gsims(self, gsims):
"""
:param gsims: a sequence of GSIM instances
"""
imts = set(from_string(imt).name for imt in self.imtls)
for gsim in gsim... |
def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInterfaceType, GraphQLObjectType, None], Field, GraphQLField]]], List[str]]]
compared_fragments, # type: PairSet
parent_fields_are_mutually_exclu... | Determines if there is a conflict between two particular fields. | Below is the the instruction that describes the task:
### Input:
Determines if there is a conflict between two particular fields.
### Response:
def _find_conflict(
context, # type: ValidationContext
cached_fields_and_fragment_names, # type: Dict[SelectionSet, Tuple[Dict[str, List[Tuple[Union[GraphQLInter... |
def length_longest_path(input):
"""
:type input: str
:rtype: int
"""
curr_len, max_len = 0, 0 # running length and max length
stack = [] # keep track of the name length
for s in input.split('\n'):
print("---------")
print("<path>:", s)
depth = s.count('\t') #... | :type input: str
:rtype: int | Below is the the instruction that describes the task:
### Input:
:type input: str
:rtype: int
### Response:
def length_longest_path(input):
"""
:type input: str
:rtype: int
"""
curr_len, max_len = 0, 0 # running length and max length
stack = [] # keep track of the name length
... |
def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) | Load proxy list from configured proxy source | Below is the the instruction that describes the task:
### Input:
Load proxy list from configured proxy source
### Response:
def load(self):
"""Load proxy list from configured proxy source"""
self._list = self._source.load()
self._list_iter = itertools.cycle(self._list) |
def trigger_replication_schedule(self, schedule_id, dry_run=False):
"""
Trigger replication immediately. Start and end dates on the schedule will be
ignored.
@param schedule_id: The id of the schedule to trigger.
@param dry_run: Whether to execute a dry run.
@return: The command corresponding t... | Trigger replication immediately. Start and end dates on the schedule will be
ignored.
@param schedule_id: The id of the schedule to trigger.
@param dry_run: Whether to execute a dry run.
@return: The command corresponding to the replication job.
@since: API v3 | Below is the the instruction that describes the task:
### Input:
Trigger replication immediately. Start and end dates on the schedule will be
ignored.
@param schedule_id: The id of the schedule to trigger.
@param dry_run: Whether to execute a dry run.
@return: The command corresponding to the repli... |
def attachmethod(target):
'''
Reference: https://blog.tonyseek.com/post/open-class-in-python/
class Spam(object):
pass
@attach_method(Spam)
def egg1(self, name):
print((self, name))
spam1 = Spam()
# OpenClass 加入的方法 egg1 可用
spam1.egg1("Test1")
# 输出Test1
'''
... | Reference: https://blog.tonyseek.com/post/open-class-in-python/
class Spam(object):
pass
@attach_method(Spam)
def egg1(self, name):
print((self, name))
spam1 = Spam()
# OpenClass 加入的方法 egg1 可用
spam1.egg1("Test1")
# 输出Test1 | Below is the the instruction that describes the task:
### Input:
Reference: https://blog.tonyseek.com/post/open-class-in-python/
class Spam(object):
pass
@attach_method(Spam)
def egg1(self, name):
print((self, name))
spam1 = Spam()
# OpenClass 加入的方法 egg1 可用
spam1.egg1("Tes... |
def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
):
"""Execute the rolling restart on the specified b... | Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
... | Below is the the instruction that describes the task:
### Input:
Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are... |
def _set_filter_change_update_delay(self, v, load=False):
"""
Setter method for filter_change_update_delay, mapped from YANG variable /rbridge_id/filter_change_update_delay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_filter_change_update_delay is considered as... | Setter method for filter_change_update_delay, mapped from YANG variable /rbridge_id/filter_change_update_delay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_filter_change_update_delay is considered as a private
method. Backends looking to populate this variable shou... | Below is the the instruction that describes the task:
### Input:
Setter method for filter_change_update_delay, mapped from YANG variable /rbridge_id/filter_change_update_delay (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_filter_change_update_delay is considered as ... |
def get_params(self, url):
"""
Extract the named parameters from a url regex. If the url regex does not contain
named parameters, they will be keyed _0, _1, ...
* Named parameters
Regex:
/photos/^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<object_id>\d... | Extract the named parameters from a url regex. If the url regex does not contain
named parameters, they will be keyed _0, _1, ...
* Named parameters
Regex:
/photos/^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{1,2})/(?P<object_id>\d+)/
URL:
http://www2.l... | Below is the the instruction that describes the task:
### Input:
Extract the named parameters from a url regex. If the url regex does not contain
named parameters, they will be keyed _0, _1, ...
* Named parameters
Regex:
/photos/^(?P<year>\d{4})/(?P<month>\w{3})/(?P<day>\d{... |
def sample(problem, N, num_levels=4, optimal_trajectories=None,
local_optimization=True):
"""Generate model inputs using the Method of Morris
Returns a NumPy matrix containing the model inputs required for Method of
Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D`
columns... | Generate model inputs using the Method of Morris
Returns a NumPy matrix containing the model inputs required for Method of
Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D`
columns, where :math:`D` is the number of parameters, :math:`G` is the
number of groups (if no groups are selec... | Below is the the instruction that describes the task:
### Input:
Generate model inputs using the Method of Morris
Returns a NumPy matrix containing the model inputs required for Method of
Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D`
columns, where :math:`D` is the number of para... |
def immediateAssignmentExtended(StartingTime_presence=0):
"""IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19"""
a = L2PseudoLength()
b = TpPd(pd=0x6)
c = MessageType(mesType=0x39) # 00111001
d = PageModeAndSpareHalfOctets()
f = ChannelDescription()
g = RequestReference()
h = TimingAdvance(... | IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19 | Below is the the instruction that describes the task:
### Input:
IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19
### Response:
def immediateAssignmentExtended(StartingTime_presence=0):
"""IMMEDIATE ASSIGNMENT EXTENDED Section 9.1.19"""
a = L2PseudoLength()
b = TpPd(pd=0x6)
c = MessageType(mesType=0x39... |
def _load_github_hooks(github_url='https://api.github.com'):
"""Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503.
"""
try:
... | Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503. | Below is the the instruction that describes the task:
### Input:
Request GitHub's IP block from their API.
Return the IP network.
If we detect a rate-limit error, raise an error message stating when
the rate limit will reset.
If something else goes wrong, raise a generic 503.
### Response:
def _... |
def calc_digest(origin, algorithm="sha1", block_size=None):
"""Calculate digest of a readable object
Args:
origin -- a readable object for which calculate digest
algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.
block_size -- the size of ... | Calculate digest of a readable object
Args:
origin -- a readable object for which calculate digest
algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.
block_size -- the size of the block to read at each iteration | Below is the the instruction that describes the task:
### Input:
Calculate digest of a readable object
Args:
origin -- a readable object for which calculate digest
algorithn -- the algorithm to use. See ``hashlib.algorithms_available`` for supported algorithms.
block_size -- the size o... |
def apply(d, leaf_key, func, new_name=None, remove_lkey=True,
list_of_dicts=False, unflatten_level=0, deepcopy=True, **kwargs):
""" apply a function to all values with a certain leaf (terminal) key
Parameters
----------
d : dict
leaf_key : str
name of leaf key
func : callable
... | apply a function to all values with a certain leaf (terminal) key
Parameters
----------
d : dict
leaf_key : str
name of leaf key
func : callable
function to apply
new_name : str
if not None, rename leaf_key
remove_lkey: bool
whether to remove original leaf_ke... | Below is the the instruction that describes the task:
### Input:
apply a function to all values with a certain leaf (terminal) key
Parameters
----------
d : dict
leaf_key : str
name of leaf key
func : callable
function to apply
new_name : str
if not None, rename leaf... |
def disallow(
self, foreign, permission="active", account=None, threshold=None, **kwargs
):
""" Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (opt... | Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (optional) The actual permission to
modify (defaults to ``active``)
:param str account: (opt... | Below is the the instruction that describes the task:
### Input:
Remove additional access to an account by some other public
key or account.
:param str foreign: The foreign account that will obtain access
:param str permission: (optional) The actual permission to
... |
def _perform_action(self, params, return_dict=True):
"""
Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Act... | Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
Returns dict or Action | Below is the the instruction that describes the task:
### Input:
Perform a droplet action.
Args:
params (dict): parameters of the action
Optional Args:
return_dict (bool): Return a dict when True (default),
otherwise return an Action.
... |
def color_intervals(colors, levels, clip=None, N=255):
"""
Maps the supplied colors into bins defined by the supplied levels.
If a clip tuple is defined the bins are clipped to the defined
range otherwise the range is computed from the levels and returned.
Arguments
---------
colors: list
... | Maps the supplied colors into bins defined by the supplied levels.
If a clip tuple is defined the bins are clipped to the defined
range otherwise the range is computed from the levels and returned.
Arguments
---------
colors: list
List of colors (usually hex string or named colors)
levels... | Below is the the instruction that describes the task:
### Input:
Maps the supplied colors into bins defined by the supplied levels.
If a clip tuple is defined the bins are clipped to the defined
range otherwise the range is computed from the levels and returned.
Arguments
---------
colors: list... |
def middle_begin(self, index):
"""
Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin
"""
if (index < 0) or (index > self.all_length):
raise ValueError(u"The given index is not valid")
self.__middle_begin = index | Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin | Below is the the instruction that describes the task:
### Input:
Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin
### Response:
def middle_begin(self, index):
"""
Set the index where MIDDLE starts.
:param int index: the new index for MIDDLE begin... |
def phone_text_subs():
"""
Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual
Number value.
Returns:
dictionary of dictionaries containing Strings mapped to Numbers
"""
Small = {
'zero': 0,
'zer0': 0,
'one': 1,
'two': 2,
'th... | Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual
Number value.
Returns:
dictionary of dictionaries containing Strings mapped to Numbers | Below is the the instruction that describes the task:
### Input:
Gets a dictionary of dictionaries that each contain alphabetic number manifestations mapped to their actual
Number value.
Returns:
dictionary of dictionaries containing Strings mapped to Numbers
### Response:
def phone_text_subs():
"""
G... |
def from_dict(cls, operation, client, **caller_metadata):
"""Factory: construct an instance from a dictionary.
:type operation: dict
:param operation: Operation as a JSON object.
:type client: :class:`~google.cloud.client.Client`
:param client: The client used to poll for the s... | Factory: construct an instance from a dictionary.
:type operation: dict
:param operation: Operation as a JSON object.
:type client: :class:`~google.cloud.client.Client`
:param client: The client used to poll for the status of the operation.
:type caller_metadata: dict
... | Below is the the instruction that describes the task:
### Input:
Factory: construct an instance from a dictionary.
:type operation: dict
:param operation: Operation as a JSON object.
:type client: :class:`~google.cloud.client.Client`
:param client: The client used to poll for the s... |
def update(self):
"""This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this D... | This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to get an URL to identify Posts from this Data Source | Below is the the instruction that describes the task:
### Input:
This method should be called to update associated Posts
It will call content-specific methods:
_get_data() to obtain list of entries
_store_post() to store obtained entry object
_get_data_source_url() to ... |
def query_download_tasks(self, task_ids, operate_type=1,
expires=None, **kwargs):
"""根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1... | 根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1:查进度信息,默认为1
:param expires: 请求失效时间,如果有,则会校验。
:type expires: int
:return: Response 对象 | Below is the the instruction that describes the task:
### Input:
根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务ID列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1:查进度信息,默认为1
:param expires: 请求失效时间,如果有,则会校验。
... |
def get_too_few_non_zero_degree_day_warning(
model_type, balance_point, degree_day_type, degree_days, minimum_non_zero
):
""" Return an empty list or a single warning wrapped in a list regarding
non-zero degree days for a set of degree days.
Parameters
----------
model_type : :any:`str`
... | Return an empty list or a single warning wrapped in a list regarding
non-zero degree days for a set of degree days.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
balance_point : :any:`float`
The balance point in question.
degree_day_type : :any:... | Below is the the instruction that describes the task:
### Input:
Return an empty list or a single warning wrapped in a list regarding
non-zero degree days for a set of degree days.
Parameters
----------
model_type : :any:`str`
Model type (e.g., ``'cdd_hdd'``).
balance_point : :any:`floa... |
def annotate_tree_properties(comments):
"""
iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it
"""
if not comments:
return
it = iter(comments)
# get the first item, this will fail if no items !
old = next(it... | iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it | Below is the the instruction that describes the task:
### Input:
iterate through nodes and adds some magic properties to each of them
representing opening list of children and closing it
### Response:
def annotate_tree_properties(comments):
"""
iterate through nodes and adds some magic properties to ea... |
def visit_function_inline(self, node):
"""Returns an GeneratedExpr for a function with the given body."""
# First pass collects the names of locals used in this function. Do this in
# a separate pass so that we know whether to resolve a name as a local or a
# global during the second pass.
func_visi... | Returns an GeneratedExpr for a function with the given body. | Below is the the instruction that describes the task:
### Input:
Returns an GeneratedExpr for a function with the given body.
### Response:
def visit_function_inline(self, node):
"""Returns an GeneratedExpr for a function with the given body."""
# First pass collects the names of locals used in this functi... |
def is_bool_dtype(arr_or_dtype):
"""
Check whether the provided array or dtype is of a boolean dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a boolean dtype.
Notes... | Check whether the provided array or dtype is of a boolean dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a boolean dtype.
Notes
-----
An ExtensionArray is considere... | Below is the the instruction that describes the task:
### Input:
Check whether the provided array or dtype is of a boolean dtype.
Parameters
----------
arr_or_dtype : array-like
The array or dtype to check.
Returns
-------
boolean
Whether or not the array or dtype is of a b... |
def hbas(self):
"""
:class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in
this Partition.
If the "dpm-storage-management" feature is enabled, this property is
`None`.
"""
# We do here some lazy loading.
if not self._hbas:
try:
... | :class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in
this Partition.
If the "dpm-storage-management" feature is enabled, this property is
`None`. | Below is the the instruction that describes the task:
### Input:
:class:`~zhmcclient.HbaManager`: Access to the :term:`HBAs <HBA>` in
this Partition.
If the "dpm-storage-management" feature is enabled, this property is
`None`.
### Response:
def hbas(self):
"""
:class:`~zhmc... |
def annotation(self, type, set=None):
"""Obtain a single annotation element.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to matc... | Obtain a single annotation element.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (str): The set to match against, only elements pertaining to this set w... | Below is the the instruction that describes the task:
### Input:
Obtain a single annotation element.
A further restriction can be made based on set.
Arguments:
Class (class): The class to select; any python class (not instance) subclassed off :class:`AbstractElement`
Set (s... |
def brightness(self, brightness):
"""
Build command for setting the brightness of the led.
:param brightness: Value to set (0.0-1.0).
:return: The command.
"""
return self._build_command(0x4E, self.convert_brightness(brightness),
select=... | Build command for setting the brightness of the led.
:param brightness: Value to set (0.0-1.0).
:return: The command. | Below is the the instruction that describes the task:
### Input:
Build command for setting the brightness of the led.
:param brightness: Value to set (0.0-1.0).
:return: The command.
### Response:
def brightness(self, brightness):
"""
Build command for setting the brightness of the ... |
def load_backends(config, callback, internal_attributes):
"""
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[strin... | Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string, dict[str, str | list[str]]]
:rtype: Sequence[satosa.backends.ba... | Below is the the instruction that describes the task:
### Input:
Load all backend modules specified in the config
:type config: satosa.satosa_config.SATOSAConfig
:type callback:
(satosa.context.Context, satosa.internal.InternalData) -> satosa.response.Response
:type internal_attributes: dict[string... |
def hincrbyfloat(self, key, field, increment=1.0):
"""Increment the float value of a hash field by the given number."""
fut = self.execute(b'HINCRBYFLOAT', key, field, increment)
return wait_convert(fut, float) | Increment the float value of a hash field by the given number. | Below is the the instruction that describes the task:
### Input:
Increment the float value of a hash field by the given number.
### Response:
def hincrbyfloat(self, key, field, increment=1.0):
"""Increment the float value of a hash field by the given number."""
fut = self.execute(b'HINCRBYFLOAT', k... |
def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)
logger.info("Websocket server listening on {address}".format(
address=self.address))
... | Runs the WebSocket server | Below is the the instruction that describes the task:
### Input:
Runs the WebSocket server
### Response:
def run_server(self):
"""
Runs the WebSocket server
"""
self.protocol = MeaseWebSocketServerProtocol
reactor.listenTCP(port=self.port, factory=self, interface=self.host)... |
def _parse_string_host(host_str):
"""
Parse host string into a dictionary host
:param host_str:
:return:
"""
host_str = EsParser._fix_host_prefix(host_str)
parsed_url = urlparse(host_str)
host = {HostParsing.HOST: parsed_url.hostname}
if parsed_url... | Parse host string into a dictionary host
:param host_str:
:return: | Below is the the instruction that describes the task:
### Input:
Parse host string into a dictionary host
:param host_str:
:return:
### Response:
def _parse_string_host(host_str):
"""
Parse host string into a dictionary host
:param host_str:
:return:
"""
... |
def _make_reserved_tokens_re(reserved_tokens):
"""Constructs compiled regex to parse out reserved tokens."""
if not reserved_tokens:
return None
escaped_tokens = [_re_escape(rt) for rt in reserved_tokens]
pattern = "(%s)" % "|".join(escaped_tokens)
reserved_tokens_re = _re_compile(pattern)
return reserv... | Constructs compiled regex to parse out reserved tokens. | Below is the the instruction that describes the task:
### Input:
Constructs compiled regex to parse out reserved tokens.
### Response:
def _make_reserved_tokens_re(reserved_tokens):
"""Constructs compiled regex to parse out reserved tokens."""
if not reserved_tokens:
return None
escaped_tokens = [_re_esc... |
def reduced_chi2(self, model, error_map=0):
"""
returns reduced chi2
:param model:
:param error_map:
:return:
"""
chi2 = self.reduced_residuals(model, error_map)
return np.sum(chi2**2) / self.num_data_evaluate() | returns reduced chi2
:param model:
:param error_map:
:return: | Below is the the instruction that describes the task:
### Input:
returns reduced chi2
:param model:
:param error_map:
:return:
### Response:
def reduced_chi2(self, model, error_map=0):
"""
returns reduced chi2
:param model:
:param error_map:
:return:
... |
def _validate_and_get_value(options, options_name, key, _type):
"""
Check that `options` has a value for `key` with type
`_type`. Return that value. `options_name` is a string representing a
human-readable name for `options` to be used when printing errors.
"""
if isinstance(options, dict):
has = lambda... | Check that `options` has a value for `key` with type
`_type`. Return that value. `options_name` is a string representing a
human-readable name for `options` to be used when printing errors. | Below is the the instruction that describes the task:
### Input:
Check that `options` has a value for `key` with type
`_type`. Return that value. `options_name` is a string representing a
human-readable name for `options` to be used when printing errors.
### Response:
def _validate_and_get_value(options, optio... |
def mouseMoveEvent(self, ev):
"""Update line with last point and current coordinates."""
pos = self.transformPos(ev.pos())
# Update coordinates in status bar if image is opened
window = self.parent().window()
if window.filePath is not None:
self.parent().window().lab... | Update line with last point and current coordinates. | Below is the the instruction that describes the task:
### Input:
Update line with last point and current coordinates.
### Response:
def mouseMoveEvent(self, ev):
"""Update line with last point and current coordinates."""
pos = self.transformPos(ev.pos())
# Update coordinates in status bar ... |
def grating_coupler_period(wavelength,
n_eff,
n_clad,
incidence_angle_deg,
diffration_order=1):
'''
Calculate the period needed for a grating coupler.
Args:
wavelength (float): The target wav... | Calculate the period needed for a grating coupler.
Args:
wavelength (float): The target wavelength for the
grating coupler.
n_eff (float): The effective index of the mode
of a waveguide with the width of the grating
coupler.
n_clad (float): The refractive... | Below is the the instruction that describes the task:
### Input:
Calculate the period needed for a grating coupler.
Args:
wavelength (float): The target wavelength for the
grating coupler.
n_eff (float): The effective index of the mode
of a waveguide with the width of th... |
def dump_data(request):
"""Exports data from whole project.
"""
# Try to grab app_label data
app_label = request.GET.get('app_label', [])
if app_label:
app_label = app_label.split(',')
return dump_to_response(request, app_label=app_label,
exclude=settings.SMUG... | Exports data from whole project. | Below is the the instruction that describes the task:
### Input:
Exports data from whole project.
### Response:
def dump_data(request):
"""Exports data from whole project.
"""
# Try to grab app_label data
app_label = request.GET.get('app_label', [])
if app_label:
app_label = app_label.s... |
def send(self, event):
"""Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClosed``, then returns
``N... | Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClosed``, then returns
``None``. Otherwise, returns a :term:... | Below is the the instruction that describes the task:
### Input:
Convert a high-level event into bytes that can be sent to the peer,
while updating our internal state machine.
Args:
event: The :ref:`event <events>` to send.
Returns:
If ``type(event) is ConnectionClo... |
def onConnsChanged(self, joined: Set[str], left: Set[str]):
"""
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number... | A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number of protocol instances.
- Check protocol instances. See `checkInstances(... | Below is the the instruction that describes the task:
### Input:
A series of operations to perform once a connection count has changed.
- Set f to max number of failures this system can handle.
- Set status to one of started, started_hungry or starting depending on
the number of protoco... |
def add_methods(methods_to_add):
''' use this to bulk add new methods to Generator '''
for i in methods_to_add:
try:
Generator.add_method(*i)
except Exception as ex:
raise Exception('issue adding {} - {}'.format(repr(i), ex)) | use this to bulk add new methods to Generator | Below is the the instruction that describes the task:
### Input:
use this to bulk add new methods to Generator
### Response:
def add_methods(methods_to_add):
''' use this to bulk add new methods to Generator '''
for i in methods_to_add:
try:
Generator.add_method(*i)
... |
def process_action(self, request, queryset):
"""
Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged as \... | Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged as \
either 'published' or 'scheduled' depending on the value... | Below is the the instruction that describes the task:
### Input:
Publishes the selected objects by passing the value of \
'when' to the object's publish method. The object's \
`purge_archives` method is also called to limit the number \
of old items that we keep around. The action is logged ... |
def discrete(self):
"""
Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
... | Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ``f2`` into continuous
>>> new_ds = df.discrete('f1 f2') | Below is the the instruction that describes the task:
### Input:
Set sequence to be discrete.
:rtype: Column
:Example:
>>> # Table schema is create table test(f1 double, f2 string)
>>> # Original continuity: f1=CONTINUOUS, f2=CONTINUOUS
>>> # Now we want to set ``f1`` and ... |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExportConfigurationContext for this ExportConfigurationInstance
:rtype: twilio.rest.preview.bulk_... | Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExportConfigurationContext for this ExportConfigurationInstance
:rtype: twilio.rest.preview.bulk_exports.export_configuration.ExportCon... | Below is the the instruction that describes the task:
### Input:
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ExportConfigurationContext for this ExportConfigurationInstance
:r... |
def getPeersWithAttrValues(self, attrName, attrValues):
'''
getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName
are in the list of possible vaues #attrValues
@param attrName - Name of attribute
@param attrValues - ... | getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName
are in the list of possible vaues #attrValues
@param attrName - Name of attribute
@param attrValues - List of possible values which will match
@return - None if no paren... | Below is the the instruction that describes the task:
### Input:
getPeersWithAttrValues - Gets peers (elements on same level) whose attribute given by #attrName
are in the list of possible vaues #attrValues
@param attrName - Name of attribute
@param attrValues - List of pos... |
def checkout(self, revision, options):
"""
Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict``
"""
rev = revision.key
self.rep... | Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict`` | Below is the the instruction that describes the task:
### Input:
Checkout a specific revision.
:param revision: The revision identifier.
:type revision: :class:`Revision`
:param options: Any additional options.
:type options: ``dict``
### Response:
def checkout(self, revision, o... |
def add_argument(self, *args, **kwargs):
"""Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstring... | Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
docstrings.
If the new arguments belong to some sub ... | Below is the the instruction that describes the task:
### Input:
Add an argument.
This method adds a new argument to the current parser. The function is
same as ``argparse.ArgumentParser.add_argument``. However, this method
tries to determine help messages for the adding argument from some
... |
def svd_moments(u, s, v, stachans, event_list, n_svs=2):
"""
Calculate relative moments/amplitudes using singular-value decomposition.
Convert basis vectors calculated by singular value \
decomposition (see the SVD functions in clustering) into relative \
moments.
For more information see the ... | Calculate relative moments/amplitudes using singular-value decomposition.
Convert basis vectors calculated by singular value \
decomposition (see the SVD functions in clustering) into relative \
moments.
For more information see the paper by \
`Rubinstein & Ellsworth (2010).
<http://www.bssaon... | Below is the the instruction that describes the task:
### Input:
Calculate relative moments/amplitudes using singular-value decomposition.
Convert basis vectors calculated by singular value \
decomposition (see the SVD functions in clustering) into relative \
moments.
For more information see the ... |
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
"""
Try and return page content in the requested format using selenium
"""
try:
# **TODO**: Find what exception this will throw and catch it and call
# self.driver.execute_script("w... | Try and return page content in the requested format using selenium | Below is the the instruction that describes the task:
### Input:
Try and return page content in the requested format using selenium
### Response:
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs):
"""
Try and return page content in the requested format using selenium
... |
def main():
"""
Handle command line arguments to convert a file to a JSON stream as a
script.
"""
logging.basicConfig(level=logging.INFO)
import argparse
parser = argparse.ArgumentParser(
description="Translate CSV or JSON input to a JSON stream, or verify "
"some... | Handle command line arguments to convert a file to a JSON stream as a
script. | Below is the the instruction that describes the task:
### Input:
Handle command line arguments to convert a file to a JSON stream as a
script.
### Response:
def main():
"""
Handle command line arguments to convert a file to a JSON stream as a
script.
"""
logging.basicConfig(level=logging.IN... |
def set_intermediates(self, intermediates, betas=None, transition_states=None):
"""Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate... | Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestrings
transition_states: list of True and False
electr... | Below is the the instruction that describes the task:
### Input:
Sets up intermediates and specifies whether it's an electrochemical step.
Either provide individual contributions or net contributions. If both are given,
only the net contributions are used.
intermediate_list: list of basestr... |
def _create_geonode_uploader_action(self):
"""Create action for Geonode uploader dialog."""
icon = resources_path('img', 'icons', 'geonode.png')
label = tr('Geonode Uploader')
self.action_geonode = QAction(
QIcon(icon), label, self.iface.mainWindow())
self.action_geon... | Create action for Geonode uploader dialog. | Below is the the instruction that describes the task:
### Input:
Create action for Geonode uploader dialog.
### Response:
def _create_geonode_uploader_action(self):
"""Create action for Geonode uploader dialog."""
icon = resources_path('img', 'icons', 'geonode.png')
label = tr('Geonode Uplo... |
def template(tem, queue=False, **kwargs):
'''
Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
sa... | Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: bash
salt '*' state.template '<Path to template on the minion... | Below is the the instruction that describes the task:
### Input:
Execute the information stored in a template file on the minion.
This function does not ask a master for a SLS file to render but
instead directly processes the file at the provided path on the minion.
CLI Example:
.. code-block:: b... |
def shared_memory(attrs=None, where=None):
'''
Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory
'''
if __grains__['os_family'] in ['RedHat', 'Debian']:
return _osquery_cmd(table='shared_memory', attrs=attrs, where=w... | Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory | Below is the the instruction that describes the task:
### Input:
Return shared_memory information from osquery
CLI Example:
.. code-block:: bash
salt '*' osquery.shared_memory
### Response:
def shared_memory(attrs=None, where=None):
'''
Return shared_memory information from osquery
... |
def prepare_ec(self, scaffolds, tour, weights):
"""
Prepare Evolutionary Computation. This converts scaffold names into
indices (integer) in the scaffolds array.
"""
scaffolds_ii = dict((s, i) for i, s in enumerate(scaffolds))
scfs = []
ww = []
for mlg in ... | Prepare Evolutionary Computation. This converts scaffold names into
indices (integer) in the scaffolds array. | Below is the the instruction that describes the task:
### Input:
Prepare Evolutionary Computation. This converts scaffold names into
indices (integer) in the scaffolds array.
### Response:
def prepare_ec(self, scaffolds, tour, weights):
"""
Prepare Evolutionary Computation. This converts sc... |
async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
"""
Injects the POST body into the FSM as a Postback message.
"""
await platform.inject_message(msg)
return json_response({
'status': 'ok',
}) | Injects the POST body into the FSM as a Postback message. | Below is the the instruction that describes the task:
### Input:
Injects the POST body into the FSM as a Postback message.
### Response:
async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
"""
Injects the POST body into the FSM as a Postback message.
"""
await platform.injec... |
def _compute_magnitude(self, rup, C):
"""
Compute the third term of the equation 1:
e1 + b1 * (M-Mh) + b2 * (M-Mh)**2 for M<=Mh
e1 + b3 * (M-Mh) otherwise
"""
m_h = 6.75
b_3 = 0.0
if rup.mag <= m_h:
return C["e1"] + (C['b1'] * (rup.mag - m_h))... | Compute the third term of the equation 1:
e1 + b1 * (M-Mh) + b2 * (M-Mh)**2 for M<=Mh
e1 + b3 * (M-Mh) otherwise | Below is the the instruction that describes the task:
### Input:
Compute the third term of the equation 1:
e1 + b1 * (M-Mh) + b2 * (M-Mh)**2 for M<=Mh
e1 + b3 * (M-Mh) otherwise
### Response:
def _compute_magnitude(self, rup, C):
"""
Compute the third term of the equation 1:
... |
def schedule_hostgroup_host_downtime(self, hostgroup, start_time, end_time, fixed,
trigger_id, duration, author, comment):
"""Schedule a downtime for each host of a hostgroup
Format of the line that triggers function call::
SCHEDULE_HOSTGROUP_HOST_DOWNTI... | Schedule a downtime for each host of a hostgroup
Format of the line that triggers function call::
SCHEDULE_HOSTGROUP_HOST_DOWNTIME;<hostgroup_name>;<start_time>;<end_time>;
<fixed>;<trigger_id>;<duration>;<author>;<comment>
:param hostgroup: hostgroup to schedule
:type hostgrou... | Below is the the instruction that describes the task:
### Input:
Schedule a downtime for each host of a hostgroup
Format of the line that triggers function call::
SCHEDULE_HOSTGROUP_HOST_DOWNTIME;<hostgroup_name>;<start_time>;<end_time>;
<fixed>;<trigger_id>;<duration>;<author>;<comment>
... |
def _resolve_type(self, env, type_ref, enforce_fully_defined=False):
"""
Resolves the data type referenced by type_ref.
If `enforce_fully_defined` is True, then the referenced type must be
fully populated (fields, parent_type, ...), and not simply a forward
reference.
""... | Resolves the data type referenced by type_ref.
If `enforce_fully_defined` is True, then the referenced type must be
fully populated (fields, parent_type, ...), and not simply a forward
reference. | Below is the the instruction that describes the task:
### Input:
Resolves the data type referenced by type_ref.
If `enforce_fully_defined` is True, then the referenced type must be
fully populated (fields, parent_type, ...), and not simply a forward
reference.
### Response:
def _resolve_ty... |
def _check_running_services(services):
"""Check that the services dict provided is actually running and provide
a list of (service, boolean) tuples for each service.
Returns both a zipped list of (service, boolean) and a list of booleans
in the same order as the services.
@param services: OrderedD... | Check that the services dict provided is actually running and provide
a list of (service, boolean) tuples for each service.
Returns both a zipped list of (service, boolean) and a list of booleans
in the same order as the services.
@param services: OrderedDict of strings: [ports], one for each service ... | Below is the the instruction that describes the task:
### Input:
Check that the services dict provided is actually running and provide
a list of (service, boolean) tuples for each service.
Returns both a zipped list of (service, boolean) and a list of booleans
in the same order as the services.
@p... |
def majorMinorVersion(sparkVersion):
"""
Given a Spark version string, return the (major version number, minor version number).
E.g., for 2.0.1-SNAPSHOT, return (2, 0).
>>> sparkVersion = "2.4.0"
>>> VersionUtils.majorMinorVersion(sparkVersion)
(2, 4)
>>> sparkVe... | Given a Spark version string, return the (major version number, minor version number).
E.g., for 2.0.1-SNAPSHOT, return (2, 0).
>>> sparkVersion = "2.4.0"
>>> VersionUtils.majorMinorVersion(sparkVersion)
(2, 4)
>>> sparkVersion = "2.3.0-SNAPSHOT"
>>> VersionUtils.majorMi... | Below is the the instruction that describes the task:
### Input:
Given a Spark version string, return the (major version number, minor version number).
E.g., for 2.0.1-SNAPSHOT, return (2, 0).
>>> sparkVersion = "2.4.0"
>>> VersionUtils.majorMinorVersion(sparkVersion)
(2, 4)
... |
def get_default_commands(self):
"""
Returns the default commands of this application.
:rtype: list[cleo.Command]
"""
commands = Application.get_default_commands(self)
self.add(ConstantsCommand())
self.add(LoaderCommand())
self.add(PyStratumCommand())
... | Returns the default commands of this application.
:rtype: list[cleo.Command] | Below is the the instruction that describes the task:
### Input:
Returns the default commands of this application.
:rtype: list[cleo.Command]
### Response:
def get_default_commands(self):
"""
Returns the default commands of this application.
:rtype: list[cleo.Command]
"""
... |
def fromstr(cls, s, *, strict=True):
"""
Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: Th... | Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
:return: The parsed JID
:rtype: :class:`JID`
See th... | Below is the the instruction that describes the task:
### Input:
Construct a JID out of a string containing it.
:param s: The string to parse.
:type s: :class:`str`
:param strict: Whether to enable strict parsing.
:type strict: :class:`bool`
:raises: See :class:`JID`
... |
def copy(self):
"""
Return a copy of this ProtoFeed, that is, a feed with all the
same attributes.
"""
other = ProtoFeed()
for key in cs.PROTOFEED_ATTRS:
value = getattr(self, key)
if isinstance(value, pd.DataFrame):
# Pandas copy D... | Return a copy of this ProtoFeed, that is, a feed with all the
same attributes. | Below is the the instruction that describes the task:
### Input:
Return a copy of this ProtoFeed, that is, a feed with all the
same attributes.
### Response:
def copy(self):
"""
Return a copy of this ProtoFeed, that is, a feed with all the
same attributes.
"""
other ... |
def bands(self):
"""
Bandpasses for which StarPopulation has magnitude data
"""
bands = []
for c in self.stars.columns:
if re.search('_mag',c):
bands.append(c)
return bands | Bandpasses for which StarPopulation has magnitude data | Below is the the instruction that describes the task:
### Input:
Bandpasses for which StarPopulation has magnitude data
### Response:
def bands(self):
"""
Bandpasses for which StarPopulation has magnitude data
"""
bands = []
for c in self.stars.columns:
if re.sea... |
def changes(self, columns=None, recurse=True, flags=0, inflated=False):
"""
Returns a dictionary of changes that have been made
to the data from this record.
:return { <orb.Column>: ( <variant> old, <variant> new), .. }
"""
output = {}
is_record = self.isReco... | Returns a dictionary of changes that have been made
to the data from this record.
:return { <orb.Column>: ( <variant> old, <variant> new), .. } | Below is the the instruction that describes the task:
### Input:
Returns a dictionary of changes that have been made
to the data from this record.
:return { <orb.Column>: ( <variant> old, <variant> new), .. }
### Response:
def changes(self, columns=None, recurse=True, flags=0, inflated=False):... |
def im_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the direct message"""
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) | Sets the topic for the direct message | Below is the the instruction that describes the task:
### Input:
Sets the topic for the direct message
### Response:
def im_set_topic(self, room_id, topic, **kwargs):
"""Sets the topic for the direct message"""
return self.__call_api_post('im.setTopic', roomId=room_id, topic=topic, kwargs=kwargs) |
def _write_enums(self, entity_name, attributes):
""" This method writes the ouput for a particular specification.
"""
self.enum_attrs_for_locale[entity_name] = attributes;
for attribute in attributes:
enum_name = "%s%sEnum" % (entity_name, attribute.name[0].upper() ... | This method writes the ouput for a particular specification. | Below is the the instruction that describes the task:
### Input:
This method writes the ouput for a particular specification.
### Response:
def _write_enums(self, entity_name, attributes):
""" This method writes the ouput for a particular specification.
"""
self.enum_attrs_for_loca... |
def read_sql(sql, con, filePath, index_col=None, coerce_float=True,
params=None, parse_dates=None, columns=None, chunksize=None):
"""
Read SQL query or database table into a DataFrameModel.
Provide a filePath argument in addition to the *args/**kwargs from
pandas.read_sql and get a DataFram... | Read SQL query or database table into a DataFrameModel.
Provide a filePath argument in addition to the *args/**kwargs from
pandas.read_sql and get a DataFrameModel.
NOTE: The chunksize option is overridden to None always (for now).
Reference:
http://pandas.pydata.org/pandas-docs/version/0.18.1/gen... | Below is the the instruction that describes the task:
### Input:
Read SQL query or database table into a DataFrameModel.
Provide a filePath argument in addition to the *args/**kwargs from
pandas.read_sql and get a DataFrameModel.
NOTE: The chunksize option is overridden to None always (for now).
R... |
def print_raw_data_file(input_file, start_index=0, limit=200, flavor='fei4b', select=None, tdc_trig_dist=False, trigger_data_mode=0, meta_data_v2=True):
"""Printing FEI4 data from raw data file for debugging.
"""
with tb.open_file(input_file + '.h5', mode="r") as file_h5:
if meta_data_v2:
... | Printing FEI4 data from raw data file for debugging. | Below is the the instruction that describes the task:
### Input:
Printing FEI4 data from raw data file for debugging.
### Response:
def print_raw_data_file(input_file, start_index=0, limit=200, flavor='fei4b', select=None, tdc_trig_dist=False, trigger_data_mode=0, meta_data_v2=True):
"""Printing FEI4 data from... |
def select_delim(self, delim):
'''Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long.
'''
size = len(delim)
if size > 20:
raise Run... | Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long. | Below is the the instruction that describes the task:
### Input:
Select desired delimeter
Args:
delim: The delimeter character you want.
Returns:
None
Raises:
RuntimeError: Delimeter too long.
### Response:
def select_delim(self, delim):
... |
def checksum(value):
"""
Calculates the checksum char used for the 16th char.
Author: Vincenzo Palazzo
"""
return chr(65 + sum(CHECKSUM_TABLE[index % 2][ALPHANUMERICS_DICT[char]]
for index, char in enumerate(value)) % 26) | Calculates the checksum char used for the 16th char.
Author: Vincenzo Palazzo | Below is the the instruction that describes the task:
### Input:
Calculates the checksum char used for the 16th char.
Author: Vincenzo Palazzo
### Response:
def checksum(value):
"""
Calculates the checksum char used for the 16th char.
Author: Vincenzo Palazzo
"""
return chr(65 + sum(CHECKSU... |
def write_dot(build_context, conf: Config, out_f):
"""Write build graph in dot format to `out_f` file-like object."""
not_buildenv_targets = get_not_buildenv_targets(build_context)
prebuilt_targets = get_prebuilt_targets(build_context)
out_f.write('strict digraph {\n')
for node in build_context.tar... | Write build graph in dot format to `out_f` file-like object. | Below is the the instruction that describes the task:
### Input:
Write build graph in dot format to `out_f` file-like object.
### Response:
def write_dot(build_context, conf: Config, out_f):
"""Write build graph in dot format to `out_f` file-like object."""
not_buildenv_targets = get_not_buildenv_targets(b... |
def from_json(self, json: Map) -> Maybe[Project]:
''' Try to instantiate a Project from the given json object.
Convert the **type** key to **tpe** and its value to
Maybe.
Make sure **root** is a directory, fall back to resolution
by **tpe/name**.
Reinsert the root dir int... | Try to instantiate a Project from the given json object.
Convert the **type** key to **tpe** and its value to
Maybe.
Make sure **root** is a directory, fall back to resolution
by **tpe/name**.
Reinsert the root dir into the json dict, filter out all keys
that aren't conta... | Below is the the instruction that describes the task:
### Input:
Try to instantiate a Project from the given json object.
Convert the **type** key to **tpe** and its value to
Maybe.
Make sure **root** is a directory, fall back to resolution
by **tpe/name**.
Reinsert the root ... |
def popitem(self, last=True): # pylint: disable=arguments-differ
u"""*x.popitem() → (k, v)*
Remove and return the most recently added item as a (key, value) pair
if *last* is True, else the least recently added item.
:raises KeyError: if *x* is empty.
"""
if not self:
... | u"""*x.popitem() → (k, v)*
Remove and return the most recently added item as a (key, value) pair
if *last* is True, else the least recently added item.
:raises KeyError: if *x* is empty. | Below is the the instruction that describes the task:
### Input:
u"""*x.popitem() → (k, v)*
Remove and return the most recently added item as a (key, value) pair
if *last* is True, else the least recently added item.
:raises KeyError: if *x* is empty.
### Response:
def popitem(self, last=... |
def map_attribute_to_seq(self,
attribute: str,
key_attribute: str,
value_attribute: Optional[str] = None) -> None:
"""Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose va... | Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose value \
is a mapping or a mapping of mappings and turns it into a \
sequence of mappings. Each entry in the original mapping is \
converted to an entry in the list. If only a key attribute is... | Below is the the instruction that describes the task:
### Input:
Converts a mapping attribute to a sequence.
This function takes an attribute of this Node whose value \
is a mapping or a mapping of mappings and turns it into a \
sequence of mappings. Each entry in the original mapping is \
... |
def getlang_by_alpha2(code):
"""
Lookup a Language object for language code `code` based on these strategies:
- Special case rules for Hebrew and Chinese Hans/Hant scripts
- Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a
language with the same `name` in the internal... | Lookup a Language object for language code `code` based on these strategies:
- Special case rules for Hebrew and Chinese Hans/Hant scripts
- Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a
language with the same `name` in the internal representaion
Returns `None` if no m... | Below is the the instruction that describes the task:
### Input:
Lookup a Language object for language code `code` based on these strategies:
- Special case rules for Hebrew and Chinese Hans/Hant scripts
- Using `alpha_2` lookup in `pycountry.languages` followed by lookup for a
language with the... |
def get_package_id(self, name):
"""
Retrieve the smart package id given is English name
@param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large".
@return: The package id that depends on the Data center and the size choosen.
"""
j... | Retrieve the smart package id given is English name
@param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large".
@return: The package id that depends on the Data center and the size choosen. | Below is the the instruction that describes the task:
### Input:
Retrieve the smart package id given is English name
@param (str) name: the Aruba Smart package size name, ie: "small", "medium", "large", "extra large".
@return: The package id that depends on the Data center and the size choosen.
### ... |
def _consolidate_auth(ssh_password=None,
ssh_pkey=None,
ssh_pkey_password=None,
allow_agent=True,
host_pkey_directories=None,
logger=None):
"""
Get sure authentication inform... | Get sure authentication information is in place.
``ssh_pkey`` may be of classes:
- ``str`` - in this case it represents a private key file; public
key will be obtained from it
- ``paramiko.Pkey`` - it will be transparently added to loaded keys | Below is the the instruction that describes the task:
### Input:
Get sure authentication information is in place.
``ssh_pkey`` may be of classes:
- ``str`` - in this case it represents a private key file; public
key will be obtained from it
- ``paramiko.Pkey`` - it will b... |
def _clear(self, node, left, right):
"""propagates the lazy updates for this node to the subtrees.
as a result the maxval, minval, sumval values for the node
are up to date.
"""
if self.lazyset[node] is not None: # first do the pending set
val = self.lazyset[node]
... | propagates the lazy updates for this node to the subtrees.
as a result the maxval, minval, sumval values for the node
are up to date. | Below is the the instruction that describes the task:
### Input:
propagates the lazy updates for this node to the subtrees.
as a result the maxval, minval, sumval values for the node
are up to date.
### Response:
def _clear(self, node, left, right):
"""propagates the lazy updates for this n... |
def c14n_uri(sqluri):
"""
Ask the backend to c14n the uri. See register_uri_backend() for
details.
If no backend is found for this uri method, a NotImplementedError
will be raised.
"""
uri_c14n_method = _get_methods_by_uri(sqluri)[METHOD_C14N_URI]
if not uri_c14n_method:
return ... | Ask the backend to c14n the uri. See register_uri_backend() for
details.
If no backend is found for this uri method, a NotImplementedError
will be raised. | Below is the the instruction that describes the task:
### Input:
Ask the backend to c14n the uri. See register_uri_backend() for
details.
If no backend is found for this uri method, a NotImplementedError
will be raised.
### Response:
def c14n_uri(sqluri):
"""
Ask the backend to c14n the uri. S... |
def age_to_date(age):
"""
преобразует возраст в год рождения. (Для фильтрации по дате рождения)
"""
today = datetime.date.today()
date = datetime.date(today.year - age - 1, today.month, today.day) + datetime.timedelta(days=1)
return date | преобразует возраст в год рождения. (Для фильтрации по дате рождения) | Below is the the instruction that describes the task:
### Input:
преобразует возраст в год рождения. (Для фильтрации по дате рождения)
### Response:
def age_to_date(age):
"""
преобразует возраст в год рождения. (Для фильтрации по дате рождения)
"""
today = datetime.date.today()
date = datet... |
def _store_entry(self, entry):
"""
Stores a new log entry and notifies listeners
:param entry: A LogEntry object
"""
# Get the logger and log the message
self.__logs.append(entry)
# Notify listeners
for listener in self.__listeners.copy():
tr... | Stores a new log entry and notifies listeners
:param entry: A LogEntry object | Below is the the instruction that describes the task:
### Input:
Stores a new log entry and notifies listeners
:param entry: A LogEntry object
### Response:
def _store_entry(self, entry):
"""
Stores a new log entry and notifies listeners
:param entry: A LogEntry object
"""... |
def phantomjs_fetch(self, url, task):
'''Fetch with phantomjs proxy'''
start_time = time.time()
self.on_fetch('phantomjs', task)
handle_error = lambda x: self.handle_error('phantomjs', url, task, start_time, x)
# check phantomjs proxy is enabled
if not self.phantomjs_pro... | Fetch with phantomjs proxy | Below is the the instruction that describes the task:
### Input:
Fetch with phantomjs proxy
### Response:
def phantomjs_fetch(self, url, task):
'''Fetch with phantomjs proxy'''
start_time = time.time()
self.on_fetch('phantomjs', task)
handle_error = lambda x: self.handle_error('phan... |
def record(self):
# type: () -> bytes
'''
Generate a string representing the Rock Ridge Rock Ridge record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
'''
if not self._initialized:
raise pycdlibexception.PyCdl... | Generate a string representing the Rock Ridge Rock Ridge record.
Parameters:
None.
Returns:
String containing the Rock Ridge record. | Below is the the instruction that describes the task:
### Input:
Generate a string representing the Rock Ridge Rock Ridge record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
### Response:
def record(self):
# type: () -> bytes
'''
Ge... |
def list(ctx, show_hidden, oath_type, period):
"""
List all credentials.
List all credentials stored on your YubiKey.
"""
ensure_validated(ctx)
controller = ctx.obj['controller']
creds = [cred
for cred in controller.list()
if show_hidden or not cred.is_hidden
... | List all credentials.
List all credentials stored on your YubiKey. | Below is the the instruction that describes the task:
### Input:
List all credentials.
List all credentials stored on your YubiKey.
### Response:
def list(ctx, show_hidden, oath_type, period):
"""
List all credentials.
List all credentials stored on your YubiKey.
"""
ensure_validated(ctx)... |
def _encode(self, obj, context):
"""Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged.
"""
func = getattr(obj, 'to_construct', None)
if callable(func):
return func(c... | Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged. | Below is the the instruction that describes the task:
### Input:
Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged.
### Response:
def _encode(self, obj, context):
"""Encodes a class to a lower-lev... |
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
"""Returns a generator which creates the next value in the range on demand"""
date_interval = Interval(lower=lower, lower_value=start, upper_value=end, upper=upper)
current = start if start in date_interval else ... | Returns a generator which creates the next value in the range on demand | Below is the the instruction that describes the task:
### Input:
Returns a generator which creates the next value in the range on demand
### Response:
def daterange(start, end, delta=timedelta(days=1), lower=Interval.CLOSED, upper=Interval.OPEN):
"""Returns a generator which creates the next value in the range... |
def open(self, filename, mode='r'):
"""Returns file object from given filename."""
self._raise_if_none()
fn = path_join(self.path, filename)
return open(fn, mode) | Returns file object from given filename. | Below is the the instruction that describes the task:
### Input:
Returns file object from given filename.
### Response:
def open(self, filename, mode='r'):
"""Returns file object from given filename."""
self._raise_if_none()
fn = path_join(self.path, filename)
return open(fn, mode... |
def commit(self, template_id, ext_json, version, description):
"""
为授权的小程序账号上传小程序代码
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param template_id: 代码库中的代码模板 ID
:param ext_json: 第三方自定义的配置
:param version: 代码版本号,开发者... | 为授权的小程序账号上传小程序代码
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param template_id: 代码库中的代码模板 ID
:param ext_json: 第三方自定义的配置
:param version: 代码版本号,开发者可自定义
:param description: 代码描述,开发者可自定义 | Below is the the instruction that describes the task:
### Input:
为授权的小程序账号上传小程序代码
详情请参考
https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&id=open1489140610_Uavc4
:param template_id: 代码库中的代码模板 ID
:param ext_json: 第三方自定义的配置
:param version: 代码版本号,开发者可自定义
:... |
def file_create(filename, settings):
"""
Creates a file.
Args:
filename (str): Filename.
settings (dict): Must be {"content": actual_content}
"""
if len(settings) != 1:
raise ValueError("Settings must only contain one item with key "
... | Creates a file.
Args:
filename (str): Filename.
settings (dict): Must be {"content": actual_content} | Below is the the instruction that describes the task:
### Input:
Creates a file.
Args:
filename (str): Filename.
settings (dict): Must be {"content": actual_content}
### Response:
def file_create(filename, settings):
"""
Creates a file.
Args:
fi... |
def create_virtualenv(venv=VENV):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Creating venv...',
run_command(['virtualenv', '-q', '--no-site-packages', VENV])
print 'done.'
print 'Installing pip in virtualenv...',
if not run_command([W... | Creates the virtual environment and installs PIP only into the
virtual environment | Below is the the instruction that describes the task:
### Input:
Creates the virtual environment and installs PIP only into the
virtual environment
### Response:
def create_virtualenv(venv=VENV):
"""Creates the virtual environment and installs PIP only into the
virtual environment
"""
print 'Cr... |
def diff(name_a, name_b=None, **kwargs):
'''
Display the difference between a snapshot of a given filesystem and
another snapshot of that filesystem from a later time or the current
contents of the filesystem.
name_a : string
name of snapshot
name_b : string
(optional) name of s... | Display the difference between a snapshot of a given filesystem and
another snapshot of that filesystem from a later time or the current
contents of the filesystem.
name_a : string
name of snapshot
name_b : string
(optional) name of snapshot or filesystem
show_changetime : boolean
... | Below is the the instruction that describes the task:
### Input:
Display the difference between a snapshot of a given filesystem and
another snapshot of that filesystem from a later time or the current
contents of the filesystem.
name_a : string
name of snapshot
name_b : string
(opt... |
def _graphql_query_waittime(self, query_hash: str, current_time: float, untracked_queries: bool = False) -> int:
"""Calculate time needed to wait before GraphQL query can be executed."""
sliding_window = 660
if query_hash not in self._graphql_query_timestamps:
self._graphql_query_tim... | Calculate time needed to wait before GraphQL query can be executed. | Below is the the instruction that describes the task:
### Input:
Calculate time needed to wait before GraphQL query can be executed.
### Response:
def _graphql_query_waittime(self, query_hash: str, current_time: float, untracked_queries: bool = False) -> int:
"""Calculate time needed to wait before GraphQL... |
def fmsin(N, fnormin=0.05, fnormax=0.45, period=None, t0=None, fnorm0=0.25, pm1=1):
"""
Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNOR... | Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNORM0, and the ambiguity between
increasing or decreasing frequency is solved by PM1.
N ... | Below is the the instruction that describes the task:
### Input:
Signal with sinusoidal frequency modulation.
generates a frequency modulation with a sinusoidal frequency.
This sinusoidal modulation is designed such that the instantaneous
frequency at time T0 is equal to FNORM0, and the ambiguity betwe... |
def visit_FunctionBody(self, node):
"""Visitor for `FunctionBody` AST node."""
for child in node.children:
return_value = self.visit(child)
if isinstance(child, ReturnStatement):
return return_value
if isinstance(child, (IfStatement, WhileStatement))... | Visitor for `FunctionBody` AST node. | Below is the the instruction that describes the task:
### Input:
Visitor for `FunctionBody` AST node.
### Response:
def visit_FunctionBody(self, node):
"""Visitor for `FunctionBody` AST node."""
for child in node.children:
return_value = self.visit(child)
if isinstance(chil... |
def putmask(self, value, blc=(), trc=(), inc=()):
"""Put image mask.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to put a data slice. Not all axes
need to be specified. Missing values default to begin, end, and 1.
The da... | Put image mask.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to put a data slice. Not all axes
need to be specified. Missing values default to begin, end, and 1.
The data should be a numpy array. Its dimensionality must be the sa... | Below is the the instruction that describes the task:
### Input:
Put image mask.
Using the arguments blc (bottom left corner), trc (top right corner),
and inc (stride) it is possible to put a data slice. Not all axes
need to be specified. Missing values default to begin, end, and 1.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.