code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def register_nonzero_counter(network, stats):
"""
Register forward hooks to count the number of nonzero floating points
values from all the tensors used by the given network during inference.
:param network: The network to attach the counter
:param stats: Dictionary holding the counter.
"""
if hasattr(ne... | Register forward hooks to count the number of nonzero floating points
values from all the tensors used by the given network during inference.
:param network: The network to attach the counter
:param stats: Dictionary holding the counter. | Below is the the instruction that describes the task:
### Input:
Register forward hooks to count the number of nonzero floating points
values from all the tensors used by the given network during inference.
:param network: The network to attach the counter
:param stats: Dictionary holding the counter.
### Re... |
def get_final_version_string(release_mode, semver, commit_count=0):
"""Generates update dictionary entries for the version string"""
version_string = ".".join(semver)
maybe_dev_version_string = version_string
updates = {}
if release_mode:
# in production, we have something like `1.2.3`, as w... | Generates update dictionary entries for the version string | Below is the the instruction that describes the task:
### Input:
Generates update dictionary entries for the version string
### Response:
def get_final_version_string(release_mode, semver, commit_count=0):
"""Generates update dictionary entries for the version string"""
version_string = ".".join(semver)
... |
def clone(self, id, name=None):
"""Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo
"""
url = 'git@gist.github.com:/{}'.format(id)
if name is None:
os.system('git clone {}'.format(url))
else:
... | Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo | Below is the the instruction that describes the task:
### Input:
Clone a gist
Arguments:
id: the gist identifier
name: the name to give the cloned repo
### Response:
def clone(self, id, name=None):
"""Clone a gist
Arguments:
id: the gist identifier
... |
def call_with_context(func, context, *args):
"""
Check if given function has more arguments than given. Call it with context
as last argument or without it.
"""
return make_context_aware(func, len(args))(*args + (context,)) | Check if given function has more arguments than given. Call it with context
as last argument or without it. | Below is the the instruction that describes the task:
### Input:
Check if given function has more arguments than given. Call it with context
as last argument or without it.
### Response:
def call_with_context(func, context, *args):
"""
Check if given function has more arguments than given. Call it with... |
def authenticate(self, req, resp, resource):
"""
Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
"""
usernam... | Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception` | Below is the the instruction that describes the task:
### Input:
Extract basic auth token from request `authorization` header, deocode the
token, verifies the username/password and return either a ``user``
object if successful else raise an `falcon.HTTPUnauthoried exception`
### Response:
def auth... |
def twofilter_smoothing(self, t, info, phi, loggamma, linear_cost=False,
return_ess=False, modif_forward=None,
modif_info=None):
"""Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object... | Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
loggamma: function
a function of (X_{t+1})
linear_cost... | Below is the the instruction that describes the task:
### Input:
Two-filter smoothing.
Parameters
----------
t: time, in range 0 <= t < T-1
info: SMC object
the information filter
phi: function
test function, a function of (X_t,X_{t+1})
logga... |
def account_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account"
api_path = "/api/v2/account"
return self.call(api_path, method="PUT", data=data, **kwargs) | https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account
### Response:
def account_update(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/chat/accounts#update-account"
api_path = "/api/v2/account"
... |
def list_objects(self, bucket_name=None, **kwargs):
"""
This method is primarily for illustration and just calls the
boto3 client implementation of list_objects but is a common task
for first time Predix BlobStore users.
"""
if not bucket_name: bucket_name = self.bucket_... | This method is primarily for illustration and just calls the
boto3 client implementation of list_objects but is a common task
for first time Predix BlobStore users. | Below is the the instruction that describes the task:
### Input:
This method is primarily for illustration and just calls the
boto3 client implementation of list_objects but is a common task
for first time Predix BlobStore users.
### Response:
def list_objects(self, bucket_name=None, **kwargs):
... |
def create_vpnservice(subnet, router, name, admin_state_up=True, profile=None):
'''
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Ro... | Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier for the VPN service
:param name: Set a name for the VPN service
... | Below is the the instruction that describes the task:
### Input:
Creates a new VPN service
CLI Example:
.. code-block:: bash
salt '*' neutron.create_vpnservice router-name name
:param subnet: Subnet unique identifier for the VPN service deployment
:param router: Router unique identifier ... |
def settings(self):
'''Generator which returns all of the statements in all of the settings tables'''
for table in self.tables:
if isinstance(table, SettingTable):
for statement in table.statements:
yield statement | Generator which returns all of the statements in all of the settings tables | Below is the the instruction that describes the task:
### Input:
Generator which returns all of the statements in all of the settings tables
### Response:
def settings(self):
'''Generator which returns all of the statements in all of the settings tables'''
for table in self.tables:
if i... |
def install_package(self, name, index=None, force=False, update=False):
"""Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bo... | Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the reinstall of packages during updates.
update (bool): Updat... | Below is the the instruction that describes the task:
### Input:
Install a given package.
Args:
name (str): The package name to install. This can be any valid
pip package specification.
index (str): The URL for a pypi index to use.
force (bool): For the r... |
def rot(vm):
"""Rotate topmost three items once to the left. ( a b c -- b c a )"""
c = vm.pop()
b = vm.pop()
a = vm.pop()
vm.push(b)
vm.push(c)
vm.push(a) | Rotate topmost three items once to the left. ( a b c -- b c a ) | Below is the the instruction that describes the task:
### Input:
Rotate topmost three items once to the left. ( a b c -- b c a )
### Response:
def rot(vm):
"""Rotate topmost three items once to the left. ( a b c -- b c a )"""
c = vm.pop()
b = vm.pop()
a = vm.pop()
vm.push(b)
vm.push(c)
... |
def parsecommonarguments(object, doc, annotationtype, required, allowed, **kwargs):
"""Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly."""
object.doc = doc #The FoLiA root document
if required is None:
required = tuple()
if allowe... | Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly. | Below is the the instruction that describes the task:
### Input:
Internal function to parse common FoLiA attributes and sets up the instance accordingly. Do not invoke directly.
### Response:
def parsecommonarguments(object, doc, annotationtype, required, allowed, **kwargs):
"""Internal function to parse commo... |
def setup_signals(self, ):
"""Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None
"""
self.browser.shot_taskfile_sel_changed.connect(self.shot_taskfile_sel_changed)
self.browser.asset_taskfile_sel_changed.connect... | Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None | Below is the the instruction that describes the task:
### Input:
Connect the signals with the slots to make the ui functional
:returns: None
:rtype: None
:raises: None
### Response:
def setup_signals(self, ):
"""Connect the signals with the slots to make the ui functional
... |
def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_rep = _get_opstr(op, cls)
op_name = _get_op_name(op, special)
eval_kwargs = _gen_eval_kwargs(op_name)
fill_zeros = _gen_fill_zeros(op_name)
construct_... | Wrapper function for Series arithmetic operations, to avoid
code duplication. | Below is the the instruction that describes the task:
### Input:
Wrapper function for Series arithmetic operations, to avoid
code duplication.
### Response:
def _arith_method_SERIES(cls, op, special):
"""
Wrapper function for Series arithmetic operations, to avoid
code duplication.
"""
str_... |
def _fill_cropping(self, image_size, view_size):
"""
Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e... | Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e.g. 0.425 represents 42.5%. *image_size* and
*view_size* are ... | Below is the the instruction that describes the task:
### Input:
Return a (left, top, right, bottom) 4-tuple containing the cropping
values required to display an image of *image_size* in *view_size*
when stretched proportionately. Each value is a percentage expressed
as a fraction of 1.0, e... |
def c_rho0(self, rho0):
"""
computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
:param rho0: density normalization in h^2/Mpc^3 (comoving)
:return: concentration parameter c
"""
if not hasattr(self, '_c_rho0_interp'):
c_ar... | computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
:param rho0: density normalization in h^2/Mpc^3 (comoving)
:return: concentration parameter c | Below is the the instruction that describes the task:
### Input:
computes the concentration given a comoving overdensity rho0 (inverse of function rho0_c)
:param rho0: density normalization in h^2/Mpc^3 (comoving)
:return: concentration parameter c
### Response:
def c_rho0(self, rho0):
"""
... |
def hierarchy_name(self, adjust_for_printing=True):
"""
return the name for this object with the parents names attached by dots.
:param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`
on the names, recursively
... | return the name for this object with the parents names attached by dots.
:param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`
on the names, recursively | Below is the the instruction that describes the task:
### Input:
return the name for this object with the parents names attached by dots.
:param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`
on the names, recursively
### Response:
def hie... |
def delete_free_shipping_coupon_by_id(cls, free_shipping_coupon_id, **kwargs):
"""Delete FreeShippingCoupon
Delete an instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>... | Delete FreeShippingCoupon
Delete an instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delete_free_shipping_coupon_by_id(free_shipping_coupon_id, async=True)
... | Below is the the instruction that describes the task:
### Input:
Delete FreeShippingCoupon
Delete an instance of FreeShippingCoupon by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.delet... |
def jsName(path,name):
'''Returns a name string without \, -, and . so that
the string will play nicely with javascript.'''
shortPath=path.replace(
"C:\\Users\\scheinerbock\\Desktop\\"+
"ideogram\\scrapeSource\\test\\","")
noDash = shortPath.replace("-","_dash_")
jsPath=noDa... | Returns a name string without \, -, and . so that
the string will play nicely with javascript. | Below is the the instruction that describes the task:
### Input:
Returns a name string without \, -, and . so that
the string will play nicely with javascript.
### Response:
def jsName(path,name):
'''Returns a name string without \, -, and . so that
the string will play nicely with javascript.'''
... |
def get_config(cls, key, default=None):
"""
Shortcut to access the application's config in your class
:param key: The key to access
:param default: The default value when None
:returns mixed:
"""
return cls._app.config.get(key, default) | Shortcut to access the application's config in your class
:param key: The key to access
:param default: The default value when None
:returns mixed: | Below is the the instruction that describes the task:
### Input:
Shortcut to access the application's config in your class
:param key: The key to access
:param default: The default value when None
:returns mixed:
### Response:
def get_config(cls, key, default=None):
"""
Shor... |
def add_done_callback(self, callback):
"""
Add a callback to run after the task completes.
The callable must take 1 argument which will be
the completed Task.
:param callback: a callable that takes a single argument which
will be the completed Task.
"""
... | Add a callback to run after the task completes.
The callable must take 1 argument which will be
the completed Task.
:param callback: a callable that takes a single argument which
will be the completed Task. | Below is the the instruction that describes the task:
### Input:
Add a callback to run after the task completes.
The callable must take 1 argument which will be
the completed Task.
:param callback: a callable that takes a single argument which
will be the completed Task.
### Res... |
async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify object has no `href` attribute, therefore cannot be retrived')
elif hasattr(self, 'http'):
return await self.http.request(('G... | Get the full object from spotify with a `href` attribute. | Below is the the instruction that describes the task:
### Input:
Get the full object from spotify with a `href` attribute.
### Response:
async def from_href(self):
"""Get the full object from spotify with a `href` attribute."""
if not hasattr(self, 'href'):
raise TypeError('Spotify obje... |
def get_version(self, version_id=None):
"""Return specific version ``ObjectVersion`` instance or HEAD.
:param version_id: Version ID of the object.
:returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or
HEAD of the stored object.
"""
return ObjectVer... | Return specific version ``ObjectVersion`` instance or HEAD.
:param version_id: Version ID of the object.
:returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or
HEAD of the stored object. | Below is the the instruction that describes the task:
### Input:
Return specific version ``ObjectVersion`` instance or HEAD.
:param version_id: Version ID of the object.
:returns: :class:`~invenio_files_rest.models.ObjectVersion` instance or
HEAD of the stored object.
### Response:
def... |
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
if self.is_derived():
return [], None
return self.fs.variant_dir_target_climb(self, self.dir, [self.name]) | Return any corresponding targets in a variant directory. | Below is the the instruction that describes the task:
### Input:
Return any corresponding targets in a variant directory.
### Response:
def alter_targets(self):
"""Return any corresponding targets in a variant directory.
"""
if self.is_derived():
return [], None
return s... |
def showDescription( self ):
"""
Shows the description for the current plugin in the interface.
"""
plugin = self.currentPlugin()
if ( not plugin ):
self.uiDescriptionTXT.setText('')
else:
self.uiDescriptionTXT.setText(plugin.description()) | Shows the description for the current plugin in the interface. | Below is the the instruction that describes the task:
### Input:
Shows the description for the current plugin in the interface.
### Response:
def showDescription( self ):
"""
Shows the description for the current plugin in the interface.
"""
plugin = self.currentPlugin()
... |
def show_hist(self, props=[], bins=20, **kwargs):
r"""
Show a quick plot of key property distributions.
Parameters
----------
props : string or list of strings
The pore and/or throat properties to be plotted as histograms
bins : int or array_like
... | r"""
Show a quick plot of key property distributions.
Parameters
----------
props : string or list of strings
The pore and/or throat properties to be plotted as histograms
bins : int or array_like
The number of bins to use when generating the histogram. ... | Below is the the instruction that describes the task:
### Input:
r"""
Show a quick plot of key property distributions.
Parameters
----------
props : string or list of strings
The pore and/or throat properties to be plotted as histograms
bins : int or array_like
... |
def fetch_more(self, rows=False, columns=False):
"""Get more columns or rows (based on axis)."""
if self.axis == 1 and self.total_rows > self.rows_loaded:
reminder = self.total_rows - self.rows_loaded
items_to_fetch = min(reminder, ROWS_TO_LOAD)
self.beginInsert... | Get more columns or rows (based on axis). | Below is the the instruction that describes the task:
### Input:
Get more columns or rows (based on axis).
### Response:
def fetch_more(self, rows=False, columns=False):
"""Get more columns or rows (based on axis)."""
if self.axis == 1 and self.total_rows > self.rows_loaded:
reminde... |
def boolean(value):
"""
Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars).
"""
if isinstance(value, bool):
return value
if value == "":
return False
return strtobool(value) | Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars). | Below is the the instruction that describes the task:
### Input:
Configuration-friendly boolean type converter.
Supports both boolean-valued and string-valued inputs (e.g. from env vars).
### Response:
def boolean(value):
"""
Configuration-friendly boolean type converter.
Supports both boolean-va... |
def base64ToImage(imgData, out_path, out_file):
""" converts a base64 string to a file """
fh = open(os.path.join(out_path, out_file), "wb")
fh.write(imgData.decode('base64'))
fh.close()
del fh
return os.path.join(out_path, out_file) | converts a base64 string to a file | Below is the the instruction that describes the task:
### Input:
converts a base64 string to a file
### Response:
def base64ToImage(imgData, out_path, out_file):
""" converts a base64 string to a file """
fh = open(os.path.join(out_path, out_file), "wb")
fh.write(imgData.decode('base64'))
... |
def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t) | Convert DATE string into a decimal year. | Below is the the instruction that describes the task:
### Input:
Convert DATE string into a decimal year.
### Response:
def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t) |
def settingsAsFacts(self, settings):
"""
Parses a string of settings.
:param setting: String of settings in the form:
``set(name1, val1), set(name2, val2)...``
"""
pattern = re.compile('set\(([a-zA-Z0-9_]+),(\[a-zA-Z0-9_]+)\)')
pairs = pattern.findall(se... | Parses a string of settings.
:param setting: String of settings in the form:
``set(name1, val1), set(name2, val2)...`` | Below is the the instruction that describes the task:
### Input:
Parses a string of settings.
:param setting: String of settings in the form:
``set(name1, val1), set(name2, val2)...``
### Response:
def settingsAsFacts(self, settings):
"""
Parses a string of settings.
... |
def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
"""
value = float(onp.array(value))
if step is None:
step = self._step
else:
self._step = step
summary =... | Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step | Below is the the instruction that describes the task:
### Input:
Saves scalar value.
Args:
tag: str: label for this data
value: int/float: number to log
step: int: training step
### Response:
def scalar(self, tag, value, step=None):
"""Saves scalar value.
Args:
tag: str: label... |
def StoreStat(self, responses):
"""Stores stat entry in the flow's state."""
index = responses.request_data["index"]
if not responses.success:
self.Log("Failed to stat file: %s", responses.status)
# Report failure.
self._FileFetchFailed(index, responses.request_data["request_name"])
... | Stores stat entry in the flow's state. | Below is the the instruction that describes the task:
### Input:
Stores stat entry in the flow's state.
### Response:
def StoreStat(self, responses):
"""Stores stat entry in the flow's state."""
index = responses.request_data["index"]
if not responses.success:
self.Log("Failed to stat file: %s", ... |
def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
"""
def f(option=option, default=default, type=type, section=section):
config = read_... | Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale')) | Below is the the instruction that describes the task:
### Input:
Guesses a default value of a CLI option from the configuration.
::
@click.option('--locale', default=config_default('locale'))
### Response:
def config_default(option, default=None, type=None, section=cli.name):
"""Guesses a default ... |
def spherical(cls, mag, theta, phi=0):
'''Returns a Vector instance from spherical coordinates'''
return cls(
mag * math.sin(phi) * math.cos(theta), # X
mag * math.sin(phi) * math.sin(theta), # Y
mag * math.cos(phi) # Z
) | Returns a Vector instance from spherical coordinates | Below is the the instruction that describes the task:
### Input:
Returns a Vector instance from spherical coordinates
### Response:
def spherical(cls, mag, theta, phi=0):
'''Returns a Vector instance from spherical coordinates'''
return cls(
mag * math.sin(phi) * math.cos(theta), # X
... |
def GetAttributes(self, urns, age=NEWEST_TIME):
"""Retrieves all the attributes for all the urns."""
urns = set([utils.SmartUnicode(u) for u in urns])
to_read = {urn: self._MakeCacheInvariant(urn, age) for urn in urns}
# Urns not present in the cache we need to get from the database.
if to_read:
... | Retrieves all the attributes for all the urns. | Below is the the instruction that describes the task:
### Input:
Retrieves all the attributes for all the urns.
### Response:
def GetAttributes(self, urns, age=NEWEST_TIME):
"""Retrieves all the attributes for all the urns."""
urns = set([utils.SmartUnicode(u) for u in urns])
to_read = {urn: self._Make... |
def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.get('text/html', '')
if 'application/javascript' in data:
js = data['application/javascript']
html +... | Converts a MIME bundle into HTML. | Below is the the instruction that describes the task:
### Input:
Converts a MIME bundle into HTML.
### Response:
def mimebundle_to_html(bundle):
"""
Converts a MIME bundle into HTML.
"""
if isinstance(bundle, tuple):
data, metadata = bundle
else:
data = bundle
html = data.ge... |
def save(self, p_todolist):
"""
Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is clo... | Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestamp. Backup file is closed afterwards. | Below is the the instruction that describes the task:
### Input:
Saves a tuple with archive, todolist and command with its arguments
into the backup file with unix timestamp as the key. Tuple is then
indexed in backup file with combination of hash calculated from
p_todolist and unix timestam... |
def add_path(self, w, h):
"""Return a newly created `a:path` child element."""
path = self._add_path()
path.w, path.h = w, h
return path | Return a newly created `a:path` child element. | Below is the the instruction that describes the task:
### Input:
Return a newly created `a:path` child element.
### Response:
def add_path(self, w, h):
"""Return a newly created `a:path` child element."""
path = self._add_path()
path.w, path.h = w, h
return path |
def instruction_PUL(self, opcode, m, register):
"""
All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the s... | All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the stack (example: LDX ,S++).
source code forms: b7 b6 b5 b4 b3... | Below is the the instruction that describes the task:
### Input:
All, some, or none of the processor registers are pulled from stack
(with the exception of stack pointer itself).
A single register may be pulled from the stack with condition codes set
by doing an autoincrement load from the ... |
def addfield(self, pkt, s, val):
# type: (Optional[packet.Packet], Union[str, Tuple[str, int, int]], int) -> str # noqa: E501
""" An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix leng... | An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix length is 8 bits and the whole byte is to
be consumed
@param packet.Packet|None pkt: the packet containing this field. Probably unuse... | Below is the the instruction that describes the task:
### Input:
An AbstractUVarIntField prefix always consumes the remaining bits
of a BitField;if no current BitField is in use (no tuple in
entry) then the prefix length is 8 bits and the whole byte is to
be consumed
@param pac... |
def volume_list(search_opts=None, profile=None, **kwargs):
'''
List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack... | List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack | Below is the the instruction that describes the task:
### Input:
List storage volumes
search_opts
Dictionary of search options
profile
Profile to use
CLI Example:
.. code-block:: bash
salt '*' nova.volume_list search_opts='{"display_name": "myblock"}' profile=openstack
#... |
def expand_dates(df, columns=[]):
"""
generate year, month, day features from specified date features
"""
columns = df.columns.intersection(columns)
df2 = df.reindex(columns=set(df.columns).difference(columns))
for column in columns:
df2[column + '_year'] = df[column].apply(lambda x: x.y... | generate year, month, day features from specified date features | Below is the the instruction that describes the task:
### Input:
generate year, month, day features from specified date features
### Response:
def expand_dates(df, columns=[]):
"""
generate year, month, day features from specified date features
"""
columns = df.columns.intersection(columns)
df2... |
def healpixMap(nside, lon, lat, fill_value=0., nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution
"""
lon_median, lat_median = np.median(lon), np.median(lat)
max_angsep = np.max(ugali.utils.projector.angsep(lon, lat, l... | Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution | Below is the the instruction that describes the task:
### Input:
Input (lon, lat) in degrees instead of (theta, phi) in radians.
Returns HEALPix map at the desired resolution
### Response:
def healpixMap(nside, lon, lat, fill_value=0., nest=False):
"""
Input (lon, lat) in degrees instead of (theta, phi... |
def getPermanence(self, columnIndex, permanence):
"""
Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.
:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences.
"""
... | Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.
:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences. | Below is the the instruction that describes the task:
### Input:
Returns the permanence values for a given column. ``permanence`` size
must match the number of inputs.
:param columnIndex: (int) column index to get permanence for.
:param permanence: (list) will be overwritten with permanences.
### R... |
def getName(obj):
"""This method finds the first parent class which is within the buildbot namespace
it prepends the name with as many ">" as the class is subclassed
"""
# elastic search does not like '.' in dict keys, so we replace by /
def sanitize(name):
return name.replace(".", "/")
... | This method finds the first parent class which is within the buildbot namespace
it prepends the name with as many ">" as the class is subclassed | Below is the the instruction that describes the task:
### Input:
This method finds the first parent class which is within the buildbot namespace
it prepends the name with as many ">" as the class is subclassed
### Response:
def getName(obj):
"""This method finds the first parent class which is within the b... |
def run(self, cmd, *args, **kwargs):
"""Run a command."""
runner = self.ctx.run if self.ctx else None
return run(cmd, runner=runner, *args, **kwargs) | Run a command. | Below is the the instruction that describes the task:
### Input:
Run a command.
### Response:
def run(self, cmd, *args, **kwargs):
"""Run a command."""
runner = self.ctx.run if self.ctx else None
return run(cmd, runner=runner, *args, **kwargs) |
def eccentricity(self, **kw):
r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments ... | r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
Any keyword arguments passed to ``apocenter()`` and
... | Below is the the instruction that describes the task:
### Input:
r"""
Returns the eccentricity computed from the mean apocenter and
mean pericenter.
.. math::
e = \frac{r_{\rm apo} - r_{\rm per}}{r_{\rm apo} + r_{\rm per}}
Parameters
----------
**kw
... |
def set_title(self, title=None):
"""
Sets the editor title.
:param title: Editor title.
:type title: unicode
:return: Method success.
:rtype: bool
"""
if not title:
# TODO: https://bugreports.qt-project.org/browse/QTBUG-27084
# ti... | Sets the editor title.
:param title: Editor title.
:type title: unicode
:return: Method success.
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Sets the editor title.
:param title: Editor title.
:type title: unicode
:return: Method success.
:rtype: bool
### Response:
def set_title(self, title=None):
"""
Sets the editor title.
:param t... |
def map(func):
"""Apply function to each value inside the sequence or dict.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict.
"""
# text is an alias for basestring on Python 2, which cannot be
# instantiated and therefore can't be used to transform the valu... | Apply function to each value inside the sequence or dict.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict. | Below is the the instruction that describes the task:
### Input:
Apply function to each value inside the sequence or dict.
Supports both dicts and sequences, key/value pairs are
expanded when applied to a dict.
### Response:
def map(func):
"""Apply function to each value inside the sequence or dict.
... |
def clean(self):
"""
Check unauthenticated user's cookie as a light check to
prevent duplicate votes.
"""
bits = (self.data["content_type"], self.data["object_pk"])
request = self.request
self.current = "%s.%s" % bits
self.previous = request.COOKIES.get("y... | Check unauthenticated user's cookie as a light check to
prevent duplicate votes. | Below is the the instruction that describes the task:
### Input:
Check unauthenticated user's cookie as a light check to
prevent duplicate votes.
### Response:
def clean(self):
"""
Check unauthenticated user's cookie as a light check to
prevent duplicate votes.
"""
b... |
def _build_context(self, request, customer_uuid):
"""
Build common context parts used by different handlers in this view.
"""
# TODO: pylint acts stupid - find a way around it without suppressing
enterprise_customer = EnterpriseCustomer.objects.get(uuid=customer_uuid) # pylint: ... | Build common context parts used by different handlers in this view. | Below is the the instruction that describes the task:
### Input:
Build common context parts used by different handlers in this view.
### Response:
def _build_context(self, request, customer_uuid):
"""
Build common context parts used by different handlers in this view.
"""
# TODO: py... |
def makevAndvPfuncs(self,policyFunc):
'''
Constructs the marginal value function for this period.
Parameters
----------
policyFunc : function
Consumption and medical care function for this period, defined over
market resources, permanent income level, and... | Constructs the marginal value function for this period.
Parameters
----------
policyFunc : function
Consumption and medical care function for this period, defined over
market resources, permanent income level, and the medical need shock.
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Constructs the marginal value function for this period.
Parameters
----------
policyFunc : function
Consumption and medical care function for this period, defined over
market resources, permanent income... |
def purge(self, jid, node):
"""
Delete all items from a node.
:param jid: JID of the PubSub service
:param node: Name of the PubSub node
:type node: :class:`str`
Requires :attr:`.xso.Feature.PURGE`.
"""
iq = aioxmpp.stanza.IQ(
type_=aioxmpp.... | Delete all items from a node.
:param jid: JID of the PubSub service
:param node: Name of the PubSub node
:type node: :class:`str`
Requires :attr:`.xso.Feature.PURGE`. | Below is the the instruction that describes the task:
### Input:
Delete all items from a node.
:param jid: JID of the PubSub service
:param node: Name of the PubSub node
:type node: :class:`str`
Requires :attr:`.xso.Feature.PURGE`.
### Response:
def purge(self, jid, node):
... |
def is_readable(filename):
"""Check if file is a regular file and is readable."""
return os.path.isfile(filename) and os.access(filename, os.R_OK) | Check if file is a regular file and is readable. | Below is the the instruction that describes the task:
### Input:
Check if file is a regular file and is readable.
### Response:
def is_readable(filename):
"""Check if file is a regular file and is readable."""
return os.path.isfile(filename) and os.access(filename, os.R_OK) |
def _add(self, *rules):
# type: (Iterable[Type[Rule]]) -> Generator[Type[Rule]]
"""
Add rules into the set. Each rule is validated and split if needed.
The method add the rules into dictionary, so the rule can be deleted with terminals or nonterminals.
:param rules: Rules to inse... | Add rules into the set. Each rule is validated and split if needed.
The method add the rules into dictionary, so the rule can be deleted with terminals or nonterminals.
:param rules: Rules to insert.
:return: Inserted rules.
:raise NotRuleException: If the parameter doesn't inherit from ... | Below is the the instruction that describes the task:
### Input:
Add rules into the set. Each rule is validated and split if needed.
The method add the rules into dictionary, so the rule can be deleted with terminals or nonterminals.
:param rules: Rules to insert.
:return: Inserted rules.
... |
def write_json_to_temp_file(data):
"""Writes JSON data to a temporary file and returns the path to it"""
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write(json.dumps(data).encode('utf-8'))
fp.close()
return fp.name | Writes JSON data to a temporary file and returns the path to it | Below is the the instruction that describes the task:
### Input:
Writes JSON data to a temporary file and returns the path to it
### Response:
def write_json_to_temp_file(data):
"""Writes JSON data to a temporary file and returns the path to it"""
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write... |
def delete_subtrie(self, key):
"""
Given a key prefix, delete the whole subtrie that starts with the key prefix.
Key will be encoded into binary array format first.
It will call `_set` with `if_delete_subtrie` set to True.
"""
validate_is_bytes(key)
self.root_h... | Given a key prefix, delete the whole subtrie that starts with the key prefix.
Key will be encoded into binary array format first.
It will call `_set` with `if_delete_subtrie` set to True. | Below is the the instruction that describes the task:
### Input:
Given a key prefix, delete the whole subtrie that starts with the key prefix.
Key will be encoded into binary array format first.
It will call `_set` with `if_delete_subtrie` set to True.
### Response:
def delete_subtrie(self, key):... |
def AddTask(self,
target,
args=(),
name="Unnamed task",
blocking=True,
inline=True):
"""Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to ta... | Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to target.
name: The name of this task. Used to identify tasks in the log.
blocking: If True we block until the task is finished, otherwise we raise
... | Below is the the instruction that describes the task:
### Input:
Adds a task to be processed later.
Args:
target: A callable which should be processed by one of the workers.
args: A tuple of arguments to target.
name: The name of this task. Used to identify tasks in the log.
blocking: I... |
def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=Tru... | We do not include the mixin as we want only PATCH and no PUT | Below is the the instruction that describes the task:
### Input:
We do not include the mixin as we want only PATCH and no PUT
### Response:
def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """
instance = self.get_object()
serializer = ... |
def open_image(fn):
""" Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
"""
flags = cv2.IMREAD_UNCHANGED+cv2.IMREAD_ANYDEPTH+cv2.IMREAD_ANYCOLO... | Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0 | Below is the the instruction that describes the task:
### Input:
Opens an image using OpenCV given the file path.
Arguments:
fn: the file path of the image
Returns:
The image in RGB format as numpy array of floats normalized to range between 0.0 - 1.0
### Response:
def open_image(fn):
... |
def update(self, request, *args, **kwargs):
"""
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items.
"""
return super(PriceListIte... | Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items. | Below is the the instruction that describes the task:
### Input:
Run **PATCH** request against */api/price-list-items/<uuid>/* to update price list item.
Only item_type, key value and units can be updated.
Only customer owner and staff can update price items.
### Response:
def update(self, request,... |
def date_from_quarter(base_date, ordinal, year):
"""
Extract date from quarter of a year
"""
interval = 3
month_start = interval * (ordinal - 1)
if month_start < 0:
month_start = 9
month_end = month_start + interval
if month_start == 0:
month_start = 1
return [
... | Extract date from quarter of a year | Below is the the instruction that describes the task:
### Input:
Extract date from quarter of a year
### Response:
def date_from_quarter(base_date, ordinal, year):
"""
Extract date from quarter of a year
"""
interval = 3
month_start = interval * (ordinal - 1)
if month_start < 0:
mon... |
def fetch_all_droplet_neighbors(self):
r"""
Returns a generator of all sets of multiple droplets that are running
on the same physical hardware
:rtype: generator of lists of `Droplet`\ s
:raises DOAPIError: if the API endpoint replies with an error
"""
for hood i... | r"""
Returns a generator of all sets of multiple droplets that are running
on the same physical hardware
:rtype: generator of lists of `Droplet`\ s
:raises DOAPIError: if the API endpoint replies with an error | Below is the the instruction that describes the task:
### Input:
r"""
Returns a generator of all sets of multiple droplets that are running
on the same physical hardware
:rtype: generator of lists of `Droplet`\ s
:raises DOAPIError: if the API endpoint replies with an error
### Resp... |
def create_ramp_plan(err, ramp):
"""
Formulate and execute on a plan to slowly add heat or cooling to the system
`err` initial error (PV - SP)
`ramp` the size of the ramp
A ramp plan might yield MVs in this order at every timestep:
[5, 0, 4, 0, 3, 0, 2, 0, 1]
where err == 5 + 4 + 3... | Formulate and execute on a plan to slowly add heat or cooling to the system
`err` initial error (PV - SP)
`ramp` the size of the ramp
A ramp plan might yield MVs in this order at every timestep:
[5, 0, 4, 0, 3, 0, 2, 0, 1]
where err == 5 + 4 + 3 + 2 + 1 | Below is the the instruction that describes the task:
### Input:
Formulate and execute on a plan to slowly add heat or cooling to the system
`err` initial error (PV - SP)
`ramp` the size of the ramp
A ramp plan might yield MVs in this order at every timestep:
[5, 0, 4, 0, 3, 0, 2, 0, 1]
... |
def create_attribute(self,column=None,listType=None,namespace=None, network=None, atype=None, verbose=False):
"""
Creates a new edge column.
:param column (string, optional): Unique name of column
:param listType (string, optional): Can be one of integer, long, double,
or st... | Creates a new edge column.
:param column (string, optional): Unique name of column
:param listType (string, optional): Can be one of integer, long, double,
or string.
:param namespace (string, optional): Node, Edge, and Network objects
support the default, local, and hid... | Below is the the instruction that describes the task:
### Input:
Creates a new edge column.
:param column (string, optional): Unique name of column
:param listType (string, optional): Can be one of integer, long, double,
or string.
:param namespace (string, optional): Node, Edge... |
def eValueToBitScore(eValue, dbSize, dbSequenceCount, queryLength,
lengthAdjustment):
"""
Convert an e-value to a bit score.
@param eValue: The C{float} e-value to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences i... | Convert an e-value to a bit score.
@param eValue: The C{float} e-value to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences in the BLAST database).
@param dbSequenceCount: The C{int} number of sequences in the database.
@param queryLeng... | Below is the the instruction that describes the task:
### Input:
Convert an e-value to a bit score.
@param eValue: The C{float} e-value to convert.
@param dbSize: The C{int} total size of the database (i.e., the sum of
the lengths of all sequences in the BLAST database).
@param dbSequenceCount:... |
def _draw_content(self):
"""
Loop through submissions and fill up the content page.
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
window = self.term.stdscr.derwin(n_rows - self._row - 1, n_cols, self._row, 0)
window.erase()
win_n_rows, win_n_cols = window.getma... | Loop through submissions and fill up the content page. | Below is the the instruction that describes the task:
### Input:
Loop through submissions and fill up the content page.
### Response:
def _draw_content(self):
"""
Loop through submissions and fill up the content page.
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
window =... |
def is_associated_file(self):
# type: () -> bool
'''
A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise.... | A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise. | Below is the the instruction that describes the task:
### Input:
A method to determine whether this file is 'associated' with another file
on the ISO.
Parameters:
None.
Returns:
True if this file is associated with another file on the ISO, False
otherwise.
### Res... |
async def connect(host, port, ssl=None):
'''
Async connect and return a Link().
'''
info = {'host': host, 'port': port, 'ssl': ssl}
reader, writer = await asyncio.open_connection(host, port, ssl=ssl)
return await Link.anit(reader, writer, info=info) | Async connect and return a Link(). | Below is the the instruction that describes the task:
### Input:
Async connect and return a Link().
### Response:
async def connect(host, port, ssl=None):
'''
Async connect and return a Link().
'''
info = {'host': host, 'port': port, 'ssl': ssl}
reader, writer = await asyncio.open_connection(ho... |
def axis(origin_size=0.04,
transform=None,
origin_color=None,
axis_radius=None,
axis_length=None):
"""
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
... | Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation matrix
origin_size : float
Radius of sphere that represents t... | Below is the the instruction that describes the task:
### Input:
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation ma... |
def build_authorization_arg(authdict):
"""
Create an "Authorization" header value from an authdict (created by generate_response()).
"""
vallist = []
for k in authdict.keys():
vallist += ['%s=%s' % (k,authdict[k])]
return 'Digest '+', '.join(vallist) | Create an "Authorization" header value from an authdict (created by generate_response()). | Below is the the instruction that describes the task:
### Input:
Create an "Authorization" header value from an authdict (created by generate_response()).
### Response:
def build_authorization_arg(authdict):
"""
Create an "Authorization" header value from an authdict (created by generate_response()).
"""
v... |
def strict_logical(self, value):
"""Validate and set the strict logical flag."""
if value is not None:
if not isinstance(value, bool):
raise TypeError(
'f90nml: error: strict_logical must be a logical value.')
else:
self._strict... | Validate and set the strict logical flag. | Below is the the instruction that describes the task:
### Input:
Validate and set the strict logical flag.
### Response:
def strict_logical(self, value):
"""Validate and set the strict logical flag."""
if value is not None:
if not isinstance(value, bool):
raise TypeError... |
def _generate_examples(self, images_dir_path):
"""Generate flower images and labels given the image directory path.
Args:
images_dir_path: path to the directory where the images are stored.
Yields:
The image path and its corresponding label.
"""
parent_dir = tf.io.gfile.listdir(images_... | Generate flower images and labels given the image directory path.
Args:
images_dir_path: path to the directory where the images are stored.
Yields:
The image path and its corresponding label. | Below is the the instruction that describes the task:
### Input:
Generate flower images and labels given the image directory path.
Args:
images_dir_path: path to the directory where the images are stored.
Yields:
The image path and its corresponding label.
### Response:
def _generate_examples... |
def blocks_to_mark_complete_on_view(self, blocks):
"""
Returns a set of blocks which should be marked complete on view and haven't been yet.
"""
blocks = {block for block in blocks if self.can_mark_block_complete_on_view(block)}
completions = self.get_completions({block.location ... | Returns a set of blocks which should be marked complete on view and haven't been yet. | Below is the the instruction that describes the task:
### Input:
Returns a set of blocks which should be marked complete on view and haven't been yet.
### Response:
def blocks_to_mark_complete_on_view(self, blocks):
"""
Returns a set of blocks which should be marked complete on view and haven't bee... |
def _find_usage_security_groups(self):
"""find usage for security groups"""
vpc_count = 0
paginator = self.conn.get_paginator('describe_db_security_groups')
for page in paginator.paginate():
for group in page['DBSecurityGroups']:
if 'VpcId' in group and group... | find usage for security groups | Below is the the instruction that describes the task:
### Input:
find usage for security groups
### Response:
def _find_usage_security_groups(self):
"""find usage for security groups"""
vpc_count = 0
paginator = self.conn.get_paginator('describe_db_security_groups')
for page in pag... |
def pem(self):
"""
Serialize in PEM format
"""
bio = Membio()
if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr):
raise CMSError("writing CMS to PEM")
return str(bio) | Serialize in PEM format | Below is the the instruction that describes the task:
### Input:
Serialize in PEM format
### Response:
def pem(self):
"""
Serialize in PEM format
"""
bio = Membio()
if not libcrypto.PEM_write_bio_CMS(bio.bio, self.ptr):
raise CMSError("writing CMS to PEM")
... |
def Read(f):
"""Reads and returns Config data from a yaml file.
Args:
f: Yaml file to parse.
Returns:
Config object as defined in this file.
Raises:
Error (some subclass): If there is a problem loading or parsing the file.
"""
try:
yaml_data = yaml.load(f)
except yaml.YAMLError as e:
... | Reads and returns Config data from a yaml file.
Args:
f: Yaml file to parse.
Returns:
Config object as defined in this file.
Raises:
Error (some subclass): If there is a problem loading or parsing the file. | Below is the the instruction that describes the task:
### Input:
Reads and returns Config data from a yaml file.
Args:
f: Yaml file to parse.
Returns:
Config object as defined in this file.
Raises:
Error (some subclass): If there is a problem loading or parsing the file.
### Response:
def Read... |
def clipped_area(ts, thresh=0, integrator=integrate.trapz):
"""Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nb... | Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://nbviewer.ipython.org/gist/kermit666/5720498
>>> t = ['2014-12-09... | Below is the the instruction that describes the task:
### Input:
Total value * time above the starting value within a TimeSeries
Arguments:
ts (pandas.Series): Time series to be integrated.
thresh (float): Value to clip the tops off at (crossings will be interpolated)
References:
http://... |
def _filter_by_statement(self, statement):
"""Filter the data collection based on a conditional statement."""
self.__class__._check_conditional_statement(statement, 1)
_filt_values, _filt_datetimes = [], []
for i, a in enumerate(self._values):
if eval(statement, {'a': a}):
... | Filter the data collection based on a conditional statement. | Below is the the instruction that describes the task:
### Input:
Filter the data collection based on a conditional statement.
### Response:
def _filter_by_statement(self, statement):
"""Filter the data collection based on a conditional statement."""
self.__class__._check_conditional_statement(state... |
def query(self, query, media=None, year=None, fields=None, extended=None, **kwargs):
"""Search by titles, descriptions, translated titles, aliases, and people.
**Note:** Results are ordered by the most relevant score.
:param query: Search title or description
:type query: :class:`~pyth... | Search by titles, descriptions, translated titles, aliases, and people.
**Note:** Results are ordered by the most relevant score.
:param query: Search title or description
:type query: :class:`~python:str`
:param media: Desired media type (or :code:`None` to return all matching items)... | Below is the the instruction that describes the task:
### Input:
Search by titles, descriptions, translated titles, aliases, and people.
**Note:** Results are ordered by the most relevant score.
:param query: Search title or description
:type query: :class:`~python:str`
:param med... |
def resize_file_to(self, in_path, out_path, keep_filename=False):
""" Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to... | Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to be stored
:return: None | Below is the the instruction that describes the task:
### Input:
Given a filename, resize and save the image per the specification into out_path
:param in_path: path to image file to save. Must be supported by PIL
:param out_path: path to the directory root for the outputted thumbnails to be store... |
def get_number_unit(number):
"""get the unit of number"""
n = str(float(number))
mult, submult = n.split('.')
if float(submult) != 0:
unit = '0.' + (len(submult)-1)*'0' + '1'
return float(unit)
else:
return float(1) | get the unit of number | Below is the the instruction that describes the task:
### Input:
get the unit of number
### Response:
def get_number_unit(number):
"""get the unit of number"""
n = str(float(number))
mult, submult = n.split('.')
if float(submult) != 0:
unit = '0.' + (len(submult)-1)*'0' + '1'
return... |
def html_scientific_notation_rate(rate):
"""Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value with html tag to sho... | Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value with html tag to show the exponent
:rtype: str | Below is the the instruction that describes the task:
### Input:
Helper for convert decimal rate using scientific notation.
For example we want to show the very detail value of fatality rate
because it might be a very small number.
:param rate: Rate value
:type rate: float
:return: Rate value... |
def docker_installed_rpms(broker):
""" Command: /usr/bin/rpm -qa --root `%s` --qf `%s`"""
ctx = broker[DockerImageContext]
root = ctx.root
fmt = DefaultSpecs.rpm_format
cmd = "/usr/bin/rpm -qa --root %s --qf '%s'" % (root, fmt)
result = ctx.shell_out(cmd)
return C... | Command: /usr/bin/rpm -qa --root `%s` --qf `%s` | Below is the the instruction that describes the task:
### Input:
Command: /usr/bin/rpm -qa --root `%s` --qf `%s`
### Response:
def docker_installed_rpms(broker):
""" Command: /usr/bin/rpm -qa --root `%s` --qf `%s`"""
ctx = broker[DockerImageContext]
root = ctx.root
fmt = DefaultSpec... |
def as_batch_body(self):
''' return the current message as expected by batch body format'''
if sys.version_info >= (3,) and isinstance(self.body, bytes):
# It HAS to be string to be serialized in JSON
body = self.body.decode('utf-8')
else:
# Python 2.7 people ... | return the current message as expected by batch body format | Below is the the instruction that describes the task:
### Input:
return the current message as expected by batch body format
### Response:
def as_batch_body(self):
''' return the current message as expected by batch body format'''
if sys.version_info >= (3,) and isinstance(self.body, bytes):
... |
def get_command_line_key_for_unknown_config_file_setting(self, key):
"""Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The con... | Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The config file key that was being set. | Below is the the instruction that describes the task:
### Input:
Compute a commandline arg key to be used for a config file setting
that doesn't correspond to any defined configargparse arg (and so
doesn't have a user-specified commandline arg key).
Args:
key: The config file ke... |
def compare_content_type(url, content_type):
'''
Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html
'''
try:
response = urllib2.urlopen(url)
except... | Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html | Below is the the instruction that describes the task:
### Input:
Compare the content type header of url param with content_type param and returns boolean
@param url -> string e.g. http://127.0.0.1/index
@param content_type -> string e.g. text/html
### Response:
def compare_content_type(url, content_type):... |
def match(self, keys, partial=True):
"""
Check if the value of this namespace is matched by
keys
'*' is treated as wildcard
Arguments:
keys -- list of keys
Examples:
ns = Namespace("a.b.c")
ns.match(["a"]) #True
ns.match(["... | Check if the value of this namespace is matched by
keys
'*' is treated as wildcard
Arguments:
keys -- list of keys
Examples:
ns = Namespace("a.b.c")
ns.match(["a"]) #True
ns.match(["a","b"]) #True
ns.match(["a","b","c"]) #True
... | Below is the the instruction that describes the task:
### Input:
Check if the value of this namespace is matched by
keys
'*' is treated as wildcard
Arguments:
keys -- list of keys
Examples:
ns = Namespace("a.b.c")
ns.match(["a"]) #True
... |
def remove_lb_nodes(self, lb_id, node_ids):
"""
Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids
"""
log.info("Removing load balancer nodes %s" % node_ids)
for node_id in node_ids:
self._request('dele... | Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids | Below is the the instruction that describes the task:
### Input:
Remove one or more nodes
:param string lb_id: Balancer id
:param list node_ids: List of node ids
### Response:
def remove_lb_nodes(self, lb_id, node_ids):
"""
Remove one or more nodes
:param string lb_id: ... |
def tuple_of(*generators):
"""
Generates a tuple by generating values for each of the specified
generators.
This is a class factory, it makes a class which is a closure around the
specified generators.
"""
class TupleOfGenerators(ArbitraryInterface):
"""
A closure class arou... | Generates a tuple by generating values for each of the specified
generators.
This is a class factory, it makes a class which is a closure around the
specified generators. | Below is the the instruction that describes the task:
### Input:
Generates a tuple by generating values for each of the specified
generators.
This is a class factory, it makes a class which is a closure around the
specified generators.
### Response:
def tuple_of(*generators):
"""
Generates a tu... |
def uncompress_file(input_file_name, file_extension, dest_dir):
"""
Uncompress gz and bz2 files
"""
if file_extension.lower() not in ('.gz', '.bz2'):
raise NotImplementedError("Received {} format. Only gz and bz2 "
"files can currently be uncompressed."
... | Uncompress gz and bz2 files | Below is the the instruction that describes the task:
### Input:
Uncompress gz and bz2 files
### Response:
def uncompress_file(input_file_name, file_extension, dest_dir):
"""
Uncompress gz and bz2 files
"""
if file_extension.lower() not in ('.gz', '.bz2'):
raise NotImplementedError("Receive... |
def reverse_lookup_from_nested_dict(values_dict):
"""
Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row... | Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key -> row_key -> sample weight
Returns dictionary mapping row_key ... | Below is the the instruction that describes the task:
### Input:
Create reverse-lookup dictionary mapping each row key to a list of triplets:
[(column key, value), ...]
Parameters
----------
nested_values_dict : dict
column_key -> row_key -> value
weights_dict : dict
column_key... |
def selected(self):
"""Action to be executed when a valid item has been selected"""
self.selected_text = self.currentText()
self.valid.emit(True, True)
self.open_dir.emit(self.selected_text) | Action to be executed when a valid item has been selected | Below is the the instruction that describes the task:
### Input:
Action to be executed when a valid item has been selected
### Response:
def selected(self):
"""Action to be executed when a valid item has been selected"""
self.selected_text = self.currentText()
self.valid.emit(True, True)... |
def load_from_json(data):
"""
Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parsed as json).
"""
if isinstance(data, str):
data = json.loads(data)
applications = [
ApplicationResponse.load_from_json(a) for a in data['a... | Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parsed as json). | Below is the the instruction that describes the task:
### Input:
Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parsed as json).
### Response:
def load_from_json(data):
"""
Load a :class:`RegistryReponse` from a dictionary or a string (that
will be parse... |
def digest_content(self, rule):
"""
Walk on rule content tokens to return a dict of properties.
This is pretty naive and will choke/fail on everything that is more
evolved than simple ``ident(string):value(string)``
Arguments:
rule (tinycss2.ast.QualifiedRule): Qual... | Walk on rule content tokens to return a dict of properties.
This is pretty naive and will choke/fail on everything that is more
evolved than simple ``ident(string):value(string)``
Arguments:
rule (tinycss2.ast.QualifiedRule): Qualified rule object as
returned by ti... | Below is the the instruction that describes the task:
### Input:
Walk on rule content tokens to return a dict of properties.
This is pretty naive and will choke/fail on everything that is more
evolved than simple ``ident(string):value(string)``
Arguments:
rule (tinycss2.ast.Qua... |
def walk_direction_preheel(self, data_frame):
"""
Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data f... | Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data frame. It should have x, y, and z columns.
:type data_frame:... | Below is the the instruction that describes the task:
### Input:
Estimate local walk (not cardinal) direction with pre-heel strike phase.
Inspired by Nirupam Roy's B.E. thesis: "WalkCompass: Finding Walking Direction Leveraging Smartphone's Inertial Sensors"
:param data_frame: The data fra... |
def ctcp_reply(self, command, dst, message=None):
"""
Sends a reply to a CTCP request.
:param command: CTCP command to use.
:type command: str
:param dst: sender of the initial request.
:type dst: str
:param message: data to attach to the reply.
:type mes... | Sends a reply to a CTCP request.
:param command: CTCP command to use.
:type command: str
:param dst: sender of the initial request.
:type dst: str
:param message: data to attach to the reply.
:type message: str | Below is the the instruction that describes the task:
### Input:
Sends a reply to a CTCP request.
:param command: CTCP command to use.
:type command: str
:param dst: sender of the initial request.
:type dst: str
:param message: data to attach to the reply.
:type mess... |
def __set_style_sheet(self):
"""
Sets the Widget stylesheet.
"""
colors = map(
lambda x: "rgb({0}, {1}, {2}, {3})".format(x.red(), x.green(), x.blue(), int(self.__opacity * 255)),
(self.__color, self.__background_color, self.__border_color))
self.setStyle... | Sets the Widget stylesheet. | Below is the the instruction that describes the task:
### Input:
Sets the Widget stylesheet.
### Response:
def __set_style_sheet(self):
"""
Sets the Widget stylesheet.
"""
colors = map(
lambda x: "rgb({0}, {1}, {2}, {3})".format(x.red(), x.green(), x.blue(), int(self.__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.