code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
"""
code = serialise_dataframe_code(dataframe_name, self.kind)
output = self._execute(code)... | Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read. | Below is the the instruction that describes the task:
### Input:
Evaluate and retrieve a Spark dataframe in the managed session.
:param dataframe_name: The name of the Spark dataframe to read.
### Response:
def read(self, dataframe_name: str) -> pandas.DataFrame:
"""Evaluate and retrieve a Spark d... |
def UpdateColums(self, cursor, field, FieldType, model, columns, UNCHANGED):
'''Updates the columns. Dont call directly
'''
table = model.__name__.lower()
if field not in columns:
n = UNCHANGED.pop()
new_sql = f"ALTER TABLE {table} ADD COLUMN {field} {FieldType} A... | Updates the columns. Dont call directly | Below is the the instruction that describes the task:
### Input:
Updates the columns. Dont call directly
### Response:
def UpdateColums(self, cursor, field, FieldType, model, columns, UNCHANGED):
'''Updates the columns. Dont call directly
'''
table = model.__name__.lower()
if field ... |
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
conn = _get_conn(ret=None)
cur = conn.cursor()
sql = '''SELECT id, full_ret FROM salt_returns WHERE jid = ?'''
cur.execute(sql, (jid,))
data = cur.fetchall()
ret = {}
if data:
... | Return the information returned when the specified job id was executed | Below is the the instruction that describes the task:
### Input:
Return the information returned when the specified job id was executed
### Response:
def get_jid(jid):
'''
Return the information returned when the specified job id was executed
'''
conn = _get_conn(ret=None)
cur = conn.cursor()
... |
def _wrap_paginated_response(cls, request, response, controls, data,
head=None):
"""Builds the metadata for a pagingated response and wraps everying in
a JSON encoded web.Response
"""
paging_response = response['paging']
if head is None:
... | Builds the metadata for a pagingated response and wraps everying in
a JSON encoded web.Response | Below is the the instruction that describes the task:
### Input:
Builds the metadata for a pagingated response and wraps everying in
a JSON encoded web.Response
### Response:
def _wrap_paginated_response(cls, request, response, controls, data,
head=None):
"""Builds ... |
def login(request):
"""
Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password
"""
if request.method == 'GET':
return render(request, 'user_login... | Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password | Below is the the instruction that describes the task:
### Input:
Log in
GET parameters:
html
turn on the HTML version of the API
POST parameters (JSON):
username:
user's name
password:
user's password
### Response:
def login(request):
"""
... |
def _make_key(func,
args,
kwds,
typed,
kwd_mark=(object(), ),
fasttypes={int, str, frozenset, type(None)},
sorted=sorted,
tuple=tuple,
type=type,
len=len):
'Make a cache key from optionally ... | Make a cache key from optionally typed positional and keyword arguments | Below is the the instruction that describes the task:
### Input:
Make a cache key from optionally typed positional and keyword arguments
### Response:
def _make_key(func,
args,
kwds,
typed,
kwd_mark=(object(), ),
fasttypes={int, str, frozenset, ... |
def get_runtime(self):
""":class:`timedelta` with the run-time, None if the Task is not running"""
if self.start is None: return None
if self.end is None:
delta = datetime.datetime.now() - self.start
else:
delta = self.end - self.start
return MyTimedelta... | :class:`timedelta` with the run-time, None if the Task is not running | Below is the the instruction that describes the task:
### Input:
:class:`timedelta` with the run-time, None if the Task is not running
### Response:
def get_runtime(self):
""":class:`timedelta` with the run-time, None if the Task is not running"""
if self.start is None: return None
if self... |
def time(self, intervals=1, *args, _show_progress=True, _print=True,
_collect_garbage=True, _quiet=True, **kwargs):
""" Measures the execution time of :prop:_callable for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
... | Measures the execution time of :prop:_callable for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
@*args: arguments to pass to the callable being timed
@**kwargs: arguments to pass to the callable being timed
... | Below is the the instruction that describes the task:
### Input:
Measures the execution time of :prop:_callable for @intervals
@intervals: #int number of intervals to measure the execution time
of the function for
@*args: arguments to pass to the callable being timed
... |
def is_enabled(name):
'''
List a Job only if its enabled
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' schedule.is_enabled name=job_name
'''
current_schedule = __salt__['schedule.list'](show_all=False, return_yaml=False)
if name in current_schedule:
... | List a Job only if its enabled
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' schedule.is_enabled name=job_name | Below is the the instruction that describes the task:
### Input:
List a Job only if its enabled
.. versionadded:: 2015.5.3
CLI Example:
.. code-block:: bash
salt '*' schedule.is_enabled name=job_name
### Response:
def is_enabled(name):
'''
List a Job only if its enabled
.. vers... |
def free_parameters(self):
"""
Returns a dictionary of free parameters for this function
:return: dictionary of free parameters
"""
free_parameters = collections.OrderedDict([(k,v) for k, v in self.parameters.iteritems() if v.free])
return free_parameters | Returns a dictionary of free parameters for this function
:return: dictionary of free parameters | Below is the the instruction that describes the task:
### Input:
Returns a dictionary of free parameters for this function
:return: dictionary of free parameters
### Response:
def free_parameters(self):
"""
Returns a dictionary of free parameters for this function
:return: diction... |
def address_offset(self):
"""
Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined
... | Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
fully defined | Below is the the instruction that describes the task:
### Input:
Byte address offset of this node relative to it's parent
If this node is an array, it's index must be known
Raises
------
ValueError
If this property is referenced on a node whose array index is not
... |
def copy_action_callback(self, *event):
"""Add a copy of all selected row dict value pairs to the clipboard"""
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
_, dict_paths = self.get_view_selection()
selected_data_list = []
f... | Add a copy of all selected row dict value pairs to the clipboard | Below is the the instruction that describes the task:
### Input:
Add a copy of all selected row dict value pairs to the clipboard
### Response:
def copy_action_callback(self, *event):
"""Add a copy of all selected row dict value pairs to the clipboard"""
if react_to_event(self.view, self.tree_view,... |
def train(nr_iter, examples):
'''Return an averaged perceptron model trained on ``examples`` for
``nr_iter`` iterations.
'''
model = AveragedPerceptron()
for i in range(nr_iter):
random.shuffle(examples)
for features, class_ in examples:
scores = model.predict(features)
... | Return an averaged perceptron model trained on ``examples`` for
``nr_iter`` iterations. | Below is the the instruction that describes the task:
### Input:
Return an averaged perceptron model trained on ``examples`` for
``nr_iter`` iterations.
### Response:
def train(nr_iter, examples):
'''Return an averaged perceptron model trained on ``examples`` for
``nr_iter`` iterations.
'''
mod... |
def checkplot_pickle_update(
currentcp,
updatedcp,
outfile=None,
outgzip=False,
pickleprotocol=None,
verbose=True
):
'''This updates the current checkplotdict with updated values provided.
Parameters
----------
currentcp : dict or str
This is ei... | This updates the current checkplotdict with updated values provided.
Parameters
----------
currentcp : dict or str
This is either a checkplotdict produced by `checkplot_pickle` above or a
checkplot pickle file produced by the same function. This checkplot will
be updated from the ... | Below is the the instruction that describes the task:
### Input:
This updates the current checkplotdict with updated values provided.
Parameters
----------
currentcp : dict or str
This is either a checkplotdict produced by `checkplot_pickle` above or a
checkplot pickle file produced b... |
def is_game_over(self):
'''
Checks if the game is over due to checkmate, stalemate or
fourfold repetition.
'''
# Stalemate or checkmate.
try:
next(self.generate_legal_moves().__iter__())
except StopIteration:
return True
# Fourfol... | Checks if the game is over due to checkmate, stalemate or
fourfold repetition. | Below is the the instruction that describes the task:
### Input:
Checks if the game is over due to checkmate, stalemate or
fourfold repetition.
### Response:
def is_game_over(self):
'''
Checks if the game is over due to checkmate, stalemate or
fourfold repetition.
'''
... |
def _sign_url(self, base_url=None, params=None, client_secret=None):
""" Sign a request URL with a Crypto Key.
Usage:
from urlsigner import sign_url
signed_url = sign_url(base_url=my_url,
params=url_params,
client_secret=CLIENT_... | Sign a request URL with a Crypto Key.
Usage:
from urlsigner import sign_url
signed_url = sign_url(base_url=my_url,
params=url_params,
client_secret=CLIENT_SECRET)
Args:
base_url - The trunk of the URL to sign. E.g. https... | Below is the the instruction that describes the task:
### Input:
Sign a request URL with a Crypto Key.
Usage:
from urlsigner import sign_url
signed_url = sign_url(base_url=my_url,
params=url_params,
client_secret=CLIENT_SECRET)
... |
def get_user_uk(cookie, tokens):
'''获取用户的uk'''
url = 'http://yun.baidu.com'
req = net.urlopen(url, headers={'Cookie': cookie.header_output()})
if req:
content = req.data.decode()
match = re.findall('/share/home\?uk=(\d+)" target=', content)
if len(match) == 1:
return ... | 获取用户的uk | Below is the the instruction that describes the task:
### Input:
获取用户的uk
### Response:
def get_user_uk(cookie, tokens):
'''获取用户的uk'''
url = 'http://yun.baidu.com'
req = net.urlopen(url, headers={'Cookie': cookie.header_output()})
if req:
content = req.data.decode()
match = re.findal... |
def align(time, time2, magnitude, magnitude2, error, error2):
"""Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2
"""
error = np.zeros(time.shape) if error is None else err... | Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2 | Below is the the instruction that describes the task:
### Input:
Synchronizes the light-curves in the two different bands.
Returns
-------
aligned_time
aligned_magnitude
aligned_magnitude2
aligned_error
aligned_error2
### Response:
def align(time, time2, magnitude, magnitude2, error, ... |
def _build(self, input_, prev_state):
"""Connects the VanillaRNN module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as input_ and state must have the same final
dimension, in order for the existing variables to be the correct size for
... | Connects the VanillaRNN module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as input_ and state must have the same final
dimension, in order for the existing variables to be the correct size for
their corresponding multiplications. The b... | Below is the the instruction that describes the task:
### Input:
Connects the VanillaRNN module into the graph.
If this is not the first time the module has been connected to the graph,
the Tensors provided as input_ and state must have the same final
dimension, in order for the existing variables to b... |
def generate_dict_schema(size, valid):
""" Generate a schema dict of size `size` using library `lib`.
In addition, it returns samples generator
:param size: Schema size
:type size: int
:param samples: The number of samples to generate
:type samples: int
:param valid: Generate valid samples... | Generate a schema dict of size `size` using library `lib`.
In addition, it returns samples generator
:param size: Schema size
:type size: int
:param samples: The number of samples to generate
:type samples: int
:param valid: Generate valid samples?
:type valid: bool
:returns | Below is the the instruction that describes the task:
### Input:
Generate a schema dict of size `size` using library `lib`.
In addition, it returns samples generator
:param size: Schema size
:type size: int
:param samples: The number of samples to generate
:type samples: int
:param valid: ... |
def create_free_shipping_promotion(cls, free_shipping_promotion, **kwargs):
"""Create FreeShippingPromotion
Create a new FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.c... | Create FreeShippingPromotion
Create a new FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shipping_promotion(free_shipping_promotion, async=True)
>>> result =... | Below is the the instruction that describes the task:
### Input:
Create FreeShippingPromotion
Create a new FreeShippingPromotion
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_free_shippin... |
def process_event(self, event_name: str, data: dict) -> None:
"""
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
... | Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
None | Below is the the instruction that describes the task:
### Input:
Process event after epoch
Args:
event_name: whether event is send after epoch or batch.
Set of values: ``"after_epoch", "after_batch"``
data: event data (dictionary)
Returns:
Non... |
def cmd_land(self, args):
'''auto land commands'''
if len(args) < 1:
self.master.mav.command_long_send(self.settings.target_system,
0,
mavutil.mavlink.MAV_CMD_DO_LAND_START,
... | auto land commands | Below is the the instruction that describes the task:
### Input:
auto land commands
### Response:
def cmd_land(self, args):
'''auto land commands'''
if len(args) < 1:
self.master.mav.command_long_send(self.settings.target_system,
0,
... |
def get_type_name(self):
"""
Returns the type name of the PKCS7 structure
:return: A string with the typename
"""
nid = _lib.OBJ_obj2nid(self._pkcs7.type)
string_type = _lib.OBJ_nid2sn(nid)
return _ffi.string(string_type) | Returns the type name of the PKCS7 structure
:return: A string with the typename | Below is the the instruction that describes the task:
### Input:
Returns the type name of the PKCS7 structure
:return: A string with the typename
### Response:
def get_type_name(self):
"""
Returns the type name of the PKCS7 structure
:return: A string with the typename
"""... |
def apply_instance_data(designspace, include_filenames=None, Font=defcon.Font):
"""Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
designspace: DesignSpaceDocument object or path (str or PathLike) to
... | Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
designspace: DesignSpaceDocument object or path (str or PathLike) to
a designspace file.
include_filenames: optional set of instance filenames... | Below is the the instruction that describes the task:
### Input:
Open UFO instances referenced by designspace, apply Glyphs instance
data if present, re-save UFOs and return updated UFO Font objects.
Args:
designspace: DesignSpaceDocument object or path (str or PathLike) to
a designspac... |
def conference(self, id, **options):
"""
This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously.
This is a voice channel only feature.
Argument: "id" is a String
Argument: **options ... | This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously.
This is a voice channel only feature.
Argument: "id" is a String
Argument: **options is a set of optional keyword arguments.
See https... | Below is the the instruction that describes the task:
### Input:
This object allows multiple lines in separate sessions to be conferenced together so that the parties on each line can talk to each other simultaneously.
This is a voice channel only feature.
Argument: "id" is a String
Argument... |
def characteristics_resolved(self):
"""
Called when all service's characteristics got resolved.
"""
self._disconnect_characteristic_signals()
characteristics_regex = re.compile(self._path + '/char[0-9abcdef]{4}$')
managed_characteristics = [
char for char in ... | Called when all service's characteristics got resolved. | Below is the the instruction that describes the task:
### Input:
Called when all service's characteristics got resolved.
### Response:
def characteristics_resolved(self):
"""
Called when all service's characteristics got resolved.
"""
self._disconnect_characteristic_signals()
... |
def update(self, table, columns, values):
"""Update one or more existing table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
... | Update one or more existing table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list of lists
:param values: Values to be modified. | Below is the the instruction that describes the task:
### Input:
Update one or more existing table rows.
:type table: str
:param table: Name of the table to be modified.
:type columns: list of str
:param columns: Name of the table columns to be modified.
:type values: list... |
def nvmlDeviceGetPowerUsage(handle):
r"""
/**
* Retrieves power usage for this GPU in milliwatts and its associated circuitry (e.g. memory)
*
* For Fermi &tm; or newer fully supported devices.
*
* On Fermi and Kepler GPUs the reading is accurate to within +/- 5% of current power draw.
... | r"""
/**
* Retrieves power usage for this GPU in milliwatts and its associated circuitry (e.g. memory)
*
* For Fermi &tm; or newer fully supported devices.
*
* On Fermi and Kepler GPUs the reading is accurate to within +/- 5% of current power draw.
*
* It is only available if powe... | Below is the the instruction that describes the task:
### Input:
r"""
/**
* Retrieves power usage for this GPU in milliwatts and its associated circuitry (e.g. memory)
*
* For Fermi &tm; or newer fully supported devices.
*
* On Fermi and Kepler GPUs the reading is accurate to within +/-... |
def meta_changed_notify_after(self, state_machine_m, _, info):
"""Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to t... | Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this editor
:param str _: Always "state_meta_signal"
:param... | Below is the the instruction that describes the task:
### Input:
Handle notification about the change of a state's meta data
The meta data of the affected state(s) are read and the view updated accordingly.
:param StateMachineModel state_machine_m: Always the state machine model belonging to this e... |
def destroy(name=None, call=None):
'''
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -d xenvm01
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
... | Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -d xenvm01 | Below is the the instruction that describes the task:
### Input:
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -d xenvm01
### Response:
def destroy(name=None, call=None):
'''
Destroy Xen VM or template instance
.. code-block:: bash
salt-cloud -d xenvm01
... |
def is_reference_target(resource, rtype, label):
""" Return true if the resource has this rtype with this label """
prop = resource.props.references.get(rtype, False)
if prop:
return label in prop | Return true if the resource has this rtype with this label | Below is the the instruction that describes the task:
### Input:
Return true if the resource has this rtype with this label
### Response:
def is_reference_target(resource, rtype, label):
""" Return true if the resource has this rtype with this label """
prop = resource.props.references.get(rtype, False)
... |
def index_row(self, dataframe):
"""
Indexes the row based on the request parameters.
"""
return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame().T | Indexes the row based on the request parameters. | Below is the the instruction that describes the task:
### Input:
Indexes the row based on the request parameters.
### Response:
def index_row(self, dataframe):
"""
Indexes the row based on the request parameters.
"""
return dataframe.loc[self.kwargs[self.lookup_url_kwarg]].to_frame(... |
def _download_repo_metadata(self, args):
'''
Connect to all repos and download metadata
'''
cache = salt.cache.Cache(self.opts, self.opts['spm_cache_dir'])
def _update_metadata(repo, repo_info):
dl_path = '{0}/SPM-METADATA'.format(repo_info['url'])
if dl_... | Connect to all repos and download metadata | Below is the the instruction that describes the task:
### Input:
Connect to all repos and download metadata
### Response:
def _download_repo_metadata(self, args):
'''
Connect to all repos and download metadata
'''
cache = salt.cache.Cache(self.opts, self.opts['spm_cache_dir'])
... |
def cp_als(X, rank, random_state=None, init='randn', **options):
"""Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be compute... | Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
random_state : integer, ``RandomState``, or ``None``, optional (... | Below is the the instruction that describes the task:
### Input:
Fits CP Decomposition using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of components to be computed.
... |
def append_dynamic(self, t, dynamic, canvas=0, color='blue'):
"""!
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dynamic (list): V... | !
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dynamic (list): Value points of dynamic that are considered on an Y axis.
@param[i... | Below is the the instruction that describes the task:
### Input:
!
@brief Append single dynamic to specified canvas (by default to the first with index '0').
@param[in] t (list): Time points that corresponds to dynamic values and considered on a X axis.
@param[in] dynamic (list): Value ... |
def diagnostic_send(self, diagFl1, diagFl2, diagFl3, diagSh1, diagSh2, diagSh3, force_mavlink1=False):
'''
Configurable diagnostic messages.
diagFl1 : Diagnostic float 1 (float)
diagFl2 : Diagnostic float 2 (float)
... | Configurable diagnostic messages.
diagFl1 : Diagnostic float 1 (float)
diagFl2 : Diagnostic float 2 (float)
diagFl3 : Diagnostic float 3 (float)
diagSh1 : Diagnostic short 1 (int16_t)... | Below is the the instruction that describes the task:
### Input:
Configurable diagnostic messages.
diagFl1 : Diagnostic float 1 (float)
diagFl2 : Diagnostic float 2 (float)
diagFl3 : Diagnostic float 3 (float)
... |
def getpreferredencoding():
"""Return preferred encoding for text I/O."""
encoding = locale.getpreferredencoding(False)
if sys.platform == 'darwin' and encoding.startswith('mac-'):
# Upgrade ancient MacOS encodings in Python < 2.7
encoding = 'utf-8'
return encoding | Return preferred encoding for text I/O. | Below is the the instruction that describes the task:
### Input:
Return preferred encoding for text I/O.
### Response:
def getpreferredencoding():
"""Return preferred encoding for text I/O."""
encoding = locale.getpreferredencoding(False)
if sys.platform == 'darwin' and encoding.startswith('mac-'):
... |
def _is_pid_running_on_unix(pid):
"""
Check if PID is running for Unix systems.
"""
try:
os.kill(pid, 0)
except OSError as err:
# if error is ESRCH, it means the process doesn't exist
return not err.errno == os.errno.ESRCH
return True | Check if PID is running for Unix systems. | Below is the the instruction that describes the task:
### Input:
Check if PID is running for Unix systems.
### Response:
def _is_pid_running_on_unix(pid):
"""
Check if PID is running for Unix systems.
"""
try:
os.kill(pid, 0)
except OSError as err:
# if error is ESRCH, it means ... |
def token(self):
"""
Returns authorization token provided by Cocaine.
The real meaning of the token is determined by its type. For example OAUTH2 token will
have "bearer" type.
:return: A tuple of token type and body.
"""
if self._token is None:
toke... | Returns authorization token provided by Cocaine.
The real meaning of the token is determined by its type. For example OAUTH2 token will
have "bearer" type.
:return: A tuple of token type and body. | Below is the the instruction that describes the task:
### Input:
Returns authorization token provided by Cocaine.
The real meaning of the token is determined by its type. For example OAUTH2 token will
have "bearer" type.
:return: A tuple of token type and body.
### Response:
def token(sel... |
def _mitogen_reset(self, mode):
"""
Forget everything we know about the connected context. This function
cannot be called _reset() since that name is used as a public API by
Ansible 2.4 wait_for_connection plug-in.
:param str mode:
Name of ContextService method to us... | Forget everything we know about the connected context. This function
cannot be called _reset() since that name is used as a public API by
Ansible 2.4 wait_for_connection plug-in.
:param str mode:
Name of ContextService method to use to discard the context, either
'put' o... | Below is the the instruction that describes the task:
### Input:
Forget everything we know about the connected context. This function
cannot be called _reset() since that name is used as a public API by
Ansible 2.4 wait_for_connection plug-in.
:param str mode:
Name of ContextSer... |
def createNewOoid(timestamp=None, depth=None):
"""Create a new Ooid for a given time, to be stored at a given depth
timestamp: the year-month-day is encoded in the ooid. If none, use current day
depth: the expected storage depth is encoded in the ooid. If non, use the defaultDepth
returns a new opaque id string... | Create a new Ooid for a given time, to be stored at a given depth
timestamp: the year-month-day is encoded in the ooid. If none, use current day
depth: the expected storage depth is encoded in the ooid. If non, use the defaultDepth
returns a new opaque id string holding 24 random hex digits and encoded date and d... | Below is the the instruction that describes the task:
### Input:
Create a new Ooid for a given time, to be stored at a given depth
timestamp: the year-month-day is encoded in the ooid. If none, use current day
depth: the expected storage depth is encoded in the ooid. If non, use the defaultDepth
returns a new... |
def synonyms(self):
"""Return a dict of term synonyms"""
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
syns[k.lower()] = v['synonym']
if not '.' in k:
syns[ROOT_TERM + '.' + k.l... | Return a dict of term synonyms | Below is the the instruction that describes the task:
### Input:
Return a dict of term synonyms
### Response:
def synonyms(self):
"""Return a dict of term synonyms"""
syns = {}
for k, v in self._declared_terms.items():
k = k.strip()
if v.get('synonym'):
... |
def reassign(self, user_ids, requester):
"""Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign
"""
path = '{0}'.format(self.collection.name)
assignments = [... | Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign | Below is the the instruction that describes the task:
### Input:
Reassign this incident to a user or list of users
:param user_ids: A non-empty list of user ids
:param requester: The email address of individual requesting reassign
### Response:
def reassign(self, user_ids, requester):
"""R... |
def modify_signature(self, signature):
""" Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
content/con... | Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
content/contentype/name, the id should be present and
... | Below is the the instruction that describes the task:
### Input:
Modify an existing signature
Can modify the content, contenttype and name. An unset attribute will
not delete the attribute but leave it untouched.
:param: signature a zobject.Signature object, with modified
... |
def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
# The chunk is a Markdown *unless* it is commented Python code.
source = '\n'.join(line[2:] for line in lines
... | Return whether a chunk contains Markdown contents. | Below is the the instruction that describes the task:
### Input:
Return whether a chunk contains Markdown contents.
### Response:
def _is_chunk_markdown(source):
"""Return whether a chunk contains Markdown contents."""
lines = source.splitlines()
if all(line.startswith('# ') for line in lines):
... |
def start_output (self):
"""Write start of checking info as DOT comment."""
super(DOTLogger, self).start_output()
if self.has_part("intro"):
self.write_intro()
self.writeln()
self.writeln(u"digraph G {")
self.writeln(u" graph [")
self.writeln(u" ... | Write start of checking info as DOT comment. | Below is the the instruction that describes the task:
### Input:
Write start of checking info as DOT comment.
### Response:
def start_output (self):
"""Write start of checking info as DOT comment."""
super(DOTLogger, self).start_output()
if self.has_part("intro"):
self.write_int... |
def arp(interface='', ipaddr='', macaddr='', **kwargs): # pylint: disable=unused-argument
'''
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:r... | NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the ARP table
CLI Example:
.. code-block:: bash
salt '*... | Below is the the instruction that describes the task:
### Input:
NAPALM returns a list of dictionaries with details of the ARP entries.
:param interface: interface name to filter on
:param ipaddr: IP address to filter on
:param macaddr: MAC address to filter on
:return: List of the entries in the A... |
def filter_single_grain(self):
'''
This subroutine is to filter out single grains. It is kind of
useless if you have tons of data still in the list. To work on
there, you have other filters (filter_desc and filter_data)
available! This filter gives an index to every grain, plots... | This subroutine is to filter out single grains. It is kind of
useless if you have tons of data still in the list. To work on
there, you have other filters (filter_desc and filter_data)
available! This filter gives an index to every grain, plots
the most important information, and then a... | Below is the the instruction that describes the task:
### Input:
This subroutine is to filter out single grains. It is kind of
useless if you have tons of data still in the list. To work on
there, you have other filters (filter_desc and filter_data)
available! This filter gives an index to ... |
def blastnprep(self):
"""Setup blastn analyses"""
# Populate threads for each gene, genome combination
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
#
# sample[self.analysistype].alleleresults = GenObject()
sa... | Setup blastn analyses | Below is the the instruction that describes the task:
### Input:
Setup blastn analyses
### Response:
def blastnprep(self):
"""Setup blastn analyses"""
# Populate threads for each gene, genome combination
for sample in self.metadata:
if sample.general.bestassemblyfile != 'NA':
... |
def _IsRetryable(error):
"""Returns whether error is likely to be retryable."""
if not isinstance(error, MySQLdb.OperationalError):
return False
if not error.args:
return False
code = error.args[0]
return code in _RETRYABLE_ERRORS | Returns whether error is likely to be retryable. | Below is the the instruction that describes the task:
### Input:
Returns whether error is likely to be retryable.
### Response:
def _IsRetryable(error):
"""Returns whether error is likely to be retryable."""
if not isinstance(error, MySQLdb.OperationalError):
return False
if not error.args:
return Fa... |
def helper_parallel_lines(start0, end0, start1, end1, filename):
"""Image for :func:`.parallel_lines_parameters` docstring."""
if NO_IMAGES:
return
figure = plt.figure()
ax = figure.gca()
points = stack1d(start0, end0, start1, end1)
ax.plot(points[0, :2], points[1, :2], marker="o")
... | Image for :func:`.parallel_lines_parameters` docstring. | Below is the the instruction that describes the task:
### Input:
Image for :func:`.parallel_lines_parameters` docstring.
### Response:
def helper_parallel_lines(start0, end0, start1, end1, filename):
"""Image for :func:`.parallel_lines_parameters` docstring."""
if NO_IMAGES:
return
figure = pl... |
def add_linguistic_type(self, lingtype, constraints=None,
timealignable=True, graphicreferences=False,
extref=None, param_dict=None):
"""Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param str constraints: Const... | Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param str constraints: Constraint name.
:param bool timealignable: Flag for time alignable.
:param bool graphicreferences: Flag for graphic references.
:param str extref: External reference.
:param... | Below is the the instruction that describes the task:
### Input:
Add a linguistic type.
:param str lingtype: Name of the linguistic type.
:param str constraints: Constraint name.
:param bool timealignable: Flag for time alignable.
:param bool graphicreferences: Flag for graphic refe... |
async def _next_event(self):
"""
Gets the next event.
"""
while True:
for event in self._connection.events():
if isinstance(event, Message):
# check if we need to buffer
if event.message_finished:
... | Gets the next event. | Below is the the instruction that describes the task:
### Input:
Gets the next event.
### Response:
async def _next_event(self):
"""
Gets the next event.
"""
while True:
for event in self._connection.events():
if isinstance(event, Message):
... |
def fit_transform(self, Xs=None, ys=None, Xt=None, yt=None):
"""Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt) and transports source samples Xs onto target
ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_fea... | Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt) and transports source samples Xs onto target
ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training input samples.
ys : array-like, ... | Below is the the instruction that describes the task:
### Input:
Build a coupling matrix from source and target sets of samples
(Xs, ys) and (Xt, yt) and transports source samples Xs onto target
ones Xt
Parameters
----------
Xs : array-like, shape (n_source_samples, n_featur... |
def normalize(self):
"""Make sure the probabilities of all values sum to 1.
Returns the normalized distribution.
Raises a ZeroDivisionError if the sum of the values is 0.
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
>>> P = P.normalize()
>>> print '%5.3f %5.3f' % (P.... | Make sure the probabilities of all values sum to 1.
Returns the normalized distribution.
Raises a ZeroDivisionError if the sum of the values is 0.
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
>>> P = P.normalize()
>>> print '%5.3f %5.3f' % (P.prob['H'], P.prob['T'])
... | Below is the the instruction that describes the task:
### Input:
Make sure the probabilities of all values sum to 1.
Returns the normalized distribution.
Raises a ZeroDivisionError if the sum of the values is 0.
>>> P = ProbDist('Flip'); P['H'], P['T'] = 35, 65
>>> P = P.normalize()
... |
def corrArray(self, inputArray):
"""#TODO: docstring
:param inputArray: #TODO: docstring
:returns: #TODO docstring
"""
outputArray = numpy.vstack([numpy.nan_to_num(currSpline(inputArray))
for currSpline in self.splines
... | #TODO: docstring
:param inputArray: #TODO: docstring
:returns: #TODO docstring | Below is the the instruction that describes the task:
### Input:
#TODO: docstring
:param inputArray: #TODO: docstring
:returns: #TODO docstring
### Response:
def corrArray(self, inputArray):
"""#TODO: docstring
:param inputArray: #TODO: docstring
:returns: #TODO docstrin... |
def free_param_names(self):
"""Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function.
"""
p = CombinedBounds(self.k.free_param_names, self.noise_k.free_param_names)
if self.mu is not None:
p = CombinedBounds(p, self.mu.free_param_names... | Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function. | Below is the the instruction that describes the task:
### Input:
Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function.
### Response:
def free_param_names(self):
"""Combined free hyperparameter names for the kernel, noise kernel and (if present) mean function.
... |
def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( sized_iterable ):
yield value
pb.update_and_print( i, sys.stderr ) | Iterate something printing progress bar to stdout | Below is the the instruction that describes the task:
### Input:
Iterate something printing progress bar to stdout
### Response:
def iterprogress( sized_iterable ):
"""
Iterate something printing progress bar to stdout
"""
pb = ProgressBar( 0, len( sized_iterable ) )
for i, value in enumerate( ... |
def getattr(self, path, fh):
"""Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the dire... | Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
all files inside the directory. On Linux, only the subdirectories... | Below is the the instruction that describes the task:
### Input:
Called by FUSE when the attributes for a file or directory are required.
Returns a dictionary with keys identical to the stat C structure of stat(2).
st_atime, st_mtime and st_ctime should be floats. On OSX, st_nlink should count
... |
def init_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application.
:param app: The application.
"""
self.app = app
self._init_extension()
self.app.before_request(self.check_implicit_rules)
if kwargs.get('ensure_author... | Initializes the Flask-Bouncer extension for the specified application.
:param app: The application. | Below is the the instruction that describes the task:
### Input:
Initializes the Flask-Bouncer extension for the specified application.
:param app: The application.
### Response:
def init_app(self, app, **kwargs):
""" Initializes the Flask-Bouncer extension for the specified application.
... |
def get_source_for(self, asm_offset, runtime=True):
""" Solidity source code snippet related to `asm_pos` evm bytecode offset.
If runtime is False, initialization bytecode source map is used
"""
srcmap = self.get_srcmap(runtime)
try:
beg, size, _, _ = srcmap[asm_... | Solidity source code snippet related to `asm_pos` evm bytecode offset.
If runtime is False, initialization bytecode source map is used | Below is the the instruction that describes the task:
### Input:
Solidity source code snippet related to `asm_pos` evm bytecode offset.
If runtime is False, initialization bytecode source map is used
### Response:
def get_source_for(self, asm_offset, runtime=True):
""" Solidity source code snip... |
def get_group_list(user, include_default=True):
'''
Returns a list of all of the system group names of which the user
is a member.
'''
if HAS_GRP is False or HAS_PWD is False:
return []
group_names = None
ugroups = set()
if hasattr(os, 'getgrouplist'):
# Try os.getgroupli... | Returns a list of all of the system group names of which the user
is a member. | Below is the the instruction that describes the task:
### Input:
Returns a list of all of the system group names of which the user
is a member.
### Response:
def get_group_list(user, include_default=True):
'''
Returns a list of all of the system group names of which the user
is a member.
'''
... |
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
bbox = denormalize_bbox(bbox, rows, cols)
x_min, y_min, x_max, y_ma... | Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop. | Below is the the instruction that describes the task:
### Input:
Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
### Response:
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols):
""... |
def find_ports(device):
"""
Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason.
"""
bus_id = device.bus
d... | Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason. | Below is the the instruction that describes the task:
### Input:
Find the port chain a device is plugged on.
This is done by searching sysfs for a device that matches the device
bus/address combination.
Useful when the underlying usb lib does not return device.port_number for
whatever reason.
### ... |
def unregister_checker(self, checker):
"""Unregister a checker instance."""
if checker in self._checkers:
self._checkers.remove(checker) | Unregister a checker instance. | Below is the the instruction that describes the task:
### Input:
Unregister a checker instance.
### Response:
def unregister_checker(self, checker):
"""Unregister a checker instance."""
if checker in self._checkers:
self._checkers.remove(checker) |
def match(self, search, **kwargs):
"""
Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP requ... | Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be ... | Below is the the instruction that describes the task:
### Input:
Searches for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. Only exact matches are returned.
This method makes a synchronous HTTP request by default. To make an
asynchro... |
def calculate_integral(self, T1, T2, method):
r'''Method to calculate the integral of a property with respect to
temperature, using a specified method. Uses SciPy's `quad` function
to perform the integral, with no options.
This method can be overwritten by subclasses who may per... | r'''Method to calculate the integral of a property with respect to
temperature, using a specified method. Uses SciPy's `quad` function
to perform the integral, with no options.
This method can be overwritten by subclasses who may perfer to add
analytical methods for some or all ... | Below is the the instruction that describes the task:
### Input:
r'''Method to calculate the integral of a property with respect to
temperature, using a specified method. Uses SciPy's `quad` function
to perform the integral, with no options.
This method can be overwritten by subclas... |
def masktorgb(mask, color='lightgreen', alpha=1.0):
"""Convert boolean mask to RGB image object for canvas overlay.
Parameters
----------
mask : ndarray
Boolean mask to overlay. 2D image only.
color : str
Color name accepted by Ginga.
alpha : float
Opacity. Unmasked da... | Convert boolean mask to RGB image object for canvas overlay.
Parameters
----------
mask : ndarray
Boolean mask to overlay. 2D image only.
color : str
Color name accepted by Ginga.
alpha : float
Opacity. Unmasked data are always transparent.
Returns
-------
rgb... | Below is the the instruction that describes the task:
### Input:
Convert boolean mask to RGB image object for canvas overlay.
Parameters
----------
mask : ndarray
Boolean mask to overlay. 2D image only.
color : str
Color name accepted by Ginga.
alpha : float
Opacity. U... |
def create(blocks, mode='basic', inplanes=16, divisor=4, num_classes=1000):
""" Vel factory function """
block_dict = {
'basic': BasicBlock,
'bottleneck': Bottleneck
}
def instantiate(**_):
return ResNetV2(block_dict[mode], blocks, inplanes=inplanes, divisor=divisor, num_classes... | Vel factory function | Below is the the instruction that describes the task:
### Input:
Vel factory function
### Response:
def create(blocks, mode='basic', inplanes=16, divisor=4, num_classes=1000):
""" Vel factory function """
block_dict = {
'basic': BasicBlock,
'bottleneck': Bottleneck
}
def instantiat... |
def unicodify(filename):
"""Make sure filename is Unicode.
Because the tarfile module on Python 2 doesn't return Unicode.
"""
if isinstance(filename, bytes):
return filename.decode(locale.getpreferredencoding())
else:
return filename | Make sure filename is Unicode.
Because the tarfile module on Python 2 doesn't return Unicode. | Below is the the instruction that describes the task:
### Input:
Make sure filename is Unicode.
Because the tarfile module on Python 2 doesn't return Unicode.
### Response:
def unicodify(filename):
"""Make sure filename is Unicode.
Because the tarfile module on Python 2 doesn't return Unicode.
""... |
def process_sub(ref, alt_str):
"""Process substitution"""
if len(ref) == len(alt_str):
if len(ref) == 1:
return record.Substitution(record.SNV, alt_str)
else:
return record.Substitution(record.MNV, alt_str)
elif len(ref) > len(alt_str):
return process_sub_grow... | Process substitution | Below is the the instruction that describes the task:
### Input:
Process substitution
### Response:
def process_sub(ref, alt_str):
"""Process substitution"""
if len(ref) == len(alt_str):
if len(ref) == 1:
return record.Substitution(record.SNV, alt_str)
else:
return r... |
def _open(self, mode=None):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
"""
if mode is None:
mode = self.mode
if self.encoding i... | Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode' | Below is the the instruction that describes the task:
### Input:
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
### Response:
def _open(self, mode=None):
"""
Open the... |
def time_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
minutes=0, hours=0, weeks=0):
"""
format of timedelta:
timedelta([days[, seconds[, microseconds[, milliseconds[,
minutes[, hours[, weeks]]]]]]])
:return: UTC time
"""
delta = timede... | format of timedelta:
timedelta([days[, seconds[, microseconds[, milliseconds[,
minutes[, hours[, weeks]]]]]]])
:return: UTC time | Below is the the instruction that describes the task:
### Input:
format of timedelta:
timedelta([days[, seconds[, microseconds[, milliseconds[,
minutes[, hours[, weeks]]]]]]])
:return: UTC time
### Response:
def time_in_a_while(days=0, seconds=0, microseconds=0, milliseconds=0,
... |
def _get_bigquery_service(self):
"""
Connect to the BigQuery service.
Calling ``GoogleCredentials.get_application_default`` requires that
you either be running in the Google Cloud, or have the
``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the path
to a c... | Connect to the BigQuery service.
Calling ``GoogleCredentials.get_application_default`` requires that
you either be running in the Google Cloud, or have the
``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the path
to a credentials JSON file.
:return: authenticated... | Below is the the instruction that describes the task:
### Input:
Connect to the BigQuery service.
Calling ``GoogleCredentials.get_application_default`` requires that
you either be running in the Google Cloud, or have the
``GOOGLE_APPLICATION_CREDENTIALS`` environment variable set to the pat... |
def simulate_diffusion(self, save_pos=False, total_emission=True,
radial=False, rs=None, seed=1, path='./',
wrap_func=wrap_periodic,
chunksize=2**19, chunkslice='times', verbose=True):
"""Simulate Brownian motion trajectories and e... | Simulate Brownian motion trajectories and emission rates.
This method performs the Brownian motion simulation using the current
set of parameters. Before running this method you can check the
disk-space requirements using :method:`print_sizes`.
Results are stored to disk in HDF5 format... | Below is the the instruction that describes the task:
### Input:
Simulate Brownian motion trajectories and emission rates.
This method performs the Brownian motion simulation using the current
set of parameters. Before running this method you can check the
disk-space requirements using :met... |
def version_variants(version):
"""Given an igraph version number, returns a list of possible version
number variants to try when looking for a suitable nightly build of the
C core to download from igraph.org."""
result = [version]
# Add trailing ".0" as needed to ensure that we have at least
#... | Given an igraph version number, returns a list of possible version
number variants to try when looking for a suitable nightly build of the
C core to download from igraph.org. | Below is the the instruction that describes the task:
### Input:
Given an igraph version number, returns a list of possible version
number variants to try when looking for a suitable nightly build of the
C core to download from igraph.org.
### Response:
def version_variants(version):
"""Given an igraph... |
def serialize(value, field):
"""
Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value
"""
assert isinstance(field, forms.Field)
if isinstance(field, forms.ModelMultipleChoiceField):
... | Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value | Below is the the instruction that describes the task:
### Input:
Form values serialization
:param object value: A value to be serialized\
for saving it into the database and later\
loading it into the form as initial value
### Response:
def serialize(value, field):
"""
Form values serializatio... |
def indent(elem, level=0):
"""
Helper function, adds indentation to XML output.
:param elem: object of Element class, representing element to which method adds intendation,
:param level: current level of intendation.
"""
i = "\n" + level * " "
j = "\n" + (level ... | Helper function, adds indentation to XML output.
:param elem: object of Element class, representing element to which method adds intendation,
:param level: current level of intendation. | Below is the the instruction that describes the task:
### Input:
Helper function, adds indentation to XML output.
:param elem: object of Element class, representing element to which method adds intendation,
:param level: current level of intendation.
### Response:
def indent(elem, level=0):
... |
def get_bin_dir(self, build_module: str) -> str:
"""Return a path to the binaries dir for a build module dir.
Create sub-tree of missing dirs as needed, and return full path
to innermost directory.
"""
bin_dir = os.path.join(self.conf.get_bin_path(), build_module)
i... | Return a path to the binaries dir for a build module dir.
Create sub-tree of missing dirs as needed, and return full path
to innermost directory. | Below is the the instruction that describes the task:
### Input:
Return a path to the binaries dir for a build module dir.
Create sub-tree of missing dirs as needed, and return full path
to innermost directory.
### Response:
def get_bin_dir(self, build_module: str) -> str:
"""Return a... |
def find_price_by_category(package, price_category):
"""Find the price in the given package that has the specified category
:param package: The AsAService, Enterprise, or Performance product package
:param price_category: The price category code to search for
:return: Returns the price for the given ca... | Find the price in the given package that has the specified category
:param package: The AsAService, Enterprise, or Performance product package
:param price_category: The price category code to search for
:return: Returns the price for the given category, or an error if not found | Below is the the instruction that describes the task:
### Input:
Find the price in the given package that has the specified category
:param package: The AsAService, Enterprise, or Performance product package
:param price_category: The price category code to search for
:return: Returns the price for the... |
def id(self):
"""
:return: the ID attribute of the sentence
:rtype: int
"""
if self._id is None:
self._id = int(self._element.get('id'))
return self._id | :return: the ID attribute of the sentence
:rtype: int | Below is the the instruction that describes the task:
### Input:
:return: the ID attribute of the sentence
:rtype: int
### Response:
def id(self):
"""
:return: the ID attribute of the sentence
:rtype: int
"""
if self._id is None:
self._id = int(self._ele... |
def v_reference_leaf_leafref(ctx, stmt):
"""Verify that all leafrefs in a leaf or leaf-list have correct path"""
if (hasattr(stmt, 'i_leafref') and
stmt.i_leafref is not None and
stmt.i_leafref_expanded is False):
path_type_spec = stmt.i_leafref
not_req_inst = not(path_type_spec... | Verify that all leafrefs in a leaf or leaf-list have correct path | Below is the the instruction that describes the task:
### Input:
Verify that all leafrefs in a leaf or leaf-list have correct path
### Response:
def v_reference_leaf_leafref(ctx, stmt):
"""Verify that all leafrefs in a leaf or leaf-list have correct path"""
if (hasattr(stmt, 'i_leafref') and
stmt.... |
def atlas_peer_has_fresh_zonefile_inventory( peer_hostport, peer_table=None ):
"""
Does the given atlas node have a fresh zonefile inventory?
"""
fresh = False
with AtlasPeerTableLocked(peer_table) as ptbl:
if peer_hostport not in ptbl.keys():
return False
now = time_no... | Does the given atlas node have a fresh zonefile inventory? | Below is the the instruction that describes the task:
### Input:
Does the given atlas node have a fresh zonefile inventory?
### Response:
def atlas_peer_has_fresh_zonefile_inventory( peer_hostport, peer_table=None ):
"""
Does the given atlas node have a fresh zonefile inventory?
"""
fresh = False
... |
def _validate_authority_uri_abs_path(host, path):
"""Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not.
"""
if len(host) > 0 and len(path) > 0 and not path.startswith("/"):
raise ValueError(
"Path in a URL with author... | Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not. | Below is the the instruction that describes the task:
### Input:
Ensure that path in URL with authority starts with a leading slash.
Raise ValueError if not.
### Response:
def _validate_authority_uri_abs_path(host, path):
"""Ensure that path in URL with authority starts with a leading slash.
... |
def compare_parts(list1, list2):
"""
if list2 does not start with list1, we can't really check and return 0
"""
for i, item in enumerate(list1):
if item != list2[i]:
return 0
if len(list2) > len(list1):
return ISDIR
else:
return ISFILE | if list2 does not start with list1, we can't really check and return 0 | Below is the the instruction that describes the task:
### Input:
if list2 does not start with list1, we can't really check and return 0
### Response:
def compare_parts(list1, list2):
"""
if list2 does not start with list1, we can't really check and return 0
"""
for i, item in enumerate(list1):
... |
def cmdify(self):
"""Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are ... | Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* Existing backslashes before a quote are doubled, so they are all
... | Below is the the instruction that describes the task:
### Input:
Encode into a cmd-executable string.
This re-implements CreateProcess's quoting logic to turn a list of
arguments into one single string for the shell to interpret.
* All double quotes are escaped with a backslash.
* ... |
def write_resources(self, resources):
"""Write the output data in resources returned by exporter
to files.
"""
for filename, data in list(resources.get('outputs', {}).items()):
# Determine where to write the file to
dest = os.path.join(self.output_dir, filename)
... | Write the output data in resources returned by exporter
to files. | Below is the the instruction that describes the task:
### Input:
Write the output data in resources returned by exporter
to files.
### Response:
def write_resources(self, resources):
"""Write the output data in resources returned by exporter
to files.
"""
for filename, data ... |
def dbmax10years(self, value=None):
""" Corresponds to IDD Field `dbmax10years`
10-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax10years`
Unit: C
if `value` is None it will not be ch... | Corresponds to IDD Field `dbmax10years`
10-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax10years`
Unit: C
if `value` is None it will not be checked against the
specification a... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `dbmax10years`
10-year return period values for maximum extreme dry-bulb temperature
Args:
value (float): value for IDD Field `dbmax10years`
Unit: C
if `value` is No... |
def get_complex_coefficients(self, params):
"""
Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given th... | Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` given the current parameter settings. By
default, this term is e... | Below is the the instruction that describes the task:
### Input:
Get the arrays ``alpha_complex_*`` and ``beta_complex_*``
This method should be overloaded by subclasses to return the arrays
``alpha_complex_real``, ``alpha_complex_imag``, ``beta_complex_real``,
and ``beta_complex_imag`` giv... |
def splits(cls, text_field, label_field, root='.data',
train='train.txt', validation='dev.txt', test='test.txt',
train_subtrees=False, **kwargs):
"""Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the... | Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used for label data.
root: The root directory that the dataset's zip archive will be
expanded into; ... | Below is the the instruction that describes the task:
### Input:
Create dataset objects for splits of the SST dataset.
Arguments:
text_field: The field that will be used for the sentence.
label_field: The field that will be used for label data.
root: The root directory t... |
def resolve_import_alias(name, import_names):
"""Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple... | Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names: iterable(tuple(str, str or None))
:returns: The original name.... | Below is the the instruction that describes the task:
### Input:
Resolve a name from an aliased import to its original name.
:param name: The potentially aliased name to resolve.
:type name: str
:param import_names: The pairs of original names and aliases
from the import.
:type import_names... |
def hourly_horizontal_infrared(self):
"""A data collection containing hourly horizontal infrared intensity in W/m2.
"""
sky_cover = self._sky_condition.hourly_sky_cover
db_temp = self._dry_bulb_condition.hourly_values
dp_temp = self._humidity_condition.hourly_dew_point_values(
... | A data collection containing hourly horizontal infrared intensity in W/m2. | Below is the the instruction that describes the task:
### Input:
A data collection containing hourly horizontal infrared intensity in W/m2.
### Response:
def hourly_horizontal_infrared(self):
"""A data collection containing hourly horizontal infrared intensity in W/m2.
"""
sky_cover = self.... |
def _finish_selecting(self, event):
"""Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion."""
self._selecting = False
canvas = self._canvas
x = canvas.canvasx(event.x)
y = canvas.canvasy(event.y)
... | Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion. | Below is the the instruction that describes the task:
### Input:
Finaliza la seleccion.
Marca como seleccionados todos los objetos que se encuentran
dentro del recuadro de seleccion.
### Response:
def _finish_selecting(self, event):
"""Finaliza la seleccion.
Marca como seleccionados... |
def getSrcBlocks(self, url, dataset="", block=""):
"""
Need to list all blocks of the dataset and its parents starting from the top
For now just list the blocks from this dataset.
Client type call...
"""
if block:
params={'block_name':block, 'open_for_writing'... | Need to list all blocks of the dataset and its parents starting from the top
For now just list the blocks from this dataset.
Client type call... | Below is the the instruction that describes the task:
### Input:
Need to list all blocks of the dataset and its parents starting from the top
For now just list the blocks from this dataset.
Client type call...
### Response:
def getSrcBlocks(self, url, dataset="", block=""):
"""
Need... |
def create_marker_table(self):
"""
Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset.
"""
connection = self.connect(autocommit=True)
cursor = connection.cursor()
try:
cursor.execute(
... | Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset. | Below is the the instruction that describes the task:
### Input:
Create marker table if it doesn't exist.
Using a separate connection since the transaction might have to be reset.
### Response:
def create_marker_table(self):
"""
Create marker table if it doesn't exist.
Using a sep... |
def pull(self):
"""
Pull selected repo from a remote git repository,
while preserving user changes
"""
if not os.path.exists(self.repo_dir):
yield from self.initialize_repo()
else:
yield from self.update() | Pull selected repo from a remote git repository,
while preserving user changes | Below is the the instruction that describes the task:
### Input:
Pull selected repo from a remote git repository,
while preserving user changes
### Response:
def pull(self):
"""
Pull selected repo from a remote git repository,
while preserving user changes
"""
if not... |
def ConvertCloudMetadataResponsesToCloudInstance(metadata_responses):
"""Convert CloudMetadataResponses to CloudInstance proto.
Ideally we'd just get the client to fill out a CloudInstance proto, but we
need to keep the flexibility of collecting new metadata and creating new
fields without a client push. So in... | Convert CloudMetadataResponses to CloudInstance proto.
Ideally we'd just get the client to fill out a CloudInstance proto, but we
need to keep the flexibility of collecting new metadata and creating new
fields without a client push. So instead we bring back essentially a dict of
results and fill the proto on t... | Below is the the instruction that describes the task:
### Input:
Convert CloudMetadataResponses to CloudInstance proto.
Ideally we'd just get the client to fill out a CloudInstance proto, but we
need to keep the flexibility of collecting new metadata and creating new
fields without a client push. So instead ... |
def validate(method, auth, *args, **kwargs):
"""Validate a method based on the METHOD_RULES above.
Raises a PyCronofyValidationError on error.
:param string method: Method being validated.
:param Auth auth: Auth instance.
:param *args: Positional arguments for method.
:param **kwargs: Keyword ... | Validate a method based on the METHOD_RULES above.
Raises a PyCronofyValidationError on error.
:param string method: Method being validated.
:param Auth auth: Auth instance.
:param *args: Positional arguments for method.
:param **kwargs: Keyword arguments for method. | Below is the the instruction that describes the task:
### Input:
Validate a method based on the METHOD_RULES above.
Raises a PyCronofyValidationError on error.
:param string method: Method being validated.
:param Auth auth: Auth instance.
:param *args: Positional arguments for method.
:param *... |
def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for the partial char as well.
'''
sub_chars = round(width * ratio * self.partial_chars_len)
ncc, self.remainder = divmod(sub_chars, self.partial_chars_len)
return n... | Get the number of complete chars.
This one figures the remainder for the partial char as well. | Below is the the instruction that describes the task:
### Input:
Get the number of complete chars.
This one figures the remainder for the partial char as well.
### Response:
def _get_ncc(self, width, ratio):
''' Get the number of complete chars.
This one figures the remainder for ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.