text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get(self, worker_id):
''' Return status report '''
code = 200
if worker_id == 'all':
report = {'workers': [{
'id': job,
'report': self._inspect_worker(job)}
for job in self.jobs]
}
elif worker_id in self.jobs:
... | 0.003356 |
def init():
"""
Initialize all global variables (:attr:`.KW_DICT`, :attr:`.KEYWORDS`,
:attr:`.KEYWORDS_LOWER`, :attr:`.KW_CACHE_PATH`) to their values.
Global variables are then used from analyzers and so on.
"""
global _INITIALIZED
if _INITIALIZED:
return
global KW_DICT
g... | 0.00113 |
def _GetAttributeContainers(
self, container_type, filter_expression=None, order_by=None):
"""Retrieves a specific type of stored attribute containers.
Args:
container_type (str): attribute container type.
filter_expression (Optional[str]): expression to filter results by.
order_by (Opt... | 0.007263 |
def add_list(self, bl):
"""
note that this pushes the cur_element, but doesn't pop it.
You'll need to do that
"""
# text:list doesn't like being a child of text:p
if self.cur_element is None:
self.add_text_frame()
self.push_element()
self.cur_e... | 0.003252 |
def _print_html(self):
"""
Internal method to call the javascript/html table.
"""
cur_path = os.path.dirname(os.path.realpath(sys.argv[0]))
shutil.copytree(cur_path+'webpage/template/', '') | 0.012605 |
def parsePathname(self, pathname):
"""Parse one or more source files.
``pathname`` may be a file name or a directory name.
"""
if os.path.isdir(pathname):
for root, dirs, files in os.walk(pathname):
dirs.sort()
files.sort()
for... | 0.003096 |
def ftp_connect(self, host, user='anonymous', password='anonymous@', port=21, timeout=30, connId='default'):
"""
Constructs FTP object, opens a connection and login.
Call this function before any other (otherwise raises exception).
Returns server output.
Parameters:
-... | 0.004184 |
def rename_component(self, old_component, new_component):
"""
Change the label of a component attached to the Bundle
:parameter str old_component: the current name of the component
(must exist)
:parameter str new_component: the desired new name of the component
(... | 0.002588 |
def set_iscsi_info(self, target_name, lun, ip_address,
port='3260', auth_method=None, username=None,
password=None):
"""Set iSCSI details of the system in UEFI boot mode.
The initiator system is set with the target details like
IQN, LUN, IP, Port et... | 0.002502 |
def experiments_fmri_download(self, experiment_id):
"""Download the fMRI data file associated with given experiment.
Parameters
----------
experiment_id : string
Unique experiment identifier
Returns
-------
FileInfo
Information about fMRI... | 0.002442 |
def extend_regex2(regexpr, reflags=0):
"""
also preprocesses flags
"""
regexpr = extend_regex(regexpr)
IGNORE_CASE_PREF = '\\c'
if regexpr.startswith(IGNORE_CASE_PREF):
# hack for vim-like ignore case
regexpr = regexpr[len(IGNORE_CASE_PREF):]
reflags = reflags | re.IGNORE... | 0.002841 |
def encry_decry_chunk(chunk, key, algo, bool_encry, assoc_data):
"""
When bool_encry is True, encrypt a chunk of the file with the key and a randomly generated nonce. When it is False,
the function extract the nonce from the cipherchunk (first 16 bytes), and decrypt the rest of the chunk.
:param chunk: ... | 0.004961 |
def load(self):
"""Loads the config"""
try:
with open(self._ef_site_config, 'r') as yml_file:
return yaml.safe_load(yml_file)
except (IOError, yaml.parser.ParserError) as error:
print("Error: {}".format(error), file=sys.stderr)
sys.exit(1) | 0.01444 |
def _python_rpath(self):
"""The relative path (from environment root) to python."""
# Windows virtualenv installation installs pip to the [Ss]cripts
# folder. Here's a simple check to support:
if sys.platform == 'win32':
return os.path.join('Scripts', 'python.exe')
re... | 0.00565 |
def stringify(syllables) :
'''This function takes a syllabification returned by syllabify and
turns it into a string, with phonemes spearated by spaces and
syllables spearated by periods.'''
ret = []
for syl in syllables :
stress, onset, nucleus, coda = syl
if stress != None and len(nucleus) != 0 :
nu... | 0.041063 |
def root_password(self, server_id, password):
'''
Change server(uuid's) root password
'''
nt_ks = self.compute_conn
nt_ks.servers.change_password(server_id, password) | 0.009709 |
def getWhatIf(number):
""" Returns a :class:`WhatIf` object corresponding to the What If article of
index passed to the function. If the index is less than zero or
greater than the maximum number of articles published thus far,
None is returned instead.
Like all the routines for handling What If articles, :fu... | 0.02599 |
def get_nics(vm_, **kwargs):
'''
Return info about the network interfaces of a named vm
:param vm_: name of the domain
:param connection: libvirt connection URI, overriding defaults
.. versionadded:: 2019.2.0
:param username: username to connect with, overriding defaults
.. versio... | 0.001555 |
def str2bool(string_, default='raise'):
"""
Convert a string to a bool.
Parameters
----------
string_ : str
default : {'raise', False}
Default behaviour if none of the "true" strings is detected.
Returns
-------
boolean : bool
Examples
--------
>>> str2bool('Tr... | 0.001255 |
def Skin(CASRN, AvailableMethods=False, Method=None): # pragma: no cover
'''This function handles the retrieval of whether or not a chemical can
be absorbed through the skin, relevant to chemical safety calculations.
This API is considered experimental, and is expected to be removed in a
future releas... | 0.000974 |
def getStretchTwistBendModulus(self, bp, frames=None, paxis='Z', masked=True, matrix=False):
r"""Calculate Bending-Stretching-Twisting matrix
It calculate elastic matrix and modulus matrix.
.. math::
\text{modulus matrix} = 4.1419464 \times \begin{bmatrix}
K_{Bx} ... | 0.004496 |
def init_app(self, app):
"""Setup the logging handlers, level and formatters.
Level (DEBUG, INFO, CRITICAL, etc) is determined by the
app.config['FLASK_LOG_LEVEL'] setting, and defaults to
``None``/``logging.NOTSET``.
"""
config_log_level = app.config.get('FLASK_LOG_LEV... | 0.001005 |
def render(self, data, div_id="chart", head=""):
"""Render the data in HTML template."""
if not self.is_valid_name(div_id):
raise ValueError(
"Name {} is invalid. Only letters, numbers, '_', and '-' are permitted ".format(
div_id))
return Template... | 0.006061 |
def groups(self) -> Set[str]:
"""The set of option-groups created by ``define``.
.. versionadded:: 3.1
"""
return set(opt.group_name for opt in self._options.values()) | 0.01 |
def crawl_fig(self, fig):
"""Crawl the figure and process all axes"""
with self.renderer.draw_figure(fig=fig,
props=utils.get_figure_properties(fig)):
for ax in fig.axes:
self.crawl_ax(ax) | 0.00738 |
def ber_from_socket(s):
"""
Reads a ber length from a socket.
Reads first byte to read the ber length first, then read the actual data.
return: (length, bytes_read, data) - a tuple of values
"""
if isinstance(s, network.SocketClient):
recv = s.receive
else:
recv = s.recv
... | 0.003091 |
def dict_to_csv(orig_dict, file_name, field_names_tuple, file_location):
"""
Function to export a dictionary to a csv file
Args:
orig_dict: The dictionary you want exported
file_name: The name of the exported file
field_names_tuple: The fieldnames in a tuple
file_location: Th... | 0.00246 |
def autoinc(self):
"""
Conditionally updates the stack version in the file associated with
this config.
This handles both official releases (i.e. QA configs), and release
candidates. Assumptions about version:
- Official release versions are MAJOR.minor, where MAJ... | 0.001291 |
def h(gbm, array_or_frame, indices_or_columns = 'all'):
"""
PURPOSE
Compute Friedman and Popescu's H statistic, in order to look for an interaction in the passed gradient-boosting
model among the variables represented by the elements of the passed array or frame and specified by the passed
indices ... | 0.007486 |
def call(self, context, x, losses=None):
"""Call the layer."""
has_length_dim = context.length_dim in x.shape.dims
if not has_length_dim:
x_shape = x.shape
shape_with_length = mtf.Shape(
x_shape.dims[:-1] + [mtf.Dimension("length", 1)]
+ x_shape.dims[-1:])
x = mtf.resha... | 0.007979 |
def parse_sam_read(sam):
"""
Parses a SAM alignment and returns a SamFile object.
Parameters
----------
sam : str or list
Either a tab delimited SAM string, or an already tokenized
list of SAM fields.
Returns
-------
SamRead
a SamRead object representat... | 0.012717 |
def write_init_files(packages):
"""Make sure package hierarchy is a "pkgutil-style namespace
package". For more detail see
https://packaging.python.org/guides/packaging-namespace-packages/
"""
init_text = """__path__ = __import__('pkgutil').extend_path(__path__, __name__)
try:
from .__doc_... | 0.004115 |
def _update_buffers(self, from_step, data, offset, is_last):
"""
Update the buffers of all steps that need data from ``from_step``.
If ``from_step`` is None it means the data is the input data.
"""
for to_step, buffer in self.target_buffers[from_step]:
parent_index =... | 0.004959 |
def vradErrorSkyAvg(vmag, spt):
"""
Calculate radial velocity error from V and the spectral type. The value of the error is an average over
the sky.
Parameters
----------
vmag - Value of V-band magnitude.
spt - String representing the spectral type of the star.
Returns
-------
The radial veloci... | 0.010965 |
def get_diagonalizing_basis(list_of_pauli_terms):
"""
Find the Pauli Term with the most non-identity terms
:param list_of_pauli_terms: List of Pauli terms to check
:return: The highest weight Pauli Term
:rtype: PauliTerm
"""
qubit_ops = set(reduce(lambda x, y: x + y,
... | 0.007648 |
def convert_words_to_uint(high_word, low_word):
"""Convert two words to a floating point"""
try:
low_num = int(low_word)
# low_word might arrive as a signed number. Convert to unsigned
if low_num < 0:
low_num = abs(low_num) + 2**15
number = (int(high_word) << 16) | lo... | 0.005141 |
def parse_seeds_xml(root):
"""
Parse <seeds> element in the UBCPI XBlock's content XML.
Args:
root (lxml.etree.Element): The root of the <seeds> node in the tree.
Returns:
a list of deserialized representation of seeds. E.g.
[{
'answer': 1, # option index starting ... | 0.002245 |
def update_datasources_cache():
"""Refresh sqllab datasources cache"""
from superset.models.core import Database
for database in db.session.query(Database).all():
if database.allow_multi_schema_metadata_fetch:
print('Fetching {} datasources ...'.format(database.name))
try:
... | 0.001548 |
def is_peering_connection_pending(conn_id=None, conn_name=None, region=None,
key=None, keyid=None, profile=None):
'''
Check if a VPC peering connection is in the pending state.
.. versionadded:: 2016.11.0
conn_id
The connection ID to check. Exclusive with con... | 0.004363 |
def redfearn(lat, lon, false_easting=None, false_northing=None,
zone=None, central_meridian=None, scale_factor=None):
"""Compute UTM projection using Redfearn's formula
lat, lon is latitude and longitude in decimal degrees
If false easting and northing are specified they will override
the... | 0.008712 |
def install_key_data(self, keydata, target):
"""Install the key data into the open file."""
target.seek(0)
contents = target.read()
ssh_opts = 'no-port-forwarding'
if keydata in contents:
raise InstallError('key data already in file - refusing '
... | 0.002604 |
def _get_win_folder_from_registry(csidl_name):
"""
This is a fallback technique at best. I'm not sure if using the
registry for this guarantees us the correct answer for all CSIDL_*
names.
"""
import _winreg
shell_folder_name = {
"CSIDL_APPDATA": "AppData",
"CSIDL_COMMON_APP... | 0.00155 |
def make_oracle(q0, q1, secret_function):
""" Gates implementing the secret function f(x)."""
# coverage: ignore
if secret_function[0]:
yield [CNOT(q0, q1), X(q1)]
if secret_function[1]:
yield CNOT(q0, q1) | 0.004184 |
def off(self):
"""Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
"""
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.pla... | 0.004762 |
def add_websocket(
self,
path: str,
endpoint: Optional[str]=None,
view_func: Optional[Callable]=None,
defaults: Optional[dict]=None,
host: Optional[str]=None,
subdomain: Optional[str]=None,
*,
strict_slashes: boo... | 0.0174 |
def logEntryExit(getLoggerCallback=logging.getLogger,
entryExitLogLevel=logging.DEBUG, logArgs=False,
logTraceback=False):
""" Returns a closure suitable for use as function/method decorator for
logging entry/exit of function/method.
getLoggerCallback: user-supplied callback ... | 0.007512 |
def send_key(self, key):
"""Send a key command to the TV."""
if isinstance(key, Keys):
key = key.value
params = '<X_KeyEvent>{}</X_KeyEvent>'.format(key)
self.soap_request(URL_CONTROL_NRC, URN_REMOTE_CONTROL,
'X_SendKey', params) | 0.006689 |
def form_valid(self, form):
""" Handles a valid form. """
user_kwargs = (
{'voter': self.request.user}
if self.request.user.is_authenticated
else {'anonymous_key': self.request.user.forum_key}
)
if self.object.user_changes:
# If user chang... | 0.00542 |
def rename(self, old_name, new_name):
"""Rename key to a new name."""
try:
self.api.rename(mkey(old_name), mkey(new_name))
except ResponseError, exc:
if "no such key" in exc.args:
raise KeyError(old_name)
raise | 0.006993 |
def minify_js(input_files, output_file):
"""
Minifies the input javascript files to the output file.
Output file may be same as input to minify in place.
In debug mode this function just concatenates the files
without minifying.
"""
from .modules import minify, utils
if not isinstance... | 0.001629 |
def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3),
trim_edge=True, **kwargs):
"""
Get an initial featuring of sphere positions in an image.
Parameters
-----------
image : :class:`peri.util.Image` object
Image object which defines the image file as we... | 0.002268 |
def results(self) -> List[TrialResult]:
"""Returns the job results, blocking until the job is complete."""
if not self._results:
job = self._update_job()
for _ in range(1000):
if job['executionStatus']['state'] in TERMINAL_STATES:
break
... | 0.00267 |
def count_channels(self):
"""If more than one channel selected, activate merge checkbox."""
merge = self.index['merge']
if len(self.idx_chan.selectedItems()) > 1:
if merge.isEnabled():
return
else:
merge.setEnabled(True)
else:
... | 0.004706 |
def SMS(self, to, body):
"""
Quickly send an SMS from a default number. Calls :py:meth:`twilio_SMS`.
* *stored credential name: TWILIO_PHONE_NUMBER*
:param string to: The phone number to send the SMS message to. Full international format.
:param string body: The... | 0.014433 |
def drop_stub_rows(self, ignore_cols=('specimen',
'sample',
'software_packages',
'num')):
"""
Drop self.df rows that have only null values,
ignoring certain columns.
... | 0.003308 |
def do_thing():
"""Execute command line cryptorito actions"""
if len(sys.argv) == 5 and sys.argv[1] == "encrypt_file":
encrypt_file(sys.argv[2], sys.argv[3], sys.argv[4])
elif len(sys.argv) == 4 and sys.argv[1] == "decrypt_file":
decrypt_file(sys.argv[2], sys.argv[3])
elif len(sys.argv) ... | 0.001018 |
def set_backgroundcolor(self, color):
'''Sets the background color of the current axes (and legend).
Use 'None' (with quotes) for transparent. To get transparent
background on saved figures, use:
pp.savefig("fig1.svg", transparent=True)
'''
ax = self.ax
... | 0.020747 |
def _force_edge_active_move(self, state: _STATE) -> _STATE:
"""Move which forces a random edge to appear on some sequence.
This move chooses random edge from the edges which do not belong to any
sequence and modifies state in such a way, that this chosen edge
appears on some sequence of... | 0.00182 |
def intent(self, intent_name, mapping={}, convert={}, default={}):
"""Decorator routes an Alexa IntentRequest and provides the slot parameters to the wrapped function.
Functions decorated as an intent are registered as the view function for the Intent's URL,
and provide the backend responses to... | 0.005263 |
def conductivity(CASRN=None, AvailableMethods=False, Method=None, full_info=True):
r'''This function handles the retrieval of a chemical's conductivity.
Lookup is based on CASRNs. Will automatically select a data source to use
if no Method is provided; returns None if the data is not available.
Functio... | 0.00124 |
def setLogLevel(level, logger=None):
"""
Sets the log level to a given string level (like "INFO"). Operates on the
root logger by default, but another logger can be specified instead.
"""
if logger is None:
logger = rootLogger
level = level.upper()
if level == "OFF": level = "CRITICA... | 0.010626 |
def start_thread(self, lpStartAddress, lpParameter=0, bSuspended = False):
"""
Remotely creates a new thread in the process.
@type lpStartAddress: int
@param lpStartAddress: Start address for the new thread.
@type lpParameter: int
@param lpParameter: Optional argumen... | 0.007252 |
def update_current_state(self, value: str,
force: bool = False) -> datetime:
"""Update the current state.
Args:
value (str): New value for sdp state
force (bool): If true, ignore allowed transitions
Returns:
datetime, update time... | 0.002171 |
def get_crop_box(self):
"""
Get coordinates of the rectangle defining the new image boundaries. It
takes into acount any specific wishes from the model (explicitely
passed in crop_box), the desired format and it's options
(flexible_height, nocrop) and mainly it's ratio. After dim... | 0.002976 |
def load_from_file(self, yamlfile, _override=True, _allow_undeclared=False):
"""Loads the configuration from a file.
Parsed contents must be a single dict mapping config key to value.
Args:
yamlfile: The opened file object to load configuration from.
See load_from_dict() for other args' descri... | 0.004902 |
def new_autoshape_sp(id_, name, prst, left, top, width, height):
"""
Return a new ``<p:sp>`` element tree configured as a base auto shape.
"""
tmpl = CT_Shape._autoshape_sp_tmpl()
xml = tmpl % (id_, name, left, top, width, height, prst)
sp = parse_xml(xml)
return ... | 0.006211 |
def process_resource_schedule(self, i, value, time_type):
"""Does the resource tag schedule and policy match the current time."""
rid = i[self.id_key]
# this is to normalize trailing semicolons which when done allows
# dateutil.parser.parse to process: value='off=(m-f,1);' properly.
... | 0.001076 |
def get_job(job_id):
"""Gets a job."""
job = current_app.apscheduler.get_job(job_id)
if not job:
return jsonify(dict(error_message='Job %s not found' % job_id), status=404)
return jsonify(job) | 0.009132 |
def portfolio_from_orders(orders, funds=1e5, price_type='close'):
"""Create a DataFrame of portfolio holdings (#'s' of shares for the symbols and dates)
Appends the "$CASH" symbol to the porfolio and initializes it to `funds` indicated.
Appends the symbol "total_value" to store the total value of cash + st... | 0.010959 |
def __set_window_title(self):
"""
Sets the Component window title.
"""
if self.has_editor_tab():
windowTitle = "{0} - {1}".format(self.__default_window_title, self.get_current_editor().file)
else:
windowTitle = "{0}".format(self.__default_window_title)
... | 0.00885 |
def _check_valid_key(self, key):
"""Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
"""
if not isinstance(key, key_type):
raise Va... | 0.004228 |
def choose_attribute(data, attributes, class_attr, fitness, method):
"""
Cycles through all the attributes and returns the attribute with the
highest information gain (or lowest entropy).
"""
best = (-1e999999, None)
for attr in attributes:
if attr == class_attr:
continue
... | 0.002294 |
def chunk(self, chunks=None, name_prefix='xarray-', token=None,
lock=False):
"""Coerce all arrays in this dataset into dask arrays with the given
chunks.
Non-dask arrays in this dataset will be converted to dask arrays. Dask
arrays will be rechunked to the given chunk size... | 0.001217 |
def _tarjan(self, function, order, stack, data):
"""Tarjan's strongly connected components algorithm.
See also:
- http://en.wikipedia.org/wiki/Tarjan's_strongly_connected_components_algorithm
"""
try:
func_data = data[function.id]
return order
ex... | 0.002579 |
def get_attrs(self, key):
"""
:param key: dataset path
:returns: dictionary of attributes for that path
"""
try:
dset = h5py.File.__getitem__(self.hdf5, key)
except KeyError:
if self.parent != ():
dset = h5py.File.__getitem__(self.p... | 0.004902 |
def _get_team(self, team):
"""
Retrieve team's name and abbreviation.
The team's name and abbreviation are embedded within the 'school_name'
tag and, in the case of the abbreviation, require special parsing as it
is located in the middle of a URI. The name and abbreviation are
... | 0.001852 |
def manhattan_distance(point1, point2):
"""!
@brief Calculate Manhattan distance between between two vectors.
\f[
dist(a, b) = \sum_{i=0}^{N}\left | a_{i} - b_{i} \right |;
\f]
@param[in] point1 (array_like): The first vector.
@param[in] point2 (array_like): The second vector.
... | 0.004815 |
def toggle_rules(self, *args):
"""Display or hide the view for constructing rules out of cards."""
if self.app.manager.current != 'rules' and not isinstance(self.app.selected_proxy, CharStatProxy):
self.app.rules.entity = self.app.selected_proxy
self.app.rules.rulebook = self.app... | 0.005319 |
def update(self, pointvol):
"""Update the bounding ellipsoids using the current set of
live points."""
# Check if we should use the pool for updating.
if self.use_pool_update:
pool = self.pool
else:
pool = None
# Update the bounding ellipsoids.
... | 0.002882 |
def edit_user_login(self, id, account_id, login_integration_id=None, login_password=None, login_sis_user_id=None, login_unique_id=None):
"""
Edit a user login.
Update an existing login for a user in the given account.
"""
path = {}
data = {}
params = {}
... | 0.004604 |
def _ParseHeader(self, format_type, value_data):
"""Parses the header.
Args:
format_type (int): format type.
value_data (bytes): value data.
Returns:
AppCompatCacheHeader: header.
Raises:
ParseError: if the value data could not be parsed.
"""
data_type_map_name = self.... | 0.005029 |
def get_file_view_cls(self, filename):
"""Returns the view class associated to a filename
"""
if filename is None:
return self.default_view_class
for pattern, cls in self.view_class_files_map:
if pattern.match(filename):
return cls
return s... | 0.005848 |
def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements):
"""Adjusts the limits of variadic sequence MPL-containers."""
for container in containers:
headerFile = os.path.join( headerDir, "limits", container + ".hpp" )
regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + c... | 0.017094 |
def choose_submit(self, submit):
"""Selects the input (or button) element to use for form submission.
:param submit: The bs4.element.Tag (or just its *name*-attribute) that
identifies the submit element to use. If ``None``, will choose the
first valid submit element in the form,... | 0.00078 |
async def close_connection(self) -> None:
"""
7.1.1. Close the WebSocket Connection
When the opening handshake succeeds, :meth:`connection_open` starts
this coroutine in a task. It waits for the data transfer phase to
complete then it closes the TCP connection cleanly.
... | 0.001074 |
def _dispatch(self, tree):
"_dispatcher function, _dispatching tree type T to method _T."
if isinstance(tree, list):
for t in tree:
self._dispatch(t)
return
meth = getattr(self, "_"+tree.__class__.__name__)
if tree.__class__.__name__ == 'NoneType' ... | 0.005236 |
def list_containers_info(self, limit=None, marker=None):
"""Returns a list of info on Containers.
For each container, a dict containing the following keys is returned:
\code
name - the name of the container
count - the number of objects in the container
bytes... | 0.006742 |
def re_based_make_clean_visible(html):
'''
Takes an HTML-like binary string as input and returns a binary
string of the same length with all tags replaced by whitespace.
This also detects script and style tags, and replaces the text
between them with whitespace.
Pre-existing whitespace of any k... | 0.000764 |
def get_model_url_base():
'''
Returns a root folder for models.
'''
url_base = get_model_url_base_from_env()
if url_base is not None:
logger.info('NNBLA_MODELS_URL_BASE is set as {}.'.format(url_base))
else:
url_base = 'https://nnabla.org/pretrained-models/nnp_models/'
return... | 0.00304 |
def _StopStyleSelectionMethod(self, doc):
"""Create a method to determine which style to apply to a stop placemark.
Args:
doc: the KML document.
Returns:
A function that should accept a Stop argument and return a tuple of
(stop placemark style id, pathway placemark style id). Either sty... | 0.003285 |
def search_shell(self):
"""
Looks for a shell service
"""
with self._lock:
if self._shell is not None:
# A shell is already there
return
reference = self._context.get_service_reference(SERVICE_SHELL)
if reference is not... | 0.005435 |
def append_table(self, name, **kwargs):
"""Create a new table."""
self.stack.append(Table(name, **kwargs)) | 0.016393 |
def tree_to_xml(self):
"""Traverses treeview and generates a ElementTree object"""
# Need to remove filter or hidden items will not be saved.
self.filter_remove(remember=True)
tree = self.treeview
root = ET.Element('interface')
items = tree.get_children()
for it... | 0.003953 |
def score(self, y_true, y_pred):
"""Calculate f1 score.
Args:
y_true (list): true sequences.
y_pred (list): predicted sequences.
Returns:
score: f1 score.
"""
score = f1_score(y_true, y_pred)
print(' - f1: {:04.2f}'.format(score * 100... | 0.004926 |
def cli(ctx, config, debug, language, verbose):
"""
Cucco allows to apply normalizations to a given text or file.
This normalizations include, among others, removal of accent
marks, stop words an extra white spaces, replacement of
punctuation symbols, emails, emojis, etc.
For more info on how t... | 0.001294 |
def _get_service_names(self):
"""
Get a list of service names from Sentinel. Tries Sentinel hosts until one succeeds; if none succeed,
raises a ConnectionError.
:return: the list of service names from Sentinel.
"""
master_info = None
connection_errors = []
... | 0.005714 |
def run(self):
""" Append version number to gvar/__init__.py """
with open('src/gvar/__init__.py', 'a') as gvfile:
gvfile.write("\n__version__ = '%s'\n" % GVAR_VERSION)
_build_py.run(self) | 0.008929 |
def generate_colormap(self,colormap=None,reverse=False):
"""use 1 colormap for the whole abf. You can change it!."""
if colormap is None:
colormap = pylab.cm.Dark2
self.cm=colormap
self.colormap=[]
for i in range(self.sweeps): #TODO: make this the only colormap
... | 0.018735 |
def nvmlUnitGetCount():
r"""
/**
* Retrieves the number of units in the system.
*
* For S-class products.
*
* @param unitCount Reference in which to return the number of units
*
* @return
* - \ref NVML_SUCCESS if \a unitC... | 0.003704 |
def call_apply_bpe(workspace_dir: str, input_fname: str, output_fname: str, model_fname: str):
"""
Call BPE apply script.
:param workspace_dir: Workspace directory where subword-nmt is checked out.
:param input_fname: Path of tokenized input file, plain text or gzipped.
:param output_fname: Path of... | 0.003885 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.