text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def from_board(cls: Type[GameT], board: chess.Board) -> GameT:
"""Creates a game from the move stack of a :class:`~chess.Board()`."""
# Setup the initial position.
game = cls()
game.setup(board.root())
node = game # type: GameNode
# Replay all moves.
for move in... | 0.004435 |
def producer_consumer(producer, consumer, addr='tcp://127.0.0.1',
port=None, context=None):
"""A producer-consumer pattern.
Parameters
----------
producer : callable
Callable that takes a single argument, a handle
for a ZeroMQ PUSH socket. Must be picklable.
co... | 0.000552 |
def catalog(self):
"""Create MOC from catalog of coordinates.
This command requires that the Healpy and Astropy libraries
be available. It attempts to load the given catalog,
and merges it with the running MOC.
The name of an ASCII catalog file should be given. The file
... | 0.000828 |
def stop(self):
"""Stop pipeline."""
urllib.request.urlcleanup()
self._player.set_state(Gst.State.NULL)
self.state = STATE_IDLE
self._tags = {} | 0.010929 |
def tail(ctx):
"""Show the last 10 lines of the log file"""
click.echo('tailing logs')
for e in ctx.tail()[-10:]:
ts = datetime.utcfromtimestamp(e['timestamp'] // 1000).isoformat()
click.echo("{}: {}".format(ts, e['message']))
click.echo('done') | 0.00361 |
def flush_all(self, time=0):
"""
Send a command to server flush|delete all keys.
:param time: Time to wait until flush in seconds.
:type time: int
:return: True in case of success, False in case of failure
:rtype: bool
"""
returns = []
for server ... | 0.004808 |
def analyze_pages(file_name, char_margin=1.0):
"""
Input: the file path to the PDF file
Output: yields the layout object for each page in the PDF
"""
log = logging.getLogger(__name__)
# Open a PDF file.
with open(os.path.realpath(file_name), "rb") as fp:
# Create a PDF parser object ... | 0.001334 |
def get_kde_contour(self, xax="area_um", yax="deform", xacc=None,
yacc=None, kde_type="histogram", kde_kwargs={},
xscale="linear", yscale="linear"):
"""Evaluate the kernel density estimate for contour plots
Parameters
----------
xax: str
... | 0.00148 |
def transform(self, X):
"""Transform a sequence of documents to a document-term matrix.
Transformation is done in parallel, and correctly handles dask
collections.
Parameters
----------
X : dask.Bag of raw text documents, length = n_samples
Samples. Each sam... | 0.002294 |
def convert(model, name=None, initial_types=None, doc_string='', target_opset=None,
targeted_onnx=onnx.__version__, custom_conversion_functions=None, custom_shape_calculators=None):
'''
This function converts the specified CoreML model into its ONNX counterpart. Some information such as the produced... | 0.00669 |
def do_uni_form(parser, token):
"""
You need to pass in at least the form/formset object, and can also pass in the
optional `crispy_forms.helpers.FormHelper` object.
helper (optional): A `crispy_forms.helper.FormHelper` object.
Usage::
{% load crispy_tags %}
{% crispy form form.he... | 0.001147 |
def memoized_property(func=None, key_factory=per_instance, **kwargs):
"""A convenience wrapper for memoizing properties.
Applied like so:
>>> class Foo(object):
... @memoized_property
... def name(self):
... pass
Is equivalent to:
>>> class Foo(object):
... @property
... @memoized_me... | 0.00586 |
def update(fields, path='', profile=None, **kwargs):
'''
.. versionadded:: 2016.3.0
Sets a dictionary of values in one call. Useful for large updates
in syndic environments. The dictionary can contain a mix of formats
such as:
.. code-block:: python
{
'/some/example/key': ... | 0.003069 |
def column(self, index_or_label):
"""Return the values of a column as an array.
table.column(label) is equivalent to table[label].
>>> tiles = Table().with_columns(
... 'letter', make_array('c', 'd'),
... 'count', make_array(2, 4),
... )
>>> list(tiles... | 0.001471 |
def error(self, error_code, value, **kwargs):
"""
Helper to add error to messages field. It fills placeholder with extra call parameters
or values from message_value map.
:param error_code: Error code to use
:rparam error_code: str
:param value: Value checked
:pa... | 0.003584 |
def clear_lock(backend=None, remote=None):
'''
.. versionadded:: 2015.5.0
Clear the fileserver update lock from VCS fileserver backends (:mod:`git
<salt.fileserver.gitfs>`, :mod:`hg <salt.fileserver.hgfs>`, :mod:`svn
<salt.fileserver.svnfs>`). This should only need to be done if a fileserver
up... | 0.000678 |
def vcontour(self, win, n, levels, labels=False, decimals=0, color=None,
vinterp=True, nudge=1e-6, newfig=True, figsize=None, layout=True):
"""Vertical contour
"""
x1, x2, y1, y2 = win
h = self.headalongline(np.linspace(x1 + nudge, x2 - nudge, n),
... | 0.003361 |
def where(self, predicate):
"""
Returns new Enumerable where elements matching predicate are selected
:param predicate: predicate as a lambda expression
:return: new Enumerable object
"""
if predicate is None:
raise NullArgumentError("No predicate given for wh... | 0.005076 |
def embeddedFileGet(self, id):
"""Retrieve embedded file content by name or by number."""
if self.isClosed or self.isEncrypted:
raise ValueError("operation illegal for closed / encrypted doc")
return _fitz.Document_embeddedFileGet(self, id) | 0.00722 |
def mime_type(filename):
""" Guess mime type for the given file name
Note: this implementation uses python_magic package which is not thread-safe, as a workaround global lock is
used for the ability to work in threaded environment
:param filename: file name to guess
:return: str
"""
# TODO: write lock-free mim... | 0.030337 |
def import_model(self, source):
"""Import and return model instance."""
model = super(NonstrictImporter, self).import_model(source)
sbml.convert_sbml_model(model)
return model | 0.009662 |
def flags(self, index):
"""Return the active flags for the given index. Add editable
flag to items other than the first column.
"""
activeFlags = (Qt.ItemIsEnabled | Qt.ItemIsSelectable |
Qt.ItemIsUserCheckable)
item = self.item(index)
column = ind... | 0.004283 |
def delete(self, **kwds):
"""
Endpoint: /album/<id>/delete.json
Deletes this album.
Returns True if successful.
Raises a TroveboxError if not.
"""
result = self._client.album.delete(self, **kwds)
self._delete_fields()
return result | 0.006579 |
def provider(self, value):
"""
Validate and set a WMI provider. Default to `ProviderArchitecture.DEFAULT`
"""
result = None
# `None` defaults to `ProviderArchitecture.DEFAULT`
defaulted_value = value or ProviderArchitecture.DEFAULT
try:
parsed_value ... | 0.005789 |
def istoken(docgraph, node_id, namespace=None):
"""returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise,... | 0.001923 |
def make_regex(string):
"""Regex string for optionally signed binary or privative feature.
>>> [make_regex(s) for s in '+spam -spam spam'.split()]
['([+]?spam)', '(-spam)', '(spam)']
>>> make_regex('+eggs-spam')
Traceback (most recent call last):
...
ValueError: inappropriate feature n... | 0.001105 |
def _extract_and_handle_bgp4_new_paths(self, update_msg):
"""Extracts new paths advertised in the given update message's
*MpReachNlri* attribute.
Assumes MPBGP capability is enabled and message was validated.
Parameters:
- update_msg: (Update) is assumed to be checked for a... | 0.000796 |
def generate_func(self, table):
"""
Generates a random table based mini-hashing function.
"""
# Ensure that `self` isn't suddenly in the closure...
n = self.n
def func(word):
return sum(x * ord(c) for x, c in zip(table, word)) % n
return func | 0.00639 |
def dtypes(self):
"""
Return the dtypes in the DataFrame.
This returns a Series with the data type of each column.
The result's index is the original DataFrame's columns. Columns
with mixed types are stored with the ``object`` dtype. See
:ref:`the User Guide <basics.dtyp... | 0.001799 |
def _get_filesystem_config(file_types):
"""Retrieve filesystem configuration, including support for specified file types.
"""
out = " filesystems {\n"
for file_type in sorted(list(file_types)):
if file_type in _FILESYSTEM_CONFIG:
out += _FILESYSTEM_CONFIG[file_type]
out += " ... | 0.005814 |
def encode(cls, value):
"""
write binary data into redis without encoding it.
:param value: bytes
:return: bytes
"""
try:
coerced = bytes(value)
if coerced == value:
return coerced
except (TypeError, UnicodeError):
... | 0.005405 |
def major_axis_endpoints(self):
"""Return the endpoints of the major axis."""
i = np.argmax(self.axlens) # find the major axis
v = self.paxes[:, i] # vector from center to major axis endpoint
return self.ctr - v, self.ctr + v | 0.007663 |
def deserialize(cls, config, credentials):
"""
A *class method* which reconstructs credentials created by
:meth:`serialize`. You can also pass it a :class:`.Credentials`
instance.
:param dict config:
The same :doc:`config` used in the :func:`.login` to get the
... | 0.001148 |
def new_pivot(self, attributes=None, exists=False):
"""
Create a new pivot model instance.
"""
pivot = self._related.new_pivot(self._parent, attributes, self._table, exists)
return pivot.set_pivot_keys(self._foreign_key, self._other_key) | 0.010791 |
def alphafilter(request, queryset, template):
"""
Render the template with the filtered queryset
"""
qs_filter = {}
for key in list(request.GET.keys()):
if '__istartswith' in key:
qs_filter[str(key)] = request.GET[key]
break
return render_to_response(
te... | 0.00211 |
def _query(self, action, qobj):
"""
returns WPToolsQuery string
"""
title = self.params.get('title')
pageid = self.params.get('pageid')
wikibase = self.params.get('wikibase')
qstr = None
if action == 'random':
qstr = qobj.random()
eli... | 0.00185 |
def preprocess_frame(frame):
"""Preprocess frame.
1. Converts [0, 255] to [-0.5, 0.5]
2. Adds uniform noise.
Args:
frame: 3-D Tensor representing pixels.
Returns:
frame: 3-D Tensor with values in between [-0.5, 0.5]
"""
# Normalize from [0.0, 1.0] -> [-0.5, 0.5]
frame = common_layers.convert_r... | 0.016279 |
def child_added(self, child):
""" Reset the item cache when a child is added """
super(AbstractWidgetItemGroup, self).child_added(child)
self.get_member('_items').reset(self) | 0.010101 |
def remaining(self):
"""
Get the remaining time-to-live of this lease.
:returns: TTL in seconds.
:rtype: int
"""
if self._expired:
raise Expired()
obj = {
u'ID': self.lease_id,
}
data = json.dumps(obj).encode('utf8')
... | 0.005006 |
def _parse_bugs_callback(self, value):
"""
Fires when we get bug information back from the XML-RPC server.
param value: dict of data from XML-RPC server. The "bugs" dict element
contains a list of bugs.
returns: ``list`` of ``AttrDict``
"""
return li... | 0.005376 |
def generate_detail_view(self):
"""Generate class based view for DetailView"""
name = model_class_form(self.model + 'DetailView')
detail_args = dict(
detailview_excludes=self.detailview_excludes,
model=self.get_model_class,
template_name=self.get_template('de... | 0.003922 |
def main(unused_argv):
"""Run the reinforcement learning loop."""
print('Wiping dir %s' % FLAGS.base_dir, flush=True)
shutil.rmtree(FLAGS.base_dir, ignore_errors=True)
dirs = [fsdb.models_dir(), fsdb.selfplay_dir(), fsdb.holdout_dir(),
fsdb.eval_dir(), fsdb.golden_chunk_dir(), fsdb.working_dir()]
f... | 0.016935 |
def trunc_neg_eigs(self, particle):
"""
Given a state represented as a model parameter vector,
returns a model parameter vector representing the same
state with any negative eigenvalues set to zero.
:param np.ndarray particle: Vector of length ``(dim ** 2, )``
repres... | 0.003623 |
def apply_groups(cls, obj, options=None, backend=None, clone=True, **kwargs):
"""Applies nested options definition grouped by type.
Applies options on an object or nested group of objects,
returning a new object with the options applied. This method
accepts the separate option namespace... | 0.001695 |
def enrolled_device_id(self, enrolled_device_id):
"""
Sets the enrolled_device_id of this EnrollmentIdentity.
The ID of the device in the Device Directory once it has been registered.
:param enrolled_device_id: The enrolled_device_id of this EnrollmentIdentity.
:type: str
... | 0.009447 |
def convert_surfaces(self, surface_nodes):
"""
Utility to convert a list of surface nodes into a single hazardlib
surface. There are four possibilities:
1. there is a single simpleFaultGeometry node; returns a
:class:`openquake.hazardlib.geo.simpleFaultSurface` instance
... | 0.001064 |
def generate(self):
"""!
@brief Generates data in line with generator parameters.
"""
data_points = []
for index_cluster in range(self.__amount_clusters):
for _ in range(self.__cluster_sizes[index_cluster]):
point = self.__generate_point(ind... | 0.00495 |
def get_min_risk(self, weights, cov_matrix):
"""
Minimizes the variance of a portfolio.
"""
def func(weights):
"""The objective function that minimizes variance."""
return np.matmul(np.matmul(weights.transpose(), cov_matrix), weights)
def func_deriv(weig... | 0.005663 |
def volume_delete(pool, volume, **kwargs):
'''
Delete a libvirt managed volume.
:param pool: libvirt storage pool name
:param volume: name of the volume to delete
:param connection: libvirt connection URI, overriding defaults
:param username: username to connect with, overriding defaults
:p... | 0.001477 |
def validate(self, value, model=None, context=None):
"""
Validate
Perform value validation against validation settings and return
simple result object
:param value: str, value to check
:param model: parent model being validated
:param context:... | 0.001912 |
def db_get_map(self, table, record, column):
"""
Gets dict type value of 'column' in 'record' in 'table'.
This method is corresponding to the following ovs-vsctl command::
$ ovs-vsctl get TBL REC COL
"""
val = self.db_get_val(table, record, column)
assert is... | 0.005587 |
def resolve_topic(topic):
"""Return class described by given topic.
Args:
topic: A string describing a class.
Returns:
A class.
Raises:
TopicResolutionError: If there is no such class.
"""
try:
module_name, _, class_name = topic.partition('#')
module = ... | 0.001634 |
def direct_mode_cluster_role_env(cluster_role_env, config_path):
"""Check cluster/[role]/[environ], if they are required"""
# otherwise, get the client.yaml file
cli_conf_file = os.path.join(config_path, CLIENT_YAML)
# if client conf doesn't exist, use default value
if not os.path.isfile(cli_conf_file):
... | 0.011791 |
def bulleted_list(items, indent=0, bullet_type='-'):
"""Format a bulleted list of values.
Parameters
----------
items : sequence
The items to make a list.
indent : int, optional
The number of spaces to add before each bullet.
bullet_type : str, optional
The bullet type t... | 0.001848 |
def get_item(key):
"""Return content in cached file in JSON format"""
CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key)
try:
return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-8'))["_"]
except (IOError, ValueError):
return None | 0.007143 |
def close_database_session(session):
"""Close connection with the database"""
try:
session.close()
except OperationalError as e:
raise DatabaseError(error=e.orig.args[1], code=e.orig.args[0]) | 0.004545 |
def is_analysis_edition_allowed(self, analysis_brain):
"""Returns if the analysis passed in can be edited by the current user
:param analysis_brain: Brain that represents an analysis
:return: True if the user can edit the analysis, otherwise False
"""
if not self.context_active:... | 0.001249 |
def createValidationDataSampler(dataset, ratio):
"""
Create `torch.utils.data.Sampler`s used to split the dataset into 2 ramdom
sampled subsets. The first should used for training and the second for
validation.
:param dataset: A valid torch.utils.data.Dataset (i.e. torchvision.datasets.MNIST)
:param ratio:... | 0.012453 |
def from_hdf(cls, filename):
"""Load camera model params from a HDF5 file
The HDF5 file should contain the following datasets:
wc : (2,) float with distortion center
lgamma : float distortion parameter
readout : float readout value
size : (2,) int image s... | 0.00199 |
def mark(self, channel_name, ts):
""" https://api.slack.com/methods/channels.mark
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'ts': ts,
})
return FromUrl('https://slack.com/api/channels.... | 0.008174 |
def modulate_data(self, buffer: np.ndarray) -> np.ndarray:
"""
:param buffer: Buffer in which the modulated data shall be written, initialized with zeros
:return:
"""
self.ui.prBarGeneration.show()
self.ui.prBarGeneration.setValue(0)
self.ui.prBarGenerat... | 0.006261 |
def status(institute_id, case_name):
"""Update status of a specific case."""
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
user_obj = store.user(current_user.email)
status = request.form.get('status', case_obj['status'])
link = url_for('.case', institute_id=institute_... | 0.003478 |
def run_shell_command(
state, host, command,
get_pty=False, timeout=None, print_output=False,
**command_kwargs
):
'''
Execute a command on the specified host.
Args:
state (``pyinfra.api.State`` obj): state object for this command
hostname (string): hostname of the target
... | 0.000377 |
def send_sticker(self, chat_id, data, reply_to_message_id=None, reply_markup=None, disable_notification=None,
timeout=None):
"""
Use this method to send .webp stickers.
:param chat_id:
:param data:
:param reply_to_message_id:
:param reply_markup:
... | 0.008897 |
async def open(self) -> None:
"""
Begin the search operation.
"""
LOGGER.debug('StorageRecordSearch.open >>>')
if self.opened:
LOGGER.debug('StorageRecordSearch.open <!< Search is already opened')
raise BadSearch('Search is already opened')
if n... | 0.005215 |
def parseCapabilities(self, capdict):
"""Parse a capabilities dictionary and adjust instance settings.
At the time this function is called, the user has requested some
settings (e.g., mode identifier), but we haven't yet asked the reader
whether those requested settings are within its c... | 0.000882 |
def _copy_each_include_files_to_include_dir(self):
"""Copy include header files for each directory to include directory.
Copy include header files
from
rpm/
rpmio/*.h
lib/*.h
build/*.h
sign/*.h
to
rp... | 0.001083 |
def window(self, windowNum=0):
""" Returns the region corresponding to the specified window of the app.
Defaults to the first window found for the corresponding PID.
"""
if self._pid == -1:
return None
x,y,w,h = PlatformManager.getWindowRect(PlatformManager.getWindow... | 0.025 |
def memory_read32(self, addr, num_words, zone=None):
"""Reads memory from the target system in units of 32-bits.
Args:
self (JLink): the ``JLink`` instance
addr (int): start address to read from
num_words (int): number of words to read
zone (str): memory zone to ... | 0.003617 |
def form_valid(self, form):
""" Handles a valid form. """
# Move the topic
topic = self.object
old_forum = topic.forum
new_forum = form.cleaned_data['forum']
topic.forum = new_forum
# Eventually lock the topic
if form.cleaned_data['lock_topic']:
... | 0.003425 |
def delete_last_line(self, file_path='', date=str(datetime.date.today())):
"""
The following code was modified from
http://stackoverflow.com/a/10289740 &
http://stackoverflow.com/a/17309010
It essentially will check if the total for the current date already
exists in tota... | 0.002283 |
def relocate(source, destination, move=False):
"""Adjust the virtual environment settings and optional move it.
Args:
source (str): Path to the existing virtual environment.
destination (str): Desired path of the virtual environment.
move (bool): Whether or not to actually move the file... | 0.001984 |
def previous(task):
"""
Return a previous Task of the same family.
By default checks if this task family only has one non-global parameter and if
it is a DateParameter, DateHourParameter or DateIntervalParameter in which case
it returns with the time decremented by 1 (hour, day or interval)
"""... | 0.005307 |
def draw(self, labels):
"""
Draw the silhouettes for each sample and the average score.
Parameters
----------
labels : array-like
An array with the cluster label for each silhouette sample,
usually computed with ``predict()``. Labels are not stored on th... | 0.001757 |
def get_weather_name(self, ip):
''' Get weather_name '''
rec = self.get_all(ip)
return rec and rec.weather_name | 0.014815 |
def decrypt(data, digest=True):
"""Decrypt provided data."""
alg, _, data = data.rpartition("$")
if not alg:
return data
data = _from_hex_digest(data) if digest else data
try:
return implementations["decryption"][alg](
data, implementations["get_key"]()
)
exce... | 0.002475 |
def _parse_kexgss_continue(self, m):
"""
Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message
"""
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
... | 0.002714 |
def get_tweepy_auth(twitter_api_key,
twitter_api_secret,
twitter_access_token,
twitter_access_token_secret):
"""Make a tweepy auth object"""
auth = tweepy.OAuthHandler(twitter_api_key, twitter_api_secret)
auth.set_access_token(twitter_access_token,... | 0.00274 |
def get_resource_links(self, item):
"""Hook for adding links to a resource object."""
if self.opts.self_url:
ret = self.dict_class()
kwargs = resolve_params(item, self.opts.self_url_kwargs or {})
ret['self'] = self.generate_url(self.opts.self_url, **kwargs)
... | 0.005682 |
def execute_predict_task(self, task_inst, predict_data, **kwargs):
"""
Do a prediction
task_inst - instance of a task
"""
result = task_inst.predict(predict_data, **task_inst.args)
return result | 0.008264 |
def expectation(P, obs):
r"""Equilibrium expectation of given observable.
Parameters
----------
P : (M, M) ndarray
Transition matrix
obs : (M,) ndarray
Observable, represented as vector on state space
Returns
-------
x : float
Expectation value
"""
pi =... | 0.002786 |
def can_access_objective_hierarchy(self):
"""Tests if this user can perform hierarchy queries.
A return of true does not guarantee successful authorization. A
return of false indicates that it is known all methods in this
session will result in a PermissionDenied. This is intended as a
... | 0.00365 |
def _flatten(iterable):
"""
Given an iterable with nested iterables, generate a flat iterable
"""
for i in iterable:
if isinstance(i, Iterable) and not isinstance(i, string_types):
for sub_i in _flatten(i):
yield sub_i
else:
yield i | 0.003289 |
def get_all_polymorphic_return(self) -> bool:
""" For now, polymorphic return type are handle by symbol artefact.
--> possible multi-polymorphic but with different constraint attached!
"""
lst = []
for s in self.values():
if hasattr(s, 'tret') and s.tret.is_polymorph... | 0.003226 |
def make_objects(self, meta, data, related_fields=None):
'''Generator of :class:`stdnet.odm.StdModel` instances with data
from database.
:parameter meta: instance of model :class:`stdnet.odm.Metaclass`.
:parameter data: iterator over instances data.
'''
make_object = meta.make_object
re... | 0.001426 |
def want_host_notification(self, timperiods, timestamp,
state, n_type, business_impact, cmd=None):
# pylint: disable=too-many-return-statements
"""Check if notification options match the state of the host
Notification is NOT wanted in ONE of the following case::
... | 0.00291 |
def mute(self):
"""get/set the current mute state"""
response = self.rendering_control.GetMute(InstanceID=1, Channel=1)
return response.CurrentMute == 1 | 0.011364 |
def AddTableColumns(self, table, columns):
"""Add columns to table if they are not already there.
Args:
table: table name as a string
columns: an iterable of column names"""
table_columns = self._table_columns.setdefault(table, [])
for attr in columns:
if attr not in table_columns:
... | 0.005682 |
def keep_indels(mut_df,
indel_len_col=True,
indel_type_col=True):
"""Filters out all mutations that are not indels.
Requires that one of the alleles have '-' indicating either an insertion
or deletion depending if found in reference allele or somatic allele
columns, resp... | 0.002674 |
def road(self):
"""
:example 도움5로
"""
pattern = self.random_element(self.road_formats)
return self.generator.parse(pattern) | 0.01227 |
def servicegroup_server_enable(sg_name, s_name, s_port, **connection_args):
'''
Enable a server:port member of a servicegroup
CLI Example:
.. code-block:: bash
salt '*' netscaler.servicegroup_server_enable 'serviceGroupName' 'serverName' 'serverPort'
'''
ret = True
server = _servi... | 0.005284 |
def verify_editor(self):
"""Verify if the software used in the changeset is a powerfull_editor.
"""
powerful_editors = [
'josm', 'level0', 'merkaartor', 'qgis', 'arcgis', 'upload.py',
'osmapi', 'Services_OpenStreetMap'
]
if self.editor is not None:
... | 0.001527 |
def create_command(
principal, permissions, endpoint_plus_path, notify_email, notify_message
):
"""
Executor for `globus endpoint permission create`
"""
if not principal:
raise click.UsageError("A security principal is required for this command")
endpoint_id, path = endpoint_plus_path
... | 0.001445 |
def merge(var1, var2):
"""
Take two copies of a variable and reconcile them. var1 is assumed
to be the higher-level variable, and so will be overridden by var2
where such becomes necessary.
"""
out = {}
out['value'] = var2.get('value', var1.get('value', None))
out['mimetype'] = var2.get(... | 0.003086 |
def patched(f):
"""Patches a given API function to not send."""
def wrapped(*args, **kwargs):
kwargs['return_response'] = False
kwargs['prefetch'] = True
return f(*args, **kwargs)
return wrapped | 0.004274 |
def setmonitor(self, enable=True):
"""Alias for setmode('monitor') or setmode('managed')
Only available with Npcap"""
# We must reset the monitor cache
if enable:
res = self.setmode('monitor')
else:
res = self.setmode('managed')
if not res:
... | 0.003876 |
def a_star_search(start, successors, state_value, is_goal):
"""
This is a searching function of A*
"""
if is_goal(start):
return [start]
explored = []
g = 1
h = state_value(start)
f = g + h
p = [start]
frontier = [(f, g, h, p)]
while frontier:
f, g, h, path = ... | 0.003382 |
def next_chunk(self):
"""
Read a chunk of arbitrary size from the underlying iterator. To get a
chunk of an specific size, use read()
"""
if self._unconsumed:
data = self._unconsumed.pop()
else:
data = self._iterator.next() # Might raise StopItera... | 0.005333 |
def add_position(self, radial=False, chunksize=2**19, chunkslice='bytes',
comp_filter=default_compression, overwrite=False,
params=dict()):
"""Add the `position` array in '/trajectories'.
"""
nparams = self.numeric_params
num_particles = nparams[... | 0.004469 |
def to_daydate(cls, *argv):
"""
Convert date to Julian day (DAYDATE)
"""
argc = len(argv)
if argc == 3:
year, month, day = argv
elif argc == 1:
dval = argv[0]
try:
year = dval.year
month = dval.month
... | 0.003617 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.