_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q268700 | release | test | def release(version):
"""Tags all submodules for a new release.
Ensures that git tags, as well as the version.py files in each submodule, agree and that the
new version is strictly greater than the current version. Will fail if the new version
is not an increment (following PEP 440). Creates a new git ... | python | {
"resource": ""
} |
q268701 | PipelineContextDefinition.passthrough_context_definition | test | def passthrough_context_definition(context_params):
'''Create a context definition from a pre-existing context. This can be useful
in testing contexts where you may want to create a context manually and then
pass it into a one-off PipelineDefinition
Args:
context (ExecutionC... | python | {
"resource": ""
} |
q268702 | input_selector_schema | test | def input_selector_schema(config_cls):
'''
A decorator for annotating a function that can take the selected properties
from a ``config_value`` in to an instance of a custom type.
Args:
config_cls (Selector)
'''
config_type = resolve_config_cls_arg(config_cls)
check.param_invariant(c... | python | {
"resource": ""
} |
q268703 | output_selector_schema | test | def output_selector_schema(config_cls):
'''
A decorator for a annotating a function that can take the selected properties
of a ``config_value`` and an instance of a custom type and materialize it.
Args:
config_cls (Selector):
'''
config_type = resolve_config_cls_arg(config_cls)
chec... | python | {
"resource": ""
} |
q268704 | IndentingPrinter.block | test | def block(self, text, prefix=''):
'''Automagically wrap a block of text.'''
wrapper = TextWrapper(
width=self.line_length - len(self.current_indent_str),
initial_indent=prefix,
subsequent_indent=prefix,
break_long_words=False,
break_on_hyphens=... | python | {
"resource": ""
} |
q268705 | download_from_s3 | test | def download_from_s3(context):
'''Download an object from s3.
Args:
info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource.
Returns:
str:
The path to the downloaded object.
'''
target_file = context.solid_config['target_file']
return con... | python | {
"resource": ""
} |
q268706 | upload_to_s3 | test | def upload_to_s3(context, file_obj):
'''Upload a file to s3.
Args:
info (ExpectationExecutionInfo): Must expose a boto3 S3 client as its `s3` resource.
Returns:
(str, str):
The bucket and key to which the file was uploaded.
'''
bucket = context.solid_config['bucket']
... | python | {
"resource": ""
} |
q268707 | user_code_error_boundary | test | def user_code_error_boundary(error_cls, msg, **kwargs):
'''
Wraps the execution of user-space code in an error boundary. This places a uniform
policy around an user code invoked by the framework. This ensures that all user
errors are wrapped in the DagsterUserCodeExecutionError, and that the original st... | python | {
"resource": ""
} |
q268708 | mkdir_p | test | def mkdir_p(newdir, mode=0o777):
"""The missing mkdir -p functionality in os."""
try:
os.makedirs(newdir, mode)
except OSError as err:
# Reraise the error unless it's about an already existing directory
if err.errno != errno.EEXIST or not os.path.isdir(newdir):
raise | python | {
"resource": ""
} |
q268709 | user_code_context_manager | test | def user_code_context_manager(user_fn, error_cls, msg):
'''Wraps the output of a user provided function that may yield or return a value and
returns a generator that asserts it only yields a single value.
'''
check.callable_param(user_fn, 'user_fn')
check.subclass_param(error_cls, 'error_cls', Dagst... | python | {
"resource": ""
} |
q268710 | _create_context_free_log | test | def _create_context_free_log(run_config, pipeline_def):
'''In the event of pipeline initialization failure, we want to be able to log the failure
without a dependency on the ExecutionContext to initialize DagsterLog
'''
check.inst_param(run_config, 'run_config', RunConfig)
check.inst_param(pipeline_... | python | {
"resource": ""
} |
q268711 | SolidExecutionResult.success | test | def success(self):
'''Whether the solid execution was successful'''
any_success = False
for step_event in itertools.chain(
self.input_expectations, self.output_expectations, self.transforms
):
if step_event.event_type == DagsterEventType.STEP_FAILURE:
... | python | {
"resource": ""
} |
q268712 | SolidExecutionResult.skipped | test | def skipped(self):
'''Whether the solid execution was skipped'''
return all(
[
step_event.event_type == DagsterEventType.STEP_SKIPPED
for step_event in itertools.chain(
self.input_expectations, self.output_expectations, self.transforms
... | python | {
"resource": ""
} |
q268713 | SolidExecutionResult.transformed_values | test | def transformed_values(self):
'''Return dictionary of transformed results, with keys being output names.
Returns None if execution result isn't a success.
Reconstructs the pipeline context to materialize values.
'''
if self.success and self.transforms:
with self.reco... | python | {
"resource": ""
} |
q268714 | SolidExecutionResult.transformed_value | test | def transformed_value(self, output_name=DEFAULT_OUTPUT):
'''Returns transformed value either for DEFAULT_OUTPUT or for the output
given as output_name. Returns None if execution result isn't a success.
Reconstructs the pipeline context to materialize value.
'''
check.str_param(o... | python | {
"resource": ""
} |
q268715 | SolidExecutionResult.failure_data | test | def failure_data(self):
'''Returns the failing step's data that happened during this solid's execution, if any'''
for result in itertools.chain(
self.input_expectations, self.output_expectations, self.transforms
):
if result.event_type == DagsterEventType.STEP_FAILURE:
... | python | {
"resource": ""
} |
q268716 | PermissiveDict | test | def PermissiveDict(fields=None):
'''A permissive dict will permit the user to partially specify the permitted fields. Any fields
that are specified and passed in will be type checked. Other fields will be allowed, but
will be ignored by the type checker.
'''
if fields:
check_user_facing_fie... | python | {
"resource": ""
} |
q268717 | _is_valid_dataset | test | def _is_valid_dataset(config_value):
'''Datasets must be of form "project.dataset" or "dataset"
'''
return re.match(
# regex matches: project.table -- OR -- table
r'^' + RE_PROJECT + r'\.' + RE_DS_TABLE + r'$|^' + RE_DS_TABLE + r'$',
config_value,
) | python | {
"resource": ""
} |
q268718 | _is_valid_table | test | def _is_valid_table(config_value):
'''Tables must be of form "project.dataset.table" or "dataset.table"
'''
return re.match(
r'^'
+ RE_PROJECT # project
+ r'\.' # .
+ RE_DS_TABLE # dataset
+ r'\.' # .
+ RE_DS_TABLE # table
+ r'$|^' #... | python | {
"resource": ""
} |
q268719 | _execute_core_transform | test | def _execute_core_transform(transform_context, inputs):
'''
Execute the user-specified transform for the solid. Wrap in an error boundary and do
all relevant logging and metrics tracking
'''
check.inst_param(transform_context, 'transform_context', SystemTransformExecutionContext)
check.dict_para... | python | {
"resource": ""
} |
q268720 | as_dagster_type | test | def as_dagster_type(
existing_type,
name=None,
description=None,
input_schema=None,
output_schema=None,
serialization_strategy=None,
storage_plugins=None,
):
'''
Takes a python cls and creates a type for it in the Dagster domain.
Args:
existing_type (cls)
The... | python | {
"resource": ""
} |
q268721 | resource | test | def resource(config_field=None, description=None):
'''A decorator for creating a resource. The decorated function will be used as the
resource_fn in a ResourceDefinition.
'''
# This case is for when decorator is used bare, without arguments.
# E.g. @resource versus @resource()
if callable(conf... | python | {
"resource": ""
} |
q268722 | PagerDutyService.EventV2_create | test | def EventV2_create(
self,
summary,
source,
severity,
event_action='trigger',
dedup_key=None,
timestamp=None,
component=None,
group=None,
event_class=None,
custom_details=None,
):
'''Events API v2 enables you to add Pager... | python | {
"resource": ""
} |
q268723 | coalesce_execution_steps | test | def coalesce_execution_steps(execution_plan):
'''Groups execution steps by solid, in topological order of the solids.'''
solid_order = _coalesce_solid_order(execution_plan)
steps = defaultdict(list)
for solid_name, solid_steps in itertools.groupby(
execution_plan.topological_steps(), lambda x... | python | {
"resource": ""
} |
q268724 | DatabaseWrapper.get_connection_params | test | def get_connection_params(self):
"""
Default method to acquire database connection parameters.
Sets connection parameters to match settings.py, and sets
default values to blank fields.
"""
valid_settings = {
'NAME': 'name',
'HOST': 'host',
... | python | {
"resource": ""
} |
q268725 | DatabaseWrapper.get_new_connection | test | def get_new_connection(self, connection_params):
"""
Receives a dictionary connection_params to setup
a connection to the database.
Dictionary correct setup is made through the
get_connection_params method.
TODO: This needs to be made more generic to accept
othe... | python | {
"resource": ""
} |
q268726 | DatabaseWrapper.create_cursor | test | def create_cursor(self, name=None):
"""
Returns an active connection cursor to the database.
"""
return Cursor(self.client_connection, self.connection, self.djongo_connection) | python | {
"resource": ""
} |
q268727 | DatabaseWrapper._close | test | def _close(self):
"""
Closes the client connection to the database.
"""
if self.connection:
with self.wrap_database_errors:
self.connection.client.close() | python | {
"resource": ""
} |
q268728 | make_mdl | test | 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) | python | {
"resource": ""
} |
q268729 | ArrayModelField.to_python | test | 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... | python | {
"resource": ""
} |
q268730 | ArrayModelField.formfield | test | 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,
... | python | {
"resource": ""
} |
q268731 | EmbeddedModelField.to_python | test | 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... | python | {
"resource": ""
} |
q268732 | ArrayReferenceManagerMixin._apply_rel_filters | test | 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)
... | python | {
"resource": ""
} |
q268733 | _compute_nfps_uniform | test | 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... | python | {
"resource": ""
} |
q268734 | _compute_nfps_real | test | 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 ... | python | {
"resource": ""
} |
q268735 | _compute_best_partitions | test | 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... | python | {
"resource": ""
} |
q268736 | optimal_partitions | test | 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 ... | python | {
"resource": ""
} |
q268737 | bBitMinHash._calc_c | test | 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,
... | python | {
"resource": ""
} |
q268738 | LeanMinHash._initialize_slots | test | 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 ... | python | {
"resource": ""
} |
q268739 | LeanMinHash.bytesize | test | 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... | python | {
"resource": ""
} |
q268740 | LeanMinHash.serialize | test | 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... | python | {
"resource": ""
} |
q268741 | LeanMinHash.deserialize | test | 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... | python | {
"resource": ""
} |
q268742 | MinHash.update | test | 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 ... | python | {
"resource": ""
} |
q268743 | MinHash.merge | test | 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... | python | {
"resource": ""
} |
q268744 | MinHash.union | test | 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 ... | python | {
"resource": ""
} |
q268745 | MinHashLSHEnsemble.index | test | 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... | python | {
"resource": ""
} |
q268746 | MinHashLSHEnsemble.query | test | 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.
... | python | {
"resource": ""
} |
q268747 | WeightedMinHashGenerator.minhash | test | 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... | python | {
"resource": ""
} |
q268748 | MinHashLSH.remove | test | 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")
... | python | {
"resource": ""
} |
q268749 | HyperLogLog.update | test | 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... | python | {
"resource": ""
} |
q268750 | HyperLogLog.count | test | 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
... | python | {
"resource": ""
} |
q268751 | HyperLogLog.merge | test | 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... | python | {
"resource": ""
} |
q268752 | HyperLogLog.clear | test | def clear(self):
'''
Reset the current HyperLogLog to empty.
'''
self.reg = np.zeros((self.m,), dtype=np.int8) | python | {
"resource": ""
} |
q268753 | apk | test | 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... | python | {
"resource": ""
} |
q268754 | mapk | test | 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
... | python | {
"resource": ""
} |
q268755 | MinHashLSHForest.index | test | 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() | python | {
"resource": ""
} |
q268756 | MinHashLSHForest.query | test | 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:
... | python | {
"resource": ""
} |
q268757 | AsyncMinHashLSH.close | test | 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... | python | {
"resource": ""
} |
q268758 | ordered_storage | test | 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... | python | {
"resource": ""
} |
q268759 | unordered_storage | test | 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... | python | {
"resource": ""
} |
q268760 | JWTSerializer.get_user | test | 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(
... | python | {
"resource": ""
} |
q268761 | SocialConnectMixin.get_social_login | test | 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 ... | python | {
"resource": ""
} |
q268762 | select_text | test | 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... | python | {
"resource": ""
} |
q268763 | parse_scoped_selector | test | 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... | python | {
"resource": ""
} |
q268764 | ConfigParser.parse_statement | test | 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:
... | python | {
"resource": ""
} |
q268765 | ConfigParser.parse_value | test | 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... | python | {
"resource": ""
} |
q268766 | ConfigParser.advance_one_line | test | 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)) | python | {
"resource": ""
} |
q268767 | ConfigParser._maybe_parse_configurable_reference | test | 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... | python | {
"resource": ""
} |
q268768 | augment_exception_message_and_reraise | test | 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... | python | {
"resource": ""
} |
q268769 | GinConfigSaverHook._markdownify_operative_config_str | test | 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 ' '... | python | {
"resource": ""
} |
q268770 | GinConfigSaverHook.after_create_session | test | 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... | python | {
"resource": ""
} |
q268771 | _ensure_wrappability | test | 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, *... | python | {
"resource": ""
} |
q268772 | _decorate_fn_or_cls | test | 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... | python | {
"resource": ""
} |
q268773 | _format_value | test | 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... | python | {
"resource": ""
} |
q268774 | clear_config | test | 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:
... | python | {
"resource": ""
} |
q268775 | bind_parameter | test | 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... | python | {
"resource": ""
} |
q268776 | query_parameter | test | 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... | python | {
"resource": ""
} |
q268777 | _might_have_parameter | test | 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... | python | {
"resource": ""
} |
q268778 | _get_cached_arg_spec | test | 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_... | python | {
"resource": ""
} |
q268779 | _get_supplied_positional_parameter_names | test | 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)] | python | {
"resource": ""
} |
q268780 | _get_all_positional_parameter_names | test | 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 | python | {
"resource": ""
} |
q268781 | _get_default_configurable_parameter_values | test | 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... | python | {
"resource": ""
} |
q268782 | config_scope | test | 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... | python | {
"resource": ""
} |
q268783 | configurable | test | 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... | python | {
"resource": ""
} |
q268784 | operative_config_str | test | 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 ... | python | {
"resource": ""
} |
q268785 | parse_config | test | 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... | python | {
"resource": ""
} |
q268786 | register_file_reader | test | 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... | python | {
"resource": ""
} |
q268787 | parse_config_file | test | 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... | python | {
"resource": ""
} |
q268788 | parse_config_files_and_bindings | test | 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... | python | {
"resource": ""
} |
q268789 | parse_value | test | 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() | python | {
"resource": ""
} |
q268790 | finalize | test | 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... | python | {
"resource": ""
} |
q268791 | _iterate_flattened_values | test | 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... | python | {
"resource": ""
} |
q268792 | iterate_references | test | 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... | python | {
"resource": ""
} |
q268793 | constant | test | 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:
... | python | {
"resource": ""
} |
q268794 | constants_from_enum | test | 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... | python | {
"resource": ""
} |
q268795 | SelectorMap.matching_selectors | test | def matching_selectors(self, partial_selector):
"""Retrieves all selectors matching `partial_selector`.
For instance, if "one.a.b" and "two.a.b" are stored in a `SelectorMap`, both
`matching_selectors('b')` and `matching_selectors('a.b')` will return them.
In the event that `partial_selector` exactly ... | python | {
"resource": ""
} |
q268796 | SelectorMap.get_all_matches | test | def get_all_matches(self, partial_selector):
"""Returns all values matching `partial_selector` as a list."""
matching_selectors = self.matching_selectors(partial_selector)
return [self._selector_map[selector] for selector in matching_selectors] | python | {
"resource": ""
} |
q268797 | SelectorMap.minimal_selector | test | def minimal_selector(self, complete_selector):
"""Returns the minimal selector that uniquely matches `complete_selector`.
Args:
complete_selector: A complete selector stored in the map.
Returns:
A partial selector that unambiguously matches `complete_selector`.
Raises:
KeyError: If ... | python | {
"resource": ""
} |
q268798 | sp_search_query | test | def sp_search_query(query):
"""Translate a Mopidy search query to a Spotify search query"""
result = []
for (field, values) in query.items():
field = SEARCH_FIELD_MAP.get(field, field)
if field is None:
continue
for value in values:
if field == 'year':
... | python | {
"resource": ""
} |
q268799 | OAuthClient._parse_retry_after | test | def _parse_retry_after(self, response):
"""Parse Retry-After header from response if it is set."""
value = response.headers.get('Retry-After')
if not value:
seconds = 0
elif re.match(r'^\s*[0-9]+\s*$', value):
seconds = int(value)
else:
date_t... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.