_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q36200 | URL.with_path | train | def with_path(self, path, *, encoded=False):
"""Return a new URL with path replaced."""
if not encoded:
path = self._PATH_QUOTER(path)
if self.is_absolute():
path = self._normalize_path(path)
if len(path) > 0 and path[0] != "/":
path = "/" + pa... | python | {
"resource": ""
} |
q36201 | URL.with_query | train | def with_query(self, *args, **kwargs):
"""Return a new URL with query part replaced.
Accepts any Mapping (e.g. dict, multidict.MultiDict instances)
or str, autoencode the argument if needed.
A sequence of (key, value) pairs is supported as well.
It also can take an arbitrary n... | python | {
"resource": ""
} |
q36202 | URL.update_query | train | def update_query(self, *args, **kwargs):
"""Return a new URL with query part updated."""
s = self._get_str_query(*args, **kwargs)
new_query = MultiDict(parse_qsl(s, keep_blank_values=True))
query = MultiDict(self.query)
query.update(new_query)
return URL(self._val._repla... | python | {
"resource": ""
} |
q36203 | URL.with_fragment | train | def with_fragment(self, fragment):
"""Return a new URL with fragment replaced.
Autoencode fragment if needed.
Clear fragment to default if None is passed.
"""
# N.B. doesn't cleanup query/fragment
if fragment is None:
fragment = ""
elif not isinstan... | python | {
"resource": ""
} |
q36204 | URL.human_repr | train | def human_repr(self):
"""Return decoded human readable string for URL representation."""
return urlunsplit(
SplitResult(
self.scheme,
self._make_netloc(
self.user, self.password, self.host, self._val.port, encode=False
),
... | python | {
"resource": ""
} |
q36205 | all_arch_srcarch_kconfigs | train | def all_arch_srcarch_kconfigs():
"""
Generates Kconfig instances for all the architectures in the kernel
"""
os.environ["srctree"] = "."
os.environ["HOSTCC"] = "gcc"
os.environ["HOSTCXX"] = "g++"
os.environ["CC"] = "gcc"
os.environ["LD"] = "ld"
for arch, srcarch in all_arch_srcarch... | python | {
"resource": ""
} |
q36206 | menuconfig | train | def menuconfig(kconf):
"""
Launches the configuration interface, returning after the user exits.
kconf:
Kconfig instance to be configured
"""
global _kconf
global _conf_filename
global _conf_changed
global _minconf_filename
global _show_all
_kconf = kconf
# Load exis... | python | {
"resource": ""
} |
q36207 | print_menuconfig_nodes | train | def print_menuconfig_nodes(node, indent):
"""
Prints a tree with all the menu entries rooted at 'node'. Child menu
entries are indented.
"""
while node:
string = node_str(node)
if string:
indent_print(string, indent)
if node.list:
print_menuconfig_nod... | python | {
"resource": ""
} |
q36208 | print_menuconfig | train | def print_menuconfig(kconf):
"""
Prints all menu entries for the configuration.
"""
# Print the expanded mainmenu text at the top. This is the same as
# kconf.top_node.prompt[0], but with variable references expanded.
print("\n======== {} ========\n".format(kconf.mainmenu_text))
print_menuc... | python | {
"resource": ""
} |
q36209 | expr_str | train | def expr_str(expr, sc_expr_str_fn=standard_sc_expr_str):
"""
Returns the string representation of the expression 'expr', as in a Kconfig
file.
Passing subexpressions of expressions to this function works as expected.
sc_expr_str_fn (default: standard_sc_expr_str):
This function is called for... | python | {
"resource": ""
} |
q36210 | standard_kconfig | train | def standard_kconfig():
"""
Helper for tools. Loads the top-level Kconfig specified as the first
command-line argument, or "Kconfig" if there are no command-line arguments.
Returns the Kconfig instance.
Exits with sys.exit() (which raises a SystemExit exception) and prints a
usage note to stder... | python | {
"resource": ""
} |
q36211 | Kconfig.write_config | train | def write_config(self, filename=None,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n",
save_old=True, verbose=True):
r"""
Writes out symbol values in the .config format. The format matches the
C implementation, including or... | python | {
"resource": ""
} |
q36212 | Kconfig.write_min_config | train | def write_min_config(self, filename,
header="# Generated by Kconfiglib (https://github.com/ulfalizer/Kconfiglib)\n"):
"""
Writes out a "minimal" configuration file, omitting symbols whose value
matches their default value. The format matches the one produced by
'... | python | {
"resource": ""
} |
q36213 | Kconfig.eval_string | train | def eval_string(self, s):
"""
Returns the tristate value of the expression 's', represented as 0, 1,
and 2 for n, m, and y, respectively. Raises KconfigError if syntax
errors are detected in 's'. Warns if undefined symbols are referenced.
As an example, if FOO and BAR are trista... | python | {
"resource": ""
} |
q36214 | Symbol.set_value | train | def set_value(self, value):
"""
Sets the user value of the symbol.
Equal in effect to assigning the value to the symbol within a .config
file. For bool and tristate symbols, use the 'assignable' attribute to
check which values can currently be assigned. Setting values outside
... | python | {
"resource": ""
} |
q36215 | tokenize | train | def tokenize(s):
r"""Returns an iterable through all subparts of string splitted by '.'
So:
>>> list(tokenize('foo.bar.wiz'))
['foo', 'bar', 'wiz']
Contrary to traditional ``.split()`` method, this function has to
deal with any type of data in the string. So it actually
interprets... | python | {
"resource": ""
} |
q36216 | aget | train | def aget(dct, key):
r"""Allow to get values deep in a dict with iterable keys
Accessing leaf values is quite straightforward:
>>> dct = {'a': {'x': 1, 'b': {'c': 2}}}
>>> aget(dct, ('a', 'x'))
1
>>> aget(dct, ('a', 'b', 'c'))
2
If key is empty, it returns unchanged... | python | {
"resource": ""
} |
q36217 | die | train | def die(msg, errlvl=1, prefix="Error: "):
"""Convenience function to write short message to stderr and quit."""
stderr("%s%s\n" % (prefix, msg))
sys.exit(errlvl) | python | {
"resource": ""
} |
q36218 | type_name | train | def type_name(value):
"""Returns pseudo-YAML type name of given value."""
return type(value).__name__ if isinstance(value, EncapsulatedNode) else \
"struct" if isinstance(value, dict) else \
"sequence" if isinstance(value, (tuple, list)) else \
type(value).__name__ | python | {
"resource": ""
} |
q36219 | do | train | def do(stream, action, key, default=None, dump=yaml_dump,
loader=ShyamlSafeLoader):
"""Return string representations of target value in stream YAML
The key is used for traversal of the YAML structure to target
the value that will be dumped.
:param stream: file like input yaml content
:para... | python | {
"resource": ""
} |
q36220 | encode | train | def encode(s):
"""Encode a folder name using IMAP modified UTF-7 encoding.
Despite the function's name, the output is still a unicode string.
"""
if not isinstance(s, text_type):
return s
r = []
_in = []
def extend_result_if_chars_buffered():
if _in:
r.extend([... | python | {
"resource": ""
} |
q36221 | decode | train | def decode(s):
"""Decode a folder name from IMAP modified UTF-7 encoding to unicode.
Despite the function's name, the input may still be a unicode
string. If the input is bytes, it's first decoded to unicode.
"""
if isinstance(s, binary_type):
s = s.decode('latin-1')
if not isinstance(s... | python | {
"resource": ""
} |
q36222 | autoclean | train | def autoclean(input_dataframe, drop_nans=False, copy=False, encoder=None,
encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided data set
Parameters
----------
input_dataframe: pandas.DataFrame
Data set to c... | python | {
"resource": ""
} |
q36223 | autoclean_cv | train | def autoclean_cv(training_dataframe, testing_dataframe, drop_nans=False, copy=False,
encoder=None, encoder_kwargs=None, ignore_update_check=False):
"""Performs a series of automated data cleaning transformations on the provided training and testing data sets
Unlike `autoclean()`, this function... | python | {
"resource": ""
} |
q36224 | Node.get_foreign_keys | train | def get_foreign_keys(cls):
"""Get foreign keys and models they refer to, so we can pre-process
the data for load_bulk
"""
foreign_keys = {}
for field in cls._meta.fields:
if (
field.get_internal_type() == 'ForeignKey' and
field.name != ... | python | {
"resource": ""
} |
q36225 | Node._process_foreign_keys | train | def _process_foreign_keys(cls, foreign_keys, node_data):
"""For each foreign key try to load the actual object so load_bulk
doesn't fail trying to load an int where django expects a
model instance
"""
for key in foreign_keys.keys():
if key in node_data:
... | python | {
"resource": ""
} |
q36226 | Node.delete | train | def delete(self):
"""Removes a node and all it's descendants."""
self.__class__.objects.filter(pk=self.pk).delete() | python | {
"resource": ""
} |
q36227 | Node.get_annotated_list_qs | train | def get_annotated_list_qs(cls, qs):
"""
Gets an annotated list from a queryset.
"""
result, info = [], {}
start_depth, prev_depth = (None, None)
for node in qs:
depth = node.get_depth()
if start_depth is None:
start_depth = depth
... | python | {
"resource": ""
} |
q36228 | Node.get_annotated_list | train | def get_annotated_list(cls, parent=None, max_depth=None):
"""
Gets an annotated list from a tree branch.
:param parent:
The node whose descendants will be annotated. The node itself
will be included in the list. If not given, the entire tree
will be annotate... | python | {
"resource": ""
} |
q36229 | TreeAdmin.get_urls | train | def get_urls(self):
"""
Adds a url to move nodes to this admin
"""
urls = super(TreeAdmin, self).get_urls()
if django.VERSION < (1, 10):
from django.views.i18n import javascript_catalog
jsi18n_url = url(r'^jsi18n/$', javascript_catalog, {'packages': ('tre... | python | {
"resource": ""
} |
q36230 | movenodeform_factory | train | def movenodeform_factory(model, form=MoveNodeForm, fields=None, exclude=None,
formfield_callback=None, widgets=None):
"""Dynamically build a MoveNodeForm subclass with the proper Meta.
:param Node model:
The subclass of :py:class:`Node` that will be handled
by the for... | python | {
"resource": ""
} |
q36231 | MoveNodeForm._clean_cleaned_data | train | def _clean_cleaned_data(self):
""" delete auxilary fields not belonging to node model """
reference_node_id = 0
if '_ref_node_id' in self.cleaned_data:
reference_node_id = self.cleaned_data['_ref_node_id']
del self.cleaned_data['_ref_node_id']
position_type = se... | python | {
"resource": ""
} |
q36232 | MoveNodeForm.add_subtree | train | def add_subtree(cls, for_node, node, options):
""" Recursively build options tree. """
if cls.is_loop_safe(for_node, node):
options.append(
(node.pk,
mark_safe(cls.mk_indent(node.get_depth()) + escape(node))))
for subnode in node.get_children():
... | python | {
"resource": ""
} |
q36233 | MoveNodeForm.mk_dropdown_tree | train | def mk_dropdown_tree(cls, model, for_node=None):
""" Creates a tree-like list of choices """
options = [(0, _('-- root --'))]
for node in model.get_root_nodes():
cls.add_subtree(for_node, node, options)
return options | python | {
"resource": ""
} |
q36234 | MP_MoveHandler.sanity_updates_after_move | train | def sanity_updates_after_move(self, oldpath, newpath):
"""
Updates the list of sql statements needed after moving nodes.
1. :attr:`depth` updates *ONLY* needed by mysql databases (*sigh*)
2. update the number of children of parent nodes
"""
if (
self.node... | python | {
"resource": ""
} |
q36235 | MP_Node.fix_tree | train | def fix_tree(cls, destructive=False):
"""
Solves some problems that can appear when transactions are not used and
a piece of code breaks, leaving the tree in an inconsistent state.
The problems this method solves are:
1. Nodes with an incorrect ``depth`` or ``numchild`` valu... | python | {
"resource": ""
} |
q36236 | MP_Node._get_path | train | def _get_path(cls, path, depth, newstep):
"""
Builds a path given some values
:param path: the base path
:param depth: the depth of the node
:param newstep: the value (integer) of the new step
"""
parentpath = cls._get_basepath(path, depth - 1)
key = cls... | python | {
"resource": ""
} |
q36237 | int2str | train | def int2str(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from integers to strings"""
return NumConv(radix, alphabet).int2str(num) | python | {
"resource": ""
} |
q36238 | str2int | train | def str2int(num, radix=10, alphabet=BASE85):
"""helper function for quick base conversions from strings to integers"""
return NumConv(radix, alphabet).str2int(num) | python | {
"resource": ""
} |
q36239 | NumConv.int2str | train | def int2str(self, num):
"""Converts an integer into a string.
:param num: A numeric value to be converted to another base as a
string.
:rtype: string
:raise TypeError: when *num* isn't an integer
:raise ValueError: when *num* isn't positive
"""
... | python | {
"resource": ""
} |
q36240 | NumConv.str2int | train | def str2int(self, num):
"""Converts a string into an integer.
If possible, the built-in python conversion will be used for speed
purposes.
:param num: A string that will be converted to an integer.
:rtype: integer
:raise ValueError: when *num* is invalid
"""
... | python | {
"resource": ""
} |
q36241 | AL_NodeManager.get_queryset | train | def get_queryset(self):
"""Sets the custom queryset as the default."""
if self.model.node_order_by:
order_by = ['parent'] + list(self.model.node_order_by)
else:
order_by = ['parent', 'sib_order']
return super(AL_NodeManager, self).get_queryset().order_by(*order_by... | python | {
"resource": ""
} |
q36242 | JSONFieldBase.pre_init | train | def pre_init(self, value, obj):
"""Convert a string value to JSON only if it needs to be deserialized.
SubfieldBase metaclass has been modified to call this method instead of
to_python so that we can check the obj state and determine if it needs to be
deserialized"""
try:
... | python | {
"resource": ""
} |
q36243 | get_model | train | def get_model(method):
"""Convert string to model class."""
@wraps(method)
def wrapper(migrator, model, *args, **kwargs):
if isinstance(model, str):
return method(migrator, migrator.orm[model], *args, **kwargs)
return method(migrator, model, *args, **kwargs)
return wrapper | python | {
"resource": ""
} |
q36244 | SchemaMigrator.from_database | train | def from_database(cls, database):
"""Initialize migrator by db."""
if isinstance(database, PostgresqlDatabase):
return PostgresqlMigrator(database)
if isinstance(database, SqliteDatabase):
return SqliteMigrator(database)
if isinstance(database, MySQLDatabase):
... | python | {
"resource": ""
} |
q36245 | SchemaMigrator.change_column | train | def change_column(self, table, column_name, field):
"""Change column."""
operations = [self.alter_change_column(table, column_name, field)]
if not field.null:
operations.extend([self.add_not_null(table, column_name)])
return operations | python | {
"resource": ""
} |
q36246 | SchemaMigrator.alter_add_column | train | def alter_add_column(self, table, column_name, field, **kwargs):
"""Fix fieldname for ForeignKeys."""
name = field.name
op = super(SchemaMigrator, self).alter_add_column(table, column_name, field, **kwargs)
if isinstance(field, pw.ForeignKeyField):
field.name = name
r... | python | {
"resource": ""
} |
q36247 | Migrator.run | train | def run(self):
"""Run operations."""
for op in self.ops:
if isinstance(op, Operation):
LOGGER.info("%s %s", op.method, op.args)
op.run()
else:
op()
self.clean() | python | {
"resource": ""
} |
q36248 | Migrator.python | train | def python(self, func, *args, **kwargs):
"""Run python code."""
self.ops.append(lambda: func(*args, **kwargs)) | python | {
"resource": ""
} |
q36249 | Migrator.sql | train | def sql(self, sql, *params):
"""Execure raw SQL."""
self.ops.append(self.migrator.sql(sql, *params)) | python | {
"resource": ""
} |
q36250 | Migrator.create_table | train | def create_table(self, model):
"""Create model and table in database.
>> migrator.create_table(model)
"""
self.orm[model._meta.table_name] = model
model._meta.database = self.database
self.ops.append(model.create_table)
return model | python | {
"resource": ""
} |
q36251 | Migrator.drop_table | train | def drop_table(self, model, cascade=True):
"""Drop model and table from database.
>> migrator.drop_table(model, cascade=True)
"""
del self.orm[model._meta.table_name]
self.ops.append(self.migrator.drop_table(model, cascade)) | python | {
"resource": ""
} |
q36252 | Migrator.add_columns | train | def add_columns(self, model, **fields):
"""Create new fields."""
for name, field in fields.items():
model._meta.add_field(name, field)
self.ops.append(self.migrator.add_column(
model._meta.table_name, field.column_name, field))
if field.unique:
... | python | {
"resource": ""
} |
q36253 | Migrator.change_columns | train | def change_columns(self, model, **fields):
"""Change fields."""
for name, field in fields.items():
old_field = model._meta.fields.get(name, field)
old_column_name = old_field and old_field.column_name
model._meta.add_field(name, field)
if isinstance(old_... | python | {
"resource": ""
} |
q36254 | Migrator.drop_columns | train | def drop_columns(self, model, *names, **kwargs):
"""Remove fields from model."""
fields = [field for field in model._meta.fields.values() if field.name in names]
cascade = kwargs.pop('cascade', True)
for field in fields:
self.__del_field__(model, field)
if field.u... | python | {
"resource": ""
} |
q36255 | Migrator.rename_column | train | def rename_column(self, model, old_name, new_name):
"""Rename field in model."""
field = model._meta.fields[old_name]
if isinstance(field, pw.ForeignKeyField):
old_name = field.column_name
self.__del_field__(model, field)
field.name = field.column_name = new_name
... | python | {
"resource": ""
} |
q36256 | Migrator.rename_table | train | def rename_table(self, model, new_name):
"""Rename table in database."""
del self.orm[model._meta.table_name]
model._meta.table_name = new_name
self.orm[model._meta.table_name] = model
self.ops.append(self.migrator.rename_table(model._meta.table_name, new_name))
return mo... | python | {
"resource": ""
} |
q36257 | Migrator.add_index | train | def add_index(self, model, *columns, **kwargs):
"""Create indexes."""
unique = kwargs.pop('unique', False)
model._meta.indexes.append((columns, unique))
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if len(columns) == 1:
... | python | {
"resource": ""
} |
q36258 | Migrator.drop_index | train | def drop_index(self, model, *columns):
"""Drop indexes."""
columns_ = []
for col in columns:
field = model._meta.fields.get(col)
if not field:
continue
if len(columns) == 1:
field.unique = field.index = False
if is... | python | {
"resource": ""
} |
q36259 | Migrator.add_not_null | train | def add_not_null(self, model, *names):
"""Add not null."""
for name in names:
field = model._meta.fields[name]
field.null = False
self.ops.append(self.migrator.add_not_null(model._meta.table_name, field.column_name))
return model | python | {
"resource": ""
} |
q36260 | Migrator.drop_not_null | train | def drop_not_null(self, model, *names):
"""Drop not null."""
for name in names:
field = model._meta.fields[name]
field.null = True
self.ops.append(self.migrator.drop_not_null(model._meta.table_name, field.column_name))
return model | python | {
"resource": ""
} |
q36261 | Migrator.add_default | train | def add_default(self, model, name, default):
"""Add default."""
field = model._meta.fields[name]
model._meta.defaults[field] = field.default = default
self.ops.append(self.migrator.apply_default(model._meta.table_name, name, field))
return model | python | {
"resource": ""
} |
q36262 | migrate | train | def migrate(name=None, database=None, directory=None, verbose=None, fake=False):
"""Migrate database."""
router = get_router(directory, database, verbose)
migrations = router.run(name, fake=fake)
if migrations:
click.echo('Migrations completed: %s' % ', '.join(migrations)) | python | {
"resource": ""
} |
q36263 | rollback | train | def rollback(name, database=None, directory=None, verbose=None):
"""Rollback a migration with given name."""
router = get_router(directory, database, verbose)
router.rollback(name) | python | {
"resource": ""
} |
q36264 | load_models | train | def load_models(module):
"""Load models from given module."""
modules = _import_submodules(module)
return {m for module in modules for m in filter(
_check_model, (getattr(module, name) for name in dir(module))
)} | python | {
"resource": ""
} |
q36265 | _check_model | train | def _check_model(obj, models=None):
"""Checks object if it's a peewee model and unique."""
return isinstance(obj, type) and issubclass(obj, pw.Model) and hasattr(obj, '_meta') | python | {
"resource": ""
} |
q36266 | compile_migrations | train | def compile_migrations(migrator, models, reverse=False):
"""Compile migrations for given models."""
source = migrator.orm.values()
if reverse:
source, models = models, source
migrations = diff_many(models, source, migrator, reverse=reverse)
if not migrations:
return False
migra... | python | {
"resource": ""
} |
q36267 | BaseRouter.model | train | def model(self):
"""Initialize and cache MigrationHistory model."""
MigrateHistory._meta.database = self.database
MigrateHistory._meta.table_name = self.migrate_table
MigrateHistory._meta.schema = self.schema
MigrateHistory.create_table(True)
return MigrateHistory | python | {
"resource": ""
} |
q36268 | BaseRouter.done | train | def done(self):
"""Scan migrations in database."""
return [mm.name for mm in self.model.select().order_by(self.model.id)] | python | {
"resource": ""
} |
q36269 | BaseRouter.diff | train | def diff(self):
"""Calculate difference between fs and db."""
done = set(self.done)
return [name for name in self.todo if name not in done] | python | {
"resource": ""
} |
q36270 | BaseRouter.migrator | train | def migrator(self):
"""Create migrator and setup it with fake migrations."""
migrator = Migrator(self.database)
for name in self.done:
self.run_one(name, migrator)
return migrator | python | {
"resource": ""
} |
q36271 | Router.todo | train | def todo(self):
"""Scan migrations in file system."""
if not os.path.exists(self.migrate_dir):
self.logger.warn('Migration directory: %s does not exist.', self.migrate_dir)
os.makedirs(self.migrate_dir)
return sorted(f[:-3] for f in os.listdir(self.migrate_dir) if self.fi... | python | {
"resource": ""
} |
q36272 | Router.read | train | def read(self, name):
"""Read migration from file."""
call_params = dict()
if os.name == 'nt' and sys.version_info >= (3, 0):
# if system is windows - force utf-8 encoding
call_params['encoding'] = 'utf-8'
with open(os.path.join(self.migrate_dir, name + '.py'), **... | python | {
"resource": ""
} |
q36273 | Router.clear | train | def clear(self):
"""Remove migrations from fs."""
super(Router, self).clear()
for name in self.todo:
filename = os.path.join(self.migrate_dir, name + '.py')
os.remove(filename) | python | {
"resource": ""
} |
q36274 | diff_one | train | def diff_one(model1, model2, **kwargs):
"""Find difference between given peewee models."""
changes = []
fields1 = model1._meta.fields
fields2 = model2._meta.fields
# Add fields
names1 = set(fields1) - set(fields2)
if names1:
fields = [fields1[name] for name in names1]
chang... | python | {
"resource": ""
} |
q36275 | diff_many | train | def diff_many(models1, models2, migrator=None, reverse=False):
"""Calculate changes for migrations from models2 to models1."""
models1 = pw.sort_models(models1)
models2 = pw.sort_models(models2)
if reverse:
models1 = reversed(models1)
models2 = reversed(models2)
models1 = OrderedDi... | python | {
"resource": ""
} |
q36276 | watch | train | def watch(path: Union[Path, str], **kwargs):
"""
Watch a directory and yield a set of changes whenever files change in that directory or its subdirectories.
"""
loop = asyncio.new_event_loop()
try:
_awatch = awatch(path, loop=loop, **kwargs)
while True:
try:
... | python | {
"resource": ""
} |
q36277 | new_event | train | def new_event(event):
"""
Wrap a raw gRPC event in a friendlier containing class.
This picks the appropriate class from one of PutEvent or DeleteEvent and
returns a new instance.
"""
op_name = event.EventType.DESCRIPTOR.values_by_number[event.type].name
if op_name == 'PUT':
cls = Pu... | python | {
"resource": ""
} |
q36278 | Lock.is_acquired | train | def is_acquired(self):
"""Check if this lock is currently acquired."""
uuid, _ = self.etcd_client.get(self.key)
if uuid is None:
return False
return uuid == self.uuid | python | {
"resource": ""
} |
q36279 | lease_to_id | train | def lease_to_id(lease):
"""Figure out if the argument is a Lease object, or the lease ID."""
lease_id = 0
if hasattr(lease, 'id'):
lease_id = lease.id
else:
try:
lease_id = int(lease)
except TypeError:
pass
return lease_id | python | {
"resource": ""
} |
q36280 | Etcd3Client.put | train | def put(self, key, value, lease=None, prev_kv=False):
"""
Save a value to etcd.
Example usage:
.. code-block:: python
>>> import etcd3
>>> etcd = etcd3.client()
>>> etcd.put('/thing/key', 'hello world')
:param key: key in etcd to set
... | python | {
"resource": ""
} |
q36281 | Etcd3Client.put_if_not_exists | train | def put_if_not_exists(self, key, value, lease=None):
"""
Atomically puts a value only if the key previously had no value.
This is the etcdv3 equivalent to setting a key with the etcdv2
parameter prevExist=false.
:param key: key in etcd to put
:param value: value to be w... | python | {
"resource": ""
} |
q36282 | Etcd3Client.delete | train | def delete(self, key, prev_kv=False, return_response=False):
"""
Delete a single key in etcd.
:param key: key in etcd to delete
:param prev_kv: return the deleted key-value pair
:type prev_kv: bool
:param return_response: return the full response
:type return_res... | python | {
"resource": ""
} |
q36283 | Etcd3Client.status | train | def status(self):
"""Get the status of the responding member."""
status_request = etcdrpc.StatusRequest()
status_response = self.maintenancestub.Status(
status_request,
self.timeout,
credentials=self.call_credentials,
metadata=self.metadata
... | python | {
"resource": ""
} |
q36284 | Etcd3Client.add_watch_callback | train | def add_watch_callback(self, *args, **kwargs):
"""
Watch a key or range of keys and call a callback on every event.
If timeout was declared during the client initialization and
the watch cannot be created during that time the method raises
a ``WatchTimedOut`` exception.
... | python | {
"resource": ""
} |
q36285 | Etcd3Client.watch_prefix | train | def watch_prefix(self, key_prefix, **kwargs):
"""Watches a range of keys with a prefix."""
kwargs['range_end'] = \
utils.increment_last_byte(utils.to_bytes(key_prefix))
return self.watch(key_prefix, **kwargs) | python | {
"resource": ""
} |
q36286 | Etcd3Client.watch_prefix_once | train | def watch_prefix_once(self, key_prefix, timeout=None, **kwargs):
"""
Watches a range of keys with a prefix and stops after the first event.
If the timeout was specified and event didn't arrived method
will raise ``WatchTimedOut`` exception.
"""
kwargs['range_end'] = \
... | python | {
"resource": ""
} |
q36287 | Etcd3Client._ops_to_requests | train | def _ops_to_requests(self, ops):
"""
Return a list of grpc requests.
Returns list from an input list of etcd3.transactions.{Put, Get,
Delete, Txn} objects.
"""
request_ops = []
for op in ops:
if isinstance(op, transactions.Put):
reques... | python | {
"resource": ""
} |
q36288 | Etcd3Client.transaction | train | def transaction(self, compare, success=None, failure=None):
"""
Perform a transaction.
Example usage:
.. code-block:: python
etcd.transaction(
compare=[
etcd.transactions.value('/doot/testing') == 'doot',
etcd.transac... | python | {
"resource": ""
} |
q36289 | Etcd3Client.lease | train | def lease(self, ttl, lease_id=None):
"""
Create a new lease.
All keys attached to this lease will be expired and deleted if the
lease expires. A lease can be sent keep alive messages to refresh the
ttl.
:param ttl: Requested time to live
:param lease_id: Request... | python | {
"resource": ""
} |
q36290 | Etcd3Client.revoke_lease | train | def revoke_lease(self, lease_id):
"""
Revoke a lease.
:param lease_id: ID of the lease to revoke.
"""
lease_revoke_request = etcdrpc.LeaseRevokeRequest(ID=lease_id)
self.leasestub.LeaseRevoke(
lease_revoke_request,
self.timeout,
creden... | python | {
"resource": ""
} |
q36291 | Etcd3Client.lock | train | def lock(self, name, ttl=60):
"""
Create a new lock.
:param name: name of the lock
:type name: string or bytes
:param ttl: length of time for the lock to live for in seconds. The
lock will be released after this time elapses, unless
refres... | python | {
"resource": ""
} |
q36292 | Etcd3Client.add_member | train | def add_member(self, urls):
"""
Add a member into the cluster.
:returns: new member
:rtype: :class:`.Member`
"""
member_add_request = etcdrpc.MemberAddRequest(peerURLs=urls)
member_add_response = self.clusterstub.MemberAdd(
member_add_request,
... | python | {
"resource": ""
} |
q36293 | Etcd3Client.remove_member | train | def remove_member(self, member_id):
"""
Remove an existing member from the cluster.
:param member_id: ID of the member to remove
"""
member_rm_request = etcdrpc.MemberRemoveRequest(ID=member_id)
self.clusterstub.MemberRemove(
member_rm_request,
se... | python | {
"resource": ""
} |
q36294 | Etcd3Client.update_member | train | def update_member(self, member_id, peer_urls):
"""
Update the configuration of an existing member in the cluster.
:param member_id: ID of the member to update
:param peer_urls: new list of peer urls the member will use to
communicate with the cluster
""... | python | {
"resource": ""
} |
q36295 | Etcd3Client.members | train | def members(self):
"""
List of all members associated with the cluster.
:type: sequence of :class:`.Member`
"""
member_list_request = etcdrpc.MemberListRequest()
member_list_response = self.clusterstub.MemberList(
member_list_request,
self.timeou... | python | {
"resource": ""
} |
q36296 | Etcd3Client.compact | train | def compact(self, revision, physical=False):
"""
Compact the event history in etcd up to a given revision.
All superseded keys with a revision less than the compaction revision
will be removed.
:param revision: revision for the compaction operation
:param physical: if s... | python | {
"resource": ""
} |
q36297 | Etcd3Client.defragment | train | def defragment(self):
"""Defragment a member's backend database to recover storage space."""
defrag_request = etcdrpc.DefragmentRequest()
self.maintenancestub.Defragment(
defrag_request,
self.timeout,
credentials=self.call_credentials,
metadata=sel... | python | {
"resource": ""
} |
q36298 | Etcd3Client.hash | train | def hash(self):
"""
Return the hash of the local KV state.
:returns: kv state hash
:rtype: int
"""
hash_request = etcdrpc.HashRequest()
return self.maintenancestub.Hash(hash_request).hash | python | {
"resource": ""
} |
q36299 | Etcd3Client.create_alarm | train | def create_alarm(self, member_id=0):
"""Create an alarm.
If no member id is given, the alarm is activated for all the
members of the cluster. Only the `no space` alarm can be raised.
:param member_id: The cluster member id to create an alarm to.
If 0, the alar... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.