code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def flatten4d3d(x):
"""Flatten a 4d-tensor into a 3d-tensor by joining width and height."""
xshape = shape_list(x)
result = tf.reshape(x, [xshape[0], xshape[1] * xshape[2], xshape[3]])
return result | Flatten a 4d-tensor into a 3d-tensor by joining width and height. | Below is the the instruction that describes the task:
### Input:
Flatten a 4d-tensor into a 3d-tensor by joining width and height.
### Response:
def flatten4d3d(x):
"""Flatten a 4d-tensor into a 3d-tensor by joining width and height."""
xshape = shape_list(x)
result = tf.reshape(x, [xshape[0], xshape[1] * xs... |
def lambda_vpc_execution_statements():
"""Allow Lambda to manipuate EC2 ENIs for VPC support."""
return [
Statement(
Effect=Allow,
Resource=['*'],
Action=[
ec2.CreateNetworkInterface,
ec2.DescribeNetworkInterfaces,
ec2.D... | Allow Lambda to manipuate EC2 ENIs for VPC support. | Below is the the instruction that describes the task:
### Input:
Allow Lambda to manipuate EC2 ENIs for VPC support.
### Response:
def lambda_vpc_execution_statements():
"""Allow Lambda to manipuate EC2 ENIs for VPC support."""
return [
Statement(
Effect=Allow,
Resource=['*'... |
def validate_object(obj, field_validators=None, non_field_validators=None,
schema=None, context=None):
"""
Takes a mapping and applies a mapping of validator functions to it
collecting and reraising any validation errors that occur.
"""
if schema is None:
schema = {}
... | Takes a mapping and applies a mapping of validator functions to it
collecting and reraising any validation errors that occur. | Below is the the instruction that describes the task:
### Input:
Takes a mapping and applies a mapping of validator functions to it
collecting and reraising any validation errors that occur.
### Response:
def validate_object(obj, field_validators=None, non_field_validators=None,
schema=None... |
def mincost_diameter_augment(graph, max_cost, candidates=None, weight=None, cost=None):
"""
PROBLEM: Bounded Cost Minimum Diameter Edge Addition (BCMD)
Args:
graph (nx.Graph): input graph
max_cost (float): maximum weighted diamter of the graph
weight (str): key of the edge weight at... | PROBLEM: Bounded Cost Minimum Diameter Edge Addition (BCMD)
Args:
graph (nx.Graph): input graph
max_cost (float): maximum weighted diamter of the graph
weight (str): key of the edge weight attribute
cost (str): key of the edge cost attribute
candidates (list): set of non-edg... | Below is the the instruction that describes the task:
### Input:
PROBLEM: Bounded Cost Minimum Diameter Edge Addition (BCMD)
Args:
graph (nx.Graph): input graph
max_cost (float): maximum weighted diamter of the graph
weight (str): key of the edge weight attribute
cost (str): key... |
def get_newsentry_meta_description(newsentry):
"""Returns the meta description for the given entry."""
if newsentry.meta_description:
return newsentry.meta_description
# If there is no seo addon found, take the info from the placeholders
text = newsentry.get_description()
if len(text) > 16... | Returns the meta description for the given entry. | Below is the the instruction that describes the task:
### Input:
Returns the meta description for the given entry.
### Response:
def get_newsentry_meta_description(newsentry):
"""Returns the meta description for the given entry."""
if newsentry.meta_description:
return newsentry.meta_description
... |
def _parse_command_response(response):
"""Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The reques... | Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:param response: The requests response object
:return: An ElementTree... | Below is the the instruction that describes the task:
### Input:
Parse an SCI command response into ElementTree XML
This is a helper method that takes a Requests Response object
of an SCI command response and will parse it into an ElementTree Element
representing the root of the XML response.
:par... |
async def _handle_message(self,
message: BaseMessage,
responder: Responder) -> Optional[Dict]:
"""
Handles a message: find a state and run it.
:return: The register that was saved
"""
async def noop(request: Request, r... | Handles a message: find a state and run it.
:return: The register that was saved | Below is the the instruction that describes the task:
### Input:
Handles a message: find a state and run it.
:return: The register that was saved
### Response:
async def _handle_message(self,
message: BaseMessage,
responder: Responder) -> Optiona... |
def create_device(name,
role,
model,
manufacturer,
site):
'''
.. versionadded:: 2019.2.0
Create a new device with a name, role, model, manufacturer and site.
All these components need to be already in Netbox.
name
The ... | .. versionadded:: 2019.2.0
Create a new device with a name, role, model, manufacturer and site.
All these components need to be already in Netbox.
name
The name of the device, e.g., ``edge_router``
role
String of device role, e.g., ``router``
model
String of device model, e... | Below is the the instruction that describes the task:
### Input:
.. versionadded:: 2019.2.0
Create a new device with a name, role, model, manufacturer and site.
All these components need to be already in Netbox.
name
The name of the device, e.g., ``edge_router``
role
String of devi... |
def group_membership_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership"
api_path = "/api/v2/group_memberships/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership | Below is the the instruction that describes the task:
### Input:
https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership
### Response:
def group_membership_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/group_memberships#show-membership"
api_p... |
def image_predict(self, X):
"""
Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p... | Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_pixels_x]
Target labels or masks. | Below is the the instruction that describes the task:
### Input:
Predicts class label for the entire image.
Parameters:
-----------
X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands]
Array of training images
y: array, shape = [n_samples] or [n_sampl... |
def last_continuous_indexes_slice(ol,value):
'''
from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
last_continuous_indexes_slice(ol,"a")
'''
length = ol.__len__()
end = None
slice = []
for i in range(length-1,-1,-1):
if(ol[i]==value):
... | from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
last_continuous_indexes_slice(ol,"a") | Below is the the instruction that describes the task:
### Input:
from elist.elist import *
ol = [1,"a","a",2,3,"a",4,"a","a","a",5]
last_continuous_indexes_slice(ol,"a")
### Response:
def last_continuous_indexes_slice(ol,value):
'''
from elist.elist import *
ol = [1,"a","a",2,3,... |
def get_relevant_versions(self, package_name: str):
"""Return a tuple: (latest release, latest stable)
If there are different, it means the latest is not a stable
"""
versions = self.get_ordered_versions(package_name)
pre_releases = [version for version in versions if not version... | Return a tuple: (latest release, latest stable)
If there are different, it means the latest is not a stable | Below is the the instruction that describes the task:
### Input:
Return a tuple: (latest release, latest stable)
If there are different, it means the latest is not a stable
### Response:
def get_relevant_versions(self, package_name: str):
"""Return a tuple: (latest release, latest stable)
I... |
def infographic_header_element(impact_function_name, feature, parent):
"""Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood'
"""
_ = feature, parent # NOQA
string_format = infographic_header['... | Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood' | Below is the the instruction that describes the task:
### Input:
Get a formatted infographic header sentence for an impact function.
For instance:
* infographic_header_element('flood') -> 'Estimated impact of a flood'
### Response:
def infographic_header_element(impact_function_name, feature, parent):
... |
def clone_with_git(repo_uri, dest_path):
"""Create a clone by cloning a git repository.
Args:
repo_uri: The URI of the git repository to clone.
dest_path: The location to clone to.
"""
log.info('Cloning git repo %s to %s', repo_uri, dest_path)
git.Repo.clone_from(repo_uri, dest_path... | Create a clone by cloning a git repository.
Args:
repo_uri: The URI of the git repository to clone.
dest_path: The location to clone to. | Below is the the instruction that describes the task:
### Input:
Create a clone by cloning a git repository.
Args:
repo_uri: The URI of the git repository to clone.
dest_path: The location to clone to.
### Response:
def clone_with_git(repo_uri, dest_path):
"""Create a clone by cloning a gi... |
def _handleAuth(fn):
''' Decorator to re-try API calls after asking the user for authentication. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
# auth, , authenticate users, internal
from yotta.lib import auth
# if yotta is being run noninteractively, then we never retry, but... | Decorator to re-try API calls after asking the user for authentication. | Below is the the instruction that describes the task:
### Input:
Decorator to re-try API calls after asking the user for authentication.
### Response:
def _handleAuth(fn):
''' Decorator to re-try API calls after asking the user for authentication. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
... |
def _init_stages(self, config, name):
'''Create a list of indirect stages.
`name` should be the name of a config item that holds a list
of names of stages, for instance, ``writers``. This looks up
the names of those stages, then creates and returns the
corresponding list of sta... | Create a list of indirect stages.
`name` should be the name of a config item that holds a list
of names of stages, for instance, ``writers``. This looks up
the names of those stages, then creates and returns the
corresponding list of stage objects. For instance, if the
config ... | Below is the the instruction that describes the task:
### Input:
Create a list of indirect stages.
`name` should be the name of a config item that holds a list
of names of stages, for instance, ``writers``. This looks up
the names of those stages, then creates and returns the
corre... |
def envelope(self, data, many):
"""Wrap result in envelope."""
if not many:
return data
result = dict(
hits=dict(
hits=data,
total=self.context.get('total', len(data))
)
)
page = self.context.get('page')
... | Wrap result in envelope. | Below is the the instruction that describes the task:
### Input:
Wrap result in envelope.
### Response:
def envelope(self, data, many):
"""Wrap result in envelope."""
if not many:
return data
result = dict(
hits=dict(
hits=data,
total... |
def _update_callbacks(self, plot):
"""
Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing
subplots into a CompositePlot and sets the plot id to match
the root level bokeh model.
"""
subplots = self.tr... | Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing
subplots into a CompositePlot and sets the plot id to match
the root level bokeh model. | Below is the the instruction that describes the task:
### Input:
Iterates over all subplots and updates existing CustomJS
callbacks with models that were replaced when compositing
subplots into a CompositePlot and sets the plot id to match
the root level bokeh model.
### Response:
def _upda... |
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
# Get the scalar values from the underlying scalar encoder
(fieldsDict, fieldNames) = self.encoder.decode(encoded)
if len(fieldsDict) == 0:
return (fieldsDict, fieldNames)
# Expect only 1 field... | See the function description in base.py | Below is the the instruction that describes the task:
### Input:
See the function description in base.py
### Response:
def decode(self, encoded, parentFieldName=''):
""" See the function description in base.py
"""
# Get the scalar values from the underlying scalar encoder
(fieldsDict, fieldNames) ... |
def read(self, timeout=READ_TIMEOUT, raw=False):
''' Read data from the arm. Data is returned as a latin_1 encoded
string, or raw bytes if 'raw' is True. '''
time.sleep(READ_SLEEP_TIME)
raw_out = self.ser.read(self.ser.in_waiting)
out = raw_out.decode(OUTPUT_ENCODING)
... | Read data from the arm. Data is returned as a latin_1 encoded
string, or raw bytes if 'raw' is True. | Below is the the instruction that describes the task:
### Input:
Read data from the arm. Data is returned as a latin_1 encoded
string, or raw bytes if 'raw' is True.
### Response:
def read(self, timeout=READ_TIMEOUT, raw=False):
''' Read data from the arm. Data is returned as a latin_1 encoded
... |
def reads_generator_to_protein_sequences_generator(
variant_and_overlapping_reads_generator,
transcript_id_whitelist=None,
protein_sequence_length=PROTEIN_SEQUENCE_LENGTH,
min_alt_rna_reads=MIN_ALT_RNA_READS,
min_variant_sequence_coverage=MIN_VARIANT_SEQUENCE_COVERAGE,
mi... | Translates each coding variant in a collection to one or more
Translation objects, which are then aggregated into equivalent
ProteinSequence objects.
Parameters
----------
variant_and_overlapping_reads_generator : generator
Yields sequence of varcode.Variant objects paired with sequences
... | Below is the the instruction that describes the task:
### Input:
Translates each coding variant in a collection to one or more
Translation objects, which are then aggregated into equivalent
ProteinSequence objects.
Parameters
----------
variant_and_overlapping_reads_generator : generator
... |
def create_spectra_lookup(lookup, fn_spectra):
"""Stores all spectra rt, injection time, and scan nr in db"""
to_store = []
mzmlmap = lookup.get_mzmlfile_map()
for fn, spectrum in fn_spectra:
spec_id = '{}_{}'.format(mzmlmap[fn], spectrum['scan'])
mzml_rt = round(float(spectrum['rt']), 1... | Stores all spectra rt, injection time, and scan nr in db | Below is the the instruction that describes the task:
### Input:
Stores all spectra rt, injection time, and scan nr in db
### Response:
def create_spectra_lookup(lookup, fn_spectra):
"""Stores all spectra rt, injection time, and scan nr in db"""
to_store = []
mzmlmap = lookup.get_mzmlfile_map()
for... |
def param (self, param, kwargs, default_value=False):
"""gets a param from kwargs, or uses a default_value. if found, it's
removed from kwargs"""
if param in kwargs:
value= kwargs[param]
del kwargs[param]
else:
value= default_value
setattr (sel... | gets a param from kwargs, or uses a default_value. if found, it's
removed from kwargs | Below is the the instruction that describes the task:
### Input:
gets a param from kwargs, or uses a default_value. if found, it's
removed from kwargs
### Response:
def param (self, param, kwargs, default_value=False):
"""gets a param from kwargs, or uses a default_value. if found, it's
rem... |
def populateWidget(self):
"""
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but i... | Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem to be an overkill, but in practice it is very fast.
Don't try ... | Below is the the instruction that describes the task:
### Input:
Populate the widget using data stored in the state
object. The order in which the individual widgets are populated
follows their arrangment.
The models are recreated every time the function is called.
This might seem t... |
def _configureShortcuts(self):
'''Add keyboard shortcuts to navigate the filesystem.'''
self._upShortcut = QtGui.QShortcut(
QtGui.QKeySequence('Backspace'), self
)
self._upShortcut.setAutoRepeat(False)
self._upShortcut.activated.connect(self._onNavigateUpButtonClicked... | Add keyboard shortcuts to navigate the filesystem. | Below is the the instruction that describes the task:
### Input:
Add keyboard shortcuts to navigate the filesystem.
### Response:
def _configureShortcuts(self):
'''Add keyboard shortcuts to navigate the filesystem.'''
self._upShortcut = QtGui.QShortcut(
QtGui.QKeySequence('Backspace'), ... |
def _commit_timer_stopped(self, lCall):
"""We're shutting down, clean up our looping call..."""
if self._commit_looper is not lCall:
log.warning('_commit_timer_stopped with wrong timer:%s not:%s',
lCall, self._commit_looper)
else:
log.debug('_commi... | We're shutting down, clean up our looping call... | Below is the the instruction that describes the task:
### Input:
We're shutting down, clean up our looping call...
### Response:
def _commit_timer_stopped(self, lCall):
"""We're shutting down, clean up our looping call..."""
if self._commit_looper is not lCall:
log.warning('_commit_time... |
def pication(rings, pos_charged, protcharged):
"""Return all pi-Cation interaction between aromatic rings and positively charged groups.
For tertiary and quaternary amines, check also the angle between the ring and the nitrogen.
"""
data = namedtuple(
'pication', 'ring charge distance offset typ... | Return all pi-Cation interaction between aromatic rings and positively charged groups.
For tertiary and quaternary amines, check also the angle between the ring and the nitrogen. | Below is the the instruction that describes the task:
### Input:
Return all pi-Cation interaction between aromatic rings and positively charged groups.
For tertiary and quaternary amines, check also the angle between the ring and the nitrogen.
### Response:
def pication(rings, pos_charged, protcharged):
""... |
def soapX(args):
"""
%prog soapX folder tag [*.fastq]
Run SOAP on a folder of paired reads and apply tag before assembly.
Optional *.fastq in the argument list will be symlinked in each folder and
co-assembled.
"""
p = OptionParser(soapX.__doc__)
opts, args = p.parse_args(args)
if ... | %prog soapX folder tag [*.fastq]
Run SOAP on a folder of paired reads and apply tag before assembly.
Optional *.fastq in the argument list will be symlinked in each folder and
co-assembled. | Below is the the instruction that describes the task:
### Input:
%prog soapX folder tag [*.fastq]
Run SOAP on a folder of paired reads and apply tag before assembly.
Optional *.fastq in the argument list will be symlinked in each folder and
co-assembled.
### Response:
def soapX(args):
"""
%pro... |
def stem(self, word, early_english=False):
"""Return Porter stem.
Parameters
----------
word : str
The word to stem
early_english : bool
Set to True in order to remove -eth & -est (2nd & 3rd person
singular verbal agreement suffixes)
... | Return Porter stem.
Parameters
----------
word : str
The word to stem
early_english : bool
Set to True in order to remove -eth & -est (2nd & 3rd person
singular verbal agreement suffixes)
Returns
-------
str
Word s... | Below is the the instruction that describes the task:
### Input:
Return Porter stem.
Parameters
----------
word : str
The word to stem
early_english : bool
Set to True in order to remove -eth & -est (2nd & 3rd person
singular verbal agreement suff... |
def get_report_status(self, report):
"""
Returns the status of a report.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show
"""
if (report.account_id is None or report.type is None or
report.report_id is None):
rai... | Returns the status of a report.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show | Below is the the instruction that describes the task:
### Input:
Returns the status of a report.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.show
### Response:
def get_report_status(self, report):
"""
Returns the status of a report.
https://c... |
async def delete(self, service_id: str) -> bool:
"""
Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful
"""
await self.docker._query(
"services/{service_id}".format(service_id=service_id), method... | Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful | Below is the the instruction that describes the task:
### Input:
Remove a service
Args:
service_id: ID or name of the service
Returns:
True if successful
### Response:
async def delete(self, service_id: str) -> bool:
"""
Remove a service
Args:
... |
def update_schema(schema_old, schema_new):
"""
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_ne... | Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
schema_new: the new schema which will overwrite/extend the old | Below is the the instruction that describes the task:
### Input:
Given an old BigQuery schema, update it with a new one.
Where a field name is the same, the new will replace the old. Any
new fields not present in the old schema will be added.
Arguments:
schema_old: the old schema to update
... |
def add_role(self, role, description=None):
""" Creates a new group """
new_group = AuthGroup(role=role, creator=self.client)
try:
new_group.save()
return True
except NotUniqueError:
return False | Creates a new group | Below is the the instruction that describes the task:
### Input:
Creates a new group
### Response:
def add_role(self, role, description=None):
""" Creates a new group """
new_group = AuthGroup(role=role, creator=self.client)
try:
new_group.save()
return True
... |
def server(self):
"""
UDP server to listen for responses.
"""
server = getattr(self, "_server", None)
if server is None:
server = WSGIServer(('', self.port), self._handle, log=None)
self._server = server
return server | UDP server to listen for responses. | Below is the the instruction that describes the task:
### Input:
UDP server to listen for responses.
### Response:
def server(self):
"""
UDP server to listen for responses.
"""
server = getattr(self, "_server", None)
if server is None:
server = WSGIServer(('', se... |
def is_in_plane(self, pp, dist_tolerance):
"""
Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: True if ... | Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: True if pp is in the plane, False otherwise | Below is the the instruction that describes the task:
### Input:
Determines if point pp is in the plane within the tolerance dist_tolerance
:param pp: point to be tested
:param dist_tolerance: tolerance on the distance to the plane within which point pp is considered in the plane
:return: Tr... |
def start_receive(self, stream):
"""
Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as
ready for reading. Safe to call from any thread. When the associated
file descriptor becomes ready for reading,
:meth:`BasicStream.on_receive` will be called.
"""
... | Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as
ready for reading. Safe to call from any thread. When the associated
file descriptor becomes ready for reading,
:meth:`BasicStream.on_receive` will be called. | Below is the the instruction that describes the task:
### Input:
Mark the :attr:`receive_side <Stream.receive_side>` on `stream` as
ready for reading. Safe to call from any thread. When the associated
file descriptor becomes ready for reading,
:meth:`BasicStream.on_receive` will be called.
#... |
def get_xid_devices():
"""
Returns a list of all Xid devices connected to your computer.
"""
devices = []
scanner = XidScanner()
for i in range(scanner.device_count()):
com = scanner.device_at_index(i)
com.open()
device = XidDevice(com)
devices.append(device)
... | Returns a list of all Xid devices connected to your computer. | Below is the the instruction that describes the task:
### Input:
Returns a list of all Xid devices connected to your computer.
### Response:
def get_xid_devices():
"""
Returns a list of all Xid devices connected to your computer.
"""
devices = []
scanner = XidScanner()
for i in range(scanne... |
def create_access_service(price, service_endpoint, consume_endpoint, timeout=None):
"""
Publish an asset with an `Access` service according to the supplied attributes.
:param price: Asset price, int
:param service_endpoint: str URL for initiating service access request
:param co... | Publish an asset with an `Access` service according to the supplied attributes.
:param price: Asset price, int
:param service_endpoint: str URL for initiating service access request
:param consume_endpoint: str URL to consume service
:param timeout: int amount of time in seconds before ... | Below is the the instruction that describes the task:
### Input:
Publish an asset with an `Access` service according to the supplied attributes.
:param price: Asset price, int
:param service_endpoint: str URL for initiating service access request
:param consume_endpoint: str URL to consume ... |
def setMethod(self, method, override_analyses=False):
""" Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
... | Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be overriden.
Returns the number of analyses affected. | Below is the the instruction that describes the task:
### Input:
Sets the specified method to the Analyses from the
Worksheet. Only sets the method if the Analysis
allows to keep the integrity.
If an analysis has already been assigned to a method, it won't
be override... |
def get_sqltext(self, format_=1):
"""retourne les requêtes actuellement lancées sur le serveur"""
if format_ == 1:
_sql = """SELECT u.sid, substr(u.username,1,12) user_name, s.sql_text
FROM v$sql s,v$session u
WHERE s.hash_value = u.sql_hash_value
AND sql... | retourne les requêtes actuellement lancées sur le serveur | Below is the the instruction that describes the task:
### Input:
retourne les requêtes actuellement lancées sur le serveur
### Response:
def get_sqltext(self, format_=1):
"""retourne les requêtes actuellement lancées sur le serveur"""
if format_ == 1:
_sql = """SELECT u.sid, substr(u.u... |
def WriteVarBytes(self, value, endian="<"):
"""
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the... | Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specify the endianness. (Default) Little endian ('<'). Use '>' for big endi... | Below is the the instruction that describes the task:
### Input:
Write an integer value in a space saving way to the stream.
Read more about variable size encoding here: http://docs.neo.org/en-us/node/network-protocol.html#convention
Args:
value (bytes):
endian (str): specif... |
def Read(self, length=None):
"""Reads data."""
if length is None:
length = self._length - self._offset
if length > self._max_unbound_read:
raise OversizedReadError("Attempted to read %d bytes when "
"Server.max_unbound_read_size is %d" %
... | Reads data. | Below is the the instruction that describes the task:
### Input:
Reads data.
### Response:
def Read(self, length=None):
"""Reads data."""
if length is None:
length = self._length - self._offset
if length > self._max_unbound_read:
raise OversizedReadError("Attempted to read %d bytes when "... |
def split_batches(self, data, minibatch_size= None):
"""Split data into minibatches with a specified size
Parameters
----------
data: iterable and indexable
List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames.
minibatch_size: int
Expected sizes of minibatc... | Split data into minibatches with a specified size
Parameters
----------
data: iterable and indexable
List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames.
minibatch_size: int
Expected sizes of minibatches split from the data.
Returns
-------
data_split... | Below is the the instruction that describes the task:
### Input:
Split data into minibatches with a specified size
Parameters
----------
data: iterable and indexable
List-like data to be split into batches. Includes spark_contextipy matrices and Pandas DataFrames.
minibatch_size: int
Expected sizes ... |
def endnodes(self):
"""|Nodes| object containing all |Node| objects currently handled by
the |HydPy| object which define a downstream end point of a network."""
endnodes = devicetools.Nodes()
for node in self.nodes:
for element in node.exits:
if ((element in s... | |Nodes| object containing all |Node| objects currently handled by
the |HydPy| object which define a downstream end point of a network. | Below is the the instruction that describes the task:
### Input:
|Nodes| object containing all |Node| objects currently handled by
the |HydPy| object which define a downstream end point of a network.
### Response:
def endnodes(self):
"""|Nodes| object containing all |Node| objects currently handled... |
def start_worker(
self):
"""start_worker
Start the helper worker process to package queued messages
and send them to Splunk
"""
# Start a worker thread responsible for sending logs
if not self.is_shutting_down(shutdown_event=self.shutdown_event) \
... | start_worker
Start the helper worker process to package queued messages
and send them to Splunk | Below is the the instruction that describes the task:
### Input:
start_worker
Start the helper worker process to package queued messages
and send them to Splunk
### Response:
def start_worker(
self):
"""start_worker
Start the helper worker process to package queued mes... |
def get_filename_and_extension_of(target_file):
"""Gets the base filename and extension of the target file.
:param target_file: the complete path of the target file
:returns: base filename and extension
"""
base_target_filename = os.path.basename(target_file)
file_name, file_ext_with_dot = os.p... | Gets the base filename and extension of the target file.
:param target_file: the complete path of the target file
:returns: base filename and extension | Below is the the instruction that describes the task:
### Input:
Gets the base filename and extension of the target file.
:param target_file: the complete path of the target file
:returns: base filename and extension
### Response:
def get_filename_and_extension_of(target_file):
"""Gets the base filena... |
def schedule(self, kind='R'):
"""Returns a list of BoxScore IDs for every game in the season.
Only needs to handle 'R' or 'P' options because decorator handles 'B'.
:param kind: 'R' for regular season, 'P' for playoffs, 'B' for both.
Defaults to 'R'.
:returns: DataFrame of s... | Returns a list of BoxScore IDs for every game in the season.
Only needs to handle 'R' or 'P' options because decorator handles 'B'.
:param kind: 'R' for regular season, 'P' for playoffs, 'B' for both.
Defaults to 'R'.
:returns: DataFrame of schedule information.
:rtype: pd.D... | Below is the the instruction that describes the task:
### Input:
Returns a list of BoxScore IDs for every game in the season.
Only needs to handle 'R' or 'P' options because decorator handles 'B'.
:param kind: 'R' for regular season, 'P' for playoffs, 'B' for both.
Defaults to 'R'.
... |
async def _reconnect(self, last_error):
"""
Cleanly disconnects and then reconnects.
"""
self._log.debug('Closing current connection...')
await self._connection.disconnect()
await helpers._cancel(
self._log,
send_loop_handle=self._send_loop_handle... | Cleanly disconnects and then reconnects. | Below is the the instruction that describes the task:
### Input:
Cleanly disconnects and then reconnects.
### Response:
async def _reconnect(self, last_error):
"""
Cleanly disconnects and then reconnects.
"""
self._log.debug('Closing current connection...')
await self._conne... |
def _get_config_path(self):
"""
Return a sensible configuration path for caching config
settings.
"""
org = self.service.space.org.name
space = self.service.space.name
name = self.name
return "~/.predix/%s/%s/%s.json" % (org, space, name) | Return a sensible configuration path for caching config
settings. | Below is the the instruction that describes the task:
### Input:
Return a sensible configuration path for caching config
settings.
### Response:
def _get_config_path(self):
"""
Return a sensible configuration path for caching config
settings.
"""
org = self.service.s... |
def is_audit_type(*args):
"""This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict]
"""
def _is_audit_type(audit_options):
if audit_options.get('audit_type') in args:
... | This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict] | Below is the the instruction that describes the task:
### Input:
This audit is included in the specified kinds of audits.
:param *args: List of AuditTypes to include this audit in
:type args: List[AuditType]
:rtype: Callable[Dict]
### Response:
def is_audit_type(*args):
"""This audit is included i... |
def to_json(self, schema_info=True):
""" JSON serialization method that account for all information-wise important part of breakpoint graph
"""
genomes = set()
result = {}
result["edges"] = []
for bgedge in self.edges():
genomes |= bgedge.multicolor.colors
... | JSON serialization method that account for all information-wise important part of breakpoint graph | Below is the the instruction that describes the task:
### Input:
JSON serialization method that account for all information-wise important part of breakpoint graph
### Response:
def to_json(self, schema_info=True):
""" JSON serialization method that account for all information-wise important part of breakp... |
def to_frame(self, data, state):
"""
Extract a single frame from the data buffer. The consumed
data should be removed from the buffer. If no complete frame
can be read, must raise a ``NoFrames`` exception.
:param data: A ``bytearray`` instance containing the data so
... | Extract a single frame from the data buffer. The consumed
data should be removed from the buffer. If no complete frame
can be read, must raise a ``NoFrames`` exception.
:param data: A ``bytearray`` instance containing the data so
far read.
:param state: An instanc... | Below is the the instruction that describes the task:
### Input:
Extract a single frame from the data buffer. The consumed
data should be removed from the buffer. If no complete frame
can be read, must raise a ``NoFrames`` exception.
:param data: A ``bytearray`` instance containing the da... |
def validate_query(self, query):
"""Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : RadarQuery
The query to valida... | Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : RadarQuery
The query to validate
Returns
-------
... | Below is the the instruction that describes the task:
### Input:
Validate a query.
Determines whether `query` is well-formed. This includes checking for all
required parameters, as well as checking parameters for valid values.
Parameters
----------
query : RadarQuery
... |
def set_model_config(model_name, config, replace=False):
"""
This function should be only used in initialization phrase
:param model_name: model name it's should be string
:param config: config should be dict. e.g.
{'__mapping_only__', '__tablename__', '__ext_model__'}
:param replace: if Tru... | This function should be only used in initialization phrase
:param model_name: model name it's should be string
:param config: config should be dict. e.g.
{'__mapping_only__', '__tablename__', '__ext_model__'}
:param replace: if True, then replace original config, False will update | Below is the the instruction that describes the task:
### Input:
This function should be only used in initialization phrase
:param model_name: model name it's should be string
:param config: config should be dict. e.g.
{'__mapping_only__', '__tablename__', '__ext_model__'}
:param replace: if Tru... |
def parse_str(text):
"""
Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For... | Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For example ``\\033[42m``
would ... | Below is the the instruction that describes the task:
### Input:
Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes... |
def get_recipe(self, recipe_name):
"""Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe.
"""
if recipe_name.endswith('.yaml'):
recipe = self._recipes.get(Reci... | Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe. | Below is the the instruction that describes the task:
### Input:
Get a recipe by name.
Args:
recipe_name (str): The name of the recipe to fetch. Can be either the
yaml file name or the name of the recipe.
### Response:
def get_recipe(self, recipe_name):
"""Get a recipe ... |
def get_org_smarthost(self, orgid, serverid):
"""Get an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['get'],
dict(orgid=orgid, serverid=serverid)) | Get an organization smarthost | Below is the the instruction that describes the task:
### Input:
Get an organization smarthost
### Response:
def get_org_smarthost(self, orgid, serverid):
"""Get an organization smarthost"""
return self.api_call(
ENDPOINTS['orgsmarthosts']['get'],
dict(orgid=orgid, serverid=... |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'scope') and self.scope is not None:
_dict['scope'] = self.scope
if hasattr(self, 'status') and self.status is not None:
_dict['status'] = self.status
i... | Return a json dictionary representing this model. | Below is the the instruction that describes the task:
### Input:
Return a json dictionary representing this model.
### Response:
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'scope') and self.scope is not None:
_dict['sc... |
def our_IsUsableForDesktopGUI(m):
""" A more leniant version of CGDisplayModeIsUsableForDesktopGUI """
if guess_bitDepth(Q.CGDisplayModeCopyPixelEncoding(m)) != 24:
return False
if Q.CGDisplayModeGetWidth(m) < 640:
return False
if Q.CGDisplayModeGetHeight(... | A more leniant version of CGDisplayModeIsUsableForDesktopGUI | Below is the the instruction that describes the task:
### Input:
A more leniant version of CGDisplayModeIsUsableForDesktopGUI
### Response:
def our_IsUsableForDesktopGUI(m):
""" A more leniant version of CGDisplayModeIsUsableForDesktopGUI """
if guess_bitDepth(Q.CGDisplayModeCopyPixelEncoding(m)) !... |
def get_queryset(self, request):
''' Restrict the listed submission files for the current user.'''
qs = super(SubmissionFileAdmin, self).get_queryset(request)
if request.user.is_superuser:
return qs
else:
return qs.filter(Q(submissions__assignment__course__tutors_... | Restrict the listed submission files for the current user. | Below is the the instruction that describes the task:
### Input:
Restrict the listed submission files for the current user.
### Response:
def get_queryset(self, request):
''' Restrict the listed submission files for the current user.'''
qs = super(SubmissionFileAdmin, self).get_queryset(request)
... |
def _Aff4Read(aff4_obj, offset, length):
"""Reads contents of given AFF4 file.
Args:
aff4_obj: An AFF4 stream instance to retrieve contents for.
offset: An offset to start the reading from.
length: A number of bytes to read. Reads the whole file if 0.
Returns:
Contents of specified AFF4 stream.
... | Reads contents of given AFF4 file.
Args:
aff4_obj: An AFF4 stream instance to retrieve contents for.
offset: An offset to start the reading from.
length: A number of bytes to read. Reads the whole file if 0.
Returns:
Contents of specified AFF4 stream.
Raises:
TypeError: If `aff4_obj` is not... | Below is the the instruction that describes the task:
### Input:
Reads contents of given AFF4 file.
Args:
aff4_obj: An AFF4 stream instance to retrieve contents for.
offset: An offset to start the reading from.
length: A number of bytes to read. Reads the whole file if 0.
Returns:
Contents of ... |
def get_data_iters_and_vocabs(args: argparse.Namespace,
model_folder: Optional[str]) -> Tuple['data_io.BaseParallelSampleIter',
List[vocab.Vocab], vocab.Vocab, model.ModelConfig]:
"""
Loads the data iterators and v... | Loads the data iterators and vocabularies.
:param args: Arguments as returned by argparse.
:param model_folder: Output folder.
:return: The scoring data iterator as well as the source and target vocabularies. | Below is the the instruction that describes the task:
### Input:
Loads the data iterators and vocabularies.
:param args: Arguments as returned by argparse.
:param model_folder: Output folder.
:return: The scoring data iterator as well as the source and target vocabularies.
### Response:
def get_data_i... |
def remove_child_objectives(self, objective_id=None):
"""Removes all children from an objective.
arg: objective_id (osid.id.Id): the Id of an objective
raise: NotFound - objective_id not found
raise: NullArgument - objective_id is null
raise: OperationFailed - unable to co... | Removes all children from an objective.
arg: objective_id (osid.id.Id): the Id of an objective
raise: NotFound - objective_id not found
raise: NullArgument - objective_id is null
raise: OperationFailed - unable to complete request
raise: PermissionDenied - authorization f... | Below is the the instruction that describes the task:
### Input:
Removes all children from an objective.
arg: objective_id (osid.id.Id): the Id of an objective
raise: NotFound - objective_id not found
raise: NullArgument - objective_id is null
raise: OperationFailed - unable t... |
def _getConfig(general_config_dir: str = None):
"""
Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object
"""
stp_config = STPConfig()
plenum_config = import_module("plenum.config")
config = stp_config
config.... | Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object | Below is the the instruction that describes the task:
### Input:
Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object
### Response:
def _getConfig(general_config_dir: str = None):
"""
Reads a file called config.py in the pr... |
def fetch(self, path, sender, msg):
"""
Start a transfer for a registered path.
:param str path:
File path.
:param mitogen.core.Sender sender:
Sender to receive file data.
:returns:
Dict containing the file metadata:
* ``size``: F... | Start a transfer for a registered path.
:param str path:
File path.
:param mitogen.core.Sender sender:
Sender to receive file data.
:returns:
Dict containing the file metadata:
* ``size``: File size in bytes.
* ``mode``: Integer file ... | Below is the the instruction that describes the task:
### Input:
Start a transfer for a registered path.
:param str path:
File path.
:param mitogen.core.Sender sender:
Sender to receive file data.
:returns:
Dict containing the file metadata:
... |
def allStockQoutation(self):
'''
订阅多只股票的行情数据
:return:
'''
logger = Logs().getNewLogger('allStockQoutation', QoutationAsynPush.dir)
markets= [Market.HK,Market.US,Market.SH,Market.SZ] #,Market.HK_FUTURE,Market.US_OPTION
stockTypes = [SecurityType.STOCK,SecurityType.... | 订阅多只股票的行情数据
:return: | Below is the the instruction that describes the task:
### Input:
订阅多只股票的行情数据
:return:
### Response:
def allStockQoutation(self):
'''
订阅多只股票的行情数据
:return:
'''
logger = Logs().getNewLogger('allStockQoutation', QoutationAsynPush.dir)
markets= [Market.HK,Market.U... |
def content():
"""Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message
"""
message = m.Message()
... | Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.message.Message | Below is the the instruction that describes the task:
### Input:
Helper method that returns just the content.
This method was added so that the text could be reused in the
dock_help module.
.. versionadded:: 3.2.2
:returns: A message object without brand element.
:rtype: safe.messaging.messag... |
def setup_column(self, widget, column=0, attribute=None, renderer=None,
property=None, from_python=None, to_python=None, model=None):
# Maybe this is too overloaded.
"""
Set up a :class:`TreeView` to display attributes of Python objects
stored in its :class:`TreeModel`.
... | Set up a :class:`TreeView` to display attributes of Python objects
stored in its :class:`TreeModel`.
This assumes that :class:`TreeViewColumn` instances have already
been added and :class:`CellRenderer` instances packed into them.
Both can be done in Glade.
*model* is the insta... | Below is the the instruction that describes the task:
### Input:
Set up a :class:`TreeView` to display attributes of Python objects
stored in its :class:`TreeModel`.
This assumes that :class:`TreeViewColumn` instances have already
been added and :class:`CellRenderer` instances packed into t... |
def connect(self, dest_pair):
"""
Connects to the specified destination through a proxy.
Uses the same API as socket's connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).
"""
if len(dest_pair) != 2 or dest_pair[0].s... | Connects to the specified destination through a proxy.
Uses the same API as socket's connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port). | Below is the the instruction that describes the task:
### Input:
Connects to the specified destination through a proxy.
Uses the same API as socket's connect().
To select the proxy server, use set_proxy().
dest_pair - 2-tuple of (IP/hostname, port).
### Response:
def connect(self, dest_pai... |
def data_filler_simple_registration(self, number_of_rows, db):
'''creates and fills the table with simple regis. information
'''
try:
simple_registration = db
for i in range(0, number_of_rows):
post_simple_reg = {
"id": rnd_id_generat... | creates and fills the table with simple regis. information | Below is the the instruction that describes the task:
### Input:
creates and fills the table with simple regis. information
### Response:
def data_filler_simple_registration(self, number_of_rows, db):
'''creates and fills the table with simple regis. information
'''
try:
simple... |
def backout_last(self, updated_singles, num_coincs):
"""Remove the recently added singles and coincs
Parameters
----------
updated_singles: dict of numpy.ndarrays
Array of indices that have been just updated in the internal
buffers of single detector triggers.
... | Remove the recently added singles and coincs
Parameters
----------
updated_singles: dict of numpy.ndarrays
Array of indices that have been just updated in the internal
buffers of single detector triggers.
num_coincs: int
The number of coincs that were... | Below is the the instruction that describes the task:
### Input:
Remove the recently added singles and coincs
Parameters
----------
updated_singles: dict of numpy.ndarrays
Array of indices that have been just updated in the internal
buffers of single detector trigger... |
def _forObject(self, obj):
"""
Create a new `Router` instance, with it's own set of routes, for
``obj``.
"""
router = type(self)()
router._routes = list(self._routes)
router._self = obj
return router | Create a new `Router` instance, with it's own set of routes, for
``obj``. | Below is the the instruction that describes the task:
### Input:
Create a new `Router` instance, with it's own set of routes, for
``obj``.
### Response:
def _forObject(self, obj):
"""
Create a new `Router` instance, with it's own set of routes, for
``obj``.
"""
route... |
def _visit_pyfiles(list, dirname, names):
"""Helper for getFilesForName()."""
# get extension for python source files
if not globals().has_key('_py_ext'):
global _py_ext
# _py_ext = [triple[0] for triple in imp.get_suffixes()
# if triple[2] == imp.PY_SOURCE][0]
_py_e... | Helper for getFilesForName(). | Below is the the instruction that describes the task:
### Input:
Helper for getFilesForName().
### Response:
def _visit_pyfiles(list, dirname, names):
"""Helper for getFilesForName()."""
# get extension for python source files
if not globals().has_key('_py_ext'):
global _py_ext
# _py_ext... |
def ind_zero_freq(self):
"""
Index of the first point for which the freqencies are equal or greater than zero.
"""
ind = np.searchsorted(self.frequencies, 0)
if ind >= len(self.frequencies):
raise ValueError("No positive frequencies found")
return ind | Index of the first point for which the freqencies are equal or greater than zero. | Below is the the instruction that describes the task:
### Input:
Index of the first point for which the freqencies are equal or greater than zero.
### Response:
def ind_zero_freq(self):
"""
Index of the first point for which the freqencies are equal or greater than zero.
"""
ind = n... |
def f_get_results(self, fast_access=False, copy=True):
""" Returns a dictionary containing the full result names as keys and the corresponding
result objects or result data items as values.
:param fast_access:
Determines whether the result objects or their values are returned
... | Returns a dictionary containing the full result names as keys and the corresponding
result objects or result data items as values.
:param fast_access:
Determines whether the result objects or their values are returned
in the dictionary. Works only for results if they contain a... | Below is the the instruction that describes the task:
### Input:
Returns a dictionary containing the full result names as keys and the corresponding
result objects or result data items as values.
:param fast_access:
Determines whether the result objects or their values are returned
... |
def alias_exists(aliases, indices=None, hosts=None, profile=None):
'''
Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example:... | Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
salt myminion elasticsearch.alias_exists None testindex | Below is the the instruction that describes the task:
### Input:
Return a boolean indicating whether given alias exists
indices
Single or multiple indices separated by comma, use _all to perform the operation on all indices.
aliases
Alias names separated by comma
CLI example::
... |
def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
"""
def create_worker(self, scheduler, worker_processes, assistant=False):
worker = luigi.worker.Worker(scheduler=scheduler, worker_process... | Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance. | Below is the the instruction that describes the task:
### Input:
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sandboxing information when
create a worker instance.
### Response:
def patch_worker_factory():
"""
Patches the ``luigi.interface._WorkerSchedulerFactory`` to include sand... |
def press(self, key_code):
""" Sends a 'down' event for the specified scan code """
if key_code >= 128:
# Media key
ev = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(
14, # type
(0, 0), # loc... | Sends a 'down' event for the specified scan code | Below is the the instruction that describes the task:
### Input:
Sends a 'down' event for the specified scan code
### Response:
def press(self, key_code):
""" Sends a 'down' event for the specified scan code """
if key_code >= 128:
# Media key
ev = NSEvent.otherEventWithType... |
def publish(self, cat, **kwargs):
"""
This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs"
"""
... | This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs" | Below is the the instruction that describes the task:
### Input:
This method is used for creating objects in the facebook graph.
The first paramter is "cat", the category of publish. In addition to "cat"
"id" must also be passed and is catched by "kwargs"
### Response:
def publish(s... |
def findNestedDirectories(self, lst):
'''
Recursive helper function for finding nested directories. If this node is a
directory node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedDirectories`` with the same list.
:Parameters:
``lst`... | Recursive helper function for finding nested directories. If this node is a
directory node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedDirectories`` with the same list.
:Parameters:
``lst`` (list)
The list each directory node is t... | Below is the the instruction that describes the task:
### Input:
Recursive helper function for finding nested directories. If this node is a
directory node, it is appended to ``lst``. Each node also calls each of its
child ``findNestedDirectories`` with the same list.
:Parameters:
... |
def GrabObject(self, identifier):
"""Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value ... | Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
RuntimeError: if the cache value is missing. | Below is the the instruction that describes the task:
### Input:
Grabs a cached object based on the identifier.
This method increments the cache value reference count.
Args:
identifier (str): VFS object identifier.
Raises:
KeyError: if the VFS object is not found in the cache.
Runti... |
def rlist_classes(module, cls_filter=None):
"""
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value... | Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's return value must be interpretable as a
boolean. Results that ev... | Below is the the instruction that describes the task:
### Input:
Attempts to list all of the classes within a given module namespace.
This method, unlike list_classes, will recurse into discovered
submodules.
If a type filter is set, it will be called with each class as its
parameter. This filter's... |
def _get_non_empty_list(cls, iter):
"""Return a list of the input, excluding all ``None`` values."""
res = []
for value in iter:
if hasattr(value, 'items'):
value = cls._get_non_empty_dict(value) or None
if value is not None:
res.append(val... | Return a list of the input, excluding all ``None`` values. | Below is the the instruction that describes the task:
### Input:
Return a list of the input, excluding all ``None`` values.
### Response:
def _get_non_empty_list(cls, iter):
"""Return a list of the input, excluding all ``None`` values."""
res = []
for value in iter:
if hasattr(v... |
def ensure_indexes(self):
"""Update the indexes"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if inde... | Update the indexes | Below is the the instruction that describes the task:
### Input:
Update the indexes
### Response:
def ensure_indexes(self):
"""Update the indexes"""
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
... |
def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties() | Update only one property in the dict | Below is the the instruction that describes the task:
### Input:
Update only one property in the dict
### Response:
def set_property(self, key, value):
"""
Update only one property in the dict
"""
self.properties[key] = value
self.sync_properties() |
def set(key, value={}, reset=False, init=False):
"""
Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the c... | Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value with the current
one
:param init: bool - If True, ... | Below is the the instruction that describes the task:
### Input:
Set data
:param key: A unique to set, best to use __name__
:param value: dict - the value to save
:param reset: bool - If true, it will reset the value to the current one.
if False, it will just update the stored value wi... |
def sens_power_send(self, adc121_vspb_volt, adc121_cspb_amp, adc121_cs1_amp, adc121_cs2_amp, force_mavlink1=False):
'''
Voltage and current sensor data
adc121_vspb_volt : Power board voltage sensor reading in volts (float)
adc121_cspb_amp ... | Voltage and current sensor data
adc121_vspb_volt : Power board voltage sensor reading in volts (float)
adc121_cspb_amp : Power board current sensor reading in amps (float)
adc121_cs1_amp : Board current sensor 1 reading in amps (float)
... | Below is the the instruction that describes the task:
### Input:
Voltage and current sensor data
adc121_vspb_volt : Power board voltage sensor reading in volts (float)
adc121_cspb_amp : Power board current sensor reading in amps (float)
adc121_cs1_... |
def MaskSolveSlow(A, b, w=5, progress=True, niter=None):
'''
Identical to `MaskSolve`, but computes the solution
the brute-force way.
'''
# Number of data points
N = b.shape[0]
# How many iterations? Default is to go through
# the entire dataset
if niter is None:
... | Identical to `MaskSolve`, but computes the solution
the brute-force way. | Below is the the instruction that describes the task:
### Input:
Identical to `MaskSolve`, but computes the solution
the brute-force way.
### Response:
def MaskSolveSlow(A, b, w=5, progress=True, niter=None):
'''
Identical to `MaskSolve`, but computes the solution
the brute-force way.
''... |
def calculate_nfft(samplerate, winlen):
"""Calculates the FFT size as a power of two greater than or equal to
the number of samples in a single window length.
Having an FFT less than the window length loses precision by dropping
many of the samples; a longer FFT than the window allows zero-padding
... | Calculates the FFT size as a power of two greater than or equal to
the number of samples in a single window length.
Having an FFT less than the window length loses precision by dropping
many of the samples; a longer FFT than the window allows zero-padding
of the FFT buffer which is neutral in terms... | Below is the the instruction that describes the task:
### Input:
Calculates the FFT size as a power of two greater than or equal to
the number of samples in a single window length.
Having an FFT less than the window length loses precision by dropping
many of the samples; a longer FFT than the windo... |
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dumps({"reception_time": self._reception_time,
"Location": json.loads(self._location.to_JSON()),
"Weather": json.loads... | Dumps object fields into a JSON formatted string
:returns: the JSON string | Below is the the instruction that describes the task:
### Input:
Dumps object fields into a JSON formatted string
:returns: the JSON string
### Response:
def to_JSON(self):
"""Dumps object fields into a JSON formatted string
:returns: the JSON string
"""
return json.dum... |
def concat(bed_files, catted=None):
"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
"""
bed_files = [x for x in bed_files if x]
if len(bed_files) == 0:
if catted:
# move to a .bed extension for downstream tools if not already
... | recursively concat a set of BED files, returning a
sorted bedtools object of the result | Below is the the instruction that describes the task:
### Input:
recursively concat a set of BED files, returning a
sorted bedtools object of the result
### Response:
def concat(bed_files, catted=None):
"""
recursively concat a set of BED files, returning a
sorted bedtools object of the result
... |
def saveAsTable(self, name, format=None, mode=None, partitionBy=None, **options):
"""Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwin... | Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwing an exception).
When `mode` is `Overwrite`, the schema of the :class:`DataFrame` doe... | Below is the the instruction that describes the task:
### Input:
Saves the content of the :class:`DataFrame` as the specified table.
In the case the table already exists, behavior of this function depends on the
save mode, specified by the `mode` function (default to throwing an exception).
... |
def resolve_all(self, import_items):
"""Resolves a list of imports.
Yields filenames.
"""
for import_item in import_items:
try:
yield self.resolve_import(import_item)
except ImportException as err:
logging.info('unknown module %s',... | Resolves a list of imports.
Yields filenames. | Below is the the instruction that describes the task:
### Input:
Resolves a list of imports.
Yields filenames.
### Response:
def resolve_all(self, import_items):
"""Resolves a list of imports.
Yields filenames.
"""
for import_item in import_items:
try:
... |
def trace_parser(self):
"""Method that parses the trace file once and updates the
:attr:`status_info` attribute with the new entries.
"""
# Check the timestamp of the tracefile. Only proceed with the parsing
# if it changed from the previous time.
size_stamp = os.path.ge... | Method that parses the trace file once and updates the
:attr:`status_info` attribute with the new entries. | Below is the the instruction that describes the task:
### Input:
Method that parses the trace file once and updates the
:attr:`status_info` attribute with the new entries.
### Response:
def trace_parser(self):
"""Method that parses the trace file once and updates the
:attr:`status_info` att... |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ErrorCode(key)
if key not in ErrorCode._member_map_:
extend_enum(ErrorCode, key, default)
return ErrorCode[key] | Backport support for original codes. | Below is the the instruction that describes the task:
### Input:
Backport support for original codes.
### Response:
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return ErrorCode(key)
if key not in ErrorCode._member_map_:
... |
def _get_example_csv(self):
"""For dimension parsing
"""
station_key = self.json["station"][0]["key"]
period = "corrected-archive"
url = self.url\
.replace(".json", "/station/{}/period/{}/data.csv"\
.format(station_key, period))
r = re... | For dimension parsing | Below is the the instruction that describes the task:
### Input:
For dimension parsing
### Response:
def _get_example_csv(self):
"""For dimension parsing
"""
station_key = self.json["station"][0]["key"]
period = "corrected-archive"
url = self.url\
.replace(... |
def inject_method(self, func, name=None):
"""
Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that there might be... | Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that there might be a better way.
Args:
self (object): insta... | Below is the the instruction that describes the task:
### Input:
Injects a function into an object instance as a bound method
The main use case of this function is for monkey patching. While monkey
patching is sometimes necessary it should generally be avoided. Thus, we
simply remind the developer that... |
def search_device_by_id(self, deviceID) -> Device:
""" searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device
"""
for d in self.devices:
... | searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device | Below is the the instruction that describes the task:
### Input:
searches a device by given id
Args:
deviceID(str): the device to search for
Returns
the Device object or None if it couldn't find a device
### Response:
def search_device_by_id(self, devic... |
def serializationDecision(cls, obj, serializedClasses,
serializedConfiguredUnits):
"""
Decide if this unit should be serialized or not eventually fix name
to fit same already serialized unit
:param obj: object to serialize
:param serializedClasses: ... | Decide if this unit should be serialized or not eventually fix name
to fit same already serialized unit
:param obj: object to serialize
:param serializedClasses: dict {unitCls : unitobj}
:param serializedConfiguredUnits: (unitCls, paramsValues) : unitObj
where paramsValues a... | Below is the the instruction that describes the task:
### Input:
Decide if this unit should be serialized or not eventually fix name
to fit same already serialized unit
:param obj: object to serialize
:param serializedClasses: dict {unitCls : unitobj}
:param serializedConfiguredUnit... |
def emit_stanza(self, element):
""""Serialize a stanza.
Must be called after `emit_head`.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:Returntype: `unicode`
... | Serialize a stanza.
Must be called after `emit_head`.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:Returntype: `unicode` | Below is the the instruction that describes the task:
### Input:
Serialize a stanza.
Must be called after `emit_head`.
:Parameters:
- `element`: the element to serialize
:Types:
- `element`: :etree:`ElementTree.Element`
:Return: serialized element
:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.