INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return dictionary of transformed results with keys being output names. Returns None if execution result isn t a success. | 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... |
Returns transformed value either for DEFAULT_OUTPUT or for the output given as output_name. Returns None if execution result isn t a success. | 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... |
Returns the failing step s data that happened during this solid s execution if any | 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:
... |
A: py: class: Dict with a name allowing it to be referenced by that name. | def NamedDict(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES):
'''
A :py:class:`Dict` with a name allowing it to be referenced by that name.
'''
check_user_facing_fields_dict(fields, 'NamedDict named "{}"'.format(name))
class _NamedDict(_ConfigComposite):
def __init... |
Schema for configuration data with string keys and typed values via: py: class: Field. | def Dict(fields):
'''
Schema for configuration data with string keys and typed values via :py:class:`Field` .
Args:
fields (Dict[str, Field])
'''
check_user_facing_fields_dict(fields, 'Dict')
class _Dict(_ConfigComposite):
def __init__(self):
key = 'Dict.' + str(Dic... |
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. | 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... |
Selectors are used when you want to be able present several different options to the user but force them to select one. For example it would not make much sense to allow them to say that a single input should be sourced from a csv and a parquet file: They must choose. | def Selector(fields):
'''Selectors are used when you want to be able present several different options to the user but
force them to select one. For example, it would not make much sense to allow them
to say that a single input should be sourced from a csv and a parquet file: They must choose.
Note tha... |
A: py: class Selector with a name allowing it to be referenced by that name. Args: name ( str ): fields ( Dict [ str Field ] ) | def NamedSelector(name, fields, description=None, type_attributes=DEFAULT_TYPE_ATTRIBUTES):
'''
A :py:class`Selector` with a name, allowing it to be referenced by that name.
Args:
name (str):
fields (Dict[str, Field])
'''
check.str_param(name, 'name')
check_user_facing_field... |
Datasets must be of form project. dataset or dataset | 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,
) |
Tables must be of form project. dataset. table or dataset. table | 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'$|^' #... |
Execute the user - specified transform for the solid. Wrap in an error boundary and do all relevant logging and metrics tracking | 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... |
Decorator version of as_dagster_type. See documentation for: py: func: as_dagster_type. | def dagster_type(
name=None,
description=None,
input_schema=None,
output_schema=None,
serialization_strategy=None,
storage_plugins=None,
):
'''
Decorator version of as_dagster_type. See documentation for :py:func:`as_dagster_type` .
'''
def _with_args(bare_cls):
check.ty... |
Takes a python cls and creates a type for it in the Dagster domain. | 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... |
A decorator for creating a resource. The decorated function will be used as the resource_fn in a ResourceDefinition. | 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... |
See https:// bit. ly/ 2OpksJC for source of the subprocess stdout/ stderr capture pattern in this function. | def run_spark_subprocess(cmd, logger):
"""See https://bit.ly/2OpksJC for source of the subprocess stdout/stderr capture pattern in this
function.
"""
# Spark sometimes logs in log4j format. In those cases, we detect and parse.
# Example log line from Spark that this is intended to match:
# 2019... |
For each key - value pair in spark conf we need to pass to CLI in format: | def parse_spark_config(spark_conf):
'''For each key-value pair in spark conf, we need to pass to CLI in format:
--conf "key=value"
'''
spark_conf_list = flatten_dict(spark_conf)
return list(
itertools.chain.from_iterable([('--conf', '{}={}'.format(*c)) for c in spark_conf_list])
) |
A SystemNamedDict object is simply a NamedDict intended for internal ( dagster ) use. | def SystemNamedDict(name, fields, description=None):
'''A SystemNamedDict object is simply a NamedDict intended for internal (dagster) use.
'''
return NamedDict(name, fields, description, ConfigTypeAttributes(is_system_config=True)) |
Events API v2 enables you to add PagerDuty s advanced event and incident management functionality to any system that can make an outbound HTTP connection. | 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... |
Groups execution steps by solid in topological order of the solids. | 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... |
Default method to acquire database connection parameters. | 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',
... |
Receives a dictionary connection_params to setup a connection to the database. | 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... |
Returns an active connection cursor to the database. | def create_cursor(self, name=None):
"""
Returns an active connection cursor to the database.
"""
return Cursor(self.client_connection, self.connection, self.djongo_connection) |
Closes the client connection to the database. | def _close(self):
"""
Closes the client connection to the database.
"""
if self.connection:
with self.wrap_database_errors:
self.connection.client.close() |
Builds an instance of model from the model_dict. | 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) |
Overrides standard to_python method from django models to allow correct translation of Mongo array to a python list. | 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... |
Returns the formfield for the array. | 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,
... |
Overrides Django s default to_python to allow correct translation to instance. | 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... |
Filter the queryset for the instance this manager is bound to. | 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)
... |
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. | 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... |
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. | 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... |
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. | 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:... |
Computes the matrix of expected false positives for all possible sub - intervals of the complete domain of set sizes. | 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 ... |
Computes the optimal partitions given the size distributions and computed number of expected false positives for all sub - intervals. | 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... |
Compute the optimal partitions given a distribution of set sizes. | 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 ... |
Estimate the Jaccard similarity ( resemblance ) between this b - bit MinHash and the other. | 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 != ... |
Compute the function A ( r b ) | 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)) |
Compute the functions C1 and C2 | 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,
... |
Initialize the slots of the LeanMinHash. | 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 ... |
Compute the byte size after serialization. | 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... |
Serialize this lean MinHash and store the result in an allocated buffer. | 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... |
Deserialize a lean MinHash from a buffer. | 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... |
Update this MinHash with a new value. The value will be hashed using the hash function specified by the hashfunc argument in the constructor. | 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 ... |
Estimate the Jaccard similarity _ ( resemblance ) between the sets represented by this MinHash and the other. | 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.
... |
Estimate the cardinality count based on the technique described in this paper <http:// ieeexplore. ieee. org/ stamp/ stamp. jsp?arnumber = 365694 > _. | 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)
... |
Merge the other MinHash with this one making this one the union of both. | 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... |
: returns: datasketch. MinHash -- A copy of this MinHash by exporting its state. | 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) |
Create a MinHash which is the union of the MinHash objects passed as arguments. | 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 ... |
Compute the false positive probability given the containment threshold. xq is the ratio of x/ q. | 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,... |
Compute the optimal parameters that minimizes the weighted sum of probabilities of false positive and false negative. xq is the ratio of x/ q. | 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... |
Index all sets given their keys MinHashes and sizes. It can be called only once after the index is created. | 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... |
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. | 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.
... |
Returns: bool: Check if the index is empty. | 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) |
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. | 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... |
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. | 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... |
Insert a key to the index together with a MinHash ( or weighted MinHash ) of the set referenced by the key. | 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.
... |
Remove the key from the index. | 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")
... |
Returns the bucket allocation counts ( see: func: ~datasketch. MinHashLSH. get_counts above ) restricted to the list of keys given. | 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
'''... |
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. | 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... |
Estimate the cardinality of the data values seen so far. | 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
... |
Merge the other HyperLogLog with this one making this the union of the two. | 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... |
Reset the current HyperLogLog to empty. | def clear(self):
'''
Reset the current HyperLogLog to empty.
'''
self.reg = np.zeros((self.m,), dtype=np.int8) |
Computes the average precision at k. | 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... |
Computes the mean average precision at k. | 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
... |
Add a unique key together with a MinHash ( or weighted MinHash ) of the set referenced by the key. | 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... |
Index all the keys added so far and make them searchable. | 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() |
Return the approximate top - k keys that have the highest Jaccard similarities to the query set. | 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:
... |
https:// golang. org/ src/ sort/ search. go?s = 2247: 2287#L49 | 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 |
Cleanup client resources and disconnect from AsyncMinHashLSH storage. | 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... |
see: class: datasketch. MinHashLSH. | 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... |
see: class: datasketch. MinHashLSH. | async def get_counts(self):
"""
see :class:`datasketch.MinHashLSH`.
"""
fs = (hashtable.itemcounts() for hashtable in self.hashtables)
return await asyncio.gather(*fs) |
Return ordered storage system based on the specified config. | 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... |
Return an unordered storage system based on the specified config. | 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... |
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. | 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()} |
: param adapter: allauth. socialaccount Adapter subclass. Usually OAuthAdapter or Auth2Adapter: param app: allauth. socialaccount. SocialApp instance: param token: allauth. socialaccount. SocialToken instance: param response: Provider s response for OAuth1. Not used in the: returns: A populated instance of the allauth.... | 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
... |
Required to allow using custom USER_DETAILS_SERIALIZER in JWTSerializer. Defining it here to avoid circular imports | 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(
... |
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. | 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 ... |
Select the correct text from the Japanese number reading and alternatives | 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... |
Merge lpair < rpair while applying semi - irregular rendaku rules | 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 == ("ろく... |
starting here it groups the number by three from the tail 1234567 - > (( 1 ) ( 234 ) ( 567 )): param number: str: rtype: tuple | 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,... |
it adds the list of spelling to the blocks ( ( 1 ) ( 034 )) - > (( 1 [ satu ] ) ( 234 [ tiga puluh empat ] ) ): param blocks: tuple: rtype: tuple | 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... |
join the words by first join lists in the tuple: param word_blocks: tuple: rtype: str | 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 ... |
Args: val: Numeric value currency ( str ): Currency code cents ( bool ): Verbose cents separator ( str ): Cent separator adjective ( bool ): Prefix currency name with adjective Returns: str: Formatted string | 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):... |
Parse scoped selector. | 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... |
Parse a single statement. | 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:
... |
Parse a single literal value. | 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... |
Advances to next line. | 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)) |
Parse a ( possibly scoped ) selector. | 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... |
Try to parse a container type ( dict list or tuple ). | 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:
... |
Try to parse a basic type ( str bool number ). | 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... |
Try to parse a configurable reference ( | 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... |
Try to parse an macro ( %scope/ name ). | 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... |
Reraises exception appending message to its string representation. | 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... |
Convert an operative config string to markdown format. | 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 ' '... |
Writes out Gin s operative config and maybe adds a summary of it. | 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... |
Find the first __init__ or __new__ method in the given class s MRO. | 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__ |
Make sure fn can be wrapped cleanly by functools. wraps. | 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, *... |
Decorate a function or class with the given decorator. | 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... |
Checks whether selector should be skipped ( if unknown ). | 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... |
Returns value in a format parseable by parse_value or None. | 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... |
Clears the global configuration. | 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:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.