Search is not available for this dataset
text stringlengths 75 104k |
|---|
def _close(self):
"""
Closes the client connection to the database.
"""
if self.connection:
with self.wrap_database_errors:
self.connection.client.close() |
def make_mdl(model, model_dict):
"""
Builds an instance of model from the model_dict.
"""
for field_name in model_dict:
field = model._meta.get_field(field_name)
model_dict[field_name] = field.to_python(model_dict[field_name])
return model(**model_dict) |
def to_python(self, value):
"""
Overrides standard to_python method from django models to allow
correct translation of Mongo array to a python list.
"""
if value is None:
return value
assert isinstance(value, list)
ret = []
for mdl_d... |
def formfield(self, **kwargs):
"""
Returns the formfield for the array.
"""
defaults = {
'form_class': ArrayFormField,
'model_container': self.model_container,
'model_form_class': self.model_form_class,
'name': self.attname,
... |
def to_python(self, value):
"""
Overrides Django's default to_python to allow correct
translation to instance.
"""
if value is None or isinstance(value, self.model_container):
return value
assert isinstance(value, dict)
instance = make_mdl(se... |
def _apply_rel_filters(self, queryset):
"""
Filter the queryset for the instance this manager is bound to.
"""
queryset._add_hints(instance=self.instance)
if self._db:
queryset = queryset.using(self._db)
queryset = queryset.filter(**self.core_filters)
... |
def _compute_nfp_uniform(l, u, cum_counts, sizes):
"""Computes the expected number of false positives caused by using
u to approximate set sizes in the interval [l, u], assuming uniform
distribution of set sizes within the interval.
Args:
l: the lower bound on set sizes.
u: the upper bo... |
def _compute_nfps_uniform(cum_counts, sizes):
"""Computes the matrix of expected false positives for all possible
sub-intervals of the complete domain of set sizes, assuming uniform
distribution of set_sizes within each sub-intervals.
Args:
cum_counts: the complete cummulative distribution of s... |
def _compute_nfp_real(l, u, counts, sizes):
"""Computes the expected number of false positives caused by using
u to approximate set sizes in the interval [l, u], using the real
set size distribution.
Args:
l: the lower bound on set sizes.
u: the upper bound on set sizes.
counts:... |
def _compute_nfps_real(counts, sizes):
"""Computes the matrix of expected false positives for all possible
sub-intervals of the complete domain of set sizes.
Args:
counts: the complete distribution of set sizes.
sizes: the complete domain of set sizes.
Return (np.array): the 2-D array ... |
def _compute_best_partitions(num_part, sizes, nfps):
"""Computes the optimal partitions given the size distributions
and computed number of expected false positives for all sub-intervals.
Args:
num_part (int): The number of partitions to create.
sizes (numpy.array): The complete domain of s... |
def optimal_partitions(sizes, counts, num_part):
"""Compute the optimal partitions given a distribution of set sizes.
Args:
sizes (numpy.array): The complete domain of set sizes in ascending
order.
counts (numpy.array): The frequencies of all set sizes in the same
order ... |
def jaccard(self, other):
'''
Estimate the Jaccard similarity (resemblance) between this b-bit
MinHash and the other.
'''
if self.b != other.b:
raise ValueError("Cannot compare two b-bit MinHashes with different\
b values")
if self.seed != ... |
def _calc_a(self, r, b):
'''
Compute the function A(r, b)
'''
if r == 0.0:
# Find the limit of A(r, b) as r -> 0.
return 1.0 / (1 << b)
return r * (1 - r) ** (2 ** b - 1) / (1 - (1 - r) ** (2 * b)) |
def _calc_c(self, a1, a2, r1, r2):
'''
Compute the functions C1 and C2
'''
if r1 == 0.0 and r2 == 0.0:
# Find the limits of C1 and C2 as r1 -> 0 and r2 -> 0
# Since the b-value must be the same and r1 = r2,
# we have A1(r1, b1) = A2(r2, b2) = A,
... |
def _initialize_slots(self, seed, hashvalues):
'''Initialize the slots of the LeanMinHash.
Args:
seed (int): The random seed controls the set of random
permutation functions generated for this LeanMinHash.
hashvalues: The hash values is the internal state of the ... |
def bytesize(self, byteorder='@'):
'''Compute the byte size after serialization.
Args:
byteorder (str, optional): This is byte order of the serialized data. Use one
of the `byte order characters
<https://docs.python.org/3/library/struct.html#byte-order-size-a... |
def serialize(self, buf, byteorder='@'):
'''
Serialize this lean MinHash and store the result in an allocated buffer.
Args:
buf (buffer): `buf` must implement the `buffer`_ interface.
One such example is the built-in `bytearray`_ class.
byteorder (str, op... |
def deserialize(cls, buf, byteorder='@'):
'''
Deserialize a lean MinHash from a buffer.
Args:
buf (buffer): `buf` must implement the `buffer`_ interface.
One such example is the built-in `bytearray`_ class.
byteorder (str. optional): This is byte order of... |
def update(self, b):
'''Update this MinHash with a new value.
The value will be hashed using the hash function specified by
the `hashfunc` argument in the constructor.
Args:
b: The value to be hashed using the hash function specified.
Example:
To update ... |
def jaccard(self, other):
'''Estimate the `Jaccard similarity`_ (resemblance) between the sets
represented by this MinHash and the other.
Args:
other (datasketch.MinHash): The other MinHash.
Returns:
float: The Jaccard similarity, which is between 0.0 and 1.0.
... |
def count(self):
'''Estimate the cardinality count based on the technique described in
`this paper <http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=365694>`_.
Returns:
int: The estimated cardinality of the set represented by this MinHash.
'''
k = len(self)
... |
def merge(self, other):
'''Merge the other MinHash with this one, making this one the union
of both.
Args:
other (datasketch.MinHash): The other MinHash.
'''
if other.seed != self.seed:
raise ValueError("Cannot merge MinHash with\
diff... |
def copy(self):
'''
:returns: datasketch.MinHash -- A copy of this MinHash by exporting its state.
'''
return MinHash(seed=self.seed, hashfunc=self.hashfunc,
hashvalues=self.digest(),
permutations=self.permutations) |
def union(cls, *mhs):
'''Create a MinHash which is the union of the MinHash objects passed as arguments.
Args:
*mhs: The MinHash objects to be united. The argument list length is variable,
but must be at least 2.
Returns:
datasketch.MinHash: A new union ... |
def _false_positive_probability(threshold, b, r, xq):
'''
Compute the false positive probability given the containment threshold.
xq is the ratio of x/q.
'''
_probability = lambda t : 1 - (1 - (t/(1 + xq - t))**float(r))**float(b)
if xq >= threshold:
a, err = integrate(_probability, 0.0,... |
def _optimal_param(threshold, num_perm, max_r, xq, false_positive_weight,
false_negative_weight):
'''
Compute the optimal parameters that minimizes the weighted sum
of probabilities of false positive and false negative.
xq is the ratio of x/q.
'''
min_error = float("inf")
opt = (0, 0... |
def index(self, entries):
'''
Index all sets given their keys, MinHashes, and sizes.
It can be called only once after the index is created.
Args:
entries (`iterable` of `tuple`): An iterable of tuples, each must be
in the form of `(key, minhash, size)`, where... |
def query(self, minhash, size):
'''
Giving the MinHash and size of the query set, retrieve
keys that references sets with containment with respect to
the query set greater than the threshold.
Args:
minhash (datasketch.MinHash): The MinHash of the query set.
... |
def is_empty(self):
'''
Returns:
bool: Check if the index is empty.
'''
return all(all(index[r].is_empty() for r in index)
for index in self.indexes) |
def jaccard(self, other):
'''Estimate the `weighted Jaccard similarity`_ between the
multi-sets represented by this weighted MinHash and the other.
Args:
other (datasketch.WeightedMinHash): The other weighted MinHash.
Returns:
float: The weighted Jaccard... |
def minhash(self, v):
'''Create a new weighted MinHash given a weighted Jaccard vector.
Each dimension is an integer
frequency of the corresponding element in the multi-set represented
by the vector.
Args:
v (numpy.array): The Jaccard vector.
'''
if... |
def insert(self, key, minhash, check_duplication=True):
'''
Insert a key to the index, together
with a MinHash (or weighted MinHash) of the set referenced by
the key.
:param str key: The identifier of the set.
:param datasketch.MinHash minhash: The MinHash of the set.
... |
def remove(self, key):
'''
Remove the key from the index.
Args:
key (hashable): The unique identifier of a set.
'''
if self.prepickle:
key = pickle.dumps(key)
if key not in self.keys:
raise ValueError("The given key does not exist")
... |
def get_subset_counts(self, *keys):
'''
Returns the bucket allocation counts (see :func:`~datasketch.MinHashLSH.get_counts` above)
restricted to the list of keys given.
Args:
keys (hashable) : the keys for which to get the bucket allocation
counts
'''... |
def update(self, b):
'''
Update the HyperLogLog with a new data value in bytes.
The value will be hashed using the hash function specified by
the `hashfunc` argument in the constructor.
Args:
b: The value to be hashed using the hash function specified.
Examp... |
def count(self):
'''
Estimate the cardinality of the data values seen so far.
Returns:
int: The estimated cardinality.
'''
# Use HyperLogLog estimation function
e = self.alpha * float(self.m ** 2) / np.sum(2.0**(-self.reg))
# Small range correction
... |
def merge(self, other):
'''
Merge the other HyperLogLog with this one, making this the union of the
two.
Args:
other (datasketch.HyperLogLog):
'''
if self.m != other.m or self.p != other.p:
raise ValueError("Cannot merge HyperLogLog with different... |
def clear(self):
'''
Reset the current HyperLogLog to empty.
'''
self.reg = np.zeros((self.m,), dtype=np.int8) |
def apk(actual, predicted, k=10):
"""
Computes the average precision at k.
This function computes the average prescision at k between two lists of
items.
Parameters
----------
actual : list
A list of elements that are to be predicted (order doesn't matter)
predicted : list... |
def mapk(actual, predicted, k=10):
"""
Computes the mean average precision at k.
This function computes the mean average prescision at k between two lists
of lists of items.
Parameters
----------
actual : list
A list of lists of elements that are to be predicted
... |
def add(self, key, minhash):
'''
Add a unique key, together
with a MinHash (or weighted MinHash) of the set referenced by the key.
Note:
The key won't be searchbale until the
:func:`datasketch.MinHashLSHForest.index` method is called.
Args:
k... |
def index(self):
'''
Index all the keys added so far and make them searchable.
'''
for i, hashtable in enumerate(self.hashtables):
self.sorted_hashtables[i] = [H for H in hashtable.keys()]
self.sorted_hashtables[i].sort() |
def query(self, minhash, k):
'''
Return the approximate top-k keys that have the highest
Jaccard similarities to the query set.
Args:
minhash (datasketch.MinHash): The MinHash of the query set.
k (int): The maximum number of keys to return.
Returns:
... |
def _binary_search(self, n, func):
'''
https://golang.org/src/sort/search.go?s=2247:2287#L49
'''
i, j = 0, n
while i < j:
h = int(i + (j - i) / 2)
if not func(h):
i = h + 1
else:
j = h
return i |
async def close(self):
"""
Cleanup client resources and disconnect from AsyncMinHashLSH storage.
"""
async with self._lock:
for t in self.hashtables:
await t.close()
if self.keys is not None:
await self.keys.close()
se... |
async def query(self, minhash):
"""
see :class:`datasketch.MinHashLSH`.
"""
if len(minhash) != self.h:
raise ValueError("Expecting minhash with length %d, "
"got %d" % (self.h, len(minhash)))
fs = (hashtable.get(self._H(minhash.hashvalues... |
async def get_counts(self):
"""
see :class:`datasketch.MinHashLSH`.
"""
fs = (hashtable.itemcounts() for hashtable in self.hashtables)
return await asyncio.gather(*fs) |
def ordered_storage(config, name=None):
'''Return ordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(list)``. Thus, the return value of this method contains
keys and values. The values are ordered lists with the last added
item a... |
def unordered_storage(config, name=None):
'''Return an unordered storage system based on the specified config.
The canonical example of such a storage container is
``defaultdict(set)``. Thus, the return value of this method contains
keys and values. The values are unordered sets.
Args:
con... |
def itemcounts(self, **kwargs):
'''Returns a dict where the keys are the keys of the container.
The values are the *lengths* of the value sequences stored
in this container.
'''
return {k: len(v) for k, v in self._dict.items()} |
def get_social_login(self, adapter, app, token, response):
"""
:param adapter: allauth.socialaccount Adapter subclass.
Usually OAuthAdapter or Auth2Adapter
:param app: `allauth.socialaccount.SocialApp` instance
:param token: `allauth.socialaccount.SocialToken` instance
... |
def get_user(self, obj):
"""
Required to allow using custom USER_DETAILS_SERIALIZER in
JWTSerializer. Defining it here to avoid circular imports
"""
rest_auth_serializers = getattr(settings, 'REST_AUTH_SERIALIZERS', {})
JWTUserDetailsSerializer = import_callable(
... |
def get_social_login(self, *args, **kwargs):
"""
Set the social login process state to connect rather than login
Refer to the implementation of get_social_login in base class and to the
allauth.socialaccount.helpers module complete_social_login function.
"""
social_login ... |
def select_text(text, reading=False, prefer=None):
"""Select the correct text from the Japanese number, reading and
alternatives"""
# select kanji number or kana reading
if reading:
text = text[1]
else:
text = text[0]
# select the preferred one or the first one from multiple alt... |
def rendaku_merge_pairs(lpair, rpair):
"""Merge lpair < rpair while applying semi-irregular rendaku rules"""
ltext, lnum = lpair
rtext, rnum = rpair
if lnum > rnum:
raise ValueError
if rpair == ("γ²γγ", 100):
if lpair == ("γγ", 3):
rtext = "γ³γγ"
elif lpair == ("γγ... |
def split_by_3(self, number):
"""
starting here, it groups the number by three from the tail
'1234567' -> (('1',),('234',),('567',))
:param number:str
:rtype:tuple
"""
blocks = ()
length = len(number)
if length < 3:
blocks += ((number,... |
def spell(self, blocks):
"""
it adds the list of spelling to the blocks
(
('1',),('034',)) -> (('1',['satu']),('234',['tiga', 'puluh', 'empat'])
)
:param blocks: tuple
:rtype: tuple
"""
word_blocks = ()
first_block = blocks[0]
if le... |
def join(self, word_blocks, float_part):
"""
join the words by first join lists in the tuple
:param word_blocks: tuple
:rtype: str
"""
word_list = []
length = len(word_blocks) - 1
first_block = word_blocks[0],
start = 0
if length == 1 and ... |
def to_currency(self, val, currency='EUR', cents=True, separator=',',
adjective=False):
"""
Args:
val: Numeric value
currency (str): Currency code
cents (bool): Verbose cents
separator (str): Cent separator
adjective (bool):... |
def parse_scoped_selector(scoped_selector):
"""Parse scoped selector."""
# Conver Macro (%scope/name) to (scope/name/macro.value)
if scoped_selector[0] == '%':
if scoped_selector.endswith('.value'):
err_str = '{} is invalid cannot use % and end with .value'
raise ValueError(err_str.format(scoped_s... |
def parse_statement(self):
"""Parse a single statement.
Returns:
Either a `BindingStatement`, `ImportStatement`, `IncludeStatement`, or
`None` if no more statements can be parsed (EOF reached).
"""
self._skip_whitespace_and_comments()
if self._current_token.kind == tokenize.ENDMARKER:
... |
def parse_value(self):
"""Parse a single literal value.
Returns:
The parsed value.
"""
parsers = [
self._maybe_parse_container, self._maybe_parse_basic_type,
self._maybe_parse_configurable_reference, self._maybe_parse_macro
]
for parser in parsers:
success, value = p... |
def advance_one_line(self):
"""Advances to next line."""
current_line = self._current_token.line_number
while current_line == self._current_token.line_number:
self._current_token = ConfigParser.Token(*next(self._token_generator)) |
def _parse_selector(self, scoped=True, allow_periods_in_scope=False):
"""Parse a (possibly scoped) selector.
A selector is a sequence of one or more valid Python-style identifiers
separated by periods (see also `SelectorMap`). A scoped selector is a
selector that may be preceded by scope names (separat... |
def _maybe_parse_container(self):
"""Try to parse a container type (dict, list, or tuple)."""
bracket_types = {
'{': ('}', dict, self._parse_dict_item),
'(': (')', tuple, self.parse_value),
'[': (']', list, self.parse_value)
}
if self._current_token.value in bracket_types:
... |
def _maybe_parse_basic_type(self):
"""Try to parse a basic type (str, bool, number)."""
token_value = ''
# Allow a leading dash to handle negative numbers.
if self._current_token.value == '-':
token_value += self._current_token.value
self._advance()
basic_type_tokens = [tokenize.NAME, t... |
def _maybe_parse_configurable_reference(self):
"""Try to parse a configurable reference (@[scope/name/]fn_name[()])."""
if self._current_token.value != '@':
return False, None
location = self._current_location()
self._advance_one_token()
scoped_name = self._parse_selector(allow_periods_in_sco... |
def _maybe_parse_macro(self):
"""Try to parse an macro (%scope/name)."""
if self._current_token.value != '%':
return False, None
location = self._current_location()
self._advance_one_token()
scoped_name = self._parse_selector(allow_periods_in_scope=True)
with utils.try_with_location(loca... |
def augment_exception_message_and_reraise(exception, message):
"""Reraises `exception`, appending `message` to its string representation."""
class ExceptionProxy(type(exception)):
"""Acts as a proxy for an exception with an augmented message."""
__module__ = type(exception).__module__
def __init__(sel... |
def _markdownify_operative_config_str(self, string):
"""Convert an operative config string to markdown format."""
# TODO: Total hack below. Implement more principled formatting.
def process(line):
"""Convert a single line to markdown format."""
if not line.startswith('#'):
return ' '... |
def after_create_session(self, session=None, coord=None):
"""Writes out Gin's operative config, and maybe adds a summary of it."""
config_str = config.operative_config_str()
if not tf.gfile.IsDirectory(self._output_dir):
tf.gfile.MakeDirs(self._output_dir)
global_step_val = 0
if session is not... |
def _find_class_construction_fn(cls):
"""Find the first __init__ or __new__ method in the given class's MRO."""
for base in type.mro(cls):
if '__init__' in base.__dict__:
return base.__init__
if '__new__' in base.__dict__:
return base.__new__ |
def _ensure_wrappability(fn):
"""Make sure `fn` can be wrapped cleanly by functools.wraps."""
# Handle "wrapped_descriptor" and "method-wrapper" types.
if isinstance(fn, (type(object.__init__), type(object.__call__))):
# pylint: disable=unnecessary-lambda
wrappable_fn = lambda *args, **kwargs: fn(*args, *... |
def _decorate_fn_or_cls(decorator, fn_or_cls, subclass=False):
"""Decorate a function or class with the given decorator.
When `fn_or_cls` is a function, applies `decorator` to the function and
returns the (decorated) result.
When `fn_or_cls` is a class and the `subclass` parameter is `False`, this will
repl... |
def _should_skip(selector, skip_unknown):
"""Checks whether `selector` should be skipped (if unknown)."""
_validate_skip_unknown(skip_unknown)
if _REGISTRY.matching_selectors(selector):
return False # Never skip known configurables.
if isinstance(skip_unknown, (list, tuple, set)):
return selector in sk... |
def _format_value(value):
"""Returns `value` in a format parseable by `parse_value`, or `None`.
Simply put, This function ensures that when it returns a string value, the
following will hold:
parse_value(_format_value(value)) == value
Args:
value: The value to format.
Returns:
A string repre... |
def clear_config(clear_constants=False):
"""Clears the global configuration.
This clears any parameter values set by `bind_parameter` or `parse_config`, as
well as the set of dynamically imported modules. It does not remove any
configurable functions or classes from the registry of configurables.
Args:
... |
def bind_parameter(binding_key, value):
"""Binds the parameter value specified by `binding_key` to `value`.
The `binding_key` argument should either be a string of the form
`maybe/scope/optional.module.names.configurable_name.parameter_name`, or a
list or tuple of `(scope, selector, parameter_name)`, where `se... |
def query_parameter(binding_key):
"""Returns the currently bound value to the specified `binding_key`.
The `binding_key` argument should look like
'maybe/some/scope/maybe.moduels.configurable_name.parameter_name'. Note that
this will not include default parameters.
Args:
binding_key: The parameter whose... |
def _might_have_parameter(fn_or_cls, arg_name):
"""Returns True if `arg_name` might be a valid parameter for `fn_or_cls`.
Specifically, this means that `fn_or_cls` either has a parameter named
`arg_name`, or has a `**kwargs` parameter.
Args:
fn_or_cls: The function or class to check.
arg_name: The nam... |
def _get_cached_arg_spec(fn):
"""Gets cached argspec for `fn`."""
arg_spec = _ARG_SPEC_CACHE.get(fn)
if arg_spec is None:
arg_spec_fn = inspect.getfullargspec if six.PY3 else inspect.getargspec
try:
arg_spec = arg_spec_fn(fn)
except TypeError:
# `fn` might be a callable object.
arg_... |
def _get_supplied_positional_parameter_names(fn, args):
"""Returns the names of the supplied arguments to the given function."""
arg_spec = _get_cached_arg_spec(fn)
# May be shorter than len(args) if args contains vararg (*args) arguments.
return arg_spec.args[:len(args)] |
def _get_all_positional_parameter_names(fn):
"""Returns the names of all positional arguments to the given function."""
arg_spec = _get_cached_arg_spec(fn)
args = arg_spec.args
if arg_spec.defaults:
args = args[:-len(arg_spec.defaults)]
return args |
def _get_default_configurable_parameter_values(fn, whitelist, blacklist):
"""Retrieve all default values for configurable parameters of a function.
Any parameters included in the supplied blacklist, or not included in the
supplied whitelist, are excluded.
Args:
fn: The function whose parameter values shou... |
def config_scope(name_or_scope):
"""Opens a new configuration scope.
Provides a context manager that opens a new explicit configuration
scope. Explicit configuration scopes restrict parameter bindings to only
certain sections of code that run within the scope. Scopes can be nested to
arbitrary depth; any con... |
def _make_configurable(fn_or_cls,
name=None,
module=None,
whitelist=None,
blacklist=None,
subclass=False):
"""Wraps `fn_or_cls` to make it configurable.
Infers the configurable name from `fn_or_cls.__... |
def configurable(name_or_fn=None, module=None, whitelist=None, blacklist=None):
"""Decorator to make a function or class configurable.
This decorator registers the decorated function/class as configurable, which
allows its parameters to be supplied from the global configuration (i.e., set
through `bind_paramet... |
def external_configurable(fn_or_cls,
name=None,
module=None,
whitelist=None,
blacklist=None):
"""Allow referencing/configuring an external class or function.
This alerts Gin to the existence of the class or func... |
def operative_config_str(max_line_length=80, continuation_indent=4):
"""Retrieve the "operative" configuration as a config string.
The operative configuration consists of all parameter values used by
configurable functions that are actually called during execution of the
current program. Parameters associated ... |
def parse_config(bindings, skip_unknown=False):
"""Parse a file, string, or list of strings containing parameter bindings.
Parses parameter binding strings to set up the global configuration. Once
`parse_config` has been called, any calls to configurable functions will have
parameter values set according to t... |
def register_file_reader(*args):
"""Register a file reader for use in parse_config_file.
Registered file readers will be used to try reading files passed to
`parse_config_file`. All file readers (beginning with the default `open`) will
be tried until one of them succeeds at opening the file.
This function m... |
def parse_config_file(config_file, skip_unknown=False):
"""Parse a Gin config file.
Args:
config_file: The path to a Gin config file.
skip_unknown: A boolean indicating whether unknown configurables and imports
should be skipped instead of causing errors (alternatively a list of
configurable na... |
def parse_config_files_and_bindings(config_files,
bindings,
finalize_config=True,
skip_unknown=False):
"""Parse a list of config files followed by extra Gin bindings.
This function is equivalent to:
f... |
def parse_value(value):
"""Parse and return a single Gin value."""
if not isinstance(value, six.string_types):
raise ValueError('value ({}) should be a string type.'.format(value))
return config_parser.ConfigParser(value, ParserDelegate()).parse_value() |
def finalize():
"""A function that should be called after parsing all Gin config files.
Calling this function allows registered "finalize hooks" to inspect (and
potentially modify) the Gin config, to provide additional functionality. Hooks
should not modify the configuration object they receive directly; inste... |
def _iterate_flattened_values(value):
"""Provides an iterator over all values in a nested structure."""
if isinstance(value, six.string_types):
yield value
return
if isinstance(value, collections.Mapping):
value = collections.ValuesView(value)
if isinstance(value, collections.Iterable):
for ne... |
def iterate_references(config, to=None):
"""Provides an iterator over references in the given config.
Args:
config: A dictionary mapping scoped configurable names to argument bindings.
to: If supplied, only yield references whose `configurable_fn` matches `to`.
Yields:
`ConfigurableReference` instan... |
def constant(name, value):
"""Creates a constant that can be referenced from gin config files.
After calling this function in Python, the constant can be referenced from
within a Gin config file using the macro syntax. For example, in Python:
gin.constant('THE_ANSWER', 42)
Then, in a Gin config file:
... |
def constants_from_enum(cls, module=None):
"""Decorator for an enum class that generates Gin constants from values.
Generated constants have format `module.ClassName.ENUM_VALUE`. The module
name is optional when using the constant.
Args:
cls: Class type.
module: The module to associate with the consta... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.