INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return a boolean to indicate if we need to reschedule another bracket iteration. | def should_reduce_configs(self, iteration, bracket_iteration):
"""Return a boolean to indicate if we need to reschedule another bracket iteration."""
n_configs_to_keep = self.get_n_config_to_keep_for_iteration(
iteration=iteration, bracket_iteration=bracket_iteration)
return n_config... |
Validates a resource | def validate_resource(resource) -> None:
"""Validates a resource"""
if resource is not None and not isinstance(resource, dict):
raise ValidationError('The resource is not valid.')
if isinstance(resource, dict) and set(resource.keys()) <= {'requests', 'limits'}:
raise ValidationError(
... |
Pod init container for setting outputs path. | def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... |
We need to nest the git path inside the project path to make it easier to create docker images. | def path(self) -> str:
"""We need to nest the git path inside the project path to make it easier
to create docker images."""
return os.path.join(self.project_path, self.project.name) |
Returns a tuple ( hash and commit object ) | def last_commit(self) -> Tuple:
"""Returns a tuple (hash, and commit object)"""
from libs.repos import git
return git.get_last_commit(repo_path=self.path) |
Validates that we can only authenticate to one S3 and one GCS. | def validate_stores_secrets_keys(stores_secrets):
"""Validates that we can only authenticate to one S3 and one GCS."""
stores = set([])
for store_secret in stores_secrets:
if store_secret['store'] in stores:
raise TensorboardValidation('Received an invalid store confi... |
Handles the case of GCS and S3 and create a volume with secret file. | def get_stores_secrets_volumes(cls, stores_secrets):
"""Handles the case of GCS and S3 and create a volume with secret file."""
volumes = []
volume_mounts = []
for store_secret in stores_secrets:
store = store_secret['store']
if store in {GCS, S3}:
... |
Create an auth command for S3 and GCS. | def get_stores_secrets_command_args(cls, stores_secrets):
"""Create an auth command for S3 and GCS."""
commands = []
for store_secret in stores_secrets:
store = store_secret['store']
if store == GCS:
commands.append('export GOOGLE_APPLICATION_CREDENTIALS={... |
Returns a token to be used x number of times to allow a user account to access certain resource. | def make_token(cls, ephemeral_token: 'RedisEphemeralTokens') -> str:
"""
Returns a token to be used x number of times to allow a user account to access
certain resource.
"""
value = ephemeral_token.key
if ephemeral_token.scope:
value += ''.join(ephemeral_token... |
Check that a token is correct for a given scope token. | def check_token(self, token: 'RedisEphemeralTokens') -> bool:
"""
Check that a token is correct for a given scope token.
"""
if self.get_state() is None: # Token expired
return False
correct_token = self.make_token(self)
self.clear()
return constant_... |
A function to find the maximum of the acquisition function | def max_compute(self, y_max, bounds, n_warmup=100000, n_iter=250):
"""A function to find the maximum of the acquisition function
It uses a combination of random sampling (cheap) and the 'L-BFGS-B' optimization method.
First by sampling `n_warmup` (1e5) points at random,
and then runnin... |
Ordering is set by a comma delimited ?ordering =... query parameter. | def get_ordering(self, request, queryset, view):
"""
Ordering is set by a comma delimited ?ordering=... query parameter.
The `ordering` query parameter can be overridden by setting
the `ordering_param` value on the OrderingFilter or by
specifying an `ORDERING_PARAM` value in the... |
Pod init container for setting outputs path. | def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... |
Generate the activation key which will be emailed to the user. | def get_activation_key(self, user):
"""
Generate the activation key which will be emailed to the user.
"""
return signing.dumps(
obj=getattr(user, user.USERNAME_FIELD),
salt=self.key_salt
) |
Send the activation email. The activation key is the username signed using TimestampSigner. | def send_activation_email(self, user):
"""
Send the activation email. The activation key is the username,
signed using TimestampSigner.
"""
activation_key = self.get_activation_key(user)
context = self.get_email_context(activation_key)
context.update({
... |
Create the inactive user account and wait for validation from superuser | def create_inactive_user(self, form):
"""Create the inactive user account and wait for validation from superuser"""
new_user = form.save(commit=False)
new_user.is_active = False
new_user.save()
return new_user |
Verify that the activation key is valid and within the permitted activation time window returning the username if valid or None if not. | def validate_key(self, activation_key):
"""
Verify that the activation key is valid and within the
permitted activation time window, returning the username if
valid or ``None`` if not.
"""
try:
username = signing.loads(
activation_key,
... |
Given the verified username look up and return the corresponding user account if it exists or None if it doesn t. | def get_user(self, username):
"""
Given the verified username, look up and return the
corresponding user account if it exists, or ``None`` if it
doesn't.
"""
User = get_user_model() # noqa
try:
user = User.objects.get(**{
User.USERNAM... |
The base activation logic ; subclasses should leave this method alone and implement activate () which is called from this method. | def get(self, request, *args, **kwargs):
"""The base activation logic; subclasses should leave this method
alone and implement activate(), which is called from this method.
"""
activated_user = self.activate(*args, **kwargs)
if activated_user:
users_signals.user_activ... |
Pod job container for task. | def get_pod_container(self,
volume_mounts,
persistence_outputs=None,
persistence_data=None,
outputs_refs_jobs=None,
outputs_refs_experiments=None,
secret_refs=None,... |
Pod sidecar container for task logs. | def get_sidecar_container(self, volume_mounts):
"""Pod sidecar container for task logs."""
return get_sidecar_container(
job_container_name=self.job_container_name,
sidecar_container_name=self.sidecar_container_name,
sidecar_docker_image=self.sidecar_docker_image,
... |
Pod spec to be used to create pods for tasks: master worker ps. | def get_task_pod_spec(self,
volume_mounts,
volumes,
resource_name,
persistence_outputs=None,
persistence_data=None,
outputs_refs_jobs=None,
... |
This validation step is done when we are sure the user does not exit on the systems and we need to create a new user. | def validate_username(username):
"""
This validation step is done when we are sure the user
does not exit on the systems and we need to create a new user.
"""
try:
validate_slug(username)
except ValidationError:
username = slugify(username)
... |
This is where you should alter the context to fit the action. | def _prepare(cls, context: Dict) -> Dict:
"""This is where you should alter the context to fit the action.
Default behaviour will leave the context as it is.
"""
if not context and cls.raise_empty_context:
raise PolyaxonActionException('{} received invalid payload context.'.... |
If experiment is a restart we should resume from last check point | def copy_experiment(experiment):
"""If experiment is a restart, we should resume from last check point"""
try:
publisher.publish_experiment_job_log(
log_lines='Copying outputs from experiment `{}` into experiment `{}`'.format(
experiment.original_experiment.unique_name, exper... |
Validate and record an event. | def record(self,
event_type: str,
event_data: Mapping = None,
instance: Any = None,
**kwargs) -> 'Event':
""" Validate and record an event.
>>> record('event.action', object_instance)
"""
if not self.is_setup:
retur... |
Build necessary code for a job to run | def generate(job,
build_path: str,
from_image: str,
build_steps: Optional[List[str]] = None,
env_vars: Optional[List[Tuple[str, str]]] = None,
nvidia_bin: str = None,
set_lang_env: bool = True,
uid: int = None,
gid: ... |
Return a list of suggestions based on random search. | def get_suggestions(self, iteration_config=None):
"""Return a list of suggestions based on random search.
Params:
matrix: `dict` representing the {hyperparam: hyperparam matrix config}.
n_suggestions: number of suggestions to make.
"""
matrix = self.hptuning_conf... |
if an array is passed set serializer to many | def get_serializer(self, *args, **kwargs):
""" if an array is passed, set serializer to many """
if isinstance(kwargs.get('data', {}), list):
kwargs['many'] = True
return super().get_serializer(*args, **kwargs) |
Task handling for sidecars logs. | def logs_handle_experiment_job(experiment_name: str,
experiment_uuid: str,
log_lines: Optional[Union[str, Iterable[str]]],
temp: bool = True) -> None:
"""Task handling for sidecars logs."""
handle_experiment_job_log(exp... |
Task handling for sidecars logs. | def logs_handle_job(job_uuid: str,
job_name: str,
log_lines: Optional[Union[str, Iterable[str]]],
temp: bool = True) -> None:
"""Task handling for sidecars logs."""
handle_job_logs(job_uuid=job_uuid,
job_name=job_name,
... |
Task handling for sidecars logs. | def logs_handle_build_job(job_uuid: str,
job_name: str,
log_lines: Optional[Union[str, Iterable[str]]],
temp: bool = True) -> None:
"""Task handling for sidecars logs."""
handle_build_job_logs(job_uuid=job_uuid,
... |
Create an iteration for the experiment group. | def create_iteration(self, num_suggestions=0):
"""Create an iteration for the experiment group."""
from db.models.experiment_groups import ExperimentGroupIteration
search_manager = self.experiment_group.search_manager
iteration_config = self.experiment_group.iteration_config
if... |
Reduce the experiments to restart. | def get_reduced_configs(self):
"""Reduce the experiments to restart."""
iteration_config = self.experiment_group.iteration_config
if iteration_config is None:
logger.error(
'Experiment group `%s` attempt to update iteration, but has no iteration',
self... |
Reduce the experiments to restart. | def reduce_configs(self):
"""Reduce the experiments to restart."""
experiment_ids = self.get_reduced_configs()
experiments = self.experiment_group.experiments.filter(id__in=experiment_ids)
self.create_iteration()
iteration_config = self.experiment_group.iteration_config
h... |
Similar to experiment_groups but uses the default manager to return archived experiments as well. | def all_experiment_groups(self):
"""
Similar to experiment_groups,
but uses the default manager to return archived experiments as well.
"""
from db.models.experiment_groups import ExperimentGroup
return ExperimentGroup.all.filter(project=self) |
Similar to jobs but uses the default manager to return archived experiments as well. | def all_jobs(self):
"""
Similar to jobs,
but uses the default manager to return archived experiments as well.
"""
from db.models.jobs import Job
return Job.all.filter(project=self) |
Similar to build_jobs but uses the default manager to return archived experiments as well. | def all_build_jobs(self):
"""
Similar to build_jobs,
but uses the default manager to return archived experiments as well.
"""
from db.models.build_jobs import BuildJob
return BuildJob.all.filter(project=self) |
Similar to notebook_jobs but uses the default manager to return archived experiments as well. | def all_notebook_jobs(self):
"""
Similar to notebook_jobs,
but uses the default manager to return archived experiments as well.
"""
from db.models.notebooks import NotebookJob
return NotebookJob.all.filter(project=self) |
Similar to tensorboard_jobs but uses the default manager to return archived experiments as well. | def all_tensorboard_jobs(self):
"""
Similar to tensorboard_jobs,
but uses the default manager to return archived experiments as well.
"""
from db.models.tensorboards import TensorboardJob
return TensorboardJob.all.filter(project=self) |
Similar to experiments but uses the default manager to return archived experiments as well. | def all_experiments(self):
"""
Similar to experiments,
but uses the default manager to return archived experiments as well.
"""
from db.models.experiments import Experiment
return Experiment.all.filter(experiment_group=self) |
Similar to group_experiments but uses the default manager to return archived experiments as well. | def all_group_experiments(self):
"""
Similar to group_experiments,
but uses the default manager to return archived experiments as well.
"""
from db.models.experiments import Experiment
if self.is_selection:
return Experiment.all.filter(selections=self)
... |
Return a dag representation of the nodes passed. | def get_dag(nodes, downstream_fn) -> Tuple[Dict, Dict]:
"""Return a dag representation of the nodes passed.
This is equally used for pipelines and pipeline runs.
Params:
nodes: an instance of `Operation` | `OperationRun` the nodes to represent en dag.
downstream_fn: a function that returns... |
Get a list of all node in the graph with no dependencies. | def get_independent_nodes(dag):
"""Get a list of all node in the graph with no dependencies."""
nodes = set(dag.keys())
dependent_nodes = set([node for downstream_nodes in dag.values() for node in downstream_nodes])
return set(nodes - dependent_nodes) |
Get orphan nodes for given dag. | def get_orphan_nodes(dag):
"""Get orphan nodes for given dag."""
independent_nodes = get_independent_nodes(dag)
return set([node for node in independent_nodes if not dag[node]]) |
Checks if the node has dependencies. | def has_dependencies(node, dag):
"""Checks if the node has dependencies."""
for downstream_nodes in dag.values():
if node in downstream_nodes:
return True
return False |
Sort the dag breath first topologically. | def sort_topologically(dag):
"""Sort the dag breath first topologically.
Only the nodes inside the dag are returned, i.e. the nodes that are also keys.
Returns:
a topological ordering of the DAG.
Raises:
an error if this is not possible (graph is not valid).
"""
dag = copy.de... |
Parse the negation modifier in an operation. | def parse_negation_operation(operation: str) -> Tuple[bool, str]:
"""Parse the negation modifier in an operation."""
_operation = operation.strip()
if not _operation:
raise QueryParserException('Operation is not valid: {}'.format(operation))
negation = False
if _operation[0] == '~':
... |
Parse the comparision operator in an operation. | def parse_comparison_operation(operation: str) -> Tuple[Optional[str], str]:
"""Parse the comparision operator in an operation."""
_operation = operation.strip()
if not _operation:
raise QueryParserException('Operation is not valid: {}'.format(operation))
# Check inclusion comparison
if _ope... |
Parse datetime operations. | def parse_datetime_operation(operation: str) -> 'QueryOpSpec':
"""Parse datetime operations.
A datetime operation can one of the following:
* single value: start_date:2014-10-10, start_date:>2014-10-10, start_date:>=2014-10-10
* negation single value: start_date:~2014-10-10
* interval: start_da... |
Parse scalar operations. | def parse_scalar_operation(operation: str) -> 'QueryOpSpec':
"""Parse scalar operations.
A scalar operation can one of the following:
* single value: start_date:12, metric1:>0.9, metric1:>=-0.12
* negation single value: metric1:~1112, metric1:~<1112 equivalent to metric1:>=1112
This parser does... |
Base parsing for expressions. | def parse_expression(expression: str) -> Tuple[str, str]:
"""Base parsing for expressions.
Every expression must follow a basic format:
`name:[modifier|operator]operation[*[operator]operation]`
So this parser just split the expression into: field name, operation.
"""
try:
_expressi... |
Split a query into different expressions. | def split_query(query: str) -> List[str]:
"""Split a query into different expressions.
Example:
name:bla, foo:<=1
"""
try:
_query = query.strip()
except (ValueError, AttributeError):
raise QueryParserException('query is not valid, received instead {}'.format(query))
exp... |
Tokenizes a standard search query in name: operations mapping. | def tokenize_query(query: str) -> Dict[str, Iterable]:
"""Tokenizes a standard search query in name: operations mapping.
Example:
moo:bla, foo:~<=1, foo:ll..ff
{
'moo': ['bla'],
'foo': ['~<=1', 'll..ff']
}
"""
expressions = split_query(query)
name_operat... |
Parses fields with underscores and return field and suffix. | def parse_field(field: str) -> Tuple[str, Optional[str]]:
"""Parses fields with underscores, and return field and suffix.
Example:
foo => foo, None
metric.foo => metric, foo
"""
_field = field.split('.')
_field = [f.strip() for f in _field]
if len(_field) == 1 and _field[0]:
... |
Set the upstream operations for operation run. | def set_op_upstreams(op_run, op):
"""Set the upstream operations for operation run."""
# We get a list of all upstream ops or the current op
upstream_ops = op.upstream_operations.values_list('id', flat=True)
# We get latest op runs for the upstream_ops
latest_op_runs = OperationRun.objects.filter(id... |
Set the upstream runs for the operation runs in the dag following the topological sort. | def set_topological_dag_upstreams(dag, ops, op_runs, runs_by_ops):
"""Set the upstream runs for the operation runs in the dag following the topological sort."""
sorted_ops = dags.sort_topologically(dag=dag)
for op_id in sorted_ops:
op_run_id = runs_by_ops[op_id]
op_run = op_runs[op_run_id]
... |
Create a pipeline run/ instance. | def create_pipeline_run(pipeline, context_by_op):
"""Create a pipeline run/instance."""
pipeline_run = PipelineRun.objects.create(pipeline=pipeline)
dag, ops = pipeline.dag
# Go trough the operation and create operation runs and the upstreams
op_runs = {}
runs_by_ops = {}
for op_id in dag.ke... |
Experiment jobs statuses | def k8s_events_handle_experiment_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Experiment jobs statuses"""
details = payload['details']
job_uuid = details['labels']['job_uuid']
logger.debug('handling events status for job_uuid: %s, status: %s',
job_uuid, payload['stat... |
Project jobs statuses | def k8s_events_handle_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Project jobs statuses"""
details = payload['details']
job_uuid = details['labels']['job_uuid']
job_name = details['labels']['job_name']
project_name = details['labels'].get('project_name')
logger.debug('handli... |
Project Plugin jobs statuses | def k8s_events_handle_plugin_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Project Plugin jobs statuses"""
details = payload['details']
app = details['labels']['app']
job_uuid = details['labels']['job_uuid']
job_name = details['labels']['job_name']
project_name = details['labe... |
Project Plugin jobs statuses | def k8s_events_handle_build_job_statuses(self: 'celery_app.task', payload: Dict) -> None:
"""Project Plugin jobs statuses"""
details = payload['details']
app = details['labels']['app']
job_uuid = details['labels']['job_uuid']
job_name = details['labels']['job_name']
project_name = details['label... |
Return a pod sidecar container. | def get_sidecar_container(job_container_name,
sidecar_container_name,
sidecar_docker_image,
sidecar_docker_image_pull_policy,
namespace,
sidecar_config,
sidecar_arg... |
Use custom exception handler for errors. | def handle_exception(self, exc):
"""Use custom exception handler for errors."""
if isinstance(
exc, (rest_exceptions.NotAuthenticated,
rest_exceptions.AuthenticationFailed)) and self.HANDLE_UNAUTHENTICATED:
return HttpResponseRedirect('{}?next={}'.format(
... |
Create resources requirements. | def get_resources(resources): # pylint:disable=too-many-branches
"""Create resources requirements.
Args:
resources: `PodResourcesConfig`
Return:
`V1ResourceRequirements`
"""
limits = {}
requests = {}
if resources is None:
return None
if resources.cpu:
i... |
This logic is extracted here to be used also with Sanic api. | def has_project_permissions(user: 'User', project: 'Project', request_method: str) -> bool:
"""This logic is extracted here to be used also with Sanic api."""
# Superusers and the creator is allowed to do everything
if user.is_staff or user.is_superuser or project.user == user:
return True
# Ot... |
Delete all group outputs. | def experiment_group_pre_delete(sender, **kwargs):
"""Delete all group outputs."""
instance = kwargs['instance']
if instance.is_selection:
return
# Delete outputs and logs
celery_app.send_task(
SchedulerCeleryTasks.STORES_SCHEDULE_OUTPUTS_DELETION,
kwargs={
'per... |
Delete all group outputs. | def experiment_group_post_delete(sender, **kwargs):
"""Delete all group outputs."""
instance = kwargs['instance']
auditor.record(event_type=EXPERIMENT_GROUP_DELETED, instance=instance)
remove_bookmarks(object_id=instance.id, content_type='experimentgroup') |
Return a static asset URL ( located within Polyaxon s static files ). | def get_asset_url(module: str, path: str) -> str:
"""Return a static asset URL (located within Polyaxon's static files).
Example:
```python
>>> get_asset_url('polyaxon', 'dist/global.css')
... "/_static/74d127b78dc7daf2c51f/polyaxon/dist/global.css"
```
"""
return '{}/{}... |
Pod init container for setting outputs path. | def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... |
Pod init container for setting outputs path. | def get_init_container(self,
init_command,
init_args,
env_vars,
context_mounts,
persistence_outputs,
persistence_data):
"""Pod init container for sett... |
Create an iteration for the experiment group ( works for grid and random ). | def create_iteration(self, num_suggestions):
"""Create an iteration for the experiment group (works for grid and random)."""
from db.models.experiment_groups import ExperimentGroupIteration
iteration_config = BaseIterationConfig(iteration=0,
num_su... |
Update the last experiment group s iteration with experiment performance. | def update_iteration(self):
"""Update the last experiment group's iteration with experiment performance."""
iteration_config = self.get_iteration_config()
if not iteration_config:
return
experiments_metrics = self.experiment_group.get_experiments_metrics(
experime... |
Update iteration s num_suggestions. | def update_iteration_num_suggestions(self, num_suggestions):
"""Update iteration's num_suggestions."""
iteration_config = self.experiment_group.iteration_config
iteration_config.num_suggestions = num_suggestions
self._update_config(iteration_config) |
We only validate the config if passed. | def validate_config(self, config):
"""We only validate the config if passed.
Also we use the ExperimentSpecification to check if this config was
intended as an experiment.
"""
# config is optional
if not config:
return config
spec = validate_experime... |
Return the second part of the event_type | def get_event_action(cls) -> Optional[str]:
"""Return the second part of the event_type
e.g.
>>> Event.event_type = 'experiment.deleted'
>>> Event.get_event_action() == 'deleted'
"""
if not cls.actor:
return None
return event_context.get_event_action... |
Get or Create a build job based on the params. | def create_build_job(user, project, config, code_reference, configmap_refs=None, secret_refs=None):
"""Get or Create a build job based on the params.
If a build job already exists, then we check if the build has already an image created.
If the image does not exists, and the job is already done we force cr... |
Scan a YAML stream and produce scanning tokens. | def scan(stream, Loader=Loader):
"""
Scan a YAML stream and produce scanning tokens.
"""
loader = Loader(stream)
try:
while loader.check_token():
yield loader.get_token()
finally:
loader.dispose() |
Parse a YAML stream and produce parsing events. | def parse(stream, Loader=Loader):
"""
Parse a YAML stream and produce parsing events.
"""
loader = Loader(stream)
try:
while loader.check_event():
yield loader.get_event()
finally:
loader.dispose() |
Parse the first YAML document in a stream and produce the corresponding representation tree. | def compose(stream, Loader=Loader):
"""
Parse the first YAML document in a stream
and produce the corresponding representation tree.
"""
loader = Loader(stream)
try:
return loader.get_single_node()
finally:
loader.dispose() |
Parse all YAML documents in a stream and produce corresponding representation trees. | def compose_all(stream, Loader=Loader):
"""
Parse all YAML documents in a stream
and produce corresponding representation trees.
"""
loader = Loader(stream)
try:
while loader.check_node():
yield loader.get_node()
finally:
loader.dispose() |
Parse the first YAML document in a stream and produce the corresponding Python object. | def load(stream, Loader=None):
"""
Parse the first YAML document in a stream
and produce the corresponding Python object.
"""
if Loader is None:
load_warning('load')
Loader = FullLoader
loader = Loader(stream)
try:
return loader.get_single_data()
finally:
... |
Parse all YAML documents in a stream and produce corresponding Python objects. | def load_all(stream, Loader=None):
"""
Parse all YAML documents in a stream
and produce corresponding Python objects.
"""
if Loader is None:
load_warning('load_all')
Loader = FullLoader
loader = Loader(stream)
try:
while loader.check_data():
yield loader.... |
Emit YAML parsing events into a stream. If stream is None return the produced string instead. | def emit(events, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None):
"""
Emit YAML parsing events into a stream.
If stream is None, return the produced string instead.
"""
getvalue = None
if stream is None:
from Strin... |
Serialize a representation tree into a YAML stream. If stream is None return the produced string instead. | def serialize(node, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a representation tree into a YAML stream.
If stream is None, return the produced string instead.
"""
return serialize_all([node], stream, Dumper=Dumper, **kwds) |
Serialize a Python object into a YAML stream. If stream is None return the produced string instead. | def dump(data, stream=None, Dumper=Dumper, **kwds):
"""
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=Dumper, **kwds) |
Serialize a sequence of Python objects into a YAML stream. Produce only basic YAML tags. If stream is None return the produced string instead. | def safe_dump_all(documents, stream=None, **kwds):
"""
Serialize a sequence of Python objects into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all(documents, stream, Dumper=SafeDumper, **kwds) |
Serialize a Python object into a YAML stream. Produce only basic YAML tags. If stream is None return the produced string instead. | def safe_dump(data, stream=None, **kwds):
"""
Serialize a Python object into a YAML stream.
Produce only basic YAML tags.
If stream is None, return the produced string instead.
"""
return dump_all([data], stream, Dumper=SafeDumper, **kwds) |
Add an implicit scalar detector. If an implicit scalar value matches the given regexp the corresponding tag is assigned to the scalar. first is a sequence of possible initial characters or None. | def add_implicit_resolver(tag, regexp, first=None,
Loader=Loader, Dumper=Dumper):
"""
Add an implicit scalar detector.
If an implicit scalar value matches the given regexp,
the corresponding tag is assigned to the scalar.
first is a sequence of possible initial characters or None.
"""
... |
Add a path based resolver for the given tag. A path is a list of keys that forms a path to a node in the representation tree. Keys can be string values integers or None. | def add_path_resolver(tag, path, kind=None, Loader=Loader, Dumper=Dumper):
"""
Add a path based resolver for the given tag.
A path is a list of keys that forms a path
to a node in the representation tree.
Keys can be string values, integers, or None.
"""
Loader.add_path_resolver(tag, path, k... |
Convert a Python object to a representation node. | def to_yaml(cls, dumper, data):
"""
Convert a Python object to a representation node.
"""
return dumper.represent_yaml_object(cls.yaml_tag, data, cls,
flow_style=cls.yaml_flow_style) |
Serialize a sequence of representation trees into a YAML stream. If stream is None return the produced string instead. | def serialize_all(nodes, stream=None, Dumper=Dumper,
canonical=None, indent=None, width=None,
allow_unicode=None, line_break=None,
encoding=None, explicit_start=None, explicit_end=None,
version=None, tags=None):
"""
Serialize a sequence of representation trees into a YAML stream.... |
Do not produce empty tokens. | def something(TokenClass):
"""Do not produce empty tokens."""
def callback(lexer, match, context):
text = match.group()
if not text:
return
yield match.start(), TokenClass, text
context.pos = match.end()
return callback |
Set the previously saved indentation level. | def set_indent(TokenClass, implicit=False):
"""Set the previously saved indentation level."""
def callback(lexer, match, context):
text = match.group()
if context.indent < context.next_indent:
context.indent_stack.append(context.indent)
context.indent = context.next_inden... |
Process an empty line in a block scalar. | def parse_block_scalar_empty_line(IndentTokenClass, ContentTokenClass):
"""Process an empty line in a block scalar."""
def callback(lexer, match, context):
text = match.group()
if (context.block_scalar_indent is None or
len(text) <= context.block_scalar_indent):
if te... |
Process indentation spaces in a plain scalar. | def parse_plain_scalar_indent(TokenClass):
"""Process indentation spaces in a plain scalar."""
def callback(lexer, match, context):
text = match.group()
if len(text) <= context.indent:
context.stack.pop()
context.stack.pop()
return
if text:
... |
Collocation score | def score(count_bigram, count1, count2, n_words):
"""Collocation score"""
if n_words <= count1 or n_words <= count2:
# only one words appears in the whole document
return 0
N = n_words
c12 = count_bigram
c1 = count1
c2 = count2
p = c2 / N
p1 = c12 / c1
p2 = (c2 - c12)... |
Normalize cases and remove plurals. | def process_tokens(words, normalize_plurals=True):
"""Normalize cases and remove plurals.
Each word is represented by the most common case.
If a word appears with an "s" on the end and without an "s" on the end,
the version with "s" is assumed to be a plural and merged with the
version without "s" ... |
Returns a single_color_func associated with the word | def get_color_func(self, word):
"""Returns a single_color_func associated with the word"""
try:
color_func = next(
color_func for (color_func, words) in self.color_func_to_words
if word in words)
except StopIteration:
color_func = self.defa... |
Random hue color generation. | def random_color_func(word=None, font_size=None, position=None,
orientation=None, font_path=None, random_state=None):
"""Random hue color generation.
Default coloring method. This just picks a random hue with value 80% and
lumination 50%.
Parameters
----------
word, font_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.