code stringlengths 75 104k | docstring stringlengths 1 46.9k | text stringlengths 164 112k |
|---|---|---|
def run_hooks(obj, hooks, *args):
"""Run each function in `hooks' with args"""
for hook in hooks:
if hook(obj, *args): return True
pass
return False | Run each function in `hooks' with args | Below is the the instruction that describes the task:
### Input:
Run each function in `hooks' with args
### Response:
def run_hooks(obj, hooks, *args):
"""Run each function in `hooks' with args"""
for hook in hooks:
if hook(obj, *args): return True
pass
return False |
def _get_part(pointlist, strokes):
"""Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts
"""
result = []
strokes = sorted(strokes)
for stroke_index in strokes:
... | Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts | Below is the the instruction that describes the task:
### Input:
Get some strokes of pointlist
Parameters
----------
pointlist : list of lists of dicts
strokes : list of integers
Returns
-------
list of lists of dicts
### Response:
def _get_part(pointlist, strokes):
"""Get some st... |
def paint(self, painter, option, index):
"""Uses the :meth:`paint<sparkle.gui.stim.components.qcomponents.QStimulusComponent.paint>`
method of the component it represents to fill in an appropriately
sized rectange. :qtdoc:`Re-implemented<QStyledItemDelegate.paint>`"""
component = index... | Uses the :meth:`paint<sparkle.gui.stim.components.qcomponents.QStimulusComponent.paint>`
method of the component it represents to fill in an appropriately
sized rectange. :qtdoc:`Re-implemented<QStyledItemDelegate.paint>` | Below is the the instruction that describes the task:
### Input:
Uses the :meth:`paint<sparkle.gui.stim.components.qcomponents.QStimulusComponent.paint>`
method of the component it represents to fill in an appropriately
sized rectange. :qtdoc:`Re-implemented<QStyledItemDelegate.paint>`
### Respons... |
def stack_xi_direction_brute(xis, bestMasses, bestXis, direction_num,
req_match, massRangeParams, metricParams, fUpper,
scaleFactor=0.8, numIterations=3000):
"""
This function is used to assess the depth of the xi_space in a specified
dimension at a ... | This function is used to assess the depth of the xi_space in a specified
dimension at a specified point in the higher dimensions. It does this by
iteratively throwing points at the space to find maxima and minima.
Parameters
-----------
xis : list or array
Position in the xi space at which... | Below is the the instruction that describes the task:
### Input:
This function is used to assess the depth of the xi_space in a specified
dimension at a specified point in the higher dimensions. It does this by
iteratively throwing points at the space to find maxima and minima.
Parameters
---------... |
def boolean(value):
"""Parse the string ``"true"`` or ``"false"`` as a boolean (case
insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False``
(respectively). If the input is from the request JSON body, the type is
already a native python boolean, and will be passed through without
furthe... | Parse the string ``"true"`` or ``"false"`` as a boolean (case
insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False``
(respectively). If the input is from the request JSON body, the type is
already a native python boolean, and will be passed through without
further parsing. | Below is the the instruction that describes the task:
### Input:
Parse the string ``"true"`` or ``"false"`` as a boolean (case
insensitive). Also accepts ``"1"`` and ``"0"`` as ``True``/``False``
(respectively). If the input is from the request JSON body, the type is
already a native python boolean, and... |
def _ensure_pinned_rows(dashboard):
'''Pin rows to the top of the dashboard.'''
pinned_row_titles = __salt__['pillar.get'](_PINNED_ROWS_PILLAR)
if not pinned_row_titles:
return
pinned_row_titles_lower = []
for title in pinned_row_titles:
pinned_row_titles_lower.append(title.lower())... | Pin rows to the top of the dashboard. | Below is the the instruction that describes the task:
### Input:
Pin rows to the top of the dashboard.
### Response:
def _ensure_pinned_rows(dashboard):
'''Pin rows to the top of the dashboard.'''
pinned_row_titles = __salt__['pillar.get'](_PINNED_ROWS_PILLAR)
if not pinned_row_titles:
return
... |
def runExperiment(args):
"""
Runs the experiment. The code is organized around what we need for specific
figures in the paper.
args is a dict representing the various parameters. We do it this way to
support multiprocessing. The function returns the args dict updated with a
number of additional keys conta... | Runs the experiment. The code is organized around what we need for specific
figures in the paper.
args is a dict representing the various parameters. We do it this way to
support multiprocessing. The function returns the args dict updated with a
number of additional keys containing performance metrics. | Below is the the instruction that describes the task:
### Input:
Runs the experiment. The code is organized around what we need for specific
figures in the paper.
args is a dict representing the various parameters. We do it this way to
support multiprocessing. The function returns the args dict updated with... |
def write_shortstr(self, s):
"""Write a string up to 255 bytes long (after any encoding).
If passed a unicode string, encode with UTF-8.
"""
self._flushbits()
if isinstance(s, string):
s = s.encode('utf-8')
if len(s) > 255:
raise FrameSyntaxError... | Write a string up to 255 bytes long (after any encoding).
If passed a unicode string, encode with UTF-8. | Below is the the instruction that describes the task:
### Input:
Write a string up to 255 bytes long (after any encoding).
If passed a unicode string, encode with UTF-8.
### Response:
def write_shortstr(self, s):
"""Write a string up to 255 bytes long (after any encoding).
If passed a uni... |
def verify_fft_options(opt,parser):
"""Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance.
... | Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance. | Below is the the instruction that describes the task:
### Input:
Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
O... |
def is_uid(uid):
"""Checks if the passed in uid is a valid UID
:param uid: The uid to check
:type uid: string
:return: True if the uid is a valid 32 alphanumeric uid or '0'
:rtype: bool
"""
if not isinstance(uid, basestring):
return False
if uid != "0" and len(uid) != 32:
... | Checks if the passed in uid is a valid UID
:param uid: The uid to check
:type uid: string
:return: True if the uid is a valid 32 alphanumeric uid or '0'
:rtype: bool | Below is the the instruction that describes the task:
### Input:
Checks if the passed in uid is a valid UID
:param uid: The uid to check
:type uid: string
:return: True if the uid is a valid 32 alphanumeric uid or '0'
:rtype: bool
### Response:
def is_uid(uid):
"""Checks if the passed in uid i... |
def drawing_update(self):
'''update line drawing'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if self.draw_callback is None:
return
self.draw_line.append(self.click_position)
if len(self.draw_line) > 1:
self.mpstate.map.add_object(mp_slipmap.Sli... | update line drawing | Below is the the instruction that describes the task:
### Input:
update line drawing
### Response:
def drawing_update(self):
'''update line drawing'''
from MAVProxy.modules.mavproxy_map import mp_slipmap
if self.draw_callback is None:
return
self.draw_line.append(self.cl... |
def search_definition(self, module, keyword, arg):
"""Search for a defintion with `keyword` `name`
Search the module and its submodules."""
r = module.search_one(keyword, arg)
if r is not None:
return r
for i in module.search('include'):
modulename = i.arg... | Search for a defintion with `keyword` `name`
Search the module and its submodules. | Below is the the instruction that describes the task:
### Input:
Search for a defintion with `keyword` `name`
Search the module and its submodules.
### Response:
def search_definition(self, module, keyword, arg):
"""Search for a defintion with `keyword` `name`
Search the module and its subm... |
def from_dict(cls, dict_in):
"""Initialize the class from a dict.
:param dict_in: The dictionary that contains the item content. Required
fields are listed class variable by that name
:type dict_in: dict
"""
kwargs = dict_in.copy()
args = [kwargs.pop(key) for... | Initialize the class from a dict.
:param dict_in: The dictionary that contains the item content. Required
fields are listed class variable by that name
:type dict_in: dict | Below is the the instruction that describes the task:
### Input:
Initialize the class from a dict.
:param dict_in: The dictionary that contains the item content. Required
fields are listed class variable by that name
:type dict_in: dict
### Response:
def from_dict(cls, dict_in):
... |
def list(self,header,choices):
"Display list of choices. As many as we can get in a page."
if not self.__list_window:
(y,x)=self.__main.getmaxyx()
self.__list_window = self.__main.subwin(35,x,0,0)
_lw=self.__list_window
_lw.keypad(1)
(y_ma... | Display list of choices. As many as we can get in a page. | Below is the the instruction that describes the task:
### Input:
Display list of choices. As many as we can get in a page.
### Response:
def list(self,header,choices):
"Display list of choices. As many as we can get in a page."
if not self.__list_window:
(y,x)=self.__main.getmaxyx()
... |
def apt_key_exists(keyid):
"""
Check if the given key id exists in apt keyring.
"""
# Command extracted from apt-key source
gpg_cmd = 'gpg --ignore-time-conflict --no-options --no-default-keyring --keyring /etc/apt/trusted.gpg'
with settings(hide('everything'), warn_only=True):
res = r... | Check if the given key id exists in apt keyring. | Below is the the instruction that describes the task:
### Input:
Check if the given key id exists in apt keyring.
### Response:
def apt_key_exists(keyid):
"""
Check if the given key id exists in apt keyring.
"""
# Command extracted from apt-key source
gpg_cmd = 'gpg --ignore-time-conflict --no... |
def start_after(self, document_fields):
"""Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
docu... | Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
document.DocumentSnapshot, dict, list, tuple]): a docum... | Below is the the instruction that describes the task:
### Input:
Start query after a cursor with this collection as parent.
See
:meth:`~.firestore_v1beta1.query.Query.start_after` for
more information on this method.
Args:
document_fields (Union[~.firestore_v1beta1.\
... |
def DSYR_numpy(A, x, alpha=1.):
"""
Performs a symmetric rank-1 update operation:
A <- A + alpha * np.dot(x,x.T)
:param A: Symmetric NxN np.array
:param x: Nx1 np.array
:param alpha: scalar
"""
A += alpha * np.dot(x[:, None], x[None, :]) | Performs a symmetric rank-1 update operation:
A <- A + alpha * np.dot(x,x.T)
:param A: Symmetric NxN np.array
:param x: Nx1 np.array
:param alpha: scalar | Below is the the instruction that describes the task:
### Input:
Performs a symmetric rank-1 update operation:
A <- A + alpha * np.dot(x,x.T)
:param A: Symmetric NxN np.array
:param x: Nx1 np.array
:param alpha: scalar
### Response:
def DSYR_numpy(A, x, alpha=1.):
"""
Performs a symmetric ... |
def read_namespaced_deployment(self, name, namespace, **kwargs):
"""
read the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment(name, namespace... | read the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment(name, namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
... | Below is the the instruction that describes the task:
### Input:
read the specified Deployment
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_deployment(name, namespace, async_req=True... |
def retrieve_console_log(self, filename=None, dir=None):
"""Retrieves the application console log (standard out and error)
files for this PE and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the creat... | Retrieves the application console log (standard out and error)
files for this PE and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the created file. Defaults to `pe_<id>_<timestamp>.stdouterr` where `id` is t... | Below is the the instruction that describes the task:
### Input:
Retrieves the application console log (standard out and error)
files for this PE and saves them as a plain text file.
An existing file with the same name will be overwritten.
Args:
filename (str): name of the crea... |
def global_set_option(self, opt, value):
"""set option on the correct option provider"""
self._all_options[opt].set_option(opt, value) | set option on the correct option provider | Below is the the instruction that describes the task:
### Input:
set option on the correct option provider
### Response:
def global_set_option(self, opt, value):
"""set option on the correct option provider"""
self._all_options[opt].set_option(opt, value) |
def _handle_uninitialized_read(self, addr, inspect=True, events=True):
"""
The default uninitialized read handler. Returns symbolic bytes.
"""
if self._uninitialized_read_handler is None:
v = self.state.solver.Unconstrained("%s_%s" % (self.id, addr), self.width*self.state.arc... | The default uninitialized read handler. Returns symbolic bytes. | Below is the the instruction that describes the task:
### Input:
The default uninitialized read handler. Returns symbolic bytes.
### Response:
def _handle_uninitialized_read(self, addr, inspect=True, events=True):
"""
The default uninitialized read handler. Returns symbolic bytes.
"""
... |
def counter(self, key, **dims):
"""Adds counter with dimensions to the registry"""
return super(RegexRegistry, self).counter(self._get_key(key), **dims) | Adds counter with dimensions to the registry | Below is the the instruction that describes the task:
### Input:
Adds counter with dimensions to the registry
### Response:
def counter(self, key, **dims):
"""Adds counter with dimensions to the registry"""
return super(RegexRegistry, self).counter(self._get_key(key), **dims) |
def _fS1(self, pos_pairs, A):
"""The gradient of the similarity constraint function w.r.t. A.
f = \sum_{ij}(x_i-x_j)A(x_i-x_j)' = \sum_{ij}d_ij*A*d_ij'
df/dA = d(d_ij*A*d_ij')/dA
Note that d_ij*A*d_ij' = tr(d_ij*A*d_ij') = tr(d_ij'*d_ij*A)
so, d(d_ij*A*d_ij')/dA = d_ij'*d_ij
"""
dim = pos_... | The gradient of the similarity constraint function w.r.t. A.
f = \sum_{ij}(x_i-x_j)A(x_i-x_j)' = \sum_{ij}d_ij*A*d_ij'
df/dA = d(d_ij*A*d_ij')/dA
Note that d_ij*A*d_ij' = tr(d_ij*A*d_ij') = tr(d_ij'*d_ij*A)
so, d(d_ij*A*d_ij')/dA = d_ij'*d_ij | Below is the the instruction that describes the task:
### Input:
The gradient of the similarity constraint function w.r.t. A.
f = \sum_{ij}(x_i-x_j)A(x_i-x_j)' = \sum_{ij}d_ij*A*d_ij'
df/dA = d(d_ij*A*d_ij')/dA
Note that d_ij*A*d_ij' = tr(d_ij*A*d_ij') = tr(d_ij'*d_ij*A)
so, d(d_ij*A*d_ij')/dA = d... |
def multi_ops(data_stream, *funcs):
""" fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream """
assert all(callable(func) for func in funcs), 'multi_ops ... | fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream | Below is the the instruction that describes the task:
### Input:
fork a generator with multiple operations/functions
data_stream - an iterable data structure (ie: list/generator/tuple)
funcs - every function that will be applied to the data_stream
### Response:
def multi_ops(data_stream,... |
def ret_dump(self, d_ret, **kwargs):
"""
JSON print results to console (or caller)
"""
b_print = True
for k, v in kwargs.items():
if k == 'JSONprint': b_print = bool(v)
if b_print:
print(
json.dumps(
... | JSON print results to console (or caller) | Below is the the instruction that describes the task:
### Input:
JSON print results to console (or caller)
### Response:
def ret_dump(self, d_ret, **kwargs):
"""
JSON print results to console (or caller)
"""
b_print = True
for k, v in kwargs.items():
if k == ... |
def init_widget(self):
""" Set the listeners
"""
w = self.window
d = self.declaration
self.set_background_color(d.background_color)
self.set_touchable(d.touchable)
self.set_outside_touchable(d.outside_touchable)
# Listen for events
w.setOnDismissL... | Set the listeners | Below is the the instruction that describes the task:
### Input:
Set the listeners
### Response:
def init_widget(self):
""" Set the listeners
"""
w = self.window
d = self.declaration
self.set_background_color(d.background_color)
self.set_touchable(d.touchable)
... |
def _update_failure_type(self):
"""
Updates the failure type of this Note's Job.
Set the linked Job's failure type to that of the most recent JobNote or
set to Not Classified if there are no JobNotes.
This is called when JobNotes are created (via .save()) and deleted (via
... | Updates the failure type of this Note's Job.
Set the linked Job's failure type to that of the most recent JobNote or
set to Not Classified if there are no JobNotes.
This is called when JobNotes are created (via .save()) and deleted (via
.delete()) and is used to resolved the FailureCla... | Below is the the instruction that describes the task:
### Input:
Updates the failure type of this Note's Job.
Set the linked Job's failure type to that of the most recent JobNote or
set to Not Classified if there are no JobNotes.
This is called when JobNotes are created (via .save()) and d... |
def get_lines_without_comments(filename: str) -> List[str]:
"""
Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols!
"""
lines = []
with open(filename) a... | Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols! | Below is the the instruction that describes the task:
### Input:
Reads a file, and returns all lines as a list, left- and right-stripping
the lines and removing everything on a line after the first ``#``.
NOTE: does not cope well with quoted ``#`` symbols!
### Response:
def get_lines_without_comments(filen... |
def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
self._right *= scale
self._calibrate_to_rect() | Resize this region against the entire axis space. | Below is the the instruction that describes the task:
### Input:
Resize this region against the entire axis space.
### Response:
def canvas_resize(self, scale):
""" Resize this region against the entire axis space. """
self._top *= scale
self._bottom *= scale
self._left *= scale
... |
def time_to_repeats(self, bins, integration_time):
"""Convert integration time to number of repeats"""
return math.ceil((self.device.sample_rate * integration_time) / bins) | Convert integration time to number of repeats | Below is the the instruction that describes the task:
### Input:
Convert integration time to number of repeats
### Response:
def time_to_repeats(self, bins, integration_time):
"""Convert integration time to number of repeats"""
return math.ceil((self.device.sample_rate * integration_time) / bins) |
def _migrate_ledger(data_directory,
old_ledger_file, new_ledger_file,
serializer: MappingSerializer = None):
"""
Test for the directory, open old and new ledger, migrate data, rename directories
"""
# we should have ChunkedFileStorage implementation of the Ledger... | Test for the directory, open old and new ledger, migrate data, rename directories | Below is the the instruction that describes the task:
### Input:
Test for the directory, open old and new ledger, migrate data, rename directories
### Response:
def _migrate_ledger(data_directory,
old_ledger_file, new_ledger_file,
serializer: MappingSerializer = None):
"... |
def download_url(self, url, **kwargs):
"""
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file
"""
if sel... | Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file | Below is the the instruction that describes the task:
### Input:
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file
### Response:
d... |
def _intersperse_insertion_rows_and_columns(self, pairwise_pvals):
"""Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
... | Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
corresponding column letter. For this reason, we need to insert an all-... | Below is the the instruction that describes the task:
### Input:
Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
co... |
def find_sparse_mode(self, core, additional, scaling, weights={}):
"""Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (a... | Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (approximately). A dictionary of weights can be
supplied which gives fur... | Below is the the instruction that describes the task:
### Input:
Find a sparse mode containing reactions of the core subset.
Return an iterator of the support of a sparse mode that contains as
many reactions from core as possible, and as few reactions from
additional as possible (approximat... |
def layout(self):
""" Calculate the widths of the columns to set the table """
ret = []
for row in self.rows:
if len(row) > len(ret):
ret += [0] * (len(row) - len(ret))
for n, field in enumera... | Calculate the widths of the columns to set the table | Below is the the instruction that describes the task:
### Input:
Calculate the widths of the columns to set the table
### Response:
def layout(self):
""" Calculate the widths of the columns to set the table """
ret = []
for row in self.rows:
i... |
def B(u, v, dfs_data):
"""The branch at u containing v is the set of all edges incident on v or any descendant of v, if a(v) == u."""
"""Bu(v) = {wx | w is in S*(v)}"""
if a(v, dfs_data) != u:
return None
return list(set([edge_id for w in S_star(v, dfs_data) for edge_id in dfs_data['graph'].get... | The branch at u containing v is the set of all edges incident on v or any descendant of v, if a(v) == u. | Below is the the instruction that describes the task:
### Input:
The branch at u containing v is the set of all edges incident on v or any descendant of v, if a(v) == u.
### Response:
def B(u, v, dfs_data):
"""The branch at u containing v is the set of all edges incident on v or any descendant of v, if a(v) ==... |
def node(self, node):
"""
Return the other node
"""
if node == self.node1:
return self.node2
elif node == self.node2:
return self.node1
else:
return None | Return the other node | Below is the the instruction that describes the task:
### Input:
Return the other node
### Response:
def node(self, node):
"""
Return the other node
"""
if node == self.node1:
return self.node2
elif node == self.node2:
return self.node1
else:... |
def _enable_read_access(self):
"""! @brief Ensure flash is accessible by initing the algo for verify.
Not all flash memories are always accessible. For instance, external QSPI. Initing the
flash algo for the VERIFY operation is the canonical way to ensure that the flash is
memor... | ! @brief Ensure flash is accessible by initing the algo for verify.
Not all flash memories are always accessible. For instance, external QSPI. Initing the
flash algo for the VERIFY operation is the canonical way to ensure that the flash is
memory mapped and accessible. | Below is the the instruction that describes the task:
### Input:
! @brief Ensure flash is accessible by initing the algo for verify.
Not all flash memories are always accessible. For instance, external QSPI. Initing the
flash algo for the VERIFY operation is the canonical way to ensure that... |
def _build_row(padded_cells, colwidths, colaligns, rowfmt):
"Return a string which represents a row of data cells."
if not rowfmt:
return None
if hasattr(rowfmt, "__call__"):
return rowfmt(padded_cells, colwidths, colaligns)
else:
return _build_simple_row(padded_cells, rowfmt) | Return a string which represents a row of data cells. | Below is the the instruction that describes the task:
### Input:
Return a string which represents a row of data cells.
### Response:
def _build_row(padded_cells, colwidths, colaligns, rowfmt):
"Return a string which represents a row of data cells."
if not rowfmt:
return None
if hasattr(rowfmt, ... |
def _iter_names(self):
"""
Generate a key/value pair for each name in this table. The key is a
(platform_id, name_id) 2-tuple and the value is the unicode text
corresponding to that key.
"""
table_format, count, strings_offset = self._table_header
table_bytes = se... | Generate a key/value pair for each name in this table. The key is a
(platform_id, name_id) 2-tuple and the value is the unicode text
corresponding to that key. | Below is the the instruction that describes the task:
### Input:
Generate a key/value pair for each name in this table. The key is a
(platform_id, name_id) 2-tuple and the value is the unicode text
corresponding to that key.
### Response:
def _iter_names(self):
"""
Generate a key/va... |
def get_dtype_counts(self):
"""Get the counts of dtypes in this object.
Returns:
The counts of dtypes in this object.
"""
if hasattr(self, "dtype"):
return pandas.Series({str(self.dtype): 1})
result = self.dtypes.value_counts()
result.ind... | Get the counts of dtypes in this object.
Returns:
The counts of dtypes in this object. | Below is the the instruction that describes the task:
### Input:
Get the counts of dtypes in this object.
Returns:
The counts of dtypes in this object.
### Response:
def get_dtype_counts(self):
"""Get the counts of dtypes in this object.
Returns:
The counts ... |
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None):
"""cut out data area based on coords.
"""
view = np.s_[y1:y2:ystep, x1:x2:xstep]
data = self._slice(view)
if astype:
data = data.astype(astype, copy=False)
return data | cut out data area based on coords. | Below is the the instruction that describes the task:
### Input:
cut out data area based on coords.
### Response:
def cutout_data(self, x1, y1, x2, y2, xstep=1, ystep=1, astype=None):
"""cut out data area based on coords.
"""
view = np.s_[y1:y2:ystep, x1:x2:xstep]
data = self._slice... |
def enhance(self):
"""Load metadata from a data service to improve naming.
:raises tvrenamer.exceptions.ShowNotFound:
when unable to find show/series name based on parsed name
:raises tvrenamer.exceptions.EpisodeNotFound:
when unable to find episode name(s) based on pars... | Load metadata from a data service to improve naming.
:raises tvrenamer.exceptions.ShowNotFound:
when unable to find show/series name based on parsed name
:raises tvrenamer.exceptions.EpisodeNotFound:
when unable to find episode name(s) based on parsed data | Below is the the instruction that describes the task:
### Input:
Load metadata from a data service to improve naming.
:raises tvrenamer.exceptions.ShowNotFound:
when unable to find show/series name based on parsed name
:raises tvrenamer.exceptions.EpisodeNotFound:
when unabl... |
def get_options(self):
"""
Return current query options for the Impala session
"""
query = 'SET'
return dict(row[:2] for row in self.con.fetchall(query)) | Return current query options for the Impala session | Below is the the instruction that describes the task:
### Input:
Return current query options for the Impala session
### Response:
def get_options(self):
"""
Return current query options for the Impala session
"""
query = 'SET'
return dict(row[:2] for row in self.con.fetchal... |
def set_brightness(self, brightness):
"""set general brightness in range 0...1"""
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightness = brightness
self._repeat_last_frame()
sequence_number = self.zmq_publisher.publish_brightness(brightne... | set general brightness in range 0...1 | Below is the the instruction that describes the task:
### Input:
set general brightness in range 0...1
### Response:
def set_brightness(self, brightness):
"""set general brightness in range 0...1"""
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightne... |
def get_command(self, ctx, name):
"""Retrieve the appropriate method from the Resource,
decorate it as a click command, and return that method.
"""
# Sanity check: Does a method exist corresponding to this
# command? If not, None is returned for click to raise
# exception... | Retrieve the appropriate method from the Resource,
decorate it as a click command, and return that method. | Below is the the instruction that describes the task:
### Input:
Retrieve the appropriate method from the Resource,
decorate it as a click command, and return that method.
### Response:
def get_command(self, ctx, name):
"""Retrieve the appropriate method from the Resource,
decorate it as a ... |
def _convert_content(self, rdtype, content):
"""
Converts type dependent record content into well formed and fully qualified
content for domain zone and returns content.
"""
if rdtype == 'TXT':
if content[0] != '"':
content = '"' + content
... | Converts type dependent record content into well formed and fully qualified
content for domain zone and returns content. | Below is the the instruction that describes the task:
### Input:
Converts type dependent record content into well formed and fully qualified
content for domain zone and returns content.
### Response:
def _convert_content(self, rdtype, content):
"""
Converts type dependent record content int... |
def smooth(x, window_len=7, window='hanning'):
"""
Smooth the data in x using convolution with a window of requested
size and type.
Parameters
----------
x : array_like(float)
A flat NumPy array containing the data to smooth
window_len : scalar(int), optional
An odd integer ... | Smooth the data in x using convolution with a window of requested
size and type.
Parameters
----------
x : array_like(float)
A flat NumPy array containing the data to smooth
window_len : scalar(int), optional
An odd integer giving the length of the window. Defaults to 7.
window... | Below is the the instruction that describes the task:
### Input:
Smooth the data in x using convolution with a window of requested
size and type.
Parameters
----------
x : array_like(float)
A flat NumPy array containing the data to smooth
window_len : scalar(int), optional
An od... |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv = sys.argv
# setup command line parser
parser = U.OptionParser(version="%prog version: $Id$",
usage=usage,
... | script main.
parses command line options in sys.argv, unless *argv* is given. | Below is the the instruction that describes the task:
### Input:
script main.
parses command line options in sys.argv, unless *argv* is given.
### Response:
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if argv is None:
argv... |
def title(msg, **options):
"""print something like a title"""
return echo(Style.BRIGHT + Fore.CYAN + "__{}__________________________".format(msg.upper().strip()) + Style.RESET_ALL + Fore.RESET, **options) | print something like a title | Below is the the instruction that describes the task:
### Input:
print something like a title
### Response:
def title(msg, **options):
"""print something like a title"""
return echo(Style.BRIGHT + Fore.CYAN + "__{}__________________________".format(msg.upper().strip()) + Style.RESET_ALL + Fore.RESET, **opt... |
def socks_proxy(self, value):
"""
Sets socks proxy setting.
:Args:
- value: The socks proxy value.
"""
self._verify_proxy_type_compatibility(ProxyType.MANUAL)
self.proxyType = ProxyType.MANUAL
self.socksProxy = value | Sets socks proxy setting.
:Args:
- value: The socks proxy value. | Below is the the instruction that describes the task:
### Input:
Sets socks proxy setting.
:Args:
- value: The socks proxy value.
### Response:
def socks_proxy(self, value):
"""
Sets socks proxy setting.
:Args:
- value: The socks proxy value.
"""
... |
def get_assessment_parts_by_banks(self, bank_ids):
"""Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
raise: ... | Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
raise: NullArgument - ``bank_ids`` is ``null``
raise: Operat... | Below is the the instruction that describes the task:
### Input:
Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
r... |
def columns(self):
"""
Returns the list of column names that this index will be expecting as \
inputs when it is called.
:return [<str>, ..]
"""
schema = self.schema()
return [schema.column(col) for col in self.__columns] | Returns the list of column names that this index will be expecting as \
inputs when it is called.
:return [<str>, ..] | Below is the the instruction that describes the task:
### Input:
Returns the list of column names that this index will be expecting as \
inputs when it is called.
:return [<str>, ..]
### Response:
def columns(self):
"""
Returns the list of column names that this index w... |
def _phase(self, line, pos):
"""
Places a phase / control circle on a qubit line at a given position.
:param int line: Qubit line at which to place the circle.
:param float pos: Position at which to place the circle.
:return: Latex string representing a control circle at the giv... | Places a phase / control circle on a qubit line at a given position.
:param int line: Qubit line at which to place the circle.
:param float pos: Position at which to place the circle.
:return: Latex string representing a control circle at the given position.
:rtype: string | Below is the the instruction that describes the task:
### Input:
Places a phase / control circle on a qubit line at a given position.
:param int line: Qubit line at which to place the circle.
:param float pos: Position at which to place the circle.
:return: Latex string representing a contr... |
def insert(self, item, safe=None): # pragma: nocover
''' [DEPRECATED] Please use save() instead. This actually calls
the underlying save function, so the name is confusing.
Insert an item into the work queue and flushes.'''
warnings.warn('Insert will be deprecated soon and removed in 1.0. Please use insert',... | [DEPRECATED] Please use save() instead. This actually calls
the underlying save function, so the name is confusing.
Insert an item into the work queue and flushes. | Below is the the instruction that describes the task:
### Input:
[DEPRECATED] Please use save() instead. This actually calls
the underlying save function, so the name is confusing.
Insert an item into the work queue and flushes.
### Response:
def insert(self, item, safe=None): # pragma: nocover
''' [DEPRE... |
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis,
enable_warning=True):
"""A datetime-version that takes datetime object list as x_axis
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numer... | A datetime-version that takes datetime object list as x_axis | Below is the the instruction that describes the task:
### Input:
A datetime-version that takes datetime object list as x_axis
### Response:
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis,
enable_warning=True):
"""A datetime-version that takes date... |
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
"""
camel = "".join(word.title() for word in value.split("_"))
return value[:1].lower() + camel[1:] | Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz' | Below is the the instruction that describes the task:
### Input:
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
'fooBarBaz'
### Response:
def snake_to_camel(value):
"""
Converts a snake_case_string to a camelCaseString.
>>> snake_to_camel("foo_bar_baz")
... |
def copy_module(target_path, my_directory_full_path, my_module):
'''
Helper function for copy_module_to_local(). Provides the actual copy
functionality, with highly cautious safeguards against copying over
important things.
Parameters
----------
target_path : string
String, file pat... | Helper function for copy_module_to_local(). Provides the actual copy
functionality, with highly cautious safeguards against copying over
important things.
Parameters
----------
target_path : string
String, file path to target location
my_directory_full_path: string
String, full... | Below is the the instruction that describes the task:
### Input:
Helper function for copy_module_to_local(). Provides the actual copy
functionality, with highly cautious safeguards against copying over
important things.
Parameters
----------
target_path : string
String, file path to tar... |
def setup_docstring_style_convention(self, text):
"""Handle convention changes."""
if text == 'Custom':
self.docstring_style_select.label.setText(
_("Show the following errors:"))
self.docstring_style_ignore.label.setText(
_("Ignore the following e... | Handle convention changes. | Below is the the instruction that describes the task:
### Input:
Handle convention changes.
### Response:
def setup_docstring_style_convention(self, text):
"""Handle convention changes."""
if text == 'Custom':
self.docstring_style_select.label.setText(
_("Show the follow... |
def keywords(self):
"""
Returns a list of all keywords that this rule object has defined.
A keyword is considered defined if the value it returns != None.
"""
defined_keywords = [
('allowempty_map', 'allowempty_map'),
('assertion', 'assertion'),
... | Returns a list of all keywords that this rule object has defined.
A keyword is considered defined if the value it returns != None. | Below is the the instruction that describes the task:
### Input:
Returns a list of all keywords that this rule object has defined.
A keyword is considered defined if the value it returns != None.
### Response:
def keywords(self):
"""
Returns a list of all keywords that this rule object has ... |
def tag(ctx, corpus, output):
"""Tag chemical entities and write CHEMDNER annotations predictions file."""
click.echo('chemdataextractor.chemdner.tag')
for line in corpus:
pmid, title, abstract = line.strip().split(u'\t')
# print(pmid)
counter = 1
d = Document(Title(title), P... | Tag chemical entities and write CHEMDNER annotations predictions file. | Below is the the instruction that describes the task:
### Input:
Tag chemical entities and write CHEMDNER annotations predictions file.
### Response:
def tag(ctx, corpus, output):
"""Tag chemical entities and write CHEMDNER annotations predictions file."""
click.echo('chemdataextractor.chemdner.tag')
f... |
def _translate_shortcut(self, name):
"""Maps a given shortcut to corresponding name
* 'run_X' or 'r_X' to 'run_XXXXXXXXX'
* 'crun' to the current run name in case of a
single run instance if trajectory is used via `v_crun`
* 'par' 'parameters'
* 'dpar' to 'derived_p... | Maps a given shortcut to corresponding name
* 'run_X' or 'r_X' to 'run_XXXXXXXXX'
* 'crun' to the current run name in case of a
single run instance if trajectory is used via `v_crun`
* 'par' 'parameters'
* 'dpar' to 'derived_parameters'
* 'res' to 'results'
... | Below is the the instruction that describes the task:
### Input:
Maps a given shortcut to corresponding name
* 'run_X' or 'r_X' to 'run_XXXXXXXXX'
* 'crun' to the current run name in case of a
single run instance if trajectory is used via `v_crun`
* 'par' 'parameters'
*... |
def load(self, days=PRELOAD_DAYS, only_cameras=None,
date_from=None, date_to=None, limit=None):
"""Load Arlo videos from the given criteria
:param days: number of days to retrieve
:param only_cameras: retrieve only <ArloCamera> on that list
:param date_from: refine from in... | Load Arlo videos from the given criteria
:param days: number of days to retrieve
:param only_cameras: retrieve only <ArloCamera> on that list
:param date_from: refine from initial date
:param date_to: refine final date
:param limit: define number of objects to return | Below is the the instruction that describes the task:
### Input:
Load Arlo videos from the given criteria
:param days: number of days to retrieve
:param only_cameras: retrieve only <ArloCamera> on that list
:param date_from: refine from initial date
:param date_to: refine final dat... |
def _onOutgoingMessageReceived(self, conn, message):
"""
Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys.
Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to ... | Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys.
Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to the onMessageReceived callback.
:param conn: connection object
... | Below is the the instruction that describes the task:
### Input:
Callback for receiving a message on a new outgoing connection. Used only if encryption is enabled to exchange the random keys.
Once the key exchange is done, this triggers the onNodeConnected callback, and further messages are deferred to the ... |
def hsplit(self, location=None, new=False, text=None):
""" Split horizontally. """
assert location is None or text is None or new is False # Don't pass two of them.
if location or text or new:
editor_buffer = self._get_or_create_editor_buffer(location=location, text=text)
e... | Split horizontally. | Below is the the instruction that describes the task:
### Input:
Split horizontally.
### Response:
def hsplit(self, location=None, new=False, text=None):
""" Split horizontally. """
assert location is None or text is None or new is False # Don't pass two of them.
if location or text or ne... |
def read_frames(file_path, frame_size, hop_size, start=0.0,
end=float('inf'), buffer_size=5760000):
"""
Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per f... | Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between two frames.
start (float): Start in seconds to read from.
... | Below is the the instruction that describes the task:
### Input:
Read an audio file frame by frame. The frames are yielded one after another.
Args:
file_path (str): Path to the file to read.
frame_size (int): The number of samples per frame.
hop_size (int): The number of samples between... |
def find_codon_mismatches(sbjct_start, sbjct_seq, qry_seq):
"""
This function takes two alligned sequence (subject and query), and
the position on the subject where the alignment starts. The sequences
are compared codon by codon. If a mis matches is found it is saved in
'mis_matches'. If a gap is ... | This function takes two alligned sequence (subject and query), and
the position on the subject where the alignment starts. The sequences
are compared codon by codon. If a mis matches is found it is saved in
'mis_matches'. If a gap is found the function get_inframe_gap is used
to find the indel sequen... | Below is the the instruction that describes the task:
### Input:
This function takes two alligned sequence (subject and query), and
the position on the subject where the alignment starts. The sequences
are compared codon by codon. If a mis matches is found it is saved in
'mis_matches'. If a gap is fou... |
def create_generic(numeric_values, textual_values, target, algorithm = util_functions.AlgorithmTypes.regression):
"""
Creates a model from a generic list numeric values and text values
numeric_values - A list of lists that are the predictors
textual_values - A list of lists that are the predictors
(... | Creates a model from a generic list numeric values and text values
numeric_values - A list of lists that are the predictors
textual_values - A list of lists that are the predictors
(each item in textual_values corresponds to the similarly indexed counterpart in numeric_values)
target - The variable that... | Below is the the instruction that describes the task:
### Input:
Creates a model from a generic list numeric values and text values
numeric_values - A list of lists that are the predictors
textual_values - A list of lists that are the predictors
(each item in textual_values corresponds to the similarly ... |
def export_kml_file(self):
"""Generate KML element tree from ``Placemarks``.
Returns:
etree.ElementTree: KML element tree depicting ``Placemarks``
"""
kml = create_elem('kml')
kml.Document = create_elem('Document')
for place in sorted(self.values(), key=lambd... | Generate KML element tree from ``Placemarks``.
Returns:
etree.ElementTree: KML element tree depicting ``Placemarks`` | Below is the the instruction that describes the task:
### Input:
Generate KML element tree from ``Placemarks``.
Returns:
etree.ElementTree: KML element tree depicting ``Placemarks``
### Response:
def export_kml_file(self):
"""Generate KML element tree from ``Placemarks``.
Retu... |
def authentication_required(meth):
"""Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method
"""
def check(cls, *args, **kwargs):
if cls.authenticated:
return meth(cls, *args, **kwargs)
raise Error("Authentic... | Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method | Below is the the instruction that describes the task:
### Input:
Simple class method decorator.
Checks if the client is currently connected.
:param meth: the original called method
### Response:
def authentication_required(meth):
"""Simple class method decorator.
Checks if the client is currentl... |
def delete_repo(self, repo_name=None, envs=[], query='/repositories/'):
"""
`repo_name` - Name of repository to delete
Delete repo in specified environments
"""
orphan_query = '/content/orphans/rpm/'
juicer.utils.Log.log_debug("Delete Repo: %s", repo_name)
for e... | `repo_name` - Name of repository to delete
Delete repo in specified environments | Below is the the instruction that describes the task:
### Input:
`repo_name` - Name of repository to delete
Delete repo in specified environments
### Response:
def delete_repo(self, repo_name=None, envs=[], query='/repositories/'):
"""
`repo_name` - Name of repository to delete
De... |
def Akers_Deans_Crosser(m, rhog, rhol, kl, mul, Cpl, D, x):
r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
Nu = \frac{hD_i}{k_l} = C Re_e^n Pr_l^{1/3}
C = 0.02... | r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
Nu = \frac{hD_i}{k_l} = C Re_e^n Pr_l^{1/3}
C = 0.0265, n=0.8 \text{ for } Re_e > 5\times10^4
C = 5... | Below is the the instruction that describes the task:
### Input:
r'''Calculates heat transfer coefficient for condensation
of a pure chemical inside a vertical tube or tube bundle, as presented in
[2]_ according to [1]_.
.. math::
Nu = \frac{hD_i}{k_l} = C Re_e^n Pr_l^{1/3}
C =... |
def add_subsegment(self, subsegment):
"""
Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter of the
parent segment.
"""
super(Subsegment, self).add_subsegment(subsegment)
self.parent_segment.increment() | Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter of the
parent segment. | Below is the the instruction that describes the task:
### Input:
Add input subsegment as a child subsegment and increment
reference counter and total subsegments counter of the
parent segment.
### Response:
def add_subsegment(self, subsegment):
"""
Add input subsegment as a child su... |
def next(self):
"""
Returns the next data value.
:return: (float|int) the next data value
"""
out = self.peek()[self._headers.index(self._field)]
self._cursor += 1
if out is not None:
self._lastValue = out
return out | Returns the next data value.
:return: (float|int) the next data value | Below is the the instruction that describes the task:
### Input:
Returns the next data value.
:return: (float|int) the next data value
### Response:
def next(self):
"""
Returns the next data value.
:return: (float|int) the next data value
"""
out = self.peek()[self._headers.index(self._fiel... |
def _encode_multipart_formdata(fields, files):
"""
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, bo... | Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (content_type, body) ready for httplib.HTTP instance | Below is the the instruction that describes the task:
### Input:
Create a multipart encoded form for use in PUTing and POSTing.
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (conten... |
def run_migrations_online(config):
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolcl... | Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context. | Below is the the instruction that describes the task:
### Input:
Run migrations in 'online' mode.
In this scenario we need to create an Engine and associate a
connection with the context.
### Response:
def run_migrations_online(config):
"""Run migrations in 'online' mode.
In this scenario we need... |
def walk(self):
""" Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly. """
for root, dirs, files in os.walk(self.path, topdown=True):
# TODO relative walk, recursive call if root excluder found?... | Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly. | Below is the the instruction that describes the task:
### Input:
Walk the directory like os.path
(yields a 3-tuple (dirpath, dirnames, filenames)
except it exclude all files/directories on the fly.
### Response:
def walk(self):
""" Walk the directory like os.path
(yields a 3-tuple (... |
def disconnect(self):
"""Disconnect from the server"""
logger.info(u'Disconnecting')
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.state = DISCONNECTED | Disconnect from the server | Below is the the instruction that describes the task:
### Input:
Disconnect from the server
### Response:
def disconnect(self):
"""Disconnect from the server"""
logger.info(u'Disconnecting')
self.sock.shutdown(socket.SHUT_RDWR)
self.sock.close()
self.state = DISCONNECTED |
def _truncnorm_sf(truncation_level, values):
"""
Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
around the mea... | Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
around the mean, in units of sigma.
:param values:
Numpy ar... | Below is the the instruction that describes the task:
### Input:
Survival function for truncated normal distribution.
Assumes zero mean, standard deviation equal to one and symmetric
truncation.
:param truncation_level:
Positive float number representing the truncation on both sides
ar... |
def _read_value(self, file):
"""Read a single value from the given file"""
if self.data_type.nptype is not None:
dtype = (np.dtype(self.data_type.nptype).newbyteorder(
self.endianness))
return fromfile(file, dtype=dtype, count=1)
return self.data_type.rea... | Read a single value from the given file | Below is the the instruction that describes the task:
### Input:
Read a single value from the given file
### Response:
def _read_value(self, file):
"""Read a single value from the given file"""
if self.data_type.nptype is not None:
dtype = (np.dtype(self.data_type.nptype).newbyteorder(... |
def _read_cache_from_file(self):
"""Read the contents of the cache from a file on disk."""
cache = {}
try:
with(open(self._cache_file_name, 'r')) as fp:
contents = fp.read()
cache = simplejson.loads(contents)
except (IOError, JSONDecodeError):
... | Read the contents of the cache from a file on disk. | Below is the the instruction that describes the task:
### Input:
Read the contents of the cache from a file on disk.
### Response:
def _read_cache_from_file(self):
"""Read the contents of the cache from a file on disk."""
cache = {}
try:
with(open(self._cache_file_name, 'r')) as... |
def get_diagonalisation(frequencies, rate_matrix=None):
"""
Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: nu... | Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: numpy.ndarray
:return: matrix diagonalisation (d, A, A^{-1})
... | Below is the the instruction that describes the task:
### Input:
Normalises and diagonalises the rate matrix.
:param frequencies: character state frequencies.
:type frequencies: numpy.array
:param rate_matrix: (optional) rate matrix (by default an all-equal-rate matrix is used)
:type rate_matrix: n... |
def _delete_vdev_info(self, vdev):
"""handle vdev related info."""
vdev = vdev.lower()
network_config_file_name = self._get_network_file()
device = self._get_device_name(vdev)
cmd = '\n'.join(("num=$(sed -n '/auto %s/=' %s)" % (device,
... | handle vdev related info. | Below is the the instruction that describes the task:
### Input:
handle vdev related info.
### Response:
def _delete_vdev_info(self, vdev):
"""handle vdev related info."""
vdev = vdev.lower()
network_config_file_name = self._get_network_file()
device = self._get_device_name(vdev)
... |
def calculate_wave(i, lst_bin, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, seconds_per_dot=SECONDS_PER_DOT):
"""
Returns product of a sin wave and morse code (dit, dah, silent)
"""
bit = morse_bin(i=i, lst_bin=lst_bin, wpm=wpm, framerate=framerate,
default... | Returns product of a sin wave and morse code (dit, dah, silent) | Below is the the instruction that describes the task:
### Input:
Returns product of a sin wave and morse code (dit, dah, silent)
### Response:
def calculate_wave(i, lst_bin, wpm=WPM, frequency=FREQUENCY, framerate=FRAMERATE, amplitude=AMPLITUDE, seconds_per_dot=SECONDS_PER_DOT):
"""
Returns product of a si... |
def to_json(self):
""" Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima.
"""
capsule = {}
capsule["Hierarchy"] = []
for (
dying,
... | Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima. | Below is the the instruction that describes the task:
### Input:
Writes the complete Morse complex merge hierarchy to a
string object.
@ Out, a string object storing the entire merge hierarchy of
all maxima.
### Response:
def to_json(self):
""" Writes the complete Morse ... |
def check_arguments(args, parser):
"""Check arguments passed by user that are not checked by argparse itself."""
if args.asm_block not in ['auto', 'manual']:
try:
args.asm_block = int(args.asm_block)
except ValueError:
parser.error('--asm-block can only be "auto", "manual... | Check arguments passed by user that are not checked by argparse itself. | Below is the the instruction that describes the task:
### Input:
Check arguments passed by user that are not checked by argparse itself.
### Response:
def check_arguments(args, parser):
"""Check arguments passed by user that are not checked by argparse itself."""
if args.asm_block not in ['auto', 'manual']... |
def nmb_neurons(self) -> Tuple[int, ...]:
"""Number of neurons of the hidden layers.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3)
>>> ann.nmb_neurons
(2, 1)
>>> ann.nmb_neurons = (3,)
>>> ann.nmb_n... | Number of neurons of the hidden layers.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3)
>>> ann.nmb_neurons
(2, 1)
>>> ann.nmb_neurons = (3,)
>>> ann.nmb_neurons
(3,)
>>> del ann.nmb_neurons
... | Below is the the instruction that describes the task:
### Input:
Number of neurons of the hidden layers.
>>> from hydpy import ANN
>>> ann = ANN(None)
>>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3)
>>> ann.nmb_neurons
(2, 1)
>>> ann.nmb_neurons = (3,)
... |
def unregister_service(self, info):
"""Unregister a service."""
try:
del(self.services[info.name.lower()])
except:
pass
now = current_time_millis()
next_time = now
i = 0
while i < 3:
if now < next_time:
self.wait... | Unregister a service. | Below is the the instruction that describes the task:
### Input:
Unregister a service.
### Response:
def unregister_service(self, info):
"""Unregister a service."""
try:
del(self.services[info.name.lower()])
except:
pass
now = current_time_millis()
ne... |
def exists(self, value=None):
"""
Return True if the given pk value exists for the given class.
If no value is given, we use the value of the current field, which
is the value of the "_pk" attribute of its instance.
"""
try:
if not value:
value... | Return True if the given pk value exists for the given class.
If no value is given, we use the value of the current field, which
is the value of the "_pk" attribute of its instance. | Below is the the instruction that describes the task:
### Input:
Return True if the given pk value exists for the given class.
If no value is given, we use the value of the current field, which
is the value of the "_pk" attribute of its instance.
### Response:
def exists(self, value=None):
... |
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Storage Groups (always global but with filters)."""
query_str = uri_parms[0]
filter_args = parse_query_parms(method, uri, query_str)
result_storage_groups = []
for sg in hmc.consoles.console.storage_groups.l... | Operation: List Storage Groups (always global but with filters). | Below is the the instruction that describes the task:
### Input:
Operation: List Storage Groups (always global but with filters).
### Response:
def get(method, hmc, uri, uri_parms, logon_required):
"""Operation: List Storage Groups (always global but with filters)."""
query_str = uri_parms[0]
... |
def conv_defs(self):
""" Reads through the JSON object and converts them to Dataset """
log.setLevel(self.log_level)
start = datetime.datetime.now()
log.debug(" Converting to a Dataset: %s Triples", len(self.results))
self.defs = RdfDataset(self.results,
... | Reads through the JSON object and converts them to Dataset | Below is the the instruction that describes the task:
### Input:
Reads through the JSON object and converts them to Dataset
### Response:
def conv_defs(self):
""" Reads through the JSON object and converts them to Dataset """
log.setLevel(self.log_level)
start = datetime.datetime.now()
... |
def color(self, color=None):
"""Returns or sets (if a value is provided) the series' colour.
:param str color: If given, the series' colour will be set to this.
:rtype: ``str``"""
if color is None:
return self._color
else:
if not isinstance(color, str):
... | Returns or sets (if a value is provided) the series' colour.
:param str color: If given, the series' colour will be set to this.
:rtype: ``str`` | Below is the the instruction that describes the task:
### Input:
Returns or sets (if a value is provided) the series' colour.
:param str color: If given, the series' colour will be set to this.
:rtype: ``str``
### Response:
def color(self, color=None):
"""Returns or sets (if a value is pro... |
def enforce_type(self, attr, val):
"""converts a value to the attribute's type"""
if not attr in self.types:
return utfstr(val)
elif self.types[attr] == 'int':
return int(float(val))
elif self.types[attr] == 'float':
return float(val)
else:
... | converts a value to the attribute's type | Below is the the instruction that describes the task:
### Input:
converts a value to the attribute's type
### Response:
def enforce_type(self, attr, val):
"""converts a value to the attribute's type"""
if not attr in self.types:
return utfstr(val)
elif self.types[attr] == 'int':... |
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n') | Save a collection of attributes | Below is the the instruction that describes the task:
### Input:
Save a collection of attributes
### Response:
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.... |
def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
return the output activation.
"""
assert len(data) == self.layers[0].size
self.layers[0].apply(data)
# Propagate trough the remaining layers.
connections... | Evaluate the network with alternative weights on the input data and
return the output activation. | Below is the the instruction that describes the task:
### Input:
Evaluate the network with alternative weights on the input data and
return the output activation.
### Response:
def feed(self, weights, data):
"""
Evaluate the network with alternative weights on the input data and
ret... |
def load_image(file) -> DataAndMetadata.DataAndMetadata:
"""
Loads the image from the file-like object or string file.
If file is a string, the file is opened and then read.
Returns a numpy ndarray of our best guess for the most important image
in the file.
"""
if isinstance(file, str) or is... | Loads the image from the file-like object or string file.
If file is a string, the file is opened and then read.
Returns a numpy ndarray of our best guess for the most important image
in the file. | Below is the the instruction that describes the task:
### Input:
Loads the image from the file-like object or string file.
If file is a string, the file is opened and then read.
Returns a numpy ndarray of our best guess for the most important image
in the file.
### Response:
def load_image(file) -> Dat... |
def group(self, *args):
"""Returns one or more subgroups of the match. Each argument is either a
group index or a group name."""
if len(args) == 0:
args = (0,)
grouplist = []
for group in args:
grouplist.append(self._get_slice(self._get_index(group), None)... | Returns one or more subgroups of the match. Each argument is either a
group index or a group name. | Below is the the instruction that describes the task:
### Input:
Returns one or more subgroups of the match. Each argument is either a
group index or a group name.
### Response:
def group(self, *args):
"""Returns one or more subgroups of the match. Each argument is either a
group index or a... |
def create_host_call(model_dir):
"""Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
"""
graph = tf.get_default_graph()
summaries = graph.get_collection(tf.GraphKeys.SUMMARIES)
... | Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call. | Below is the the instruction that describes the task:
### Input:
Construct a host_call writing scalar summaries.
Args:
model_dir: String containing path to train
Returns:
(fn, args) Pair to be called by TPUEstimator as the host_call.
### Response:
def create_host_call(model_dir):
"""Construct a hos... |
def build_wigner_circuits(circuit, phis, thetas, qubits,
qreg, creg):
"""Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
... | Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]): phis
thetas (np.matrix[[complex]]): thetas
qubits (l... | Below is the the instruction that describes the task:
### Input:
Create the circuits to rotate to points in phase space
Args:
circuit (QuantumCircuit): The circuit to be appended with tomography
state preparation and/or measurements.
phis (np.matrix[[complex]]):... |
def interact(self,
msg='SHUTIT PAUSE POINT',
shutit_pexpect_child=None,
print_input=True,
level=1,
resize=True,
color='32',
default_msg=None,
wait=-1):
"""Same as pause_point, but sets up the terminal ready for unm... | Same as pause_point, but sets up the terminal ready for unmediated
interaction. | Below is the the instruction that describes the task:
### Input:
Same as pause_point, but sets up the terminal ready for unmediated
interaction.
### Response:
def interact(self,
msg='SHUTIT PAUSE POINT',
shutit_pexpect_child=None,
print_input=True,
level=1,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.