code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, request)
token = res.continuation_token
while token is not None:
res2 = self.get_data_raw_with_toke... | The method is getting data by raw request | Below is the the instruction that describes the task:
### Input:
The method is getting data by raw request
### Response:
def get_data_raw(self, request):
"""The method is getting data by raw request"""
path = '/api/1.0/data/raw/'
res = self._api_post(definition.RawDataResponse, path, req... |
def render_json(tree, indent):
"""Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:retu... | Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of spaces to indent json
:returns: json representation of the tree
... | Below is the the instruction that describes the task:
### Input:
Converts the tree into a flat json representation.
The json repr will be a list of hashes, each hash having 2 fields:
- package
- dependencies: list of dependencies
:param dict tree: dependency tree
:param int indent: no. of ... |
def set_choice_order(self, choice_ids, inline_region):
""" reorder choices per the passed in list
:param choice_ids:
:return:
"""
reordered_choices = []
current_choice_ids = [c['id'] for c in self.my_osid_object_form._my_map['choices'][inline_region]]
if set(choic... | reorder choices per the passed in list
:param choice_ids:
:return: | Below is the the instruction that describes the task:
### Input:
reorder choices per the passed in list
:param choice_ids:
:return:
### Response:
def set_choice_order(self, choice_ids, inline_region):
""" reorder choices per the passed in list
:param choice_ids:
:return:
... |
def get(self, call_sid):
"""
Constructs a MemberContext
:param call_sid: The Call SID of the resource(s) to fetch
:returns: twilio.rest.api.v2010.account.queue.member.MemberContext
:rtype: twilio.rest.api.v2010.account.queue.member.MemberContext
"""
return Membe... | Constructs a MemberContext
:param call_sid: The Call SID of the resource(s) to fetch
:returns: twilio.rest.api.v2010.account.queue.member.MemberContext
:rtype: twilio.rest.api.v2010.account.queue.member.MemberContext | Below is the the instruction that describes the task:
### Input:
Constructs a MemberContext
:param call_sid: The Call SID of the resource(s) to fetch
:returns: twilio.rest.api.v2010.account.queue.member.MemberContext
:rtype: twilio.rest.api.v2010.account.queue.member.MemberContext
### Resp... |
def get_nn_info(self, structure, n):
"""
Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest relative
neighbor distance-based method with VIRE atomic/ionic radii.
Args:
structure (Structure): in... | Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest relative
neighbor distance-based method with VIRE atomic/ionic radii.
Args:
structure (Structure): input structure.
n (integer): index of site for... | Below is the the instruction that describes the task:
### Input:
Get all near-neighbor sites as well as the associated image locations
and weights of the site with index n using the closest relative
neighbor distance-based method with VIRE atomic/ionic radii.
Args:
structure (St... |
def unapi(request):
"""
This view implements unAPI 1.0 (see http://unapi.info).
"""
id = request.GET.get('id')
format = request.GET.get('format')
if format is not None:
try:
publications = Publication.objects.filter(pk=int(id))
if not publications:
raise ValueError
except ValueError:
# inv... | This view implements unAPI 1.0 (see http://unapi.info). | Below is the the instruction that describes the task:
### Input:
This view implements unAPI 1.0 (see http://unapi.info).
### Response:
def unapi(request):
"""
This view implements unAPI 1.0 (see http://unapi.info).
"""
id = request.GET.get('id')
format = request.GET.get('format')
if format is not None:
t... |
def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr(model.objects, 'visible'):
qs = qs.visible()
if adapter.exclude_fields:
qs = qs.exclude(*adapte... | Indel all objects given a model | Below is the the instruction that describes the task:
### Input:
Indel all objects given a model
### Response:
def index_model(index_name, adapter):
''' Indel all objects given a model'''
model = adapter.model
log.info('Indexing {0} objects'.format(model.__name__))
qs = model.objects
if hasattr... |
def calculate_local_order_parameter(self, oscillatory_network, start_iteration = None, stop_iteration = None):
"""!
@brief Calculates local order parameter.
@details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:
... | !
@brief Calculates local order parameter.
@details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:
\f[
r_{c}=\left | \sum_{i=0}^{N} \frac{1}{N_{i}} \sum_{j=0}e^{ \theta_{j} - \theta_{i} } \right |;
... | Below is the the instruction that describes the task:
### Input:
!
@brief Calculates local order parameter.
@details Local order parameter or so-called level of local or partial synchronization is calculated by following expression:
\f[
r_{c}=\left | \sum_{i=0}^{N} \fra... |
def delete_blacklist_entry(self, blacklist_entry_id):
"""Delete an existing blacklist entry.
Keyword arguments:
blacklist_entry_id -- The unique identifier of the blacklist entry to delete.
"""
delete_blacklist_endpoint = Template("${rest_root}/blacklist/${public_key}/${... | Delete an existing blacklist entry.
Keyword arguments:
blacklist_entry_id -- The unique identifier of the blacklist entry to delete. | Below is the the instruction that describes the task:
### Input:
Delete an existing blacklist entry.
Keyword arguments:
blacklist_entry_id -- The unique identifier of the blacklist entry to delete.
### Response:
def delete_blacklist_entry(self, blacklist_entry_id):
"""Delete an exi... |
def bota_gorda(game):
'''
Prefers to play dominoes with higher point values.
:param Game game: game to play
:return: None
'''
game.valid_moves = tuple(sorted(game.valid_moves, key=lambda m: -(m[0].first + m[0].second))) | Prefers to play dominoes with higher point values.
:param Game game: game to play
:return: None | Below is the the instruction that describes the task:
### Input:
Prefers to play dominoes with higher point values.
:param Game game: game to play
:return: None
### Response:
def bota_gorda(game):
'''
Prefers to play dominoes with higher point values.
:param Game game: game to play
:retur... |
def _format_char(char):
"""Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
"""
if char is None:
r... | Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible. | Below is the the instruction that describes the task:
### Input:
Prepares a single character for passing to ctypes calls, needs to return
an integer but can also pass None which will keep the current character
instead of overwriting it.
This is called often and needs to be optimized whenever possible.
... |
def double_exponential_moving_average(data, period):
"""
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
"""
catch_errors.check_for_period_error(data, period)
dema = (2 * ema(data, period)) - ema(ema(data, period), period)
return dema | Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA) | Below is the the instruction that describes the task:
### Input:
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
### Response:
def double_exponential_moving_average(data, period):
"""
Double Exponential Moving Average.
Formula:
DEMA = 2*EMA - EMA(EMA)
"""
catch... |
def process_transaction(self, transaction):
"""Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute.
"""
asset = transaction.asset
if isinstance(asset, Future)... | Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute. | Below is the the instruction that describes the task:
### Input:
Add a transaction to ledger, updating the current state as needed.
Parameters
----------
transaction : zp.Transaction
The transaction to execute.
### Response:
def process_transaction(self, transaction):
"... |
def main(loader, name):
"""
Here we iterate through the datasets and score them with a classifier using different encodings.
"""
scores = []
raw_scores_ds = {}
# first get the dataset
X, y, mapping = loader()
clf = linear_model.LogisticRegression(solver='lbfgs', multi_class='auto', m... | Here we iterate through the datasets and score them with a classifier using different encodings. | Below is the the instruction that describes the task:
### Input:
Here we iterate through the datasets and score them with a classifier using different encodings.
### Response:
def main(loader, name):
"""
Here we iterate through the datasets and score them with a classifier using different encodings.
"... |
def _unscheduleAction(self):
"""
Unschedule current action
Note that it does not add record to action log and does not do
required steps to resume previous action. If you need this - use
_cancelScheduledAction
"""
logger.trace("{} unscheduling actions".format(se... | Unschedule current action
Note that it does not add record to action log and does not do
required steps to resume previous action. If you need this - use
_cancelScheduledAction | Below is the the instruction that describes the task:
### Input:
Unschedule current action
Note that it does not add record to action log and does not do
required steps to resume previous action. If you need this - use
_cancelScheduledAction
### Response:
def _unscheduleAction(self):
... |
def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns y-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, mass2, xi2)
phi2 = phi2_from_phi_a_phi_s(phi_a, phi_s)
return chi_perp * numpy.sin(phi2) | Returns y-component spin for secondary mass. | Below is the the instruction that describes the task:
### Input:
Returns y-component spin for secondary mass.
### Response:
def spin2y_from_mass1_mass2_xi2_phi_a_phi_s(mass1, mass2, xi2, phi_a, phi_s):
"""Returns y-component spin for secondary mass.
"""
chi_perp = chi_perp_from_mass1_mass2_xi2(mass1, m... |
def _render_section(self, output, params, indent=0):
"""
It takes a dictionary and recurses through.
For key-value pair it checks whether the value is a dictionary
and prepends the key with &
It passes the valued to the same function, increasing the indentation
If the va... | It takes a dictionary and recurses through.
For key-value pair it checks whether the value is a dictionary
and prepends the key with &
It passes the valued to the same function, increasing the indentation
If the value is a list, I assume that this is something the user
wants to ... | Below is the the instruction that describes the task:
### Input:
It takes a dictionary and recurses through.
For key-value pair it checks whether the value is a dictionary
and prepends the key with &
It passes the valued to the same function, increasing the indentation
If the value ... |
def depth_soil_conductivity(self, value=None):
"""Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specific... | Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises... | Below is the the instruction that describes the task:
### Input:
Corresponds to IDD Field `depth_soil_conductivity`
Args:
value (float): value for IDD Field `depth_soil_conductivity`
Unit: W/m-K,
if `value` is None it will not be checked against the
... |
def render(self, filename):
"""Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
"""
self.elapsed_time = -time()
dpi = 100
fig = figure(figsize=(16, 9), dpi=dpi)
with self.writer.s... | Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class. | Below is the the instruction that describes the task:
### Input:
Perform initialization of render, set quality and size video attributes and then call template method that
is defined in child class.
### Response:
def render(self, filename):
"""Perform initialization of render, set quality and size ... |
def NewFromJSON(data):
"""
Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance.
"""
return Comment(
body=data.get('body', None),
posted_at=... | Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance. | Below is the the instruction that describes the task:
### Input:
Create a new Comment instance from a JSON dict.
Args:
data (dict): JSON dictionary representing a Comment.
Returns:
A Comment instance.
### Response:
def NewFromJSON(data):
"""
Create a new Co... |
def magictype(text, prompt_template="default", speed=1):
"""Echo each character in ``text`` as keyboard characters are pressed.
Characters are echo'd ``speed`` characters at a time.
"""
echo_prompt(prompt_template)
cursor_position = 0
return_to_regular_type = False
with raw_mode():
w... | Echo each character in ``text`` as keyboard characters are pressed.
Characters are echo'd ``speed`` characters at a time. | Below is the the instruction that describes the task:
### Input:
Echo each character in ``text`` as keyboard characters are pressed.
Characters are echo'd ``speed`` characters at a time.
### Response:
def magictype(text, prompt_template="default", speed=1):
"""Echo each character in ``text`` as keyboard ch... |
def until(name,
m_args=None,
m_kwargs=None,
condition=None,
period=0,
timeout=604800):
'''
Loop over an execution module until a condition is met.
name
The name of the execution module
m_args
The execution module's positional arguments
... | Loop over an execution module until a condition is met.
name
The name of the execution module
m_args
The execution module's positional arguments
m_kwargs
The execution module's keyword arguments
condition
The condition which must be met for the loop to break. This
... | Below is the the instruction that describes the task:
### Input:
Loop over an execution module until a condition is met.
name
The name of the execution module
m_args
The execution module's positional arguments
m_kwargs
The execution module's keyword arguments
condition
... |
def get_images(self, results=15, start=0, license=None, cache=True):
"""Get a list of artist images
Args:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of ... | Get a list of artist images
Args:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of results to return
start (int): An integer starting valu... | Below is the the instruction that describes the task:
### Input:
Get a list of artist images
Args:
cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True.
results (int): An integer number of results to ... |
def write_points(self, data, *args, **kwargs):
"""Write to multiple time series names.
:param data: A dictionary mapping series names to pandas DataFrames
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param batch_size: [Optional] Value to writ... | Write to multiple time series names.
:param data: A dictionary mapping series names to pandas DataFrames
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param batch_size: [Optional] Value to write the points in batches
instead of all at one ... | Below is the the instruction that describes the task:
### Input:
Write to multiple time series names.
:param data: A dictionary mapping series names to pandas DataFrames
:param time_precision: [Optional, default 's'] Either 's', 'm', 'ms'
or 'u'.
:param batch_size: [Optional] Va... |
def trapped_signals(cls, new_signal_handler):
"""A contextmanager which temporarily overrides signal handling."""
try:
previous_signal_handler = cls.reset_signal_handler(new_signal_handler)
yield
finally:
cls.reset_signal_handler(previous_signal_handler) | A contextmanager which temporarily overrides signal handling. | Below is the the instruction that describes the task:
### Input:
A contextmanager which temporarily overrides signal handling.
### Response:
def trapped_signals(cls, new_signal_handler):
"""A contextmanager which temporarily overrides signal handling."""
try:
previous_signal_handler = cls.reset_signa... |
def list(self, where):
'''
List the current schedule items
'''
if where == 'pillar':
schedule = self._get_schedule(include_opts=False)
elif where == 'opts':
schedule = self._get_schedule(include_pillar=False)
else:
schedule = self._get_... | List the current schedule items | Below is the the instruction that describes the task:
### Input:
List the current schedule items
### Response:
def list(self, where):
'''
List the current schedule items
'''
if where == 'pillar':
schedule = self._get_schedule(include_opts=False)
elif where == 'op... |
def get_most_recent_event(self, originator_id, lt=None, lte=None):
"""
Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: ge... | Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: get highest at or before this position
:return: domain event | Below is the the instruction that describes the task:
### Input:
Gets a domain event from the sequence identified by `originator_id`
at the highest position.
:param originator_id: ID of a sequence of events
:param lt: get highest before this position
:param lte: get highest at or be... |
def filter(self, **search_args):
"""
Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources
"""
search_args = search_args or {}
raw_resources = []
for url, paginator_params in se... | Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources | Below is the the instruction that describes the task:
### Input:
Get a filtered list of resources
:param search_args: To be translated into ?arg1=value1&arg2=value2...
:return: A list of resources
### Response:
def filter(self, **search_args):
"""
Get a filtered list of resources
... |
def memoize(func=None, maxlen=None):
"""Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
... | Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of being re-evaluated.
This decorator assumes that candidates ar... | Below is the the instruction that describes the task:
### Input:
Cache a function's return value each time it is called.
This function serves as a function decorator to provide a caching of
evaluated fitness values. If called later with the same arguments,
the cached value is returned instead of b... |
def get_HEAD_SHA1(git_dir):
"""Not locked!
"""
head_file = os.path.join(git_dir, 'HEAD')
with open(head_file, 'r') as hf:
head_contents = hf.read().strip()
assert head_contents.startswith('ref: ')
ref_filename = head_contents[5:] # strip off "ref: "
real_ref = os.path.join(git_dir, ... | Not locked! | Below is the the instruction that describes the task:
### Input:
Not locked!
### Response:
def get_HEAD_SHA1(git_dir):
"""Not locked!
"""
head_file = os.path.join(git_dir, 'HEAD')
with open(head_file, 'r') as hf:
head_contents = hf.read().strip()
assert head_contents.startswith('ref: ')... |
def qteInsertMode(self, pos: int, mode: str, value):
"""
Insert ``mode`` at position ``pos``.
If ``pos`` is negative then this is equivalent to ``pos=0``. If it
is larger than the number of modes in the list then it is appended
as the last element.
|Args|
* ``p... | Insert ``mode`` at position ``pos``.
If ``pos`` is negative then this is equivalent to ``pos=0``. If it
is larger than the number of modes in the list then it is appended
as the last element.
|Args|
* ``pos`` (**int**): insertion point.
* ``mode`` (**str**): name of mo... | Below is the the instruction that describes the task:
### Input:
Insert ``mode`` at position ``pos``.
If ``pos`` is negative then this is equivalent to ``pos=0``. If it
is larger than the number of modes in the list then it is appended
as the last element.
|Args|
* ``pos``... |
def copyto(self, src, where=None):
"""Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, cop... | Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such that where[n] is True, copy particle n in src
into self (at locat... | Below is the the instruction that describes the task:
### Input:
Emulates function `copyto` in NumPy.
Parameters
----------
where: (N,) bool ndarray
True if particle n in src must be copied.
src: (N,) `ThetaParticles` object
source
for each n such tha... |
def get_yaml_schema(self):
"""GetYamlSchema.
[Preview API]
:rtype: object
"""
response = self._send(http_method='GET',
location_id='1f9990b9-1dba-441f-9c2e-6485888c42b6',
version='5.1-preview.1')
return self._des... | GetYamlSchema.
[Preview API]
:rtype: object | Below is the the instruction that describes the task:
### Input:
GetYamlSchema.
[Preview API]
:rtype: object
### Response:
def get_yaml_schema(self):
"""GetYamlSchema.
[Preview API]
:rtype: object
"""
response = self._send(http_method='GET',
... |
def install(self, host):
"""Setup common to all Qt-based hosts"""
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
log.info("Headless host")
return
print("aboutToQuit..")
self.app.aboutToQuit.connect(se... | Setup common to all Qt-based hosts | Below is the the instruction that describes the task:
### Input:
Setup common to all Qt-based hosts
### Response:
def install(self, host):
"""Setup common to all Qt-based hosts"""
print("Installing..")
if self._state["installed"]:
return
if self.is_headless():
... |
def riak_http_search_query(self, solr_core, solr_params, count_deleted=False):
"""
This method is for advanced SOLR queries. Riak HTTP search query endpoint,
sends solr_params and query string as a proxy and returns solr reponse.
Args:
solr_core (str): solr core on w... | This method is for advanced SOLR queries. Riak HTTP search query endpoint,
sends solr_params and query string as a proxy and returns solr reponse.
Args:
solr_core (str): solr core on which query will be executed
solr_params (str): solr specific query params,... | Below is the the instruction that describes the task:
### Input:
This method is for advanced SOLR queries. Riak HTTP search query endpoint,
sends solr_params and query string as a proxy and returns solr reponse.
Args:
solr_core (str): solr core on which query will be executed
... |
def build_extension(extensions: Sequence[ExtensionHeader]) -> str:
"""
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`.
"""
return ", ".join(
build_extension_item(name, parameters) for name, parameters in extensions
) | Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`. | Below is the the instruction that describes the task:
### Input:
Unparse a ``Sec-WebSocket-Extensions`` header.
This is the reverse of :func:`parse_extension`.
### Response:
def build_extension(extensions: Sequence[ExtensionHeader]) -> str:
"""
Unparse a ``Sec-WebSocket-Extensions`` header.
This ... |
def get_found_includes(self, env, scanner, path):
"""Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested.
"""
memo_key = (id(env), id(scanner), path)
try:
... | Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested. | Below is the the instruction that describes the task:
### Input:
Return the included implicit dependencies in this file.
Cache results so we only scan the file once per path
regardless of how many times this information is requested.
### Response:
def get_found_includes(self, env, scanner, path):
... |
def iget_batches(task_ids, batch_size=10):
"""Yield out a map of the keys and futures in batches of the batch size
passed in.
"""
make_key = lambda _id: ndb.Key(FuriousAsyncMarker, _id)
for keys in i_batch(imap(make_key, task_ids), batch_size):
yield izip(keys, ndb.get_multi_async(keys)) | Yield out a map of the keys and futures in batches of the batch size
passed in. | Below is the the instruction that describes the task:
### Input:
Yield out a map of the keys and futures in batches of the batch size
passed in.
### Response:
def iget_batches(task_ids, batch_size=10):
"""Yield out a map of the keys and futures in batches of the batch size
passed in.
"""
make_... |
def save(self, name):
"""
Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
"""
self.finalize()
with open(name, 'wb+') as f:
if six.PY3:
f.write(self.fileobj.getbuffer())
... | Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str | Below is the the instruction that describes the task:
### Input:
Save the string buffer to a file. Finalizes prior to saving.
:param name: File path.
:type name: unicode | str
### Response:
def save(self, name):
"""
Save the string buffer to a file. Finalizes prior to saving.
... |
def get_image_size(self, token, resolution=0):
"""
Return the size of the volume (3D). Convenient for when you want
to download the entirety of a dataset.
Arguments:
token (str): The token for which to find the dataset image bounds
resolution (int : 0): The resol... | Return the size of the volume (3D). Convenient for when you want
to download the entirety of a dataset.
Arguments:
token (str): The token for which to find the dataset image bounds
resolution (int : 0): The resolution at which to get image bounds.
Defaults to 0, ... | Below is the the instruction that describes the task:
### Input:
Return the size of the volume (3D). Convenient for when you want
to download the entirety of a dataset.
Arguments:
token (str): The token for which to find the dataset image bounds
resolution (int : 0): The res... |
def des_cbc_pkcs5_encrypt(key, data, iv):
"""
Encrypts plaintext using DES with a 56 bit key
:param key:
The encryption key - a byte string 8 bytes long (includes error correction bits)
:param data:
The plaintext - a byte string
:param iv:
The 8-byte initialization vector ... | Encrypts plaintext using DES with a 56 bit key
:param key:
The encryption key - a byte string 8 bytes long (includes error correction bits)
:param data:
The plaintext - a byte string
:param iv:
The 8-byte initialization vector to use - a byte string - set as None
to genera... | Below is the the instruction that describes the task:
### Input:
Encrypts plaintext using DES with a 56 bit key
:param key:
The encryption key - a byte string 8 bytes long (includes error correction bits)
:param data:
The plaintext - a byte string
:param iv:
The 8-byte initial... |
def ConsultarConstanciaCTGPDF(self, numero_ctg=None,
archivo="constancia.pdf"):
"Operación Consultar Constancia de CTG en PDF"
ret = self.client.consultarConstanciaCTGPDF(request=dict(
auth={
'token': self.Token... | Operación Consultar Constancia de CTG en PDF | Below is the the instruction that describes the task:
### Input:
Operación Consultar Constancia de CTG en PDF
### Response:
def ConsultarConstanciaCTGPDF(self, numero_ctg=None,
archivo="constancia.pdf"):
"Operación Consultar Constancia de CTG en PDF"
ret = s... |
def combo_serve(request, path, client):
"""
Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended ... | Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files work as intended before rolling out
to production. | Below is the the instruction that describes the task:
### Input:
Handles generating a 'combo' file for the given path. This is similar to
what happens when we upload to S3. Processors are applied, and we get
the value that we would if we were serving from S3. This is a good way
to make sure combo files ... |
def write_tsv(self, path):
"""Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None
"""
with open(path, 'wb') as ofh:
writer = csv.writer(
... | Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None | Below is the the instruction that describes the task:
### Input:
Write the database to a tab-delimited text file.
Parameters
----------
path: str
The path name of the file.
Returns
-------
None
### Response:
def write_tsv(self, path):
"""Write t... |
def _get_help_record(opt):
"""Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-... | Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' directive, which expects
comma-separated opts and option argument... | Below is the the instruction that describes the task:
### Input:
Re-implementation of click.Opt.get_help_record.
The variant of 'get_help_record' found in Click makes uses of slashes to
separate multiple opts, and formats option arguments using upper case. This
is not compatible with Sphinx's 'option' ... |
def sample_histograms(fig, input_sample, problem, param_dict):
'''Plots a set of subplots of histograms of the input sample
'''
num_vars = problem['num_vars']
names = problem['names']
framing = 101 + (num_vars * 10)
# Find number of levels
num_levels = len(set(input_sample[:, 1]))
ou... | Plots a set of subplots of histograms of the input sample | Below is the the instruction that describes the task:
### Input:
Plots a set of subplots of histograms of the input sample
### Response:
def sample_histograms(fig, input_sample, problem, param_dict):
'''Plots a set of subplots of histograms of the input sample
'''
num_vars = problem['num_vars']
na... |
def new_item(self, hash_key, range_key=None, attrs=None):
"""
Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB.
"""
return Item(self, hash_key, range_key, attrs) | Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB. | Below is the the instruction that describes the task:
### Input:
Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB.
### Response:
def new_item(self, hash_key, range_key=None, attrs=None):
"""
Return an new, unsaved Item which can later be PUT to
Amazon DynamoDB.
... |
def handle_mark_read_request(cls, request, message, dispatch, hash_is_valid, redirect_to):
"""Handles a request to mark a message as read.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
:p... | Handles a request to mark a message as read.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
:param bool hash_is_valid: Flag indicating that user supplied request signature is correct
:para... | Below is the the instruction that describes the task:
### Input:
Handles a request to mark a message as read.
:param Request request: Request instance
:param Message message: Message model instance
:param Dispatch dispatch: Dispatch model instance
:param bool hash_is_valid: Flag ind... |
def update_install_json():
"""Update the install.json configuration file if exists."""
if not os.path.isfile('install.json'):
return
with open('install.json', 'r') as f:
install_json = json.load(f)
if install_json.get('programMain'):
install_json['pr... | Update the install.json configuration file if exists. | Below is the the instruction that describes the task:
### Input:
Update the install.json configuration file if exists.
### Response:
def update_install_json():
"""Update the install.json configuration file if exists."""
if not os.path.isfile('install.json'):
return
with open('i... |
def topDownCompute(self, encoded):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute]
"""
if self.minval is None or self.maxval is None:
return [EncoderResult(value=0, scalar=0,
encoding=numpy.zeros(self.n))]
return super(AdaptiveScalarEncoder, self)... | [overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute] | Below is the the instruction that describes the task:
### Input:
[overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute]
### Response:
def topDownCompute(self, encoded):
"""
[overrides nupic.encoders.scalar.ScalarEncoder.topDownCompute]
"""
if self.minval is None or self.maxval is None:
... |
def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
body = params
data = self._post_resource(url, body)
shift = self.shift_from_json(data["shift"])
return shift | Creates a shift
http://dev.wheniwork.com/#create/update-shift | Below is the the instruction that describes the task:
### Input:
Creates a shift
http://dev.wheniwork.com/#create/update-shift
### Response:
def create_shift(self, params={}):
"""
Creates a shift
http://dev.wheniwork.com/#create/update-shift
"""
url = "/2/shifts/"
... |
def get_label(self, code):
"""Returns string label for given code string
Inverse of get_code
Parameters
----------
code: String
\tCode string, field 1 of style tuple
"""
for style in self.styles:
if style[1] == code:
return ... | Returns string label for given code string
Inverse of get_code
Parameters
----------
code: String
\tCode string, field 1 of style tuple | Below is the the instruction that describes the task:
### Input:
Returns string label for given code string
Inverse of get_code
Parameters
----------
code: String
\tCode string, field 1 of style tuple
### Response:
def get_label(self, code):
"""Returns string label... |
def generate_twofactor_code_for_time(shared_secret, timestamp):
"""Generate Steam 2FA code for timestamp
:param shared_secret: authenticator shared secret
:type shared_secret: bytes
:param timestamp: timestamp to use, if left out uses current time
:type timestamp: int
:return: steam two factor ... | Generate Steam 2FA code for timestamp
:param shared_secret: authenticator shared secret
:type shared_secret: bytes
:param timestamp: timestamp to use, if left out uses current time
:type timestamp: int
:return: steam two factor code
:rtype: str | Below is the the instruction that describes the task:
### Input:
Generate Steam 2FA code for timestamp
:param shared_secret: authenticator shared secret
:type shared_secret: bytes
:param timestamp: timestamp to use, if left out uses current time
:type timestamp: int
:return: steam two factor co... |
def downloadMARCOAI(doc_id, base):
"""
Download MARC OAI document with given `doc_id` from given (logical) `base`.
Funny part is, that some documents can be obtained only with this function
in their full text.
Args:
doc_id (str): You will get this from :func:`getDocumentIDs`.
... | Download MARC OAI document with given `doc_id` from given (logical) `base`.
Funny part is, that some documents can be obtained only with this function
in their full text.
Args:
doc_id (str): You will get this from :func:`getDocumentIDs`.
base (str, optional): Base from which you wa... | Below is the the instruction that describes the task:
### Input:
Download MARC OAI document with given `doc_id` from given (logical) `base`.
Funny part is, that some documents can be obtained only with this function
in their full text.
Args:
doc_id (str): You will get this from :func:`... |
def Start(self,
file_size=0,
maximum_pending_files=1000,
use_external_stores=False):
"""Initialize our state."""
super(MultiGetFileLogic, self).Start()
self.state.files_hashed = 0
self.state.use_external_stores = use_external_stores
self.state.file_size = file_si... | Initialize our state. | Below is the the instruction that describes the task:
### Input:
Initialize our state.
### Response:
def Start(self,
file_size=0,
maximum_pending_files=1000,
use_external_stores=False):
"""Initialize our state."""
super(MultiGetFileLogic, self).Start()
self.state.fi... |
def get_file_from_url(job, any_url, encryption_key=None, per_file_encryption=True,
write_to_jobstore=True):
"""
Download a supplied URL that points to a file on an http, https or ftp server. If the file is
found to be an https s3 link then the file is downloaded using `get_file_from_s... | Download a supplied URL that points to a file on an http, https or ftp server. If the file is
found to be an https s3 link then the file is downloaded using `get_file_from_s3`. The file is
downloaded and written to the jobstore if requested.
Encryption arguments are for passing to `get_file_from_s3` if req... | Below is the the instruction that describes the task:
### Input:
Download a supplied URL that points to a file on an http, https or ftp server. If the file is
found to be an https s3 link then the file is downloaded using `get_file_from_s3`. The file is
downloaded and written to the jobstore if requested.
... |
def remote(self, remote_base=None, username=None, password=None):
"""
Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
... | Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
password for local repository | Below is the the instruction that describes the task:
### Input:
Configures remote access
Parameters
----------
remote_base : str
base URL path for remote repository
username : str
user name for remote repository
password : str
password fo... |
def _cache_update_needed(self, courseid):
"""
:param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else
"""
if courseid not in self._cache:
return Tru... | :param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else | Below is the the instruction that describes the task:
### Input:
:param courseid: the (valid) course id of the course
:raise InvalidNameException, CourseNotFoundException
:return: True if an update of the cache is needed, False else
### Response:
def _cache_update_needed(self, courseid):
""... |
def adaptStandardLogging(loggerName, logCategory, targetModule):
"""
Make a logger from the standard library log through the Flumotion logging
system.
@param loggerName: The standard logger to adapt, e.g. 'library.module'
@type loggerName: str
@param logCategory: The Flumotion log category to u... | Make a logger from the standard library log through the Flumotion logging
system.
@param loggerName: The standard logger to adapt, e.g. 'library.module'
@type loggerName: str
@param logCategory: The Flumotion log category to use when reporting output
from the standard logger, e.... | Below is the the instruction that describes the task:
### Input:
Make a logger from the standard library log through the Flumotion logging
system.
@param loggerName: The standard logger to adapt, e.g. 'library.module'
@type loggerName: str
@param logCategory: The Flumotion log category to use when ... |
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "... | Auto Generated Code | Below is the the instruction that describes the task:
### Input:
Auto Generated Code
### Response:
def get_media_detail_output_interface_interface_identifier_gbic_gbc_vendor_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element(... |
def _set_port_profile_domain(self, v, load=False):
"""
Setter method for port_profile_domain, mapped from YANG variable /port_profile_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_profile_domain is considered as a private
method. Backends looking... | Setter method for port_profile_domain, mapped from YANG variable /port_profile_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_profile_domain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj... | Below is the the instruction that describes the task:
### Input:
Setter method for port_profile_domain, mapped from YANG variable /port_profile_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_port_profile_domain is considered as a private
method. Backends l... |
def dump_nt_sorted(g: Graph) -> List[str]:
"""
Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g
"""
return [l.decode('ascii') for l in sorted(g.serialize(format='nt').splitlines()) if l] | Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g | Below is the the instruction that describes the task:
### Input:
Dump graph g in a sorted n3 format
:param g: graph to dump
:return: stringified representation of g
### Response:
def dump_nt_sorted(g: Graph) -> List[str]:
"""
Dump graph g in a sorted n3 format
:param g: graph to dump
:retur... |
def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return self._from_parsed_parts(self._drv, self._root,
self._parts[:-1] + [name]) | Return a new path with the file name changed. | Below is the the instruction that describes the task:
### Input:
Return a new path with the file name changed.
### Response:
def with_name(self, name):
"""Return a new path with the file name changed."""
if not self.name:
raise ValueError("%r has an empty name" % (self,))
return... |
def mute(ip):
"""Polyfill for muting the TV."""
tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip)
count = 0
while count > 30:
count = count + 1
request = requests.get(tv_url + 'volumedown')
if request.status_code != 20... | Polyfill for muting the TV. | Below is the the instruction that describes the task:
### Input:
Polyfill for muting the TV.
### Response:
def mute(ip):
"""Polyfill for muting the TV."""
tv_url = 'http://{}:6095/controller?action=keyevent&keycode='.format(ip)
count = 0
while count > 30:
count = ... |
def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# returns a single list combining keys and args
try:
iter(keys)
# a string can be iterated, but indicates
# keys wasn't passed as a list
if isinstance(ke... | Shamelessly copied from redis-py. | Below is the the instruction that describes the task:
### Input:
Shamelessly copied from redis-py.
### Response:
def _list_or_args(self, keys, args):
"""
Shamelessly copied from redis-py.
"""
# returns a single list combining keys and args
try:
iter(keys)
... |
def send_batch(messages, api_key=None, secure=None, test=None, **request_args):
'''Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https ... | Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Postmark API.
Defaults to `True`
:param test: Use the Postma... | Below is the the instruction that describes the task:
### Input:
Send a batch of messages.
:param messages: Messages to send.
:type message: A list of `dict` or :class:`Message`
:param api_key: Your Postmark API key. Required, if `test` is not `True`.
:param secure: Use the https scheme for the Pos... |
def create_upload_url(success_path,
max_bytes_per_blob=None,
max_bytes_total=None,
**options):
"""Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_... | Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_bytes_per_blob: The maximum size in bytes that any one blob in the
upload can be or None for no maximum size.
max_bytes_total: The maximum size in bytes tha... | Below is the the instruction that describes the task:
### Input:
Create upload URL for POST form.
Args:
success_path: Path within application to call when POST is successful
and upload is complete.
max_bytes_per_blob: The maximum size in bytes that any one blob in the
upload can be or None fo... |
def two_phase_dP_gravitational(angle, z, alpha_i, rho_li, rho_gi,
alpha_o=None, rho_lo=None, rho_go=None, g=g):
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segm... | r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segment with a known difference in elevation (and ideally
known inlet and outlet pressures so density dependence can be included).
.. math:... | Below is the the instruction that describes the task:
### Input:
r'''This function handles calculation of two-phase liquid-gas pressure drop
due to gravitation for flow inside channels. This is a discrete
calculation for a segment with a known difference in elevation (and ideally
known inlet and outlet... |
def release(self, resource):
"""release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failure to do so could result in de... | release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failure to do so could result in deadlock.
:param resource: Resour... | Below is the the instruction that describes the task:
### Input:
release(resource)
Returns a resource to the pool. Most of the time you will want
to use :meth:`transaction`, but if you use :meth:`acquire`,
you must release the acquired resource back to the pool when
finished. Failur... |
def itertuples(self, index=True, name="Pandas"):
"""
Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The... | Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The name of the returned namedtuples or None to return regular
... | Below is the the instruction that describes the task:
### Input:
Iterate over DataFrame rows as namedtuples.
Parameters
----------
index : bool, default True
If True, return the index as the first element of the tuple.
name : str or None, default "Pandas"
The... |
def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
"""
if self._state == _State.CLOSED:
self._invalid_state("abort() called")
return
self._force_close(None) | Immediately close the stream, without sending remaining buffers or
performing a proper shutdown. | Below is the the instruction that describes the task:
### Input:
Immediately close the stream, without sending remaining buffers or
performing a proper shutdown.
### Response:
def abort(self):
"""
Immediately close the stream, without sending remaining buffers or
performing a proper... |
def get_fields(self):
"""
Return all field objects
:rtype: a list of :class:`EncodedField` objects
"""
if self.__cache_all_fields is None:
self.__cache_all_fields = []
for i in self.get_classes():
for j in i.get_fields():
... | Return all field objects
:rtype: a list of :class:`EncodedField` objects | Below is the the instruction that describes the task:
### Input:
Return all field objects
:rtype: a list of :class:`EncodedField` objects
### Response:
def get_fields(self):
"""
Return all field objects
:rtype: a list of :class:`EncodedField` objects
"""
if self.__... |
def main():
'''
Bootstrapper CLI
'''
parser = argparse.ArgumentParser(prog='kclboot',
description='kclboot - Kinesis Client Library Bootstrapper')
subparsers = parser.add_subparsers(title='Subcommands', help='Additional help', dest='subparser')
# Common arguments
jar_path_parser =... | Bootstrapper CLI | Below is the the instruction that describes the task:
### Input:
Bootstrapper CLI
### Response:
def main():
'''
Bootstrapper CLI
'''
parser = argparse.ArgumentParser(prog='kclboot',
description='kclboot - Kinesis Client Library Bootstrapper')
subparsers = parser.add_subparsers(title='... |
def run_sls_remove(sls_cmd, env_vars):
"""Run sls remove command."""
sls_process = subprocess.Popen(sls_cmd,
stdout=subprocess.PIPE,
env=env_vars)
stdoutdata, _stderrdata = sls_process.communicate()
sls_return = sls_process.wait()
... | Run sls remove command. | Below is the the instruction that describes the task:
### Input:
Run sls remove command.
### Response:
def run_sls_remove(sls_cmd, env_vars):
"""Run sls remove command."""
sls_process = subprocess.Popen(sls_cmd,
stdout=subprocess.PIPE,
e... |
def debug(self):
"""Retrieve the debug information from the identity manager."""
url = '{}debug/status'.format(self.url)
try:
return make_request(url, timeout=self.timeout)
except ServerError as err:
return {"error": str(err)} | Retrieve the debug information from the identity manager. | Below is the the instruction that describes the task:
### Input:
Retrieve the debug information from the identity manager.
### Response:
def debug(self):
"""Retrieve the debug information from the identity manager."""
url = '{}debug/status'.format(self.url)
try:
return make_requ... |
def GetName(obj):
"""A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode characters).
This function makes this behaviou... | A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode characters).
This function makes this behaviour consistent and always... | Below is the the instruction that describes the task:
### Input:
A compatibility wrapper for getting object's name.
In Python 2 class names are returned as `bytes` (since class names can contain
only ASCII characters) whereas in Python 3 they are `unicode` (since class
names can contain arbitrary unicode cha... |
def save(self, fname=''):
"""
Save the list of items to AIKIF core and optionally to local file fname
"""
if fname != '':
with open(fname, 'w') as f:
for i in self.lstPrograms:
f.write(self.get_file_info_line(i, ','))
# sa... | Save the list of items to AIKIF core and optionally to local file fname | Below is the the instruction that describes the task:
### Input:
Save the list of items to AIKIF core and optionally to local file fname
### Response:
def save(self, fname=''):
"""
Save the list of items to AIKIF core and optionally to local file fname
"""
if fname != '':
... |
def serialize_to_file(obj, file_name, append=False):
"""Pickle obj to file_name."""
logging.info("Serializing to file %s.", file_name)
with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file:
pickle.dump(obj, output_file)
logging.info("Done serializing to file %s.", file_name) | Pickle obj to file_name. | Below is the the instruction that describes the task:
### Input:
Pickle obj to file_name.
### Response:
def serialize_to_file(obj, file_name, append=False):
"""Pickle obj to file_name."""
logging.info("Serializing to file %s.", file_name)
with tf.gfile.Open(file_name, "a+" if append else "wb") as output_file... |
def check(self, request, secret):
"""Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
... | Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Keyword arguments:
request -- A request object which can be cons... | Below is the the instruction that describes the task:
### Input:
Verifies whether or not the request bears an authorization appropriate and valid for this version of the signature.
This verifies every element of the signature, including the timestamp's value.
Does not alter the request.
Key... |
def delete_library(self, library):
"""
Delete an Arctic Library, and all associated collections in the MongoDB.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
"""
lib = ArcticLibraryBinding(self, librar... | Delete an Arctic Library, and all associated collections in the MongoDB.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library' | Below is the the instruction that describes the task:
### Input:
Delete an Arctic Library, and all associated collections in the MongoDB.
Parameters
----------
library : `str`
The name of the library. e.g. 'library' or 'user.library'
### Response:
def delete_library(self, libra... |
def wheel(self, load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_name, key = self._prep_auth_info(load)
# Authenticate
auth_check = self.loadauth.check_authentication(
load,
... | Send a master control function back to the wheel system | Below is the the instruction that describes the task:
### Input:
Send a master control function back to the wheel system
### Response:
def wheel(self, load):
'''
Send a master control function back to the wheel system
'''
# All wheel ops pass through eauth
auth_type, err_nam... |
def update(self, read, write, manage):
"""
Update the SyncListPermissionInstance
:param bool read: Read access.
:param bool write: Write access.
:param bool manage: Manage access.
:returns: Updated SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.s... | Update the SyncListPermissionInstance
:param bool read: Read access.
:param bool write: Write access.
:param bool manage: Manage access.
:returns: Updated SyncListPermissionInstance
:rtype: twilio.rest.sync.v1.service.sync_list.sync_list_permission.SyncListPermissionInstance | Below is the the instruction that describes the task:
### Input:
Update the SyncListPermissionInstance
:param bool read: Read access.
:param bool write: Write access.
:param bool manage: Manage access.
:returns: Updated SyncListPermissionInstance
:rtype: twilio.rest.sync.v1... |
def _generate_struct_class_custom_annotations(self, ns, data_type):
"""
The _process_custom_annotations function allows client code to access
custom annotations defined in the spec.
"""
self.emit('def _process_custom_annotations(self, annotation_type, field_path, processor):')
... | The _process_custom_annotations function allows client code to access
custom annotations defined in the spec. | Below is the the instruction that describes the task:
### Input:
The _process_custom_annotations function allows client code to access
custom annotations defined in the spec.
### Response:
def _generate_struct_class_custom_annotations(self, ns, data_type):
"""
The _process_custom_annotation... |
def drawRect(self, x1, y1, x2, y2, angle=0):
"""
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The Y of the top-lef... | Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The Y of the top-left corner of the rectangle.
:param x2: The X of the ... | Below is the the instruction that describes the task:
### Input:
Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The ... |
def normalize(self):
"""Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits
"""
if self.moc is None:
... | Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits | Below is the the instruction that describes the task:
### Input:
Normalize the MOC to a given order.
This command takes a MOC order (0-29) and normalizes the MOC so that
its maximum order is the given order.
::
pymoctool a.fits --normalize 10 --output a_10.fits
### Response:
... |
def _trim_buffer_garbage(rawmessage, debug=True):
"""Remove leading bytes from a byte stream.
A proper message byte stream begins with 0x02.
"""
while rawmessage and rawmessage[0] != MESSAGE_START_CODE_0X02:
if debug:
_LOGGER.debug('Buffer content: %s', binascii.hexlify(rawmessage))... | Remove leading bytes from a byte stream.
A proper message byte stream begins with 0x02. | Below is the the instruction that describes the task:
### Input:
Remove leading bytes from a byte stream.
A proper message byte stream begins with 0x02.
### Response:
def _trim_buffer_garbage(rawmessage, debug=True):
"""Remove leading bytes from a byte stream.
A proper message byte stream begins with... |
def find_wheels(projects, search_dirs):
"""Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
"""
wheels = []
# Look through SEARCH_DIRS for the first suitable wheel. Don't bothe... | Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT | Below is the the instruction that describes the task:
### Input:
Find wheels from which we can import PROJECTS.
Scan through SEARCH_DIRS for a wheel for each PROJECT in turn. Return
a list of the first wheel found for each PROJECT
### Response:
def find_wheels(projects, search_dirs):
"""Find wheels fr... |
def remove_children(self, reset_parent=True):
"""
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
"""
if reset_parent:
for child in self.children:
... | Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children | Below is the the instruction that describes the task:
### Input:
Remove all the children of this node.
:param bool reset_parent: if ``True``, set to ``None`` the parent attribute
of the children
### Response:
def remove_children(self, reset_parent=True):
"""
... |
def generate_unique_key(master_key_path, url):
"""
Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL
"""
with open(master... | Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL | Below is the the instruction that describes the task:
### Input:
Input1: Path to the BD2K Master Key (for S3 Encryption)
Input2: S3 URL (e.g. https://s3-us-west-2.amazonaws.com/cgl-driver-projects-encrypted/wcdt/exome_bams/DTB-111-N.bam)
Returns: 32-byte unique key generated for that URL
### Response:
def... |
def endpoint_name(self, endpoint_name):
"""
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: ... | Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoint_name: The endpoint_name of this PreSharedKey.
:type: str | Below is the the instruction that describes the task:
### Input:
Sets the endpoint_name of this PreSharedKey.
The unique endpoint identifier that this pre-shared key applies to. 16-64 [printable](https://en.wikipedia.org/wiki/ASCII#Printable_characters) (non-control) ASCII characters.
:param endpoi... |
def _execute(self, operation): # type: (Operation) -> None
"""
Execute a given operation.
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(operation) | Execute a given operation. | Below is the the instruction that describes the task:
### Input:
Execute a given operation.
### Response:
def _execute(self, operation): # type: (Operation) -> None
"""
Execute a given operation.
"""
method = operation.job_type
getattr(self, "_execute_{}".format(method))(o... |
def query_mongo_sort_decend(
database_name,
collection_name,
query={},
skip=0,
limit=getattr(
settings,
'MONGO_LIMIT',
200),
return_keys=(),
sortkey=None):
"""return a response_dict with a list of search results in decending
... | return a response_dict with a list of search results in decending
order based on a sort key | Below is the the instruction that describes the task:
### Input:
return a response_dict with a list of search results in decending
order based on a sort key
### Response:
def query_mongo_sort_decend(
database_name,
collection_name,
query={},
skip=0,
limit=getattr(
... |
def get_vcf_header(source):
"""Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object
"""
head = HeaderParser()
#Parse the header lines
for line in source:
line = line.rst... | Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object | Below is the the instruction that describes the task:
### Input:
Get the header lines of a vcf file
Args:
source(iterable): A vcf file
Returns:
head (HeaderParser): A headerparser object
### Response:
def get_vcf_header(source):
"""Get the header lines of a... |
def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
else:
return _make_frame(message, OPCODE_TEXT) | Make text message. | Below is the the instruction that describes the task:
### Input:
Make text message.
### Response:
def make_message(message, binary=False):
"""Make text message."""
if isinstance(message, str):
message = message.encode('utf-8')
if binary:
return _make_frame(message, OPCODE_BINARY)
e... |
def S_star(u, dfs_data):
"""The set of all descendants of u, with u added."""
s_u = S(u, dfs_data)
if u not in s_u:
s_u.append(u)
return s_u | The set of all descendants of u, with u added. | Below is the the instruction that describes the task:
### Input:
The set of all descendants of u, with u added.
### Response:
def S_star(u, dfs_data):
"""The set of all descendants of u, with u added."""
s_u = S(u, dfs_data)
if u not in s_u:
s_u.append(u)
return s_u |
def detect(self, G):
"""Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G)
... | Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> lrc = cp.LowRankCore()
>>> lrc.detect(G) | Below is the the instruction that describes the task:
### Input:
Detect a single core-periphery pair.
Parameters
----------
G : NetworkX graph object
Examples
--------
>>> import networkx as nx
>>> import cpalgorithm as cpa
>>> G = nx.karate_club_graph() # load the karate club network.
>>> ... |
def sync_in_records(self, force=False):
"""Synchronize from files to records"""
self.log('---- Sync Files ----')
for f in self.build_source_files:
f.record_to_objects()
# Only the metadata needs to be driven to the objects, since the other files are used as code,
# ... | Synchronize from files to records | Below is the the instruction that describes the task:
### Input:
Synchronize from files to records
### Response:
def sync_in_records(self, force=False):
"""Synchronize from files to records"""
self.log('---- Sync Files ----')
for f in self.build_source_files:
f.record_to_object... |
def set_class_weight(self, class_weight='auto', y=None):
""" Sets the class_weight of the classifier to match y """
if class_weight is None:
cw = None
try:
self.clf.set_params(class_weight=cw)
except ValueError:
pass
elif cla... | Sets the class_weight of the classifier to match y | Below is the the instruction that describes the task:
### Input:
Sets the class_weight of the classifier to match y
### Response:
def set_class_weight(self, class_weight='auto', y=None):
""" Sets the class_weight of the classifier to match y """
if class_weight is None:
cw = None
... |
def solve_max(self, expr):
"""
Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution
:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int]
"""
if isinsta... | Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution
:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int] | Below is the the instruction that describes the task:
### Input:
Solves a symbolic :class:`~manticore.core.smtlib.expression.Expression` into
its maximum solution
:param manticore.core.smtlib.Expression expr: Symbolic value to solve
:return: Concrete value
:rtype: list[int]
### Resp... |
def to_json(self, sort_keys=False):
"""Produce a JSON-encoded SBP message.
"""
d = self.to_json_dict()
return json.dumps(d, sort_keys=sort_keys) | Produce a JSON-encoded SBP message. | Below is the the instruction that describes the task:
### Input:
Produce a JSON-encoded SBP message.
### Response:
def to_json(self, sort_keys=False):
"""Produce a JSON-encoded SBP message.
"""
d = self.to_json_dict()
return json.dumps(d, sort_keys=sort_keys) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.