code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def add_walk_distances_to_db_python(gtfs, osm_path, cutoff_distance_m=1000):
"""
Computes the walk paths between stops, and updates these to the gtfs database.
Parameters
----------
gtfs: gtfspy.GTFS or str
A GTFS object or a string representation.
osm_path: str
path to the Open... | Computes the walk paths between stops, and updates these to the gtfs database.
Parameters
----------
gtfs: gtfspy.GTFS or str
A GTFS object or a string representation.
osm_path: str
path to the OpenStreetMap file
cutoff_distance_m: number
maximum allowed distance in meters
... | Below is the the instruction that describes the task:
### Input:
Computes the walk paths between stops, and updates these to the gtfs database.
Parameters
----------
gtfs: gtfspy.GTFS or str
A GTFS object or a string representation.
osm_path: str
path to the OpenStreetMap file
c... |
def _get_regular_expression_of_symbols(self):
"""
Returns the regular expression to search all symbols.
:return: The regular expression to search all symbols.
:rtype: str
"""
regular_expression = None
for symbol in self.symbols:
formated_symbol = sel... | Returns the regular expression to search all symbols.
:return: The regular expression to search all symbols.
:rtype: str | Below is the the instruction that describes the task:
### Input:
Returns the regular expression to search all symbols.
:return: The regular expression to search all symbols.
:rtype: str
### Response:
def _get_regular_expression_of_symbols(self):
"""
Returns the regular expression t... |
def clear_file(self):
"""stub"""
if (self.get_file_metadata().is_read_only() or
self.get_file_metadata().is_required()):
raise NoAccess()
if 'assetId' in self.my_osid_object_form._my_map['fileId']:
rm = self.my_osid_object_form._get_provider_manager('REPOS... | stub | Below is the the instruction that describes the task:
### Input:
stub
### Response:
def clear_file(self):
"""stub"""
if (self.get_file_metadata().is_read_only() or
self.get_file_metadata().is_required()):
raise NoAccess()
if 'assetId' in self.my_osid_object_form.... |
def is_unitary(
matrix: np.ndarray,
*,
rtol: float = 1e-5,
atol: float = 1e-8) -> bool:
"""Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-ma... | Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: The per-matrix-entry absolute tolerance on equality.
Returns:
... | Below is the the instruction that describes the task:
### Input:
Determines if a matrix is approximately unitary.
A matrix is unitary if it's square and its adjoint is its inverse.
Args:
matrix: The matrix to check.
rtol: The per-matrix-entry relative tolerance on equality.
atol: T... |
def _parse_vars(self, tokens):
"""
Given an iterable of tokens, returns variables and their values as a
dictionary.
For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'}
"""
key_values = {}... | Given an iterable of tokens, returns variables and their values as a
dictionary.
For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'} | Below is the the instruction that describes the task:
### Input:
Given an iterable of tokens, returns variables and their values as a
dictionary.
For example:
['dtap=prod', 'comment=some comment']
Returns:
{'dtap': 'prod', 'comment': 'some comment'}
### Response:
de... |
def _transform_incoming(self, son, collection, skip=0):
"""Recursively replace all keys that need transforming."""
skip = 0 if skip < 0 else skip
if isinstance(son, dict):
for (key, value) in son.items():
if key.startswith('$'):
if isinstance(value... | Recursively replace all keys that need transforming. | Below is the the instruction that describes the task:
### Input:
Recursively replace all keys that need transforming.
### Response:
def _transform_incoming(self, son, collection, skip=0):
"""Recursively replace all keys that need transforming."""
skip = 0 if skip < 0 else skip
if isinstance... |
def set_limit_override(self, limit_name, value, override_ta=True):
"""
Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to... | Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to the
:py:meth:`~awslimitchecker.limit.AwsLimit.set_limit_override`
meth... | Below is the the instruction that describes the task:
### Input:
Set a new limit ``value`` for the specified limit, overriding
the default. If ``override_ta`` is True, also use this value
instead of any found by Trusted Advisor. This method simply
passes the data through to the
:py:m... |
def debug(frame=None):
"""Set breakpoint at current location, or a specified frame"""
# ???
if frame is None:
frame = _frame().f_back
dbg = RemoteCeleryTrepan()
dbg.say(BANNER.format(self=dbg))
# dbg.say(SESSION_STARTED.format(self=dbg))
trepan.api.debug(dbg_opts=dbg.dbg_opts) | Set breakpoint at current location, or a specified frame | Below is the the instruction that describes the task:
### Input:
Set breakpoint at current location, or a specified frame
### Response:
def debug(frame=None):
"""Set breakpoint at current location, or a specified frame"""
# ???
if frame is None:
frame = _frame().f_back
dbg = RemoteCeleryTr... |
def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode element is reset.
"""
super(Table, self).removeChild(child)
if child.tagName == ligolw.Column.tagName:
self._update_column_info()
return child | Remove a child from this element. The child element is
returned, and it's parentNode element is reset. | Below is the the instruction that describes the task:
### Input:
Remove a child from this element. The child element is
returned, and it's parentNode element is reset.
### Response:
def removeChild(self, child):
"""
Remove a child from this element. The child element is
returned, and it's parentNode elem... |
def set_or_edit_conditional_breakpoint(self):
"""Set/Edit conditional breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.switch_to_plugin()
editorstack.set_or_edit_conditional_breakpoint() | Set/Edit conditional breakpoint | Below is the the instruction that describes the task:
### Input:
Set/Edit conditional breakpoint
### Response:
def set_or_edit_conditional_breakpoint(self):
"""Set/Edit conditional breakpoint"""
editorstack = self.get_current_editorstack()
if editorstack is not None:
self.sw... |
def OnShiftVideo(self, event):
"""Shifts through the video"""
length = self.player.get_length()
time = self.player.get_time()
if event.GetWheelRotation() < 0:
target_time = max(0, time-length/100.0)
elif event.GetWheelRotation() > 0:
target_time = min(le... | Shifts through the video | Below is the the instruction that describes the task:
### Input:
Shifts through the video
### Response:
def OnShiftVideo(self, event):
"""Shifts through the video"""
length = self.player.get_length()
time = self.player.get_time()
if event.GetWheelRotation() < 0:
target... |
def set_basic_params(self, no_expire=None, expire_scan_interval=None, report_freed=None):
"""
:param bool no_expire: Disable auto sweep of expired items.
Since uWSGI 1.2, cache item expiration is managed by a thread in the master process,
to reduce the risk of deadlock. This thre... | :param bool no_expire: Disable auto sweep of expired items.
Since uWSGI 1.2, cache item expiration is managed by a thread in the master process,
to reduce the risk of deadlock. This thread can be disabled
(making item expiry a no-op) with the this option.
:param int expire_s... | Below is the the instruction that describes the task:
### Input:
:param bool no_expire: Disable auto sweep of expired items.
Since uWSGI 1.2, cache item expiration is managed by a thread in the master process,
to reduce the risk of deadlock. This thread can be disabled
(making it... |
def get_short_uid(self, uid):
"""Get the shortend UID for the given UID.
:param uid: the full UID to shorten
:type uid: str
:returns: the shortend uid or the empty string
:rtype: str
"""
if uid:
short_uids = self.get_short_uid_dict()
for l... | Get the shortend UID for the given UID.
:param uid: the full UID to shorten
:type uid: str
:returns: the shortend uid or the empty string
:rtype: str | Below is the the instruction that describes the task:
### Input:
Get the shortend UID for the given UID.
:param uid: the full UID to shorten
:type uid: str
:returns: the shortend uid or the empty string
:rtype: str
### Response:
def get_short_uid(self, uid):
"""Get the shor... |
def append(self, point):
"""
appends a copy of the given point to this sequence
"""
point = Point(point)
self._elements.append(point) | appends a copy of the given point to this sequence | Below is the the instruction that describes the task:
### Input:
appends a copy of the given point to this sequence
### Response:
def append(self, point):
"""
appends a copy of the given point to this sequence
"""
point = Point(point)
self._elements.append(point) |
def get_subgraph_by_node_search(graph: BELGraph, query: Strings) -> BELGraph:
"""Get a sub-graph induced over all nodes matching the query string.
:param graph: A BEL Graph
:param query: A query string or iterable of query strings for node names
Thinly wraps :func:`search_node_names` and :func:`get_su... | Get a sub-graph induced over all nodes matching the query string.
:param graph: A BEL Graph
:param query: A query string or iterable of query strings for node names
Thinly wraps :func:`search_node_names` and :func:`get_subgraph_by_induction`. | Below is the the instruction that describes the task:
### Input:
Get a sub-graph induced over all nodes matching the query string.
:param graph: A BEL Graph
:param query: A query string or iterable of query strings for node names
Thinly wraps :func:`search_node_names` and :func:`get_subgraph_by_induct... |
def gravity(latitude, H):
r'''Calculates local acceleration due to gravity `g` according to [1]_.
Uses latitude and height to calculate `g`.
.. math::
g = 9.780356(1 + 0.0052885\sin^2\phi - 0.0000059^22\phi)
- 3.086\times 10^{-6} H
Parameters
----------
latitude : float
... | r'''Calculates local acceleration due to gravity `g` according to [1]_.
Uses latitude and height to calculate `g`.
.. math::
g = 9.780356(1 + 0.0052885\sin^2\phi - 0.0000059^22\phi)
- 3.086\times 10^{-6} H
Parameters
----------
latitude : float
Degrees, [degrees]
H : fl... | Below is the the instruction that describes the task:
### Input:
r'''Calculates local acceleration due to gravity `g` according to [1]_.
Uses latitude and height to calculate `g`.
.. math::
g = 9.780356(1 + 0.0052885\sin^2\phi - 0.0000059^22\phi)
- 3.086\times 10^{-6} H
Parameters
... |
def getPreprocessorDefinitions(self, engineRoot, delimiter=' '):
"""
Returns the list of preprocessor definitions for this library, joined using the specified delimiter
"""
return delimiter.join(self.resolveRoot(self.definitions, engineRoot)) | Returns the list of preprocessor definitions for this library, joined using the specified delimiter | Below is the the instruction that describes the task:
### Input:
Returns the list of preprocessor definitions for this library, joined using the specified delimiter
### Response:
def getPreprocessorDefinitions(self, engineRoot, delimiter=' '):
"""
Returns the list of preprocessor definitions for this library, ... |
def process_xml(xml_str):
"""Return processor with Statements extracted from a Sparser XML.
Parameters
----------
xml_str : str
The XML string obtained by reading content with Sparser, using the
'xml' output mode.
Returns
-------
sp : SparserXMLProcessor
A SparserXM... | Return processor with Statements extracted from a Sparser XML.
Parameters
----------
xml_str : str
The XML string obtained by reading content with Sparser, using the
'xml' output mode.
Returns
-------
sp : SparserXMLProcessor
A SparserXMLProcessor which has extracted St... | Below is the the instruction that describes the task:
### Input:
Return processor with Statements extracted from a Sparser XML.
Parameters
----------
xml_str : str
The XML string obtained by reading content with Sparser, using the
'xml' output mode.
Returns
-------
sp : Spa... |
def get_owner_names_value(self, obj):
"""Extract owners' names."""
return [
self._get_user(user)
for user in get_users_with_permission(obj, get_full_perm('owner', obj))
] | Extract owners' names. | Below is the the instruction that describes the task:
### Input:
Extract owners' names.
### Response:
def get_owner_names_value(self, obj):
"""Extract owners' names."""
return [
self._get_user(user)
for user in get_users_with_permission(obj, get_full_perm('owner', obj))
... |
def get_work_item_template(self, project, type, fields=None, as_of=None, expand=None):
"""GetWorkItemTemplate.
[Preview API] Returns a single work item from a template.
:param str project: Project ID or project name
:param str type: The work item type name
:param str fields: Comm... | GetWorkItemTemplate.
[Preview API] Returns a single work item from a template.
:param str project: Project ID or project name
:param str type: The work item type name
:param str fields: Comma-separated list of requested fields
:param datetime as_of: AsOf UTC date time string
... | Below is the the instruction that describes the task:
### Input:
GetWorkItemTemplate.
[Preview API] Returns a single work item from a template.
:param str project: Project ID or project name
:param str type: The work item type name
:param str fields: Comma-separated list of requested... |
def _find_single(self, match_class, **keywds):
"""implementation details"""
self._logger.debug('find single query execution - started')
start_time = timeit.default_timer()
norm_keywds = self.__normalize_args(**keywds)
decl_matcher = self.__create_matcher(match_class, **norm_keywd... | implementation details | Below is the the instruction that describes the task:
### Input:
implementation details
### Response:
def _find_single(self, match_class, **keywds):
"""implementation details"""
self._logger.debug('find single query execution - started')
start_time = timeit.default_timer()
norm_keyw... |
def spans(self, layer):
"""Retrieve (start, end) tuples denoting the spans of given layer elements.
Returns
-------
list of (int, int)
List of (start, end) tuples.
"""
spans = []
for data in self[layer]:
spans.append((data[START], data[END... | Retrieve (start, end) tuples denoting the spans of given layer elements.
Returns
-------
list of (int, int)
List of (start, end) tuples. | Below is the the instruction that describes the task:
### Input:
Retrieve (start, end) tuples denoting the spans of given layer elements.
Returns
-------
list of (int, int)
List of (start, end) tuples.
### Response:
def spans(self, layer):
"""Retrieve (start, end) tuple... |
def _element_to_dict(data, position, obj_end, opts):
"""Decode a single key, value pair."""
element_type = data[position:position + 1]
position += 1
element_name, position = _get_c_string(data, position, opts)
try:
value, position = _ELEMENT_GETTER[element_type](data, position,
... | Decode a single key, value pair. | Below is the the instruction that describes the task:
### Input:
Decode a single key, value pair.
### Response:
def _element_to_dict(data, position, obj_end, opts):
"""Decode a single key, value pair."""
element_type = data[position:position + 1]
position += 1
element_name, position = _get_c_string... |
def _filter_tables_by_time(self, tables, start_time, end_time):
"""Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int... | Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int
The unix time after which records will be fetched
end_... | Below is the the instruction that describes the task:
### Input:
Filter a table dictionary and return table names based on the range
of start and end times in unix seconds.
Parameters
----------
tables : dict
Dates referenced by table names
start_time : int
... |
def dump(self, force=False):
"""
Encodes the value using DER
:param force:
If the encoded contents already exist, clear them and regenerate
to ensure they are in DER format instead of BER format
:return:
A byte string of the DER-encoded value
... | Encodes the value using DER
:param force:
If the encoded contents already exist, clear them and regenerate
to ensure they are in DER format instead of BER format
:return:
A byte string of the DER-encoded value | Below is the the instruction that describes the task:
### Input:
Encodes the value using DER
:param force:
If the encoded contents already exist, clear them and regenerate
to ensure they are in DER format instead of BER format
:return:
A byte string of the DER-e... |
def generate(self):
"""
Generates and returns a numeric captcha image in base64 format.
Saves the correct answer in `session['captcha_answer']`
Use later as:
src = captcha.generate()
<img src="{{src}}">
"""
answer = self.rand.randrange(se... | Generates and returns a numeric captcha image in base64 format.
Saves the correct answer in `session['captcha_answer']`
Use later as:
src = captcha.generate()
<img src="{{src}}"> | Below is the the instruction that describes the task:
### Input:
Generates and returns a numeric captcha image in base64 format.
Saves the correct answer in `session['captcha_answer']`
Use later as:
src = captcha.generate()
<img src="{{src}}">
### Response:
def generate(self):
... |
def md_to_text(content):
""" Converts markdown content to text """
text = None
html = markdown.markdown(content)
if html:
text = html_to_text(content)
return text | Converts markdown content to text | Below is the the instruction that describes the task:
### Input:
Converts markdown content to text
### Response:
def md_to_text(content):
""" Converts markdown content to text """
text = None
html = markdown.markdown(content)
if html:
text = html_to_text(content)
return text |
def sequence(arcs):
"""sequence: make a list of cities to visit, from set of arcs"""
succ = {}
for (i,j) in arcs:
succ[i] = j
curr = 1 # first node being visited
sol = [curr]
for i in range(len(arcs)-2):
curr = succ[curr]
sol.append(curr)
return sol | sequence: make a list of cities to visit, from set of arcs | Below is the the instruction that describes the task:
### Input:
sequence: make a list of cities to visit, from set of arcs
### Response:
def sequence(arcs):
"""sequence: make a list of cities to visit, from set of arcs"""
succ = {}
for (i,j) in arcs:
succ[i] = j
curr = 1 # first node be... |
def mk_request_non(self, method, path):
"""
Create a request.
:param method: the CoAP method
:param path: the path of the request
:return: the request
"""
request = Request()
request.destination = self.server
request.code = method.number
... | Create a request.
:param method: the CoAP method
:param path: the path of the request
:return: the request | Below is the the instruction that describes the task:
### Input:
Create a request.
:param method: the CoAP method
:param path: the path of the request
:return: the request
### Response:
def mk_request_non(self, method, path):
"""
Create a request.
:param method: t... |
def use_storage_service(self, service_name, custom_path):
"""
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage ... | Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional, and must already exist, use absolute paths only) | Below is the the instruction that describes the task:
### Input:
Sets the current storage service to service_name and runs the connect method on the service.
:param str service_name: Name of the storage service
:param str custom_path: Custom path where to download tracks for local storage (optional... |
def check_cgroup_availability(wait=1):
"""
Basic utility to check the availability and permissions of cgroups.
This will log some warnings for the user if necessary.
On some systems, daemons such as cgrulesengd might interfere with the cgroups
of a process soon after it was started. Thus this functi... | Basic utility to check the availability and permissions of cgroups.
This will log some warnings for the user if necessary.
On some systems, daemons such as cgrulesengd might interfere with the cgroups
of a process soon after it was started. Thus this function starts a process,
waits a configurable amoun... | Below is the the instruction that describes the task:
### Input:
Basic utility to check the availability and permissions of cgroups.
This will log some warnings for the user if necessary.
On some systems, daemons such as cgrulesengd might interfere with the cgroups
of a process soon after it was started... |
def participation_coef(W, ci, degree='undirected'):
'''
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
com... | Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
community affiliation vector
degree : str
Flag to descr... | Below is the the instruction that describes the task:
### Input:
Participation coefficient is a measure of diversity of intermodular
connections of individual nodes.
Parameters
----------
W : NxN np.ndarray
binary/weighted directed/undirected connection matrix
ci : Nx1 np.ndarray
... |
def uptodate():
'''
Call the REST endpoint to see if the packages on the "server" are up to date.
'''
DETAILS = _load_state()
for p in DETAILS['packages']:
version_float = float(DETAILS['packages'][p])
version_float = version_float + 1.0
DETAILS['packages'][p] = six.text_type... | Call the REST endpoint to see if the packages on the "server" are up to date. | Below is the the instruction that describes the task:
### Input:
Call the REST endpoint to see if the packages on the "server" are up to date.
### Response:
def uptodate():
'''
Call the REST endpoint to see if the packages on the "server" are up to date.
'''
DETAILS = _load_state()
for p in DET... |
def get_credentials_from_env():
"""Get credentials from environment variables.
Preference of credentials is:
- No credentials if DATASTORE_EMULATOR_HOST is set.
- Google APIs Signed JWT credentials based on
DATASTORE_SERVICE_ACCOUNT and DATASTORE_PRIVATE_KEY_FILE
environments variables
- Google Applicati... | Get credentials from environment variables.
Preference of credentials is:
- No credentials if DATASTORE_EMULATOR_HOST is set.
- Google APIs Signed JWT credentials based on
DATASTORE_SERVICE_ACCOUNT and DATASTORE_PRIVATE_KEY_FILE
environments variables
- Google Application Default
https://developers.googl... | Below is the the instruction that describes the task:
### Input:
Get credentials from environment variables.
Preference of credentials is:
- No credentials if DATASTORE_EMULATOR_HOST is set.
- Google APIs Signed JWT credentials based on
DATASTORE_SERVICE_ACCOUNT and DATASTORE_PRIVATE_KEY_FILE
environment... |
def _resource(methode, zone, resource_type, resource_selector, **kwargs):
'''
internal resource hanlder
methode : string
add or update
zone : string
name of zone
resource_type : string
type of resource
resource_selector : string
unique resource identifier
**k... | internal resource hanlder
methode : string
add or update
zone : string
name of zone
resource_type : string
type of resource
resource_selector : string
unique resource identifier
**kwargs : string|int|...
resource properties | Below is the the instruction that describes the task:
### Input:
internal resource hanlder
methode : string
add or update
zone : string
name of zone
resource_type : string
type of resource
resource_selector : string
unique resource identifier
**kwargs : string|in... |
def read_configuration(self):
"""
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
"""
# get distutils to do the work
... | Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration. | Below is the the instruction that describes the task:
### Input:
Read the PyPI access configuration as supported by distutils, getting
PyPI to do the actual work. This populates ``username``, ``password``,
``realm`` and ``url`` attributes from the configuration.
### Response:
def read_configuration... |
def cwd_filt(depth):
"""Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned."""
cwd = os.getcwdu().replace(HOME,"~")
out = os.sep.join(cwd.split(os.sep)[-depth:])
return out or os.sep | Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned. | Below is the the instruction that describes the task:
### Input:
Return the last depth elements of the current working directory.
$HOME is always replaced with '~'.
If depth==0, the full path is returned.
### Response:
def cwd_filt(depth):
"""Return the last depth elements of the current working direc... |
def inspect_to_metadata(metadata_object, inspect_data):
"""
process data from `docker inspect` and update provided metadata object
:param metadata_object: instance of Metadata
:param inspect_data: dict, metadata from `docker inspect` or `dockert_client.images()`
:return: instance of Metadata
""... | process data from `docker inspect` and update provided metadata object
:param metadata_object: instance of Metadata
:param inspect_data: dict, metadata from `docker inspect` or `dockert_client.images()`
:return: instance of Metadata | Below is the the instruction that describes the task:
### Input:
process data from `docker inspect` and update provided metadata object
:param metadata_object: instance of Metadata
:param inspect_data: dict, metadata from `docker inspect` or `dockert_client.images()`
:return: instance of Metadata
### R... |
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
"""Get console screen buffer info object."""
handle = handles[stream_id]
csbi = CONSOLE_SCREEN_BUFFER_INFO()
success = windll.kernel32.GetConsoleScreenBufferInfo(
handle, byref(csbi))
if not success:
raise WinError()
return csbi | Get console screen buffer info object. | Below is the the instruction that describes the task:
### Input:
Get console screen buffer info object.
### Response:
def GetConsoleScreenBufferInfo(stream_id=STDOUT):
"""Get console screen buffer info object."""
handle = handles[stream_id]
csbi = CONSOLE_SCREEN_BUFFER_INFO()
success = windll.kerne... |
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
"""Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls.
"""
lock = lock_cls(path)
max_t = time.time() + timeout
while True:
if time.time() >= ... | Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls. | Below is the the instruction that describes the task:
### Input:
Cooperative file lock. Uses `lockfile.LockFile` polling under the hood.
`maxdelay` defines the interval between individual polls.
### Response:
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0):
"""Cooperative file lock. Uses... |
def configure(self, inputs, outputs):
"""Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Property`)
:para... | Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Property`)
:param outputs: iterable of output property models
... | Below is the the instruction that describes the task:
### Input:
Configure activity input and output.
You need to provide a list of input and output :class:`Property`. Does not work with lists of propery id's.
:param inputs: iterable of input property models
:type inputs: list(:class:`Prop... |
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
return s.uint8 + GetVarSize(self.Key) + GetVarSize(self.Field) + GetVarSize(self.Value) | Get the total size in bytes of the object.
Returns:
int: size. | Below is the the instruction that describes the task:
### Input:
Get the total size in bytes of the object.
Returns:
int: size.
### Response:
def Size(self):
"""
Get the total size in bytes of the object.
Returns:
int: size.
"""
return s.ui... |
def _dfs_postorder(node, visited):
"""Iterate through nodes in DFS post-order."""
if node.lo is not None:
yield from _dfs_postorder(node.lo, visited)
if node.hi is not None:
yield from _dfs_postorder(node.hi, visited)
if node not in visited:
visited.add(node)
yield node | Iterate through nodes in DFS post-order. | Below is the the instruction that describes the task:
### Input:
Iterate through nodes in DFS post-order.
### Response:
def _dfs_postorder(node, visited):
"""Iterate through nodes in DFS post-order."""
if node.lo is not None:
yield from _dfs_postorder(node.lo, visited)
if node.hi is not None:
... |
def subn(pattern, repl, string, count=0, flags=0):
"""Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that wer... | Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutions that were made. repl can be either a string or a
callable; if ... | Below is the the instruction that describes the task:
### Input:
Return a 2-tuple containing (new_string, number).
new_string is the string obtained by replacing the leftmost
non-overlapping occurrences of the pattern in the source
string by the replacement repl. number is the number of
substitutio... |
def _sync_dag_view_permissions(self, dag_id, access_control):
"""Set the access policy on the given DAG's ViewModel.
:param dag_id: the ID of the DAG whose permissions should be updated
:type dag_id: string
:param access_control: a dict where each key is a rolename and
each ... | Set the access policy on the given DAG's ViewModel.
:param dag_id: the ID of the DAG whose permissions should be updated
:type dag_id: string
:param access_control: a dict where each key is a rolename and
each value is a set() of permission names (e.g.,
{'can_dag_read'}
... | Below is the the instruction that describes the task:
### Input:
Set the access policy on the given DAG's ViewModel.
:param dag_id: the ID of the DAG whose permissions should be updated
:type dag_id: string
:param access_control: a dict where each key is a rolename and
each valu... |
def to_mesh(obj):
'''
to_mesh(obj) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself
a mesh object.
The following objects can be converted into meshes:
* a mesh object
* a tuple (coords, faces) where coords is a coordinate matrix and faces is a matrix of
... | to_mesh(obj) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself
a mesh object.
The following objects can be converted into meshes:
* a mesh object
* a tuple (coords, faces) where coords is a coordinate matrix and faces is a matrix of
coordinate indices tha... | Below is the the instruction that describes the task:
### Input:
to_mesh(obj) yields a Mesh object that is equivalent to obj or identical to obj if obj is itself
a mesh object.
The following objects can be converted into meshes:
* a mesh object
* a tuple (coords, faces) where coords is a coor... |
def _pload32(ins):
""" Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
"""
output = _pload(ins.quad[2], 4)
output.append('push de')
output.append('push hl')
return output | Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address. | Below is the the instruction that describes the task:
### Input:
Loads from stack pointer (SP) + X, being
X 2st parameter.
1st operand must be a SIGNED integer.
2nd operand cannot be an immediate nor an address.
### Response:
def _pload32(ins):
""" Loads from stack pointer (SP) + X, being
X 2s... |
def open(self, output_only = False, shared = True):
"""Open HID device and obtain 'Collection Information'.
It effectively prepares the HidDevice object for reading and writing
"""
if self.is_opened():
raise HIDError("Device already opened")
sharing_flags = 0
... | Open HID device and obtain 'Collection Information'.
It effectively prepares the HidDevice object for reading and writing | Below is the the instruction that describes the task:
### Input:
Open HID device and obtain 'Collection Information'.
It effectively prepares the HidDevice object for reading and writing
### Response:
def open(self, output_only = False, shared = True):
"""Open HID device and obtain 'Collection In... |
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
'''
if not salt.utils.validate.net.mac(bdaddr):
raise CommandExecutionError(
'Invalid BD address passed to bluetooth.... | Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE | Below is the the instruction that describes the task:
### Input:
Block a specific bluetooth device by BD Address
CLI Example:
.. code-block:: bash
salt '*' bluetooth.block DE:AD:BE:EF:CA:FE
### Response:
def block(bdaddr):
'''
Block a specific bluetooth device by BD Address
CLI Exam... |
def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
division = obj
# In case of house special election,
# use parent division.
if obj.level.name == Div... | All content for a state's page on an election day. | Below is the the instruction that describes the task:
### Input:
All content for a state's page on an election day.
### Response:
def get_content(self, obj):
"""All content for a state's page on an election day."""
election_day = ElectionDay.objects.get(
date=self.context['election_date... |
def pub_dates(soup):
"""
return a list of all the pub dates
"""
pub_dates = []
tags = raw_parser.pub_date(soup)
for tag in tags:
pub_date = OrderedDict()
copy_attribute(tag.attrs, 'publication-format', pub_date)
copy_attribute(tag.attrs, 'date-type', pub_date)
cop... | return a list of all the pub dates | Below is the the instruction that describes the task:
### Input:
return a list of all the pub dates
### Response:
def pub_dates(soup):
"""
return a list of all the pub dates
"""
pub_dates = []
tags = raw_parser.pub_date(soup)
for tag in tags:
pub_date = OrderedDict()
copy_at... |
def status(cls):
"""Retrieve global status from status.gandi.net."""
return cls.json_get('%s/status' % cls.api_url, empty_key=True,
send_key=False) | Retrieve global status from status.gandi.net. | Below is the the instruction that describes the task:
### Input:
Retrieve global status from status.gandi.net.
### Response:
def status(cls):
"""Retrieve global status from status.gandi.net."""
return cls.json_get('%s/status' % cls.api_url, empty_key=True,
send_key=False... |
def text_editor(file='', background=False, return_cmd=False):
'''Starts the default graphical text editor.
Start the user's preferred graphical text editor, optionally with a file.
Args:
file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file).
background (bool): Runs... | Starts the default graphical text editor.
Start the user's preferred graphical text editor, optionally with a file.
Args:
file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file).
background (bool): Runs the editor in the background, instead of waiting for completion. ... | Below is the the instruction that describes the task:
### Input:
Starts the default graphical text editor.
Start the user's preferred graphical text editor, optionally with a file.
Args:
file (str) : The file to be opened with the editor. Defaults to an empty string (i.e. no file).
background (bool): R... |
def _process_using_meta_feature_generator(self, X, meta_feature_generator):
"""Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make s... | Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary learner
has the method.
Args:
X (array-like)... | Below is the the instruction that describes the task:
### Input:
Process using secondary learner meta-feature generator
Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba,
this internal method gives the ability to use any string. Just make sure secondary lear... |
def run_in_parallel(programs, nsamples, cxn, shuffle=True):
"""
Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of
programs that executes the input programs in parallel. Optionally randomize within each
qubit-specific sequence.
The programs are passed as a 2d a... | Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of
programs that executes the input programs in parallel. Optionally randomize within each
qubit-specific sequence.
The programs are passed as a 2d array of Quil programs, where the (first) outer axis iterates
over di... | Below is the the instruction that describes the task:
### Input:
Take sequences of Protoquil programs on disjoint qubits and execute a single sequence of
programs that executes the input programs in parallel. Optionally randomize within each
qubit-specific sequence.
The programs are passed as a 2d arra... |
def vq_discrete_unbottleneck(x, hparams):
"""Simple undiscretization from vector quantized representation."""
x_shape = common_layers.shape_list(x)
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_flat = tf.reshape(x, [-1, bottleneck_size])
result = tf.matmul(x_flat, means)
result = tf... | Simple undiscretization from vector quantized representation. | Below is the the instruction that describes the task:
### Input:
Simple undiscretization from vector quantized representation.
### Response:
def vq_discrete_unbottleneck(x, hparams):
"""Simple undiscretization from vector quantized representation."""
x_shape = common_layers.shape_list(x)
bottleneck_size = 2*... |
def sort_download_list(self):
"""
Method for sorting the list of download requests. Band images have priority before metadata files. If bands
images or metadata files are specified with a list they will be sorted in the same order as in the list.
Otherwise they will be sorted alphabetica... | Method for sorting the list of download requests. Band images have priority before metadata files. If bands
images or metadata files are specified with a list they will be sorted in the same order as in the list.
Otherwise they will be sorted alphabetically (band B8A will be between B08 and B09). | Below is the the instruction that describes the task:
### Input:
Method for sorting the list of download requests. Band images have priority before metadata files. If bands
images or metadata files are specified with a list they will be sorted in the same order as in the list.
Otherwise they will be... |
def status(self):
"""Reads a command response status.
If there is no response message then the returned status message will
be an empty string.
Raises:
NNTPError: If data is required to be read from the socket and fails.
NNTPProtocolError: If the status line can... | Reads a command response status.
If there is no response message then the returned status message will
be an empty string.
Raises:
NNTPError: If data is required to be read from the socket and fails.
NNTPProtocolError: If the status line can't be parsed.
NNT... | Below is the the instruction that describes the task:
### Input:
Reads a command response status.
If there is no response message then the returned status message will
be an empty string.
Raises:
NNTPError: If data is required to be read from the socket and fails.
N... |
def make_entity_name(name):
"""Creates a valid PlantUML entity name from the given value."""
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
name = name.replace(char, "_")
return name | Creates a valid PlantUML entity name from the given value. | Below is the the instruction that describes the task:
### Input:
Creates a valid PlantUML entity name from the given value.
### Response:
def make_entity_name(name):
"""Creates a valid PlantUML entity name from the given value."""
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
... |
async def delete(self, *, reason=None):
"""|coro|
Deletes the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this role. Shows up on the ... | |coro|
Deletes the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this role. Shows up on the audit log.
Raises
--------
... | Below is the the instruction that describes the task:
### Input:
|coro|
Deletes the role.
You must have the :attr:`~Permissions.manage_roles` permission to
use this.
Parameters
-----------
reason: Optional[:class:`str`]
The reason for deleting this role... |
def get_hg_revision(repopath):
"""Return Mercurial revision for the repository located at repopath
Result is a tuple (global, local, branch), with None values on error
For example:
>>> get_hg_revision(".")
('eba7273c69df+', '2015+', 'default')
"""
try:
ass... | Return Mercurial revision for the repository located at repopath
Result is a tuple (global, local, branch), with None values on error
For example:
>>> get_hg_revision(".")
('eba7273c69df+', '2015+', 'default') | Below is the the instruction that describes the task:
### Input:
Return Mercurial revision for the repository located at repopath
Result is a tuple (global, local, branch), with None values on error
For example:
>>> get_hg_revision(".")
('eba7273c69df+', '2015+', 'default')
#... |
def close(self):
"""Closes this response."""
if self._connection:
self._connection.close()
self._response.close() | Closes this response. | Below is the the instruction that describes the task:
### Input:
Closes this response.
### Response:
def close(self):
"""Closes this response."""
if self._connection:
self._connection.close()
self._response.close() |
def train_epoch(model:nn.Module, dl:DataLoader, opt:optim.Optimizer, loss_func:LossFunction)->None:
"Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`."
model.train()
for xb,yb in dl:
loss = loss_func(model(xb), yb)
loss.backward()
opt.ste... | Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`. | Below is the the instruction that describes the task:
### Input:
Simple training of `model` for 1 epoch of `dl` using optim `opt` and loss function `loss_func`.
### Response:
def train_epoch(model:nn.Module, dl:DataLoader, opt:optim.Optimizer, loss_func:LossFunction)->None:
"Simple training of `model` for 1 ep... |
def getOneMessage ( self ):
"""
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until... | I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore call me in a loop until I return None. | Below is the the instruction that describes the task:
### Input:
I pull one complete message off the buffer and return it decoded
as a dict. If there is no complete message in the buffer, I
return None.
Note that the buffer can contain more than once message. You
should therefore ca... |
def do_struct(self, subcmd, opts, message):
"""${cmd_name}: get the structure of the specified message
${cmd_usage}
${cmd_option_list}
"""
client = MdClient(self.maildir, filesystem=self.filesystem)
as_json = getattr(opts, "json", False)
client.getstruct(message,... | ${cmd_name}: get the structure of the specified message
${cmd_usage}
${cmd_option_list} | Below is the the instruction that describes the task:
### Input:
${cmd_name}: get the structure of the specified message
${cmd_usage}
${cmd_option_list}
### Response:
def do_struct(self, subcmd, opts, message):
"""${cmd_name}: get the structure of the specified message
${cmd_usage... |
def format_records(records):
"""Serialise multiple records"""
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted | Serialise multiple records | Below is the the instruction that describes the task:
### Input:
Serialise multiple records
### Response:
def format_records(records):
"""Serialise multiple records"""
formatted = list()
for record_ in records:
formatted.append(format_record(record_))
return formatted |
def get_degree_cols(df):
"""
Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees.
"""
vals = ['lon_w', 'lon_e', 'lat_lon_precision', 'pole_lon',
'paleolon', 'paleolon_sigma',
'lon', 'lon_sigma', 'vgp_lon', ... | Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees. | Below is the the instruction that describes the task:
### Input:
Take in a pandas DataFrame, and return a list of columns
that are in that DataFrame AND should be between 0 - 360 degrees.
### Response:
def get_degree_cols(df):
"""
Take in a pandas DataFrame, and return a list of columns
that are in... |
def write_eval_records(bt_table, game_data, last_game):
"""Write all eval_records to eval_table
In addition to writing new rows table_state must be updated in
row `table_state` columns `metadata:eval_game_counter`
Args:
bt_table: bigtable table to add rows to.
game_data: metadata pairs (c... | Write all eval_records to eval_table
In addition to writing new rows table_state must be updated in
row `table_state` columns `metadata:eval_game_counter`
Args:
bt_table: bigtable table to add rows to.
game_data: metadata pairs (column name, value) for each eval record.
last_game: last... | Below is the the instruction that describes the task:
### Input:
Write all eval_records to eval_table
In addition to writing new rows table_state must be updated in
row `table_state` columns `metadata:eval_game_counter`
Args:
bt_table: bigtable table to add rows to.
game_data: metadata pa... |
def add_file(self, name, required=False, error=None, extensions=None):
""" Add a file field to parse on request (uploads) """
if name is None:
return
self.file_arguments.append(dict(
name=name,
required=required,
error=error,
ex... | Add a file field to parse on request (uploads) | Below is the the instruction that describes the task:
### Input:
Add a file field to parse on request (uploads)
### Response:
def add_file(self, name, required=False, error=None, extensions=None):
""" Add a file field to parse on request (uploads) """
if name is None:
return
... |
def uniform_binning_correction(x, n_bits=8):
"""Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0).
Args:
x: 4-D Tensor of shape (NHWC)
n_bits: optional.
Returns:
x: x ~ U(x, x + 1.0 / 256)
objective: Equivalent to -q(x)*log(q(x)).
"""
n_bins = 2**n_bits
batch_size, height, width, n_channels ... | Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0).
Args:
x: 4-D Tensor of shape (NHWC)
n_bits: optional.
Returns:
x: x ~ U(x, x + 1.0 / 256)
objective: Equivalent to -q(x)*log(q(x)). | Below is the the instruction that describes the task:
### Input:
Replaces x^i with q^i(x) = U(x, x + 1.0 / 256.0).
Args:
x: 4-D Tensor of shape (NHWC)
n_bits: optional.
Returns:
x: x ~ U(x, x + 1.0 / 256)
objective: Equivalent to -q(x)*log(q(x)).
### Response:
def uniform_binning_correction(x,... |
def get_updated(self, from_time, to_time=None):
"""
Retrives a list of series that have changed on TheTVDB since a provided from time parameter and optionally to an
specified to time.
:param from_time: An epoch representation of the date from which to restrict the query to.
:par... | Retrives a list of series that have changed on TheTVDB since a provided from time parameter and optionally to an
specified to time.
:param from_time: An epoch representation of the date from which to restrict the query to.
:param to_time: An optional epcoh representation of the date to which to... | Below is the the instruction that describes the task:
### Input:
Retrives a list of series that have changed on TheTVDB since a provided from time parameter and optionally to an
specified to time.
:param from_time: An epoch representation of the date from which to restrict the query to.
:pa... |
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
hourly, monthly, tag, columns, limit):
"""List virtual servers."""
vsi = SoftLayer.VSManager(env.client)
guests = vsi.list_instances(hourly=hourly,
monthly=monthly,
... | List virtual servers. | Below is the the instruction that describes the task:
### Input:
List virtual servers.
### Response:
def cli(env, sortby, cpu, domain, datacenter, hostname, memory, network,
hourly, monthly, tag, columns, limit):
"""List virtual servers."""
vsi = SoftLayer.VSManager(env.client)
guests = vsi.li... |
def GetRendererForValueOrClass(cls, value, limit_lists=-1):
"""Returns renderer corresponding to a given value and rendering args."""
if inspect.isclass(value):
value_cls = value
else:
value_cls = value.__class__
cache_key = "%s_%d" % (value_cls.__name__, limit_lists)
try:
render... | Returns renderer corresponding to a given value and rendering args. | Below is the the instruction that describes the task:
### Input:
Returns renderer corresponding to a given value and rendering args.
### Response:
def GetRendererForValueOrClass(cls, value, limit_lists=-1):
"""Returns renderer corresponding to a given value and rendering args."""
if inspect.isclass(value)... |
def substitute_timestep(self, regex, timestep):
"""
Substitute a new timestep value using regex.
"""
# Make one change at a time, each change affects subsequent matches.
timestep_changed = False
while True:
matches = re.finditer(regex, self.str, re.MULTILINE ... | Substitute a new timestep value using regex. | Below is the the instruction that describes the task:
### Input:
Substitute a new timestep value using regex.
### Response:
def substitute_timestep(self, regex, timestep):
"""
Substitute a new timestep value using regex.
"""
# Make one change at a time, each change affects subseque... |
def crossvalidate_model(self, classifier, data, num_folds, rnd, output=None):
"""
Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data:... | Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data: the data to evaluate on
:type data: Instances
:param num_folds: the number of fol... | Below is the the instruction that describes the task:
### Input:
Crossvalidates the model using the specified data, number of folds and random number generator wrapper.
:param classifier: the classifier to cross-validate
:type classifier: Classifier
:param data: the data to evaluate on
... |
def split_no_wd_params(layer_groups:Collection[nn.Module])->List[List[nn.Parameter]]:
"Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest."
split_params = []
for l in layer_groups:
l1,l2 = [],[]
for c in l.children():
if isinsta... | Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest. | Below is the the instruction that describes the task:
### Input:
Separate the parameters in `layer_groups` between `no_wd_types` and bias (`bias_types`) from the rest.
### Response:
def split_no_wd_params(layer_groups:Collection[nn.Module])->List[List[nn.Parameter]]:
"Separate the parameters in `layer_groups`... |
def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path):
with h5py.File(reactfn, 'r') as f:
A = f['/metastable/A'][:]
lambnew = f['/metastable/lambda'].value.ravel(order='F') # some are not 1-D!
"""
concatenate along the reaction dimension, axis=-1
"""
vnew = np.concaten... | concatenate along the reaction dimension, axis=-1 | Below is the the instruction that describes the task:
### Input:
concatenate along the reaction dimension, axis=-1
### Response:
def getMetastable(rates, ver: np.ndarray, lamb, br, reactfn: Path):
with h5py.File(reactfn, 'r') as f:
A = f['/metastable/A'][:]
lambnew = f['/metastable/lambda'].val... |
def split_focus(self):
"""Divide the focus edit widget at the cursor location."""
focus = self.lines[self.focus]
pos = focus.edit_pos
edit = urwid.Edit("", focus.edit_text[pos:], allow_tab=True)
edit.original_text = ""
focus.set_edit_text(focus.edit_text[:pos])
e... | Divide the focus edit widget at the cursor location. | Below is the the instruction that describes the task:
### Input:
Divide the focus edit widget at the cursor location.
### Response:
def split_focus(self):
"""Divide the focus edit widget at the cursor location."""
focus = self.lines[self.focus]
pos = focus.edit_pos
edit = urwid.Edi... |
def update_session(fname=None):
"""Update current Scapy session from the file specified in the fname arg.
params:
- fname: file to load the scapy session from"""
if fname is None:
fname = conf.session
try:
s = six.moves.cPickle.load(gzip.open(fname, "rb"))
except IOError:
... | Update current Scapy session from the file specified in the fname arg.
params:
- fname: file to load the scapy session from | Below is the the instruction that describes the task:
### Input:
Update current Scapy session from the file specified in the fname arg.
params:
- fname: file to load the scapy session from
### Response:
def update_session(fname=None):
"""Update current Scapy session from the file specified in the fna... |
def formatted_str_to_val(data, format, enum_set=None):
""" Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable... | Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an iterable of enums which are used as part of the converstion process
... | Below is the the instruction that describes the task:
### Input:
Return an unsigned integer representation of the data given format specified.
:param data: a string holding the value to convert
:param format: a string holding a format which will be used to convert the data string
:param enum_set: an it... |
def fgp_dual(p, data, alpha, niter, grad, proj_C, proj_P, tol=None, **kwargs):
"""Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : ... | Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : float
regularization parameter
niter : int
number of iterations
... | Below is the the instruction that describes the task:
### Input:
Computes a solution to the ROF problem with the fast gradient
projection algorithm.
Parameters
----------
p : np.array
dual initial variable
data : np.array
noisy data / proximal point
alpha : float
reg... |
def replace_by_key(pif, key, subs, new_key=None, remove=False):
"""Replace values that match a key
Deeply traverses the pif object, looking for `key` and
replacing values in accordance with `subs`. If `new_key`
is set, the replaced values are assigned to that key. If
`remove` is `True`, the old `... | Replace values that match a key
Deeply traverses the pif object, looking for `key` and
replacing values in accordance with `subs`. If `new_key`
is set, the replaced values are assigned to that key. If
`remove` is `True`, the old `key` pairs are removed. | Below is the the instruction that describes the task:
### Input:
Replace values that match a key
Deeply traverses the pif object, looking for `key` and
replacing values in accordance with `subs`. If `new_key`
is set, the replaced values are assigned to that key. If
`remove` is `True`, the old `ke... |
def get_downloads(self):
"""
:calls: `GET /repos/:owner/:repo/downloads <http://developer.github.com/v3/repos/downloads>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Download.Download`
"""
return github.PaginatedList.PaginatedList(
github.Do... | :calls: `GET /repos/:owner/:repo/downloads <http://developer.github.com/v3/repos/downloads>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Download.Download` | Below is the the instruction that describes the task:
### Input:
:calls: `GET /repos/:owner/:repo/downloads <http://developer.github.com/v3/repos/downloads>`_
:rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Download.Download`
### Response:
def get_downloads(self):
"""
... |
def increment_day_start_ut(self, day_start_ut, n_days=1):
"""Increment the GTFS-definition of "day start".
Parameters
----------
day_start_ut : int
unixtime of the previous start of day. If this time is between
12:00 or greater, there *will* be bugs. To solve t... | Increment the GTFS-definition of "day start".
Parameters
----------
day_start_ut : int
unixtime of the previous start of day. If this time is between
12:00 or greater, there *will* be bugs. To solve this, run the
input through day_start_ut first.
n_... | Below is the the instruction that describes the task:
### Input:
Increment the GTFS-definition of "day start".
Parameters
----------
day_start_ut : int
unixtime of the previous start of day. If this time is between
12:00 or greater, there *will* be bugs. To solve t... |
def serialize(self, content):
""" Serialize to JSON.
:return string: serializaed JSON
"""
worker = JSONSerializer(
scheme=self.resource,
options=self.resource._meta.emit_options,
format=self.resource._meta.emit_format,
**self.resource._me... | Serialize to JSON.
:return string: serializaed JSON | Below is the the instruction that describes the task:
### Input:
Serialize to JSON.
:return string: serializaed JSON
### Response:
def serialize(self, content):
""" Serialize to JSON.
:return string: serializaed JSON
"""
worker = JSONSerializer(
scheme=self.re... |
def process_analyses(analysis_system_instance, analysis_method, sleep_time):
"""Process all analyses which are scheduled for the analysis system instance.
This function does not terminate on its own, give it a SIGINT or Ctrl+C to stop.
:param analysis_system_instance: The analysis system instance for whic... | Process all analyses which are scheduled for the analysis system instance.
This function does not terminate on its own, give it a SIGINT or Ctrl+C to stop.
:param analysis_system_instance: The analysis system instance for which the analyses are scheduled.
:param analysis_method: A function or method which... | Below is the the instruction that describes the task:
### Input:
Process all analyses which are scheduled for the analysis system instance.
This function does not terminate on its own, give it a SIGINT or Ctrl+C to stop.
:param analysis_system_instance: The analysis system instance for which the analyses ... |
def SignMessage(self, message, script_hash):
"""
Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message
"""
keypai... | Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message | Below is the the instruction that describes the task:
### Input:
Sign a message with a specified script_hash.
Args:
message (str): a hex encoded message to sign
script_hash (UInt160): a bytearray (len 20).
Returns:
str: the signed message
### Response:
def Sign... |
def find(self, path, all=False):
"""
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
"""
matches = []
for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()):
if normpath(elem['output_filename']) == normpath(path):
... | Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT | Below is the the instruction that describes the task:
### Input:
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
### Response:
def find(self, path, all=False):
"""
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
"""
matches = []
for elem in ch... |
def open(self, mode):
"""
Open the underlying .hdf5 file and the parent, if any
"""
if self.hdf5 == (): # not already open
kw = dict(mode=mode, libver='latest')
if mode == 'r':
kw['swmr'] = True
try:
self.hdf5 = hdf5.Fi... | Open the underlying .hdf5 file and the parent, if any | Below is the the instruction that describes the task:
### Input:
Open the underlying .hdf5 file and the parent, if any
### Response:
def open(self, mode):
"""
Open the underlying .hdf5 file and the parent, if any
"""
if self.hdf5 == (): # not already open
kw = dict(mode... |
def _run_sbgenomics(args):
"""Run CWL on SevenBridges platform and Cancer Genomics Cloud.
"""
assert not args.no_container, "Seven Bridges runs require containers"
main_file, json_file, project_name = _get_main_and_json(args.directory)
flags = []
cmd = ["sbg-cwl-runner"] + flags + args.toolargs ... | Run CWL on SevenBridges platform and Cancer Genomics Cloud. | Below is the the instruction that describes the task:
### Input:
Run CWL on SevenBridges platform and Cancer Genomics Cloud.
### Response:
def _run_sbgenomics(args):
"""Run CWL on SevenBridges platform and Cancer Genomics Cloud.
"""
assert not args.no_container, "Seven Bridges runs require containers"
... |
def floyd_warshall_get_path(self, distance, nextn, i, j):
'''
API:
floyd_warshall_get_path(self, distance, nextn, i, j):
Description:
Finds shortest path between i and j using distance and nextn
dictionaries.
Pre:
(1) distance and nextn are... | API:
floyd_warshall_get_path(self, distance, nextn, i, j):
Description:
Finds shortest path between i and j using distance and nextn
dictionaries.
Pre:
(1) distance and nextn are outputs of floyd_warshall method.
(2) The graph does not have a n... | Below is the the instruction that describes the task:
### Input:
API:
floyd_warshall_get_path(self, distance, nextn, i, j):
Description:
Finds shortest path between i and j using distance and nextn
dictionaries.
Pre:
(1) distance and nextn are outputs ... |
def axisfn(reverse=False, principal_node_type=xml.dom.Node.ELEMENT_NODE):
"""Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node typ... | Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node type. | Below is the the instruction that describes the task:
### Input:
Axis function decorator.
An axis function will take a node as an argument and return a sequence
over the nodes along an XPath axis. Axis functions have two extra
attributes indicating the axis direction and principal node type.
### Respo... |
def show_info(ulog, verbose):
"""Show general information from an ULog"""
m1, s1 = divmod(int(ulog.start_timestamp/1e6), 60)
h1, m1 = divmod(m1, 60)
m2, s2 = divmod(int((ulog.last_timestamp - ulog.start_timestamp)/1e6), 60)
h2, m2 = divmod(m2, 60)
print("Logging start time: {:d}:{:02d}:{:02d}, d... | Show general information from an ULog | Below is the the instruction that describes the task:
### Input:
Show general information from an ULog
### Response:
def show_info(ulog, verbose):
"""Show general information from an ULog"""
m1, s1 = divmod(int(ulog.start_timestamp/1e6), 60)
h1, m1 = divmod(m1, 60)
m2, s2 = divmod(int((ulog.last_ti... |
def get_logger(name=None, filename=None, filemode=None, level=WARNING):
"""Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The ... | Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The file mode to open the file (corresponding to `filename`),
default is 'a... | Below is the the instruction that describes the task:
### Input:
Gets a customized logger.
Parameters
----------
name: str, optional
Name of the logger.
filename: str, optional
The filename to which the logger's output will be sent.
filemode: str, optional
The file mode ... |
def fn_abs(self, value):
"""
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number.
"""
if is_ndarray(value):
return numpy.absolute(value)
else:
return abs(value) | Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number. | Below is the the instruction that describes the task:
### Input:
Return the absolute value of a number.
:param value: The number.
:return: The absolute value of the number.
### Response:
def fn_abs(self, value):
"""
Return the absolute value of a number.
:param value: The ... |
def _convert_sky_coords(self):
"""
Convert to sky coordinates
"""
parsed_angles = [(x, y)
for x, y in zip(self.coord[:-1:2], self.coord[1::2])
if (isinstance(x, coordinates.Angle) and isinstance(y, coordinates.Angle))
... | Convert to sky coordinates | Below is the the instruction that describes the task:
### Input:
Convert to sky coordinates
### Response:
def _convert_sky_coords(self):
"""
Convert to sky coordinates
"""
parsed_angles = [(x, y)
for x, y in zip(self.coord[:-1:2], self.coord[1::2])
... |
def set_start_date(self, date):
"""Sets the start date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: ... | Sets the start date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: mandatory -- This method must be implemente... | Below is the the instruction that describes the task:
### Input:
Sets the start date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``nu... |
def find_entity_view(self, view_type, begin_entity=None, filter={},
properties=None):
"""Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_typ... | Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_type: str
:param begin_entity: The MOR to start searching for the entity. \
The default is to start the searc... | Below is the the instruction that describes the task:
### Input:
Find a ManagedEntity of the requested type.
Traverses the MOB looking for an entity matching the filter.
:param view_type: The type of ManagedEntity to find.
:type view_type: str
:param begin_entity: The MOR to start ... |
def record_process(self, process, prg=''):
"""
log a process or program - log a physical program (.py, .bat, .exe)
"""
self._log(self.logFileProcess, force_to_string(process), prg) | log a process or program - log a physical program (.py, .bat, .exe) | Below is the the instruction that describes the task:
### Input:
log a process or program - log a physical program (.py, .bat, .exe)
### Response:
def record_process(self, process, prg=''):
"""
log a process or program - log a physical program (.py, .bat, .exe)
"""
self._log(self.lo... |
def blacklist_bulk(self, blacklist):
"""
Add blacklist entries to the engine node in bulk. For blacklist to work,
you must also create a rule with action "Apply Blacklist".
First create your blacklist entries using :class:`smc.elements.other.Blacklist`
then provide the blacklist ... | Add blacklist entries to the engine node in bulk. For blacklist to work,
you must also create a rule with action "Apply Blacklist".
First create your blacklist entries using :class:`smc.elements.other.Blacklist`
then provide the blacklist to this method.
:param blacklist Blackli... | Below is the the instruction that describes the task:
### Input:
Add blacklist entries to the engine node in bulk. For blacklist to work,
you must also create a rule with action "Apply Blacklist".
First create your blacklist entries using :class:`smc.elements.other.Blacklist`
then provide th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.