code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def no_results(channel):
"""Creates an embed UI for when there were no results
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
"""
gui = ui_embed.UI(
channel,
"No results",
":c",
... | Creates an embed UI for when there were no results
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object | Below is the the instruction that describes the task:
### Input:
Creates an embed UI for when there were no results
Args:
channel (discord.Channel): The Discord channel to bind the embed to
Returns:
ui (ui_embed.UI): The embed UI object
### Response:
def no_results(channel):
"""Create... |
def remove_pending_work_units(self, work_spec_name, work_unit_names):
'''Remove some work units in the pending list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work un... | Remove some work units in the pending list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work units will be.
Note that this function has the potential to confuse worker... | Below is the the instruction that describes the task:
### Input:
Remove some work units in the pending list.
If `work_unit_names` is :const:`None` (which must be passed
explicitly), all pending work units in `work_spec_name` are
removed; otherwise only the specific named work units will be.... |
def get_all_publications(return_namedtuples=True):
"""
Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Ret... | Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
Returns:
list: List of :class:`.Publication` structures co... | Below is the the instruction that describes the task:
### Input:
Get list publications from all available source.
Args:
return_namedtuples (bool, default True): Convert :class:`.Publication`
structures to namedtuples (used in AMQP
communication).
... |
def determineMaxWindowSize(dtype, limit=None):
"""
Determines the largest square window size that can be used, based on
the specified datatype and amount of currently available system memory.
If `limit` is specified, then this value will be returned in the event
that it is smaller than the maximum computed size.... | Determines the largest square window size that can be used, based on
the specified datatype and amount of currently available system memory.
If `limit` is specified, then this value will be returned in the event
that it is smaller than the maximum computed size. | Below is the the instruction that describes the task:
### Input:
Determines the largest square window size that can be used, based on
the specified datatype and amount of currently available system memory.
If `limit` is specified, then this value will be returned in the event
that it is smaller than the maximu... |
def get_frames(tback, is_breakpoint):
"""Builds a list of ErrorFrame objects from a traceback"""
frames = []
while tback is not None:
if tback.tb_next is None and is_breakpoint:
break
filename = tback.tb_frame.f_code.co_filename
function = tback.tb_frame.f_code.co_name... | Builds a list of ErrorFrame objects from a traceback | Below is the the instruction that describes the task:
### Input:
Builds a list of ErrorFrame objects from a traceback
### Response:
def get_frames(tback, is_breakpoint):
"""Builds a list of ErrorFrame objects from a traceback"""
frames = []
while tback is not None:
if tback.tb_next is None an... |
def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs):
"""Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyC... | Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyChord uses -1e+30
and MultiNest -0.179769313486231571E+309). However in... | Below is the the instruction that describes the task:
### Input:
Maps the iso-likelihood contours on which points were born to the
index of the dead point on this contour.
MultiNest and PolyChord use different values to identify the inital live
points which were sampled from the whole prior (PolyChord ... |
def get_field_for_object(field_type, field_id, form):
'''
This tag allows one to get a specific series or event form field
in registration views.
'''
field_name = field_type + '_' + str(field_id)
return form.__getitem__(field_name) | This tag allows one to get a specific series or event form field
in registration views. | Below is the the instruction that describes the task:
### Input:
This tag allows one to get a specific series or event form field
in registration views.
### Response:
def get_field_for_object(field_type, field_id, form):
'''
This tag allows one to get a specific series or event form field
in re... |
def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
try:
stopwords = pkgutil.get_data("justext", file_path)
except IOError:
raise ValueError(
"Stoplist for language '%s'... | Returns an built-in stop-list for the language as a set of words. | Below is the the instruction that describes the task:
### Input:
Returns an built-in stop-list for the language as a set of words.
### Response:
def get_stoplist(language):
"""Returns an built-in stop-list for the language as a set of words."""
file_path = os.path.join("stoplists", "%s.txt" % language)
... |
def get_random_cached_bottlenecks(sess, image_lists, how_many, category,
bottleneck_dir, image_dir, jpeg_data_tensor,
decoded_image_tensor, resized_input_tensor,
bottleneck_tensor, module_name):
"""Retrieves bottlene... | Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
sess: Current TensorFlow Session.
image_lists: OrderedDict of tr... | Below is the the instruction that describes the task:
### Input:
Retrieves bottleneck values for cached images.
If no distortions are being applied, this function can retrieve the cached
bottleneck values directly from disk for images. It picks a random set of
images from the specified category.
Args:
... |
def json_charts(self, req):
""" Return charting data.
"""
disk_used, disk_total, disk_detail = 0, 0, []
for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep):
disk_usage = self.guarded(psutil.disk_usage, os.path.expanduser(disk_usage_path.strip()))
if ... | Return charting data. | Below is the the instruction that describes the task:
### Input:
Return charting data.
### Response:
def json_charts(self, req):
""" Return charting data.
"""
disk_used, disk_total, disk_detail = 0, 0, []
for disk_usage_path in self.cfg.disk_usage_path.split(os.pathsep):
... |
def change_breakpoint_state(self, bp_number, enabled, condition=None):
""" Change breakpoint status or `condition` expression.
:param bp_number: number of breakpoint to change
:return: None or an error message (string)
"""
if not (0 <= bp_number < len(IKBreakpoint.break... | Change breakpoint status or `condition` expression.
:param bp_number: number of breakpoint to change
:return: None or an error message (string) | Below is the the instruction that describes the task:
### Input:
Change breakpoint status or `condition` expression.
:param bp_number: number of breakpoint to change
:return: None or an error message (string)
### Response:
def change_breakpoint_state(self, bp_number, enabled, condition=No... |
def lstm_area_attention_base():
"""Hparams for LSTM with area attention."""
hparams = lstm_luong_attention()
hparams.batch_size = 16384
hparams.num_hidden_layers = 2
hparams.hidden_size = 1024
hparams.num_heads = 4
hparams.dropout = 0.2
hparams.learning_rate = 0.1
hparams.max_area_width = 2
hparams.... | Hparams for LSTM with area attention. | Below is the the instruction that describes the task:
### Input:
Hparams for LSTM with area attention.
### Response:
def lstm_area_attention_base():
"""Hparams for LSTM with area attention."""
hparams = lstm_luong_attention()
hparams.batch_size = 16384
hparams.num_hidden_layers = 2
hparams.hidden_size = ... |
def connect(self):
"""Logs into the specified ftp server and returns connector."""
for tried_connection_count in range(CFG_FTP_CONNECTION_ATTEMPTS):
try:
self.ftp = FtpHandler(self.config.OXFORD.URL,
self.config.OXFORD.LOGIN,
... | Logs into the specified ftp server and returns connector. | Below is the the instruction that describes the task:
### Input:
Logs into the specified ftp server and returns connector.
### Response:
def connect(self):
"""Logs into the specified ftp server and returns connector."""
for tried_connection_count in range(CFG_FTP_CONNECTION_ATTEMPTS):
t... |
def stop(self, ignore_state=False):
"""Stops the service."""
self.logger.debug("Stop service")
self._toggle_running(False, ignore_state) | Stops the service. | Below is the the instruction that describes the task:
### Input:
Stops the service.
### Response:
def stop(self, ignore_state=False):
"""Stops the service."""
self.logger.debug("Stop service")
self._toggle_running(False, ignore_state) |
def update_or_create(cls, org, provider, exists):
"""
Update or create credentials state.
"""
instance, created = cls.objects.update_or_create(
org=org,
provider=provider,
defaults={'exists': exists},
)
return instance, created | Update or create credentials state. | Below is the the instruction that describes the task:
### Input:
Update or create credentials state.
### Response:
def update_or_create(cls, org, provider, exists):
"""
Update or create credentials state.
"""
instance, created = cls.objects.update_or_create(
org=org,
... |
def fetch(self, webfonts):
"""
Store every defined webfonts.
Webfont are stored with sort on their name.
Args:
webfonts (dict): Dictionnary of webfont settings from
``settings.ICOMOON_WEBFONTS``.
"""
sorted_keys = sorted(webfonts.keys())
... | Store every defined webfonts.
Webfont are stored with sort on their name.
Args:
webfonts (dict): Dictionnary of webfont settings from
``settings.ICOMOON_WEBFONTS``. | Below is the the instruction that describes the task:
### Input:
Store every defined webfonts.
Webfont are stored with sort on their name.
Args:
webfonts (dict): Dictionnary of webfont settings from
``settings.ICOMOON_WEBFONTS``.
### Response:
def fetch(self, webfonts)... |
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)):
"""Remove long expired full_hash entries."""
q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timestamp, '-{} SECONDS')
'''
log.info('Cleaning up full_hash entries expired more than {} seconds ago.'.format(ke... | Remove long expired full_hash entries. | Below is the the instruction that describes the task:
### Input:
Remove long expired full_hash entries.
### Response:
def cleanup_full_hashes(self, keep_expired_for=(60 * 60 * 12)):
"""Remove long expired full_hash entries."""
q = '''DELETE FROM full_hash WHERE expires_at < datetime(current_timesta... |
def TryCompile( self, text, extension):
"""Compiles the program given in text to an env.Object, using extension
as file extension (e.g. '.c'). Returns 1, if compilation was
successful, 0 otherwise. The target is saved in self.lastTarget (for
further processing).
"""
retur... | Compiles the program given in text to an env.Object, using extension
as file extension (e.g. '.c'). Returns 1, if compilation was
successful, 0 otherwise. The target is saved in self.lastTarget (for
further processing). | Below is the the instruction that describes the task:
### Input:
Compiles the program given in text to an env.Object, using extension
as file extension (e.g. '.c'). Returns 1, if compilation was
successful, 0 otherwise. The target is saved in self.lastTarget (for
further processing).
### Res... |
def detect_images_and_tex(
file_list,
allowed_image_types=('eps', 'png', 'ps', 'jpg', 'pdf'),
timeout=20):
"""Detect from a list of files which are TeX or images.
:param: file_list (list): list of absolute file paths
:param: allowed_image_types (list): list of allows image formats
... | Detect from a list of files which are TeX or images.
:param: file_list (list): list of absolute file paths
:param: allowed_image_types (list): list of allows image formats
:param: timeout (int): the timeout value on shell commands.
:return: (image_list, tex_file) (([string, string, ...], string)):
... | Below is the the instruction that describes the task:
### Input:
Detect from a list of files which are TeX or images.
:param: file_list (list): list of absolute file paths
:param: allowed_image_types (list): list of allows image formats
:param: timeout (int): the timeout value on shell commands.
:... |
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
... | Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None | Below is the the instruction that describes the task:
### Input:
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
... |
def fill_opacity(self, opacity):
"""
:param opacity: 0.0 ~ 1.0
"""
opacity = pgmagick.DrawableFillOpacity(float(opacity))
self.drawer.append(opacity) | :param opacity: 0.0 ~ 1.0 | Below is the the instruction that describes the task:
### Input:
:param opacity: 0.0 ~ 1.0
### Response:
def fill_opacity(self, opacity):
"""
:param opacity: 0.0 ~ 1.0
"""
opacity = pgmagick.DrawableFillOpacity(float(opacity))
self.drawer.append(opacity) |
def all_cities():
"""
Get a list of all Backpage city names.
Returns:
list of city names as Strings
"""
cities = []
fname = pkg_resources.resource_filename(__name__, 'resources/CityPops.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')
for row in reader:
... | Get a list of all Backpage city names.
Returns:
list of city names as Strings | Below is the the instruction that describes the task:
### Input:
Get a list of all Backpage city names.
Returns:
list of city names as Strings
### Response:
def all_cities():
"""
Get a list of all Backpage city names.
Returns:
list of city names as Strings
"""
cities = []
fname = pkg_resour... |
def get_root(root, phonetic, compound):
"""Get the root form without markers.
Parameters
----------
root: str
The word root form.
phonetic: boolean
If True, add phonetic information to the root forms.
compound: boolean
if True, add compound word markers to root forms.
... | Get the root form without markers.
Parameters
----------
root: str
The word root form.
phonetic: boolean
If True, add phonetic information to the root forms.
compound: boolean
if True, add compound word markers to root forms. | Below is the the instruction that describes the task:
### Input:
Get the root form without markers.
Parameters
----------
root: str
The word root form.
phonetic: boolean
If True, add phonetic information to the root forms.
compound: boolean
if True, add compound word mar... |
def _coord2offset(self, coord):
"""Convert a normalized coordinate to an item offset."""
size = self.size
offset = 0
for dim, index in enumerate(coord):
size //= self._normshape[dim]
offset += size * index
return offset | Convert a normalized coordinate to an item offset. | Below is the the instruction that describes the task:
### Input:
Convert a normalized coordinate to an item offset.
### Response:
def _coord2offset(self, coord):
"""Convert a normalized coordinate to an item offset."""
size = self.size
offset = 0
for dim, index in enumerate(coord):
... |
def create_rack(self):
"""Get an instance of rack services facade."""
return Rack(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | Get an instance of rack services facade. | Below is the the instruction that describes the task:
### Input:
Get an instance of rack services facade.
### Response:
def create_rack(self):
"""Get an instance of rack services facade."""
return Rack(
self.networkapi_url,
self.user,
self.password,
s... |
def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
'''
idxstore = IndexStore()
idxstore._val2i = term_to_index_dict
idxstore._next_i = len(term_to_index_dict)
idxstore._i2val = [None for _ in range(idxstore._next_i)]
... | Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore | Below is the the instruction that describes the task:
### Input:
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
IndexStore
### Response:
def build(term_to_index_dict):
'''
Parameters
----------
term_to_index_dict: term -> idx dictionary
Returns
-------
In... |
def terminateMember(self, clusterId, memberId):
"""
Parameters:
- clusterId
- memberId
"""
self.send_terminateMember(clusterId, memberId)
return self.recv_terminateMember() | Parameters:
- clusterId
- memberId | Below is the the instruction that describes the task:
### Input:
Parameters:
- clusterId
- memberId
### Response:
def terminateMember(self, clusterId, memberId):
"""
Parameters:
- clusterId
- memberId
"""
self.send_terminateMember(clusterId, membe... |
def add_interrupt(self, interrupt):
"""
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants.
"""
self.interrupts.append(interrupt)
self.constants[interrupt.name] = interrupt.address | Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants. | Below is the the instruction that describes the task:
### Input:
Adds the interrupt to the internal interrupt storage ``self.interrupts`` and
registers the interrupt address in the internal constants.
### Response:
def add_interrupt(self, interrupt):
"""
Adds the interrupt to the internal interrupt storage `... |
def handle_exception(self, frame, exc_info):
"""This function is called if an exception occurs,
but only if we are to stop at or just below this level."""
type_, value, tb = exc_info
# Python 3 is broken see http://bugs.python.org/issue17413
_value = value
if not isinstan... | This function is called if an exception occurs,
but only if we are to stop at or just below this level. | Below is the the instruction that describes the task:
### Input:
This function is called if an exception occurs,
but only if we are to stop at or just below this level.
### Response:
def handle_exception(self, frame, exc_info):
"""This function is called if an exception occurs,
but only if ... |
def stream(self, code):
"""Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code.
"""
self._say("Streaming code.")
if type(code) in [str, text_type]:
code = code.split... | Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code. | Below is the the instruction that describes the task:
### Input:
Stream in RiveScript source code dynamically.
:param code: Either a string containing RiveScript code or an array of
lines of RiveScript code.
### Response:
def stream(self, code):
"""Stream in RiveScript source code dyna... |
def to_json(self, version=Version.latest):
"""Tries to convert an object into a JSON representation and return
the resulting string
An Object can define how it is serialized by overriding the as_version()
implementation. A caller may further define how the object is serialized
b... | Tries to convert an object into a JSON representation and return
the resulting string
An Object can define how it is serialized by overriding the as_version()
implementation. A caller may further define how the object is serialized
by passing in a custom encoder. The default encoder wil... | Below is the the instruction that describes the task:
### Input:
Tries to convert an object into a JSON representation and return
the resulting string
An Object can define how it is serialized by overriding the as_version()
implementation. A caller may further define how the object is seria... |
def xdr(self):
"""Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
"""
kp = Xdr.StellarXDRPacker()
kp.pack_Pu... | Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure. | Below is the the instruction that describes the task:
### Input:
Generate base64 encoded XDR PublicKey object.
Return a base64 encoded PublicKey XDR object, for sending over the wire
when interacting with stellar.
:return: The base64 encoded PublicKey XDR structure.
### Response:
def xdr(... |
def get_saver(scope, collections=(tf.GraphKeys.GLOBAL_VARIABLES,), # pylint: disable=redefined-outer-name
context=None, **kwargs):
"""Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same... | Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same variables to be restored into another similar scope or
module using a complementary `tf.train.Saver` object.
Args:
scope: Scope or module. Va... | Below is the the instruction that describes the task:
### Input:
Builds a `tf.train.Saver` for the scope or module, with normalized names.
The names of the variables are normalized to remove the scope prefix.
This allows the same variables to be restored into another similar scope or
module using a complemen... |
def _check_custom_url_parameters(self):
"""Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter.
"""
for param in self.custom_url_params:
if param not in CustomUrlParam:
raise ValueError('P... | Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter. | Below is the the instruction that describes the task:
### Input:
Checks if custom url parameters are valid parameters.
Throws ValueError if the provided parameter is not a valid parameter.
### Response:
def _check_custom_url_parameters(self):
"""Checks if custom url parameters are valid parameters... |
def read_features(self, tol=1e-3):
"""Reads the features from a file and stores them in the current
object.
Parameters
----------
tol: float
Tolerance level to detect duration of audio.
"""
try:
# Read JSON file
with open(self.... | Reads the features from a file and stores them in the current
object.
Parameters
----------
tol: float
Tolerance level to detect duration of audio. | Below is the the instruction that describes the task:
### Input:
Reads the features from a file and stores them in the current
object.
Parameters
----------
tol: float
Tolerance level to detect duration of audio.
### Response:
def read_features(self, tol=1e-3):
... |
def random(*args):
"""
Counts up sequentially from a number based on the current time
:rtype int:
"""
current_frame = inspect.currentframe().f_back
trace_string = ""
while current_frame.f_back:
trace_string = trace_string + current_frame.f_back.f_code.co_name
current_fr... | Counts up sequentially from a number based on the current time
:rtype int: | Below is the the instruction that describes the task:
### Input:
Counts up sequentially from a number based on the current time
:rtype int:
### Response:
def random(*args):
"""
Counts up sequentially from a number based on the current time
:rtype int:
"""
current_frame = inspect.curre... |
def create_transaction(self, to_account):
"""Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transacti... | Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The account the transaction is into / out of.
Returns:
Tr... | Below is the the instruction that describes the task:
### Input:
Create a transaction for this statement amount and account, into to_account
This will also set this StatementLine's ``transaction`` attribute to the newly
created transaction.
Args:
to_account (Account): The accou... |
def run(self):
""" This defines the sequence of actions that are taken when the hierarchy is executed. A hierarchy state
executes all its child states recursively. Principally this code collects all input data for the next
child state, executes it, stores its output data and determines the next ... | This defines the sequence of actions that are taken when the hierarchy is executed. A hierarchy state
executes all its child states recursively. Principally this code collects all input data for the next
child state, executes it, stores its output data and determines the next state
based on the ... | Below is the the instruction that describes the task:
### Input:
This defines the sequence of actions that are taken when the hierarchy is executed. A hierarchy state
executes all its child states recursively. Principally this code collects all input data for the next
child state, executes it, store... |
def fetch_by_coord(self,coord):
"""get a single entry by the coordinate location [blockStart, innerStart]
.. warning:: creates a new instance of a BAMFile object when maybe the one we had would have worked
"""
#print coord
#print self.path
#b2 = BAMFile(self.path,blockStart=coord[0],innerStart=... | get a single entry by the coordinate location [blockStart, innerStart]
.. warning:: creates a new instance of a BAMFile object when maybe the one we had would have worked | Below is the the instruction that describes the task:
### Input:
get a single entry by the coordinate location [blockStart, innerStart]
.. warning:: creates a new instance of a BAMFile object when maybe the one we had would have worked
### Response:
def fetch_by_coord(self,coord):
"""get a single entry by... |
def orbit_posvel(Ms,eccs,semimajors,mreds,obspos=None):
"""returns positions in projected AU and velocities in km/s for given mean anomalies
Returns positions and velocities as SkyCoord objects. Uses
``orbitutils.kepler.Efn`` to calculate eccentric anomalies using interpolation.
Parameters
--... | returns positions in projected AU and velocities in km/s for given mean anomalies
Returns positions and velocities as SkyCoord objects. Uses
``orbitutils.kepler.Efn`` to calculate eccentric anomalies using interpolation.
Parameters
----------
Ms, eccs, semimajors, mreds : float or array-like
... | Below is the the instruction that describes the task:
### Input:
returns positions in projected AU and velocities in km/s for given mean anomalies
Returns positions and velocities as SkyCoord objects. Uses
``orbitutils.kepler.Efn`` to calculate eccentric anomalies using interpolation.
Parameters
... |
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''
Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
'''
raise EvaluateException("Unimplemented evaluation", sw.Backtrace(elt)) | Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize | Below is the the instruction that describes the task:
### Input:
Parameters:
elt -- the current DOMWrapper element
sw -- soapWriter object
pyobj -- python object to serialize
### Response:
def serialize(self, elt, sw, pyobj, name=None, orig=None, **kw):
'''
Paramet... |
def collect_tokens(cls, parseresult, mode):
"""
Collect the tokens from a (potentially) nested parse result.
"""
inner = '(%s)' if mode=='parens' else '[%s]'
if parseresult is None: return []
tokens = []
for token in parseresult.asList():
# If value is... | Collect the tokens from a (potentially) nested parse result. | Below is the the instruction that describes the task:
### Input:
Collect the tokens from a (potentially) nested parse result.
### Response:
def collect_tokens(cls, parseresult, mode):
"""
Collect the tokens from a (potentially) nested parse result.
"""
inner = '(%s)' if mode=='paren... |
def merge( self, other_cluster ):
"""
Combine two clusters into a single cluster.
Args:
other_cluster (Cluster): The second cluster to combine.
Returns:
(Cluster): The combination of both clusters.
"""
new_cluster = Cluster( self.sites | other_... | Combine two clusters into a single cluster.
Args:
other_cluster (Cluster): The second cluster to combine.
Returns:
(Cluster): The combination of both clusters. | Below is the the instruction that describes the task:
### Input:
Combine two clusters into a single cluster.
Args:
other_cluster (Cluster): The second cluster to combine.
Returns:
(Cluster): The combination of both clusters.
### Response:
def merge( self, other_cluster )... |
def uncancel_invoice(self, invoice_id):
"""
Uncancelles an invoice
:param invoice_id: the invoice id
"""
return self._create_put_request(
resource=INVOICES,
billomat_id=invoice_id,
command=UNCANCEL,
) | Uncancelles an invoice
:param invoice_id: the invoice id | Below is the the instruction that describes the task:
### Input:
Uncancelles an invoice
:param invoice_id: the invoice id
### Response:
def uncancel_invoice(self, invoice_id):
"""
Uncancelles an invoice
:param invoice_id: the invoice id
"""
return self._create_put_... |
def summarize(manager: Manager):
"""Summarize the contents of the database."""
click.echo('Networks: {}'.format(manager.count_networks()))
click.echo('Edges: {}'.format(manager.count_edges()))
click.echo('Nodes: {}'.format(manager.count_nodes()))
click.echo('Namespaces: {}'.format(manager.count_name... | Summarize the contents of the database. | Below is the the instruction that describes the task:
### Input:
Summarize the contents of the database.
### Response:
def summarize(manager: Manager):
"""Summarize the contents of the database."""
click.echo('Networks: {}'.format(manager.count_networks()))
click.echo('Edges: {}'.format(manager.count_e... |
def client_receives_binary(self, name=None, timeout=None, label=None):
"""Receive raw binary message.
If client `name` is not given, uses the latest client. Optional message
`label` is shown on logs.
Examples:
| ${binary} = | Client receives binary |
| ${binary} = | Cli... | Receive raw binary message.
If client `name` is not given, uses the latest client. Optional message
`label` is shown on logs.
Examples:
| ${binary} = | Client receives binary |
| ${binary} = | Client receives binary | Client1 | timeout=5 | | Below is the the instruction that describes the task:
### Input:
Receive raw binary message.
If client `name` is not given, uses the latest client. Optional message
`label` is shown on logs.
Examples:
| ${binary} = | Client receives binary |
| ${binary} = | Client receives ... |
def fso_exists(self, path):
'overlays os.path.exists()'
try:
return self._exists(self.deref(path))
except os.error:
return False | overlays os.path.exists() | Below is the the instruction that describes the task:
### Input:
overlays os.path.exists()
### Response:
def fso_exists(self, path):
'overlays os.path.exists()'
try:
return self._exists(self.deref(path))
except os.error:
return False |
def get_external_commands_from_arbiters(self):
"""Get external commands from our arbiters
As of now, only the arbiter are requested to provide their external commands that
the receiver will push to all the known schedulers to make them being executed.
:return: None
"""
... | Get external commands from our arbiters
As of now, only the arbiter are requested to provide their external commands that
the receiver will push to all the known schedulers to make them being executed.
:return: None | Below is the the instruction that describes the task:
### Input:
Get external commands from our arbiters
As of now, only the arbiter are requested to provide their external commands that
the receiver will push to all the known schedulers to make them being executed.
:return: None
### Respo... |
def configure(working_dir, config_file=None, force=False, interactive=False):
"""
Configure blockstack: find and store configuration parameters to the config file.
Optionally prompt for missing data interactively (with interactive=True). Or, raise an exception
if there are any fields missing.
Optiona... | Configure blockstack: find and store configuration parameters to the config file.
Optionally prompt for missing data interactively (with interactive=True). Or, raise an exception
if there are any fields missing.
Optionally force a re-prompting for all configuration details (with force=True)
Return {'bl... | Below is the the instruction that describes the task:
### Input:
Configure blockstack: find and store configuration parameters to the config file.
Optionally prompt for missing data interactively (with interactive=True). Or, raise an exception
if there are any fields missing.
Optionally force a re-prom... |
def mod_root(a, p):
""" Return a root of `a' modulo p """
if a == 0:
return 0
if not mod_issquare(a, p):
raise ValueError
n = 2
while mod_issquare(n, p):
n += 1
q = p - 1
r = 0
while not q.getbit(r):
r += 1
q = q >> r
y = pow(n, q, p)
h = q >> ... | Return a root of `a' modulo p | Below is the the instruction that describes the task:
### Input:
Return a root of `a' modulo p
### Response:
def mod_root(a, p):
""" Return a root of `a' modulo p """
if a == 0:
return 0
if not mod_issquare(a, p):
raise ValueError
n = 2
while mod_issquare(n, p):
n += 1
... |
def GetMethod(self, name, descriptor):
"""
.. deprecated:: 3.1.0
Use :meth:`get_method` instead.
"""
warnings.warn("deprecated, use get_method instead. This function might be removed in a later release!", DeprecationWarning)
return self.get_method(name, descriptor) | .. deprecated:: 3.1.0
Use :meth:`get_method` instead. | Below is the the instruction that describes the task:
### Input:
.. deprecated:: 3.1.0
Use :meth:`get_method` instead.
### Response:
def GetMethod(self, name, descriptor):
"""
.. deprecated:: 3.1.0
Use :meth:`get_method` instead.
"""
warnings.warn("deprecate... |
def add_route(route, endpoint=None, **kw):
"""Add a new JSON API route
"""
# ensure correct amout of slashes
def apiurl(route):
return '/'.join(s.strip('/') for s in ["", BASE_URL, route])
return add_senaite_route(apiurl(route), endpoint, **kw) | Add a new JSON API route | Below is the the instruction that describes the task:
### Input:
Add a new JSON API route
### Response:
def add_route(route, endpoint=None, **kw):
"""Add a new JSON API route
"""
# ensure correct amout of slashes
def apiurl(route):
return '/'.join(s.strip('/') for s in ["", BASE_URL, route... |
async def retry_async(self, func, partition_id, retry_message,
final_failure_message, max_retries, host_id):
"""
Throws if it runs out of retries. If it returns, action succeeded.
"""
created_okay = False
retry_count = 0
while not created_okay an... | Throws if it runs out of retries. If it returns, action succeeded. | Below is the the instruction that describes the task:
### Input:
Throws if it runs out of retries. If it returns, action succeeded.
### Response:
async def retry_async(self, func, partition_id, retry_message,
final_failure_message, max_retries, host_id):
"""
Throws if it r... |
def stack_call(self, *args):
"""Stacks a redis command inside the object.
The syntax is the same than the call() method a Client class.
Args:
*args: full redis command as variable length argument list.
Examples:
>>> pipeline = Pipeline()
>>> pipelin... | Stacks a redis command inside the object.
The syntax is the same than the call() method a Client class.
Args:
*args: full redis command as variable length argument list.
Examples:
>>> pipeline = Pipeline()
>>> pipeline.stack_call("HSET", "key", "field", "va... | Below is the the instruction that describes the task:
### Input:
Stacks a redis command inside the object.
The syntax is the same than the call() method a Client class.
Args:
*args: full redis command as variable length argument list.
Examples:
>>> pipeline = Pipel... |
def get_keys(self, transport, bucket, timeout=None):
"""
get_keys(bucket, timeout=None)
Lists all keys in a bucket.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: This request is automatically re... | get_keys(bucket, timeout=None)
Lists all keys in a bucket.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: This request is automatically retried :attr:`retries`
times if it fails due to network error.
... | Below is the the instruction that describes the task:
### Input:
get_keys(bucket, timeout=None)
Lists all keys in a bucket.
.. warning:: Do not use this in production, as it requires
traversing through all keys stored in a cluster.
.. note:: This request is automatically retrie... |
def obfn_gvar(self):
"""This method is inserted into the inner cbpdn object,
replacing its own obfn_gvar method, thereby providing a hook for
applying the additional steps necessary for the AMS method.
"""
# Get inner cbpdn object gvar
gv = self.inner_obfn_gvar().copy()
... | This method is inserted into the inner cbpdn object,
replacing its own obfn_gvar method, thereby providing a hook for
applying the additional steps necessary for the AMS method. | Below is the the instruction that describes the task:
### Input:
This method is inserted into the inner cbpdn object,
replacing its own obfn_gvar method, thereby providing a hook for
applying the additional steps necessary for the AMS method.
### Response:
def obfn_gvar(self):
"""This metho... |
def is_same_file(path1, path2):
"""Return True if path1 is the same file as path2.
The reason for this dance is that samefile throws if either file doesn't
exist.
Args:
path1: str or path-like.
path2: str or path-like.
Returns:
bool. True if the same file, False if not.
... | Return True if path1 is the same file as path2.
The reason for this dance is that samefile throws if either file doesn't
exist.
Args:
path1: str or path-like.
path2: str or path-like.
Returns:
bool. True if the same file, False if not. | Below is the the instruction that describes the task:
### Input:
Return True if path1 is the same file as path2.
The reason for this dance is that samefile throws if either file doesn't
exist.
Args:
path1: str or path-like.
path2: str or path-like.
Returns:
bool. True if t... |
def getRoom(self, _id):
""" Retrieve a room from it's id """
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
return SockJSRoomHandler._room[self._gcls() + _id]
return None | Retrieve a room from it's id | Below is the the instruction that describes the task:
### Input:
Retrieve a room from it's id
### Response:
def getRoom(self, _id):
""" Retrieve a room from it's id """
if SockJSRoomHandler._room.has_key(self._gcls() + _id):
return SockJSRoomHandler._room[self._gcls() + _id]
ret... |
def modified_lines(filename, extra_data, commit=None):
"""Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not modified.
commit: th... | Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not modified.
commit: the complete sha1 (40 chars) of the commit. Note that specifying... | Below is the the instruction that describes the task:
### Input:
Returns the lines that have been modifed for this file.
Args:
filename: the file to check.
extra_data: is the extra_data returned by modified_files. Additionally, a
value of None means that the file was not modified.
com... |
def compare_pointer(self, data):
'''
Compares the string data
@return: True if the data is different
'''
if self.old_pointed != data:
self.old_pointed = data
return True
return False | Compares the string data
@return: True if the data is different | Below is the the instruction that describes the task:
### Input:
Compares the string data
@return: True if the data is different
### Response:
def compare_pointer(self, data):
'''
Compares the string data
@return: True if the data is different
'''
if self.old_pointed... |
def isexec(path):
'''
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
'''
return os.path.isfile(path) and os.access(path, os.X_OK) | Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Check if given path points to an executable file.
:param path: file path
:type path: str
:return: True if executable, False otherwise
:rtype: bool
### Response:
def isexec(path):
'''
Check if given path points to an executabl... |
def isometric_remesh(script, SamplingRate=10):
"""Isometric parameterization: remeshing
"""
filter_xml = ''.join([
' <filter name="Iso Parametrization Remeshing">\n',
' <Param name="SamplingRate"',
'value="%d"' % SamplingRate,
'description="Sampling Rate"',
'type... | Isometric parameterization: remeshing | Below is the the instruction that describes the task:
### Input:
Isometric parameterization: remeshing
### Response:
def isometric_remesh(script, SamplingRate=10):
"""Isometric parameterization: remeshing
"""
filter_xml = ''.join([
' <filter name="Iso Parametrization Remeshing">\n',
'... |
def get_version(release_level=True):
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i.%(micro)i" % __version_info__]
if release_level and __version_info__['releaselevel'] != 'final':
vers.append('%(releaselevel)s%(serial)i' % __version_info__)
return ''.join(... | Return the formatted version information | Below is the the instruction that describes the task:
### Input:
Return the formatted version information
### Response:
def get_version(release_level=True):
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i.%(micro)i" % __version_info__]
if release_level and __versio... |
def asAccessibleTo(self, query):
"""
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given role, from the ... | @param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given role, from the given query. | Below is the the instruction that describes the task:
### Input:
@param query: An Axiom query describing the Items to retrieve, which this
role can access.
@type query: an L{iaxiom.IQuery} provider.
@return: an iterable which yields the shared proxies that are available
to the given... |
def _write_image_description(self):
"""Write metadata to ImageDescription tag."""
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0):
return
colormapped = self._colormap is not None
if self._imagej:
isrgb = self._s... | Write metadata to ImageDescription tag. | Below is the the instruction that describes the task:
### Input:
Write metadata to ImageDescription tag.
### Response:
def _write_image_description(self):
"""Write metadata to ImageDescription tag."""
if (not self._datashape or self._datashape[0] == 1 or
self._descriptionoffset <= 0... |
def shuffle_srv(records):
"""Randomly reorder SRV records using their weights.
:Parameters:
- `records`: SRV records to shuffle.
:Types:
- `records`: sequence of :dns:`dns.rdtypes.IN.SRV`
:return: reordered records.
:returntype: `list` of :dns:`dns.rdtypes.IN.SRV`"""
if not rec... | Randomly reorder SRV records using their weights.
:Parameters:
- `records`: SRV records to shuffle.
:Types:
- `records`: sequence of :dns:`dns.rdtypes.IN.SRV`
:return: reordered records.
:returntype: `list` of :dns:`dns.rdtypes.IN.SRV` | Below is the the instruction that describes the task:
### Input:
Randomly reorder SRV records using their weights.
:Parameters:
- `records`: SRV records to shuffle.
:Types:
- `records`: sequence of :dns:`dns.rdtypes.IN.SRV`
:return: reordered records.
:returntype: `list` of :dns:`d... |
def build_interpolators(self):
"""Compute 1-D interpolation functions for all the transforms so they're continuous.."""
self.phi_continuous = []
for xi, phii in zip(self.ace.x, self.ace.x_transforms):
self.phi_continuous.append(interp1d(xi, phii))
self.inverse_theta_continuou... | Compute 1-D interpolation functions for all the transforms so they're continuous.. | Below is the the instruction that describes the task:
### Input:
Compute 1-D interpolation functions for all the transforms so they're continuous..
### Response:
def build_interpolators(self):
"""Compute 1-D interpolation functions for all the transforms so they're continuous.."""
self.phi_continuo... |
def build_directory(
sass_path, css_path, output_style='nested',
_root_sass=None, _root_css=None, strip_extension=False,
):
"""Compiles all Sass/SCSS files in ``path`` to CSS.
:param sass_path: the path of the directory which contains source files
to compile
:type sass_path: :... | Compiles all Sass/SCSS files in ``path`` to CSS.
:param sass_path: the path of the directory which contains source files
to compile
:type sass_path: :class:`str`, :class:`basestring`
:param css_path: the path of the directory compiled CSS files will go
:type css_path: :class:`str`... | Below is the the instruction that describes the task:
### Input:
Compiles all Sass/SCSS files in ``path`` to CSS.
:param sass_path: the path of the directory which contains source files
to compile
:type sass_path: :class:`str`, :class:`basestring`
:param css_path: the path of the ... |
def acs2d(input, exec_path='', time_stamps=False, verbose=False, quiet=False,
exe_args=None):
r"""
Run the acs2d.e executable as from the shell.
Output is automatically named based on input suffix:
+--------------------+----------------+------------------------------+
| INPUT ... | r"""
Run the acs2d.e executable as from the shell.
Output is automatically named based on input suffix:
+--------------------+----------------+------------------------------+
| INPUT | OUTPUT | EXPECTED DATA |
+====================+================+=... | Below is the the instruction that describes the task:
### Input:
r"""
Run the acs2d.e executable as from the shell.
Output is automatically named based on input suffix:
+--------------------+----------------+------------------------------+
| INPUT | OUTPUT | EXPECTED D... |
def _get_possible_query_bridging_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None):
'''Input is dict qry_name -> list of nucmer hits to that qry. Returns dict qry_name -> tuple(start hit, end hit)'''
bridges = {}
writing_log_file = None not in [log_fh, log_outprefix]
for qry_n... | Input is dict qry_name -> list of nucmer hits to that qry. Returns dict qry_name -> tuple(start hit, end hit) | Below is the the instruction that describes the task:
### Input:
Input is dict qry_name -> list of nucmer hits to that qry. Returns dict qry_name -> tuple(start hit, end hit)
### Response:
def _get_possible_query_bridging_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None):
'''Input is dict qry_nam... |
def pattern(self, value):
"""
Setter for **self.__pattern** attribute.
:param value: Attribute value.
:type value: unicode
"""
if value is not None:
assert type(value) in (unicode, QString), \
"'{0}' attribute: '{1}' type is not 'unicode' or ... | Setter for **self.__pattern** attribute.
:param value: Attribute value.
:type value: unicode | Below is the the instruction that describes the task:
### Input:
Setter for **self.__pattern** attribute.
:param value: Attribute value.
:type value: unicode
### Response:
def pattern(self, value):
"""
Setter for **self.__pattern** attribute.
:param value: Attribute value.... |
def qteEmulateKeypresses(self, keysequence):
"""
Emulate the Qt key presses that define ``keysequence``.
The method will put the keys into a queue and process them one
by one once the event loop is idle, ie. the event loop
executes all signals and macros associated with the emul... | Emulate the Qt key presses that define ``keysequence``.
The method will put the keys into a queue and process them one
by one once the event loop is idle, ie. the event loop
executes all signals and macros associated with the emulated
key press first before the next one is emulated.
... | Below is the the instruction that describes the task:
### Input:
Emulate the Qt key presses that define ``keysequence``.
The method will put the keys into a queue and process them one
by one once the event loop is idle, ie. the event loop
executes all signals and macros associated with the ... |
def regex_validation_sealer(fields, defaults, RegexType=type(re.compile(""))):
"""
Example sealer that just does regex-based validation.
"""
required = set(fields) - set(defaults)
if required:
raise TypeError(
"regex_validation_sealer doesn't support required arguments. Fields th... | Example sealer that just does regex-based validation. | Below is the the instruction that describes the task:
### Input:
Example sealer that just does regex-based validation.
### Response:
def regex_validation_sealer(fields, defaults, RegexType=type(re.compile(""))):
"""
Example sealer that just does regex-based validation.
"""
required = set(fields) - ... |
def add_status_parser(subparsers, parent_parser):
"""Adds argument parser for the status command
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
"""
parser = subparsers.add_parser(
'status',
help... | Adds argument parser for the status command
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object | Below is the the instruction that describes the task:
### Input:
Adds argument parser for the status command
Args:
subparsers: Add parsers to this subparser object
parent_parser: The parent argparse.ArgumentParser object
### Response:
def add_status_parser(subparsers, parent_parser... |
def create_notifications(users, notification_model, notification_type, related_object):
"""
create notifications in a background job to avoid slowing down users
"""
# shortcuts for readability
Notification = notification_model
# text
additional = related_object.__dict__ if related_object el... | create notifications in a background job to avoid slowing down users | Below is the the instruction that describes the task:
### Input:
create notifications in a background job to avoid slowing down users
### Response:
def create_notifications(users, notification_model, notification_type, related_object):
"""
create notifications in a background job to avoid slowing down user... |
def add_install_button(self, grid_lang, row, column):
"""
Add button that opens the window for installing more assistants
"""
btn = self.button_with_label('<b>Install more...</b>')
if row == 0 and column == 0:
grid_lang.add(btn)
else:
grid_lang.att... | Add button that opens the window for installing more assistants | Below is the the instruction that describes the task:
### Input:
Add button that opens the window for installing more assistants
### Response:
def add_install_button(self, grid_lang, row, column):
"""
Add button that opens the window for installing more assistants
"""
btn = self.but... |
def teardown(self):
'''Teardown trust domain by removing trusted devices.'''
for device in self.devices:
self._remove_trustee(device)
self._populate_domain()
self.domain = {} | Teardown trust domain by removing trusted devices. | Below is the the instruction that describes the task:
### Input:
Teardown trust domain by removing trusted devices.
### Response:
def teardown(self):
'''Teardown trust domain by removing trusted devices.'''
for device in self.devices:
self._remove_trustee(device)
self._popu... |
def get_embeddings_index(embedding_type='glove.42B.300d', embedding_dims=None, embedding_path=None, cache=True):
"""Retrieves embeddings index from embedding name or path. Will automatically download and cache as needed.
Args:
embedding_type: The embedding type to load.
embedding_path: Path to ... | Retrieves embeddings index from embedding name or path. Will automatically download and cache as needed.
Args:
embedding_type: The embedding type to load.
embedding_path: Path to a local embedding to use instead of the embedding type. Ignores `embedding_type` if specified.
Returns:
The... | Below is the the instruction that describes the task:
### Input:
Retrieves embeddings index from embedding name or path. Will automatically download and cache as needed.
Args:
embedding_type: The embedding type to load.
embedding_path: Path to a local embedding to use instead of the embedding t... |
def _add_file(self, path, **params):
"""
Attempt to add a file to the system monitoring mechanism.
"""
log = self._getparam('log', self._discard, **params)
fd = None
try:
fd = os.open(path, os.O_RDONLY)
except Exception as e:
if not self.paths[... | Attempt to add a file to the system monitoring mechanism. | Below is the the instruction that describes the task:
### Input:
Attempt to add a file to the system monitoring mechanism.
### Response:
def _add_file(self, path, **params):
"""
Attempt to add a file to the system monitoring mechanism.
"""
log = self._getparam('log', self._discard, **pa... |
def set_relay_off(self):
"""Turn the relay off."""
if self.get_relay_state():
try:
request = requests.get(
'{}/relay'.format(self.resource), params={'state': '0'},
timeout=self.timeout)
if request.status_code == 200:
... | Turn the relay off. | Below is the the instruction that describes the task:
### Input:
Turn the relay off.
### Response:
def set_relay_off(self):
"""Turn the relay off."""
if self.get_relay_state():
try:
request = requests.get(
'{}/relay'.format(self.resource), params={'st... |
def lignesFichier(nf):
""" L'ensemble de lignes du fichier qui ne sont ni vides ni commentées.
* Les fichiers de Collatinus ont adopté le point d'exclamation
* en début de ligne pour introduire un commentaire.
* Ces lignes doivent être ignorées par le programme.
:param nf: Nom du fichi... | L'ensemble de lignes du fichier qui ne sont ni vides ni commentées.
* Les fichiers de Collatinus ont adopté le point d'exclamation
* en début de ligne pour introduire un commentaire.
* Ces lignes doivent être ignorées par le programme.
:param nf: Nom du fichier
:type nf: str
:yield... | Below is the the instruction that describes the task:
### Input:
L'ensemble de lignes du fichier qui ne sont ni vides ni commentées.
* Les fichiers de Collatinus ont adopté le point d'exclamation
* en début de ligne pour introduire un commentaire.
* Ces lignes doivent être ignorées par le p... |
def project_sequence(s, permutation=None):
"""
Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The se... | Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
xs, ys: The sequence of projected points in coordinates as two lists | Below is the the instruction that describes the task:
### Input:
Projects a point or sequence of points using `project_point` to lists xs, ys
for plotting with Matplotlib.
Parameters
----------
s, Sequence-like
The sequence of points (3-tuples) to be projected.
Returns
-------
... |
def _openResources(self):
""" Uses open the underlying file
"""
with Image.open(self._fileName) as image:
self._array = np.asarray(image)
self._bands = image.getbands()
# Fill attributes. For now assume that the info item are not overridden by
# ... | Uses open the underlying file | Below is the the instruction that describes the task:
### Input:
Uses open the underlying file
### Response:
def _openResources(self):
""" Uses open the underlying file
"""
with Image.open(self._fileName) as image:
self._array = np.asarray(image)
self._bands = imag... |
def unpack(self):
"""Decompose a GVariant into a native Python object."""
LEAF_ACCESSORS = {
'b': self.get_boolean,
'y': self.get_byte,
'n': self.get_int16,
'q': self.get_uint16,
'i': self.get_int32,
'u': self.get_uint32,
... | Decompose a GVariant into a native Python object. | Below is the the instruction that describes the task:
### Input:
Decompose a GVariant into a native Python object.
### Response:
def unpack(self):
"""Decompose a GVariant into a native Python object."""
LEAF_ACCESSORS = {
'b': self.get_boolean,
'y': self.get_byte,
... |
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = util.get_single_outfile(outdir, archive)
cmdlist.extend(["-o", outfile, archive])
return cmdlist | Extract an RZIP archive. | Below is the the instruction that describes the task:
### Input:
Extract an RZIP archive.
### Response:
def extract_rzip (archive, compression, cmd, verbosity, interactive, outdir):
"""Extract an RZIP archive."""
cmdlist = [cmd, '-d', '-k']
if verbosity > 1:
cmdlist.append('-v')
outfile = u... |
def setChatPhoto(self, chat_id, photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return self._api_request_with_file('setChatPhoto', _rectify(p), 'photo', photo) | See: https://core.telegram.org/bots/api#setchatphoto | Below is the the instruction that describes the task:
### Input:
See: https://core.telegram.org/bots/api#setchatphoto
### Response:
def setChatPhoto(self, chat_id, photo):
""" See: https://core.telegram.org/bots/api#setchatphoto """
p = _strip(locals(), more=['photo'])
return self._api_requ... |
def onlasso(self, verts):
"""
Main function to control the action of the lasso, allows user to draw on data image and adjust thematic map
:param verts: the vertices selected by the lasso
:return: nothin, but update the selection array so lassoed region now has the selected theme, redraws... | Main function to control the action of the lasso, allows user to draw on data image and adjust thematic map
:param verts: the vertices selected by the lasso
:return: nothin, but update the selection array so lassoed region now has the selected theme, redraws canvas | Below is the the instruction that describes the task:
### Input:
Main function to control the action of the lasso, allows user to draw on data image and adjust thematic map
:param verts: the vertices selected by the lasso
:return: nothin, but update the selection array so lassoed region now has the ... |
def next_packet(self):
"""
Process next packet if present
"""
try:
start_byte_index = self.buffer.index(velbus.START_BYTE)
except ValueError:
self.buffer = bytes([])
return
if start_byte_index >= 0:
self.buffer = self.buffer... | Process next packet if present | Below is the the instruction that describes the task:
### Input:
Process next packet if present
### Response:
def next_packet(self):
"""
Process next packet if present
"""
try:
start_byte_index = self.buffer.index(velbus.START_BYTE)
except ValueError:
... |
def _gl_look_at(self, pos, target, up):
"""
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
"""
z = vector.normalise(pos - target)
x = vector.normalise(vector3.cross(vector.normalis... | The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up | Below is the the instruction that describes the task:
### Input:
The standard lookAt method
:param pos: current position
:param target: target position to look at
:param up: direction up
### Response:
def _gl_look_at(self, pos, target, up):
"""
The standard lookAt method
... |
def _link_package_versions(self, link, search_name):
"""
Return an iterable of triples (pkg_resources_version_key,
link, python_version) that can be extracted from the given
link.
Meant to be overridden by subclasses, not called by clients.
"""
if link.egg_fragme... | Return an iterable of triples (pkg_resources_version_key,
link, python_version) that can be extracted from the given
link.
Meant to be overridden by subclasses, not called by clients. | Below is the the instruction that describes the task:
### Input:
Return an iterable of triples (pkg_resources_version_key,
link, python_version) that can be extracted from the given
link.
Meant to be overridden by subclasses, not called by clients.
### Response:
def _link_package_versions(... |
def set_cluster_info(self,
disallow_cluster_termination=None,
enable_ganglia_monitoring=None,
datadog_api_token=None,
datadog_app_token=None,
node_bootstrap=None,
master_... | Args:
`disallow_cluster_termination`: Set this to True if you don't want
qubole to auto-terminate idle clusters. Use this option with
extreme caution.
`enable_ganglia_monitoring`: Set this to True if you want to enable
ganglia... | Below is the the instruction that describes the task:
### Input:
Args:
`disallow_cluster_termination`: Set this to True if you don't want
qubole to auto-terminate idle clusters. Use this option with
extreme caution.
`enable_ganglia_monitoring... |
def actions(self, **parameters):
"""Returns a list of actions (alerts) that have been generated for
your account.
Optional Parameters:
* from -- Only include actions generated later than this timestamp.
Format is UNIX time.
Type: Integer
... | Returns a list of actions (alerts) that have been generated for
your account.
Optional Parameters:
* from -- Only include actions generated later than this timestamp.
Format is UNIX time.
Type: Integer
Default: None
*... | Below is the the instruction that describes the task:
### Input:
Returns a list of actions (alerts) that have been generated for
your account.
Optional Parameters:
* from -- Only include actions generated later than this timestamp.
Format is UNIX time.
... |
def main():
'''
Parse command line options and launch the prebuilder.
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
version=xtuml.version.complete_string,
formatter=optparse.TitledHelp... | Parse command line options and launch the prebuilder. | Below is the the instruction that describes the task:
### Input:
Parse command line options and launch the prebuilder.
### Response:
def main():
'''
Parse command line options and launch the prebuilder.
'''
parser = optparse.OptionParser(usage="%prog [options] <model_path> [another_model_path..]",
... |
def _infer_embedded_object(value):
"""
Infer CIMProperty/CIMParameter.embedded_object from the CIM value.
"""
if value is None:
# The default behavior is to assume that a value of None is not
# an embedded object. If the user wants that, they must specify
# the embedded_object p... | Infer CIMProperty/CIMParameter.embedded_object from the CIM value. | Below is the the instruction that describes the task:
### Input:
Infer CIMProperty/CIMParameter.embedded_object from the CIM value.
### Response:
def _infer_embedded_object(value):
"""
Infer CIMProperty/CIMParameter.embedded_object from the CIM value.
"""
if value is None:
# The default be... |
def update(self, resource, uri=None, force=False, timeout=-1, custom_headers=None):
"""Makes a PUT request to update a resource when a request body is required.
Args:
resource: Data to update the resource.
uri: Resource uri
force: If set to true, the operation comple... | Makes a PUT request to update a resource when a request body is required.
Args:
resource: Data to update the resource.
uri: Resource uri
force: If set to true, the operation completes despite any problems
with network connectivity or errors on the resource it... | Below is the the instruction that describes the task:
### Input:
Makes a PUT request to update a resource when a request body is required.
Args:
resource: Data to update the resource.
uri: Resource uri
force: If set to true, the operation completes despite any problems
... |
def populate_local_cache(self):
"""Populate the local cache from DB.
Read the entries from FW DB and Calls routines to populate the cache.
"""
fw_dict = self.get_all_fw_db()
for fw_id in fw_dict:
LOG.info("Populating cache for FW %s", fw_id)
fw_data = fw_... | Populate the local cache from DB.
Read the entries from FW DB and Calls routines to populate the cache. | Below is the the instruction that describes the task:
### Input:
Populate the local cache from DB.
Read the entries from FW DB and Calls routines to populate the cache.
### Response:
def populate_local_cache(self):
"""Populate the local cache from DB.
Read the entries from FW DB and Calls... |
def load_info(self, client, info):
"""Fill out information about the gateway"""
if 'identity' in info:
info['stages'] = client.get_stages(restApiId=info['identity'])['item']
info['resources'] = client.get_resources(restApiId=info['identity'])['items']
for resource in ... | Fill out information about the gateway | Below is the the instruction that describes the task:
### Input:
Fill out information about the gateway
### Response:
def load_info(self, client, info):
"""Fill out information about the gateway"""
if 'identity' in info:
info['stages'] = client.get_stages(restApiId=info['identity'])['it... |
def collection_generator(collection):
"""This function returns a generator which iterates over the collection,
similar to Collection.itertuples(). Collections are viewed by this module,
regardless of type, as a mapping from an index to the value. For sets, the
"index" is the value itself (ie, (V, V)).... | This function returns a generator which iterates over the collection,
similar to Collection.itertuples(). Collections are viewed by this module,
regardless of type, as a mapping from an index to the value. For sets, the
"index" is the value itself (ie, (V, V)). For dicts, it's a string, and
for lists... | Below is the the instruction that describes the task:
### Input:
This function returns a generator which iterates over the collection,
similar to Collection.itertuples(). Collections are viewed by this module,
regardless of type, as a mapping from an index to the value. For sets, the
"index" is the va... |
def GetPupil(self):
"""Retrieve pupil data
"""
pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType',
'ApertureValue',
'entrancePupilDiameter',
'entrancePupil... | Retrieve pupil data | Below is the the instruction that describes the task:
### Input:
Retrieve pupil data
### Response:
def GetPupil(self):
"""Retrieve pupil data
"""
pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType',
'ApertureValue',
... |
def _update_panic_status(self, status=None):
"""
Updates the panic status of the alarm panel.
:param status: status to use to update
:type status: boolean
:returns: boolean indicating the new status
"""
if status is None:
return
if status !=... | Updates the panic status of the alarm panel.
:param status: status to use to update
:type status: boolean
:returns: boolean indicating the new status | Below is the the instruction that describes the task:
### Input:
Updates the panic status of the alarm panel.
:param status: status to use to update
:type status: boolean
:returns: boolean indicating the new status
### Response:
def _update_panic_status(self, status=None):
"""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.