repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
thieman/dagobah | dagobah/core/core.py | Dagobah.from_backend | def from_backend(self, dagobah_id):
""" Reconstruct this Dagobah instance from the backend. """
logger.debug('Reconstructing Dagobah instance from backend with ID {0}'.format(dagobah_id))
rec = self.backend.get_dagobah_json(dagobah_id)
if not rec:
raise DagobahError('dagobah with id %s does not exist '
'in backend' % dagobah_id)
self._construct_from_json(rec) | python | def from_backend(self, dagobah_id):
""" Reconstruct this Dagobah instance from the backend. """
logger.debug('Reconstructing Dagobah instance from backend with ID {0}'.format(dagobah_id))
rec = self.backend.get_dagobah_json(dagobah_id)
if not rec:
raise DagobahError('dagobah with id %s does not exist '
'in backend' % dagobah_id)
self._construct_from_json(rec) | [
"def",
"from_backend",
"(",
"self",
",",
"dagobah_id",
")",
":",
"logger",
".",
"debug",
"(",
"'Reconstructing Dagobah instance from backend with ID {0}'",
".",
"format",
"(",
"dagobah_id",
")",
")",
"rec",
"=",
"self",
".",
"backend",
".",
"get_dagobah_json",
"("... | Reconstruct this Dagobah instance from the backend. | [
"Reconstruct",
"this",
"Dagobah",
"instance",
"from",
"the",
"backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L70-L77 | train | 34,500 |
thieman/dagobah | dagobah/core/core.py | Dagobah._construct_from_json | def _construct_from_json(self, rec):
""" Construct this Dagobah instance from a JSON document. """
self.delete()
for required_key in ['dagobah_id', 'created_jobs']:
setattr(self, required_key, rec[required_key])
for job_json in rec.get('jobs', []):
self._add_job_from_spec(job_json)
self.commit(cascade=True) | python | def _construct_from_json(self, rec):
""" Construct this Dagobah instance from a JSON document. """
self.delete()
for required_key in ['dagobah_id', 'created_jobs']:
setattr(self, required_key, rec[required_key])
for job_json in rec.get('jobs', []):
self._add_job_from_spec(job_json)
self.commit(cascade=True) | [
"def",
"_construct_from_json",
"(",
"self",
",",
"rec",
")",
":",
"self",
".",
"delete",
"(",
")",
"for",
"required_key",
"in",
"[",
"'dagobah_id'",
",",
"'created_jobs'",
"]",
":",
"setattr",
"(",
"self",
",",
"required_key",
",",
"rec",
"[",
"required_ke... | Construct this Dagobah instance from a JSON document. | [
"Construct",
"this",
"Dagobah",
"instance",
"from",
"a",
"JSON",
"document",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L80-L91 | train | 34,501 |
thieman/dagobah | dagobah/core/core.py | Dagobah.add_job_from_json | def add_job_from_json(self, job_json, destructive=False):
""" Construct a new Job from an imported JSON spec. """
logger.debug('Importing job from JSON document: {0}'.format(job_json))
rec = self.backend.decode_import_json(job_json)
if destructive:
try:
self.delete_job(rec['name'])
except DagobahError: # expected if no job with this name
pass
self._add_job_from_spec(rec, use_job_id=False)
self.commit(cascade=True) | python | def add_job_from_json(self, job_json, destructive=False):
""" Construct a new Job from an imported JSON spec. """
logger.debug('Importing job from JSON document: {0}'.format(job_json))
rec = self.backend.decode_import_json(job_json)
if destructive:
try:
self.delete_job(rec['name'])
except DagobahError: # expected if no job with this name
pass
self._add_job_from_spec(rec, use_job_id=False)
self.commit(cascade=True) | [
"def",
"add_job_from_json",
"(",
"self",
",",
"job_json",
",",
"destructive",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"'Importing job from JSON document: {0}'",
".",
"format",
"(",
"job_json",
")",
")",
"rec",
"=",
"self",
".",
"backend",
".",
"... | Construct a new Job from an imported JSON spec. | [
"Construct",
"a",
"new",
"Job",
"from",
"an",
"imported",
"JSON",
"spec",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L94-L105 | train | 34,502 |
thieman/dagobah | dagobah/core/core.py | Dagobah._add_job_from_spec | def _add_job_from_spec(self, job_json, use_job_id=True):
""" Add a single job to the Dagobah from a spec. """
job_id = (job_json['job_id']
if use_job_id
else self.backend.get_new_job_id())
self.add_job(str(job_json['name']), job_id)
job = self.get_job(job_json['name'])
if job_json.get('cron_schedule', None):
job.schedule(job_json['cron_schedule'])
for task in job_json.get('tasks', []):
self.add_task_to_job(job,
str(task['command']),
str(task['name']),
soft_timeout=task.get('soft_timeout', 0),
hard_timeout=task.get('hard_timeout', 0),
hostname=task.get('hostname', None))
dependencies = job_json.get('dependencies', {})
for from_node, to_nodes in dependencies.iteritems():
for to_node in to_nodes:
job.add_dependency(from_node, to_node)
if job_json.get('notes', None):
job.update_job_notes(job_json['notes']) | python | def _add_job_from_spec(self, job_json, use_job_id=True):
""" Add a single job to the Dagobah from a spec. """
job_id = (job_json['job_id']
if use_job_id
else self.backend.get_new_job_id())
self.add_job(str(job_json['name']), job_id)
job = self.get_job(job_json['name'])
if job_json.get('cron_schedule', None):
job.schedule(job_json['cron_schedule'])
for task in job_json.get('tasks', []):
self.add_task_to_job(job,
str(task['command']),
str(task['name']),
soft_timeout=task.get('soft_timeout', 0),
hard_timeout=task.get('hard_timeout', 0),
hostname=task.get('hostname', None))
dependencies = job_json.get('dependencies', {})
for from_node, to_nodes in dependencies.iteritems():
for to_node in to_nodes:
job.add_dependency(from_node, to_node)
if job_json.get('notes', None):
job.update_job_notes(job_json['notes']) | [
"def",
"_add_job_from_spec",
"(",
"self",
",",
"job_json",
",",
"use_job_id",
"=",
"True",
")",
":",
"job_id",
"=",
"(",
"job_json",
"[",
"'job_id'",
"]",
"if",
"use_job_id",
"else",
"self",
".",
"backend",
".",
"get_new_job_id",
"(",
")",
")",
"self",
"... | Add a single job to the Dagobah from a spec. | [
"Add",
"a",
"single",
"job",
"to",
"the",
"Dagobah",
"from",
"a",
"spec",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L108-L133 | train | 34,503 |
thieman/dagobah | dagobah/core/core.py | Dagobah.commit | def commit(self, cascade=False):
""" Commit this Dagobah instance to the backend.
If cascade is True, all child Jobs are commited as well.
"""
logger.debug('Committing Dagobah instance with cascade={0}'.format(cascade))
self.backend.commit_dagobah(self._serialize())
if cascade:
[job.commit() for job in self.jobs] | python | def commit(self, cascade=False):
""" Commit this Dagobah instance to the backend.
If cascade is True, all child Jobs are commited as well.
"""
logger.debug('Committing Dagobah instance with cascade={0}'.format(cascade))
self.backend.commit_dagobah(self._serialize())
if cascade:
[job.commit() for job in self.jobs] | [
"def",
"commit",
"(",
"self",
",",
"cascade",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"'Committing Dagobah instance with cascade={0}'",
".",
"format",
"(",
"cascade",
")",
")",
"self",
".",
"backend",
".",
"commit_dagobah",
"(",
"self",
".",
"_s... | Commit this Dagobah instance to the backend.
If cascade is True, all child Jobs are commited as well. | [
"Commit",
"this",
"Dagobah",
"instance",
"to",
"the",
"backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L137-L145 | train | 34,504 |
thieman/dagobah | dagobah/core/core.py | Dagobah.delete | def delete(self):
""" Delete this Dagobah instance from the Backend. """
logger.debug('Deleting Dagobah instance with ID {0}'.format(self.dagobah_id))
self.jobs = []
self.created_jobs = 0
self.backend.delete_dagobah(self.dagobah_id) | python | def delete(self):
""" Delete this Dagobah instance from the Backend. """
logger.debug('Deleting Dagobah instance with ID {0}'.format(self.dagobah_id))
self.jobs = []
self.created_jobs = 0
self.backend.delete_dagobah(self.dagobah_id) | [
"def",
"delete",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting Dagobah instance with ID {0}'",
".",
"format",
"(",
"self",
".",
"dagobah_id",
")",
")",
"self",
".",
"jobs",
"=",
"[",
"]",
"self",
".",
"created_jobs",
"=",
"0",
"self",
".... | Delete this Dagobah instance from the Backend. | [
"Delete",
"this",
"Dagobah",
"instance",
"from",
"the",
"Backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L148-L153 | train | 34,505 |
thieman/dagobah | dagobah/core/core.py | Dagobah.add_job | def add_job(self, job_name, job_id=None):
""" Create a new, empty Job. """
logger.debug('Creating a new job named {0}'.format(job_name))
if not self._name_is_available(job_name):
raise DagobahError('name %s is not available' % job_name)
if not job_id:
job_id = self.backend.get_new_job_id()
self.created_jobs += 1
self.jobs.append(Job(self,
self.backend,
job_id,
job_name))
job = self.get_job(job_name)
job.commit() | python | def add_job(self, job_name, job_id=None):
""" Create a new, empty Job. """
logger.debug('Creating a new job named {0}'.format(job_name))
if not self._name_is_available(job_name):
raise DagobahError('name %s is not available' % job_name)
if not job_id:
job_id = self.backend.get_new_job_id()
self.created_jobs += 1
self.jobs.append(Job(self,
self.backend,
job_id,
job_name))
job = self.get_job(job_name)
job.commit() | [
"def",
"add_job",
"(",
"self",
",",
"job_name",
",",
"job_id",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Creating a new job named {0}'",
".",
"format",
"(",
"job_name",
")",
")",
"if",
"not",
"self",
".",
"_name_is_available",
"(",
"job_name",
... | Create a new, empty Job. | [
"Create",
"a",
"new",
"empty",
"Job",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L156-L172 | train | 34,506 |
thieman/dagobah | dagobah/core/core.py | Dagobah.get_host | def get_host(self, hostname):
""" Returns a Host dict with config options, or None if none exists"""
if hostname in self.get_hosts():
return self.load_ssh_conf().lookup(hostname)
logger.warn('Tried to find host with name {0}, but host not found'.format(hostname))
return None | python | def get_host(self, hostname):
""" Returns a Host dict with config options, or None if none exists"""
if hostname in self.get_hosts():
return self.load_ssh_conf().lookup(hostname)
logger.warn('Tried to find host with name {0}, but host not found'.format(hostname))
return None | [
"def",
"get_host",
"(",
"self",
",",
"hostname",
")",
":",
"if",
"hostname",
"in",
"self",
".",
"get_hosts",
"(",
")",
":",
"return",
"self",
".",
"load_ssh_conf",
"(",
")",
".",
"lookup",
"(",
"hostname",
")",
"logger",
".",
"warn",
"(",
"'Tried to fi... | Returns a Host dict with config options, or None if none exists | [
"Returns",
"a",
"Host",
"dict",
"with",
"config",
"options",
"or",
"None",
"if",
"none",
"exists"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L205-L210 | train | 34,507 |
thieman/dagobah | dagobah/core/core.py | Dagobah.get_job | def get_job(self, job_name):
""" Returns a Job by name, or None if none exists. """
for job in self.jobs:
if job.name == job_name:
return job
logger.warn('Tried to find job with name {0}, but job not found'.format(job_name))
return None | python | def get_job(self, job_name):
""" Returns a Job by name, or None if none exists. """
for job in self.jobs:
if job.name == job_name:
return job
logger.warn('Tried to find job with name {0}, but job not found'.format(job_name))
return None | [
"def",
"get_job",
"(",
"self",
",",
"job_name",
")",
":",
"for",
"job",
"in",
"self",
".",
"jobs",
":",
"if",
"job",
".",
"name",
"==",
"job_name",
":",
"return",
"job",
"logger",
".",
"warn",
"(",
"'Tried to find job with name {0}, but job not found'",
".",... | Returns a Job by name, or None if none exists. | [
"Returns",
"a",
"Job",
"by",
"name",
"or",
"None",
"if",
"none",
"exists",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L212-L218 | train | 34,508 |
thieman/dagobah | dagobah/core/core.py | Dagobah.delete_job | def delete_job(self, job_name):
""" Delete a job by name, or error out if no such job exists. """
logger.debug('Deleting job {0}'.format(job_name))
for idx, job in enumerate(self.jobs):
if job.name == job_name:
self.backend.delete_job(job.job_id)
del self.jobs[idx]
self.commit()
return
raise DagobahError('no job with name %s exists' % job_name) | python | def delete_job(self, job_name):
""" Delete a job by name, or error out if no such job exists. """
logger.debug('Deleting job {0}'.format(job_name))
for idx, job in enumerate(self.jobs):
if job.name == job_name:
self.backend.delete_job(job.job_id)
del self.jobs[idx]
self.commit()
return
raise DagobahError('no job with name %s exists' % job_name) | [
"def",
"delete_job",
"(",
"self",
",",
"job_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting job {0}'",
".",
"format",
"(",
"job_name",
")",
")",
"for",
"idx",
",",
"job",
"in",
"enumerate",
"(",
"self",
".",
"jobs",
")",
":",
"if",
"job",
".... | Delete a job by name, or error out if no such job exists. | [
"Delete",
"a",
"job",
"by",
"name",
"or",
"error",
"out",
"if",
"no",
"such",
"job",
"exists",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L221-L230 | train | 34,509 |
thieman/dagobah | dagobah/core/core.py | Dagobah.add_task_to_job | def add_task_to_job(self, job_or_job_name, task_command, task_name=None,
**kwargs):
""" Add a task to a job owned by the Dagobah instance. """
if isinstance(job_or_job_name, Job):
job = job_or_job_name
else:
job = self.get_job(job_or_job_name)
if not job:
raise DagobahError('job %s does not exist' % job_or_job_name)
logger.debug('Adding task with command {0} to job {1}'.format(task_command, job.name))
if not job.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current " +
"state: %s"
% job.state.status)
job.add_task(task_command, task_name, **kwargs)
job.commit() | python | def add_task_to_job(self, job_or_job_name, task_command, task_name=None,
**kwargs):
""" Add a task to a job owned by the Dagobah instance. """
if isinstance(job_or_job_name, Job):
job = job_or_job_name
else:
job = self.get_job(job_or_job_name)
if not job:
raise DagobahError('job %s does not exist' % job_or_job_name)
logger.debug('Adding task with command {0} to job {1}'.format(task_command, job.name))
if not job.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current " +
"state: %s"
% job.state.status)
job.add_task(task_command, task_name, **kwargs)
job.commit() | [
"def",
"add_task_to_job",
"(",
"self",
",",
"job_or_job_name",
",",
"task_command",
",",
"task_name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"job_or_job_name",
",",
"Job",
")",
":",
"job",
"=",
"job_or_job_name",
"else",
"... | Add a task to a job owned by the Dagobah instance. | [
"Add",
"a",
"task",
"to",
"a",
"job",
"owned",
"by",
"the",
"Dagobah",
"instance",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L233-L253 | train | 34,510 |
thieman/dagobah | dagobah/core/core.py | Dagobah._name_is_available | def _name_is_available(self, job_name):
""" Returns Boolean of whether the specified name is already in use. """
return (False
if [job for job in self.jobs if job.name == job_name]
else True) | python | def _name_is_available(self, job_name):
""" Returns Boolean of whether the specified name is already in use. """
return (False
if [job for job in self.jobs if job.name == job_name]
else True) | [
"def",
"_name_is_available",
"(",
"self",
",",
"job_name",
")",
":",
"return",
"(",
"False",
"if",
"[",
"job",
"for",
"job",
"in",
"self",
".",
"jobs",
"if",
"job",
".",
"name",
"==",
"job_name",
"]",
"else",
"True",
")"
] | Returns Boolean of whether the specified name is already in use. | [
"Returns",
"Boolean",
"of",
"whether",
"the",
"specified",
"name",
"is",
"already",
"in",
"use",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L255-L259 | train | 34,511 |
thieman/dagobah | dagobah/core/core.py | Dagobah._serialize | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Dagobah object to JSON. """
result = {'dagobah_id': self.dagobah_id,
'created_jobs': self.created_jobs,
'jobs': [job._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for job in self.jobs]}
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | python | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Dagobah object to JSON. """
result = {'dagobah_id': self.dagobah_id,
'created_jobs': self.created_jobs,
'jobs': [job._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for job in self.jobs]}
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | [
"def",
"_serialize",
"(",
"self",
",",
"include_run_logs",
"=",
"False",
",",
"strict_json",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'dagobah_id'",
":",
"self",
".",
"dagobah_id",
",",
"'created_jobs'",
":",
"self",
".",
"created_jobs",
",",
"'jobs'",
... | Serialize a representation of this Dagobah object to JSON. | [
"Serialize",
"a",
"representation",
"of",
"this",
"Dagobah",
"object",
"to",
"JSON",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L262-L271 | train | 34,512 |
thieman/dagobah | dagobah/core/core.py | Job.commit | def commit(self):
""" Store metadata on this Job to the backend. """
logger.debug('Committing job {0}'.format(self.name))
self.backend.commit_job(self._serialize())
self.parent.commit() | python | def commit(self):
""" Store metadata on this Job to the backend. """
logger.debug('Committing job {0}'.format(self.name))
self.backend.commit_job(self._serialize())
self.parent.commit() | [
"def",
"commit",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Committing job {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"backend",
".",
"commit_job",
"(",
"self",
".",
"_serialize",
"(",
")",
")",
"self",
".",
"pa... | Store metadata on this Job to the backend. | [
"Store",
"metadata",
"on",
"this",
"Job",
"to",
"the",
"backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L313-L317 | train | 34,513 |
thieman/dagobah | dagobah/core/core.py | Job.add_task | def add_task(self, command, name=None, **kwargs):
""" Adds a new Task to the graph with no edges. """
logger.debug('Adding task with command {0} to job {1}'.format(command, self.name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
if name is None:
name = command
new_task = Task(self, command, name, **kwargs)
self.tasks[name] = new_task
self.add_node(name)
self.commit() | python | def add_task(self, command, name=None, **kwargs):
""" Adds a new Task to the graph with no edges. """
logger.debug('Adding task with command {0} to job {1}'.format(command, self.name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
if name is None:
name = command
new_task = Task(self, command, name, **kwargs)
self.tasks[name] = new_task
self.add_node(name)
self.commit() | [
"def",
"add_task",
"(",
"self",
",",
"command",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding task with command {0} to job {1}'",
".",
"format",
"(",
"command",
",",
"self",
".",
"name",
")",
")",
"if"... | Adds a new Task to the graph with no edges. | [
"Adds",
"a",
"new",
"Task",
"to",
"the",
"graph",
"with",
"no",
"edges",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L320-L333 | train | 34,514 |
thieman/dagobah | dagobah/core/core.py | Job.add_dependency | def add_dependency(self, from_task_name, to_task_name):
""" Add a dependency between two tasks. """
logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
self.add_edge(from_task_name, to_task_name)
self.commit() | python | def add_dependency(self, from_task_name, to_task_name):
""" Add a dependency between two tasks. """
logger.debug('Adding dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
self.add_edge(from_task_name, to_task_name)
self.commit() | [
"def",
"add_dependency",
"(",
"self",
",",
"from_task_name",
",",
"to_task_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Adding dependency from {0} to {1}'",
".",
"format",
"(",
"from_task_name",
",",
"to_task_name",
")",
")",
"if",
"not",
"self",
".",
"state"... | Add a dependency between two tasks. | [
"Add",
"a",
"dependency",
"between",
"two",
"tasks",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L336-L345 | train | 34,515 |
thieman/dagobah | dagobah/core/core.py | Job.delete_task | def delete_task(self, task_name):
""" Deletes the named Task in this Job. """
logger.debug('Deleting task {0}'.format(task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
if task_name not in self.tasks:
raise DagobahError('task %s does not exist' % task_name)
self.tasks.pop(task_name)
self.delete_node(task_name)
self.commit() | python | def delete_task(self, task_name):
""" Deletes the named Task in this Job. """
logger.debug('Deleting task {0}'.format(task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
if task_name not in self.tasks:
raise DagobahError('task %s does not exist' % task_name)
self.tasks.pop(task_name)
self.delete_node(task_name)
self.commit() | [
"def",
"delete_task",
"(",
"self",
",",
"task_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting task {0}'",
".",
"format",
"(",
"task_name",
")",
")",
"if",
"not",
"self",
".",
"state",
".",
"allow_change_graph",
":",
"raise",
"DagobahError",
"(",
"... | Deletes the named Task in this Job. | [
"Deletes",
"the",
"named",
"Task",
"in",
"this",
"Job",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L348-L361 | train | 34,516 |
thieman/dagobah | dagobah/core/core.py | Job.delete_dependency | def delete_dependency(self, from_task_name, to_task_name):
""" Delete a dependency between two tasks. """
logger.debug('Deleting dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
self.delete_edge(from_task_name, to_task_name)
self.commit() | python | def delete_dependency(self, from_task_name, to_task_name):
""" Delete a dependency between two tasks. """
logger.debug('Deleting dependency from {0} to {1}'.format(from_task_name, to_task_name))
if not self.state.allow_change_graph:
raise DagobahError("job's graph is immutable in its current state: %s"
% self.state.status)
self.delete_edge(from_task_name, to_task_name)
self.commit() | [
"def",
"delete_dependency",
"(",
"self",
",",
"from_task_name",
",",
"to_task_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Deleting dependency from {0} to {1}'",
".",
"format",
"(",
"from_task_name",
",",
"to_task_name",
")",
")",
"if",
"not",
"self",
".",
"s... | Delete a dependency between two tasks. | [
"Delete",
"a",
"dependency",
"between",
"two",
"tasks",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L364-L373 | train | 34,517 |
thieman/dagobah | dagobah/core/core.py | Job.schedule | def schedule(self, cron_schedule, base_datetime=None):
""" Schedules the job to run periodically using Cron syntax. """
logger.debug('Scheduling job {0} with cron schedule {1}'.format(self.name, cron_schedule))
if not self.state.allow_change_schedule:
raise DagobahError("job's schedule cannot be changed in state: %s"
% self.state.status)
if cron_schedule is None:
self.cron_schedule = None
self.cron_iter = None
self.next_run = None
else:
if base_datetime is None:
base_datetime = datetime.utcnow()
self.cron_schedule = cron_schedule
self.cron_iter = croniter(cron_schedule, base_datetime)
self.next_run = self.cron_iter.get_next(datetime)
logger.debug('Determined job {0} next run of {1}'.format(self.name, self.next_run))
self.commit() | python | def schedule(self, cron_schedule, base_datetime=None):
""" Schedules the job to run periodically using Cron syntax. """
logger.debug('Scheduling job {0} with cron schedule {1}'.format(self.name, cron_schedule))
if not self.state.allow_change_schedule:
raise DagobahError("job's schedule cannot be changed in state: %s"
% self.state.status)
if cron_schedule is None:
self.cron_schedule = None
self.cron_iter = None
self.next_run = None
else:
if base_datetime is None:
base_datetime = datetime.utcnow()
self.cron_schedule = cron_schedule
self.cron_iter = croniter(cron_schedule, base_datetime)
self.next_run = self.cron_iter.get_next(datetime)
logger.debug('Determined job {0} next run of {1}'.format(self.name, self.next_run))
self.commit() | [
"def",
"schedule",
"(",
"self",
",",
"cron_schedule",
",",
"base_datetime",
"=",
"None",
")",
":",
"logger",
".",
"debug",
"(",
"'Scheduling job {0} with cron schedule {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"cron_schedule",
")",
")",
"if",
"not",... | Schedules the job to run periodically using Cron syntax. | [
"Schedules",
"the",
"job",
"to",
"run",
"periodically",
"using",
"Cron",
"syntax",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L376-L397 | train | 34,518 |
thieman/dagobah | dagobah/core/core.py | Job.start | def start(self):
""" Begins the job by kicking off all tasks with no dependencies. """
logger.info('Job {0} starting job run'.format(self.name))
if not self.state.allow_start:
raise DagobahError('job cannot be started in its current state; ' +
'it is probably already running')
self.initialize_snapshot()
# don't increment if the job was run manually
if self.cron_iter and datetime.utcnow() > self.next_run:
self.next_run = self.cron_iter.get_next(datetime)
self.run_log = {'job_id': self.job_id,
'name': self.name,
'parent_id': self.parent.dagobah_id,
'log_id': self.backend.get_new_log_id(),
'start_time': datetime.utcnow(),
'tasks': {}}
self._set_status('running')
logger.debug('Job {0} resetting all tasks prior to start'.format(self.name))
for task in self.tasks.itervalues():
task.reset()
logger.debug('Job {0} seeding run logs'.format(self.name))
for task_name in self.ind_nodes(self.snapshot):
self._put_task_in_run_log(task_name)
self.tasks[task_name].start()
self._commit_run_log() | python | def start(self):
""" Begins the job by kicking off all tasks with no dependencies. """
logger.info('Job {0} starting job run'.format(self.name))
if not self.state.allow_start:
raise DagobahError('job cannot be started in its current state; ' +
'it is probably already running')
self.initialize_snapshot()
# don't increment if the job was run manually
if self.cron_iter and datetime.utcnow() > self.next_run:
self.next_run = self.cron_iter.get_next(datetime)
self.run_log = {'job_id': self.job_id,
'name': self.name,
'parent_id': self.parent.dagobah_id,
'log_id': self.backend.get_new_log_id(),
'start_time': datetime.utcnow(),
'tasks': {}}
self._set_status('running')
logger.debug('Job {0} resetting all tasks prior to start'.format(self.name))
for task in self.tasks.itervalues():
task.reset()
logger.debug('Job {0} seeding run logs'.format(self.name))
for task_name in self.ind_nodes(self.snapshot):
self._put_task_in_run_log(task_name)
self.tasks[task_name].start()
self._commit_run_log() | [
"def",
"start",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} starting job run'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"not",
"self",
".",
"state",
".",
"allow_start",
":",
"raise",
"DagobahError",
"(",
"'job cannot be st... | Begins the job by kicking off all tasks with no dependencies. | [
"Begins",
"the",
"job",
"by",
"kicking",
"off",
"all",
"tasks",
"with",
"no",
"dependencies",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L400-L431 | train | 34,519 |
thieman/dagobah | dagobah/core/core.py | Job.retry | def retry(self):
""" Restarts failed tasks of a job. """
logger.info('Job {0} retrying all failed tasks'.format(self.name))
self.initialize_snapshot()
failed_task_names = []
for task_name, log in self.run_log['tasks'].items():
if log.get('success', True) == False:
failed_task_names.append(task_name)
if len(failed_task_names) == 0:
raise DagobahError('no failed tasks to retry')
self._set_status('running')
self.run_log['last_retry_time'] = datetime.utcnow()
logger.debug('Job {0} seeding run logs'.format(self.name))
for task_name in failed_task_names:
self._put_task_in_run_log(task_name)
self.tasks[task_name].start()
self._commit_run_log() | python | def retry(self):
""" Restarts failed tasks of a job. """
logger.info('Job {0} retrying all failed tasks'.format(self.name))
self.initialize_snapshot()
failed_task_names = []
for task_name, log in self.run_log['tasks'].items():
if log.get('success', True) == False:
failed_task_names.append(task_name)
if len(failed_task_names) == 0:
raise DagobahError('no failed tasks to retry')
self._set_status('running')
self.run_log['last_retry_time'] = datetime.utcnow()
logger.debug('Job {0} seeding run logs'.format(self.name))
for task_name in failed_task_names:
self._put_task_in_run_log(task_name)
self.tasks[task_name].start()
self._commit_run_log() | [
"def",
"retry",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} retrying all failed tasks'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"initialize_snapshot",
"(",
")",
"failed_task_names",
"=",
"[",
"]",
"for",
"task_name",... | Restarts failed tasks of a job. | [
"Restarts",
"failed",
"tasks",
"of",
"a",
"job",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L434-L456 | train | 34,520 |
thieman/dagobah | dagobah/core/core.py | Job.terminate_all | def terminate_all(self):
""" Terminate all currently running tasks. """
logger.info('Job {0} terminating all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.terminate() | python | def terminate_all(self):
""" Terminate all currently running tasks. """
logger.info('Job {0} terminating all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.terminate() | [
"def",
"terminate_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} terminating all currently running tasks'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
".",
"itervalues",
"(",
")",
":",
... | Terminate all currently running tasks. | [
"Terminate",
"all",
"currently",
"running",
"tasks",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L459-L464 | train | 34,521 |
thieman/dagobah | dagobah/core/core.py | Job.kill_all | def kill_all(self):
""" Kill all currently running jobs. """
logger.info('Job {0} killing all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.kill() | python | def kill_all(self):
""" Kill all currently running jobs. """
logger.info('Job {0} killing all currently running tasks'.format(self.name))
for task in self.tasks.itervalues():
if task.started_at and not task.completed_at:
task.kill() | [
"def",
"kill_all",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Job {0} killing all currently running tasks'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"for",
"task",
"in",
"self",
".",
"tasks",
".",
"itervalues",
"(",
")",
":",
"if",
"... | Kill all currently running jobs. | [
"Kill",
"all",
"currently",
"running",
"jobs",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L467-L472 | train | 34,522 |
thieman/dagobah | dagobah/core/core.py | Job.edit | def edit(self, **kwargs):
""" Change this Job's name.
This will affect the historical data available for this
Job, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} changing name to {1}'.format(self.name, kwargs.get('name')))
if not self.state.allow_edit_job:
raise DagobahError('job cannot be edited in its current state')
if 'name' in kwargs and isinstance(kwargs['name'], str):
if not self.parent._name_is_available(kwargs['name']):
raise DagobahError('new job name %s is not available' %
kwargs['name'])
for key in ['name']:
if key in kwargs and isinstance(kwargs[key], str):
setattr(self, key, kwargs[key])
self.parent.commit(cascade=True) | python | def edit(self, **kwargs):
""" Change this Job's name.
This will affect the historical data available for this
Job, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} changing name to {1}'.format(self.name, kwargs.get('name')))
if not self.state.allow_edit_job:
raise DagobahError('job cannot be edited in its current state')
if 'name' in kwargs and isinstance(kwargs['name'], str):
if not self.parent._name_is_available(kwargs['name']):
raise DagobahError('new job name %s is not available' %
kwargs['name'])
for key in ['name']:
if key in kwargs and isinstance(kwargs[key], str):
setattr(self, key, kwargs[key])
self.parent.commit(cascade=True) | [
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} changing name to {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"kwargs",
".",
"get",
"(",
"'name'",
")",
")",
")",
"if",
"not",
"self",
".",
... | Change this Job's name.
This will affect the historical data available for this
Job, e.g. past run logs will no longer be accessible. | [
"Change",
"this",
"Job",
"s",
"name",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L475-L495 | train | 34,523 |
thieman/dagobah | dagobah/core/core.py | Job.edit_task | def edit_task(self, task_name, **kwargs):
""" Change the name of a Task owned by this Job.
This will affect the historical data available for this
Task, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} editing task {1}'.format(self.name, task_name))
if not self.state.allow_edit_task:
raise DagobahError("tasks cannot be edited in this job's " +
"current state")
if task_name not in self.tasks:
raise DagobahError('task %s not found' % task_name)
if 'name' in kwargs and isinstance(kwargs['name'], str):
if kwargs['name'] in self.tasks:
raise DagobahError('task name %s is unavailable' %
kwargs['name'])
task = self.tasks[task_name]
for key in ['name', 'command']:
if key in kwargs and isinstance(kwargs[key], str):
setattr(task, key, kwargs[key])
if 'soft_timeout' in kwargs:
task.set_soft_timeout(kwargs['soft_timeout'])
if 'hard_timeout' in kwargs:
task.set_hard_timeout(kwargs['hard_timeout'])
if 'hostname' in kwargs:
task.set_hostname(kwargs['hostname'])
if 'name' in kwargs and isinstance(kwargs['name'], str):
self.rename_edges(task_name, kwargs['name'])
self.tasks[kwargs['name']] = task
del self.tasks[task_name]
self.parent.commit(cascade=True) | python | def edit_task(self, task_name, **kwargs):
""" Change the name of a Task owned by this Job.
This will affect the historical data available for this
Task, e.g. past run logs will no longer be accessible.
"""
logger.debug('Job {0} editing task {1}'.format(self.name, task_name))
if not self.state.allow_edit_task:
raise DagobahError("tasks cannot be edited in this job's " +
"current state")
if task_name not in self.tasks:
raise DagobahError('task %s not found' % task_name)
if 'name' in kwargs and isinstance(kwargs['name'], str):
if kwargs['name'] in self.tasks:
raise DagobahError('task name %s is unavailable' %
kwargs['name'])
task = self.tasks[task_name]
for key in ['name', 'command']:
if key in kwargs and isinstance(kwargs[key], str):
setattr(task, key, kwargs[key])
if 'soft_timeout' in kwargs:
task.set_soft_timeout(kwargs['soft_timeout'])
if 'hard_timeout' in kwargs:
task.set_hard_timeout(kwargs['hard_timeout'])
if 'hostname' in kwargs:
task.set_hostname(kwargs['hostname'])
if 'name' in kwargs and isinstance(kwargs['name'], str):
self.rename_edges(task_name, kwargs['name'])
self.tasks[kwargs['name']] = task
del self.tasks[task_name]
self.parent.commit(cascade=True) | [
"def",
"edit_task",
"(",
"self",
",",
"task_name",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} editing task {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"task_name",
")",
")",
"if",
"not",
"self",
".",
"state",
"."... | Change the name of a Task owned by this Job.
This will affect the historical data available for this
Task, e.g. past run logs will no longer be accessible. | [
"Change",
"the",
"name",
"of",
"a",
"Task",
"owned",
"by",
"this",
"Job",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L508-L547 | train | 34,524 |
thieman/dagobah | dagobah/core/core.py | Job._complete_task | def _complete_task(self, task_name, **kwargs):
""" Marks this task as completed. Kwargs are stored in the run log. """
logger.debug('Job {0} marking task {1} as completed'.format(self.name, task_name))
self.run_log['tasks'][task_name] = kwargs
for node in self.downstream(task_name, self.snapshot):
self._start_if_ready(node)
try:
self.backend.acquire_lock()
self._commit_run_log()
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
if kwargs.get('success', None) == False:
task = self.tasks[task_name]
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('task_failed',
task._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
self._on_completion() | python | def _complete_task(self, task_name, **kwargs):
""" Marks this task as completed. Kwargs are stored in the run log. """
logger.debug('Job {0} marking task {1} as completed'.format(self.name, task_name))
self.run_log['tasks'][task_name] = kwargs
for node in self.downstream(task_name, self.snapshot):
self._start_if_ready(node)
try:
self.backend.acquire_lock()
self._commit_run_log()
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
if kwargs.get('success', None) == False:
task = self.tasks[task_name]
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('task_failed',
task._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
self._on_completion() | [
"def",
"_complete_task",
"(",
"self",
",",
"task_name",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} marking task {1} as completed'",
".",
"format",
"(",
"self",
".",
"name",
",",
"task_name",
")",
")",
"self",
".",
"run_log",
... | Marks this task as completed. Kwargs are stored in the run log. | [
"Marks",
"this",
"task",
"as",
"completed",
".",
"Kwargs",
"are",
"stored",
"in",
"the",
"run",
"log",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L550-L579 | train | 34,525 |
thieman/dagobah | dagobah/core/core.py | Job._put_task_in_run_log | def _put_task_in_run_log(self, task_name):
""" Initializes the run log task entry for this task. """
logger.debug('Job {0} initializing run log entry for task {1}'.format(self.name, task_name))
data = {'start_time': datetime.utcnow(),
'command': self.tasks[task_name].command}
self.run_log['tasks'][task_name] = data | python | def _put_task_in_run_log(self, task_name):
""" Initializes the run log task entry for this task. """
logger.debug('Job {0} initializing run log entry for task {1}'.format(self.name, task_name))
data = {'start_time': datetime.utcnow(),
'command': self.tasks[task_name].command}
self.run_log['tasks'][task_name] = data | [
"def",
"_put_task_in_run_log",
"(",
"self",
",",
"task_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} initializing run log entry for task {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"task_name",
")",
")",
"data",
"=",
"{",
"'start_time'",
":",
... | Initializes the run log task entry for this task. | [
"Initializes",
"the",
"run",
"log",
"task",
"entry",
"for",
"this",
"task",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L582-L587 | train | 34,526 |
thieman/dagobah | dagobah/core/core.py | Job._on_completion | def _on_completion(self):
""" Checks to see if the Job has completed, and cleans up if it has. """
logger.debug('Job {0} running _on_completion check'.format(self.name))
if self.state.status != 'running' or (not self._is_complete()):
return
for job, results in self.run_log['tasks'].iteritems():
if results.get('success', False) == False:
self._set_status('failed')
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('job_failed',
self._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
break
if self.state.status != 'failed':
self._set_status('waiting')
self.run_log = {}
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('job_complete',
self._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
self.destroy_snapshot() | python | def _on_completion(self):
""" Checks to see if the Job has completed, and cleans up if it has. """
logger.debug('Job {0} running _on_completion check'.format(self.name))
if self.state.status != 'running' or (not self._is_complete()):
return
for job, results in self.run_log['tasks'].iteritems():
if results.get('success', False) == False:
self._set_status('failed')
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('job_failed',
self._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
break
if self.state.status != 'failed':
self._set_status('waiting')
self.run_log = {}
try:
self.backend.acquire_lock()
if self.event_handler:
self.event_handler.emit('job_complete',
self._serialize(include_run_logs=True))
except:
logger.exception("Error in handling events.")
finally:
self.backend.release_lock()
self.destroy_snapshot() | [
"def",
"_on_completion",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} running _on_completion check'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"self",
".",
"state",
".",
"status",
"!=",
"'running'",
"or",
"(",
"not",
"self"... | Checks to see if the Job has completed, and cleans up if it has. | [
"Checks",
"to",
"see",
"if",
"the",
"Job",
"has",
"completed",
"and",
"cleans",
"up",
"if",
"it",
"has",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L597-L631 | train | 34,527 |
thieman/dagobah | dagobah/core/core.py | Job._start_if_ready | def _start_if_ready(self, task_name):
""" Start this task if all its dependencies finished successfully. """
logger.debug('Job {0} running _start_if_ready for task {1}'.format(self.name, task_name))
task = self.tasks[task_name]
dependencies = self._dependencies(task_name, self.snapshot)
for dependency in dependencies:
if self.run_log['tasks'].get(dependency, {}).get('success', False) == True:
continue
return
self._put_task_in_run_log(task_name)
task.start() | python | def _start_if_ready(self, task_name):
""" Start this task if all its dependencies finished successfully. """
logger.debug('Job {0} running _start_if_ready for task {1}'.format(self.name, task_name))
task = self.tasks[task_name]
dependencies = self._dependencies(task_name, self.snapshot)
for dependency in dependencies:
if self.run_log['tasks'].get(dependency, {}).get('success', False) == True:
continue
return
self._put_task_in_run_log(task_name)
task.start() | [
"def",
"_start_if_ready",
"(",
"self",
",",
"task_name",
")",
":",
"logger",
".",
"debug",
"(",
"'Job {0} running _start_if_ready for task {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"task_name",
")",
")",
"task",
"=",
"self",
".",
"tasks",
"[",
"ta... | Start this task if all its dependencies finished successfully. | [
"Start",
"this",
"task",
"if",
"all",
"its",
"dependencies",
"finished",
"successfully",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L634-L644 | train | 34,528 |
thieman/dagobah | dagobah/core/core.py | Job._commit_run_log | def _commit_run_log(self):
"""" Commit the current run log to the backend. """
logger.debug('Committing run log for job {0}'.format(self.name))
self.backend.commit_log(self.run_log) | python | def _commit_run_log(self):
"""" Commit the current run log to the backend. """
logger.debug('Committing run log for job {0}'.format(self.name))
self.backend.commit_log(self.run_log) | [
"def",
"_commit_run_log",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Committing run log for job {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"backend",
".",
"commit_log",
"(",
"self",
".",
"run_log",
")"
] | Commit the current run log to the backend. | [
"Commit",
"the",
"current",
"run",
"log",
"to",
"the",
"backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L655-L658 | train | 34,529 |
thieman/dagobah | dagobah/core/core.py | Job._serialize | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Job to a Python dict object. """
# return tasks in sorted order if graph is in a valid state
try:
topo_sorted = self.topological_sort()
t = [self.tasks[task]._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for task in topo_sorted]
except:
t = [task._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for task in self.tasks.itervalues()]
dependencies = {}
for k, v in self.graph.iteritems():
dependencies[k] = list(v)
result = {'job_id': self.job_id,
'name': self.name,
'parent_id': self.parent.dagobah_id,
'tasks': t,
'dependencies': dependencies,
'status': self.state.status,
'cron_schedule': self.cron_schedule,
'next_run': self.next_run,
'notes': self.notes}
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | python | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Job to a Python dict object. """
# return tasks in sorted order if graph is in a valid state
try:
topo_sorted = self.topological_sort()
t = [self.tasks[task]._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for task in topo_sorted]
except:
t = [task._serialize(include_run_logs=include_run_logs,
strict_json=strict_json)
for task in self.tasks.itervalues()]
dependencies = {}
for k, v in self.graph.iteritems():
dependencies[k] = list(v)
result = {'job_id': self.job_id,
'name': self.name,
'parent_id': self.parent.dagobah_id,
'tasks': t,
'dependencies': dependencies,
'status': self.state.status,
'cron_schedule': self.cron_schedule,
'next_run': self.next_run,
'notes': self.notes}
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | [
"def",
"_serialize",
"(",
"self",
",",
"include_run_logs",
"=",
"False",
",",
"strict_json",
"=",
"False",
")",
":",
"# return tasks in sorted order if graph is in a valid state",
"try",
":",
"topo_sorted",
"=",
"self",
".",
"topological_sort",
"(",
")",
"t",
"=",
... | Serialize a representation of this Job to a Python dict object. | [
"Serialize",
"a",
"representation",
"of",
"this",
"Job",
"to",
"a",
"Python",
"dict",
"object",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L661-L691 | train | 34,530 |
thieman/dagobah | dagobah/core/core.py | Job.initialize_snapshot | def initialize_snapshot(self):
""" Copy the DAG and validate """
logger.debug('Initializing DAG snapshot for job {0}'.format(self.name))
if self.snapshot is not None:
logging.warn("Attempting to initialize DAG snapshot without " +
"first destroying old snapshot.")
snapshot_to_validate = deepcopy(self.graph)
is_valid, reason = self.validate(snapshot_to_validate)
if not is_valid:
raise DagobahError(reason)
self.snapshot = snapshot_to_validate | python | def initialize_snapshot(self):
""" Copy the DAG and validate """
logger.debug('Initializing DAG snapshot for job {0}'.format(self.name))
if self.snapshot is not None:
logging.warn("Attempting to initialize DAG snapshot without " +
"first destroying old snapshot.")
snapshot_to_validate = deepcopy(self.graph)
is_valid, reason = self.validate(snapshot_to_validate)
if not is_valid:
raise DagobahError(reason)
self.snapshot = snapshot_to_validate | [
"def",
"initialize_snapshot",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Initializing DAG snapshot for job {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"self",
".",
"snapshot",
"is",
"not",
"None",
":",
"logging",
".",
"warn",
... | Copy the DAG and validate | [
"Copy",
"the",
"DAG",
"and",
"validate"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L693-L706 | train | 34,531 |
thieman/dagobah | dagobah/core/core.py | Task.reset | def reset(self):
""" Reset this Task to a clean state prior to execution. """
logger.debug('Resetting task {0}'.format(self.name))
self.stdout_file = os.tmpfile()
self.stderr_file = os.tmpfile()
self.stdout = ""
self.stderr = ""
self.started_at = None
self.completed_at = None
self.successful = None
self.terminate_sent = False
self.kill_sent = False
self.remote_failure = False | python | def reset(self):
""" Reset this Task to a clean state prior to execution. """
logger.debug('Resetting task {0}'.format(self.name))
self.stdout_file = os.tmpfile()
self.stderr_file = os.tmpfile()
self.stdout = ""
self.stderr = ""
self.started_at = None
self.completed_at = None
self.successful = None
self.terminate_sent = False
self.kill_sent = False
self.remote_failure = False | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Resetting task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"stdout_file",
"=",
"os",
".",
"tmpfile",
"(",
")",
"self",
".",
"stderr_file",
"=",
"os",
"."... | Reset this Task to a clean state prior to execution. | [
"Reset",
"this",
"Task",
"to",
"a",
"clean",
"state",
"prior",
"to",
"execution",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L774-L791 | train | 34,532 |
thieman/dagobah | dagobah/core/core.py | Task.start | def start(self):
""" Begin execution of this task. """
logger.info('Starting task {0}'.format(self.name))
self.reset()
if self.hostname:
host = self.parent_job.parent.get_host(self.hostname)
if host:
self.remote_ssh(host)
else:
self.remote_failure = True
else:
self.process = subprocess.Popen(self.command,
shell=True,
env=os.environ.copy(),
stdout=self.stdout_file,
stderr=self.stderr_file)
self.started_at = datetime.utcnow()
self._start_check_timer() | python | def start(self):
""" Begin execution of this task. """
logger.info('Starting task {0}'.format(self.name))
self.reset()
if self.hostname:
host = self.parent_job.parent.get_host(self.hostname)
if host:
self.remote_ssh(host)
else:
self.remote_failure = True
else:
self.process = subprocess.Popen(self.command,
shell=True,
env=os.environ.copy(),
stdout=self.stdout_file,
stderr=self.stderr_file)
self.started_at = datetime.utcnow()
self._start_check_timer() | [
"def",
"start",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Starting task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"reset",
"(",
")",
"if",
"self",
".",
"hostname",
":",
"host",
"=",
"self",
".",
"parent_job",
... | Begin execution of this task. | [
"Begin",
"execution",
"of",
"this",
"task",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L793-L811 | train | 34,533 |
thieman/dagobah | dagobah/core/core.py | Task.remote_ssh | def remote_ssh(self, host):
""" Execute a command on SSH. Takes a paramiko host dict """
logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
try:
self.remote_client = paramiko.SSHClient()
self.remote_client.load_system_host_keys()
self.remote_client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.remote_client.connect(host['hostname'], username=host['user'],
key_filename=host['identityfile'][0],
timeout=82800)
transport = self.remote_client.get_transport()
transport.set_keepalive(10)
self.remote_channel = transport.open_session()
self.remote_channel.get_pty()
self.remote_channel.exec_command(self.command)
except Exception as e:
logger.warn('Exception encountered in remote task execution')
self.remote_failure = True
self.stderr += 'Exception when trying to SSH related to: '
self.stderr += '{0}: {1}\n"'.format(type(e).__name__, str(e))
self.stderr += 'Was looking for host "{0}"\n'.format(str(host))
self.stderr += 'Found in config:\n'
self.stderr += 'host: "{0}"\n'.format(str(host))
self.stderr += 'hostname: "{0}"\n'.format(str(host.get('hostname')))
self.stderr += 'user: "{0}"\n'.format(str(host.get('user')))
self.stderr += 'identityfile: "{0}"\n'.format(str(host.get('identityfile')))
self.remote_client.close() | python | def remote_ssh(self, host):
""" Execute a command on SSH. Takes a paramiko host dict """
logger.info('Starting remote execution of task {0} on host {1}'.format(self.name, host['hostname']))
try:
self.remote_client = paramiko.SSHClient()
self.remote_client.load_system_host_keys()
self.remote_client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
self.remote_client.connect(host['hostname'], username=host['user'],
key_filename=host['identityfile'][0],
timeout=82800)
transport = self.remote_client.get_transport()
transport.set_keepalive(10)
self.remote_channel = transport.open_session()
self.remote_channel.get_pty()
self.remote_channel.exec_command(self.command)
except Exception as e:
logger.warn('Exception encountered in remote task execution')
self.remote_failure = True
self.stderr += 'Exception when trying to SSH related to: '
self.stderr += '{0}: {1}\n"'.format(type(e).__name__, str(e))
self.stderr += 'Was looking for host "{0}"\n'.format(str(host))
self.stderr += 'Found in config:\n'
self.stderr += 'host: "{0}"\n'.format(str(host))
self.stderr += 'hostname: "{0}"\n'.format(str(host.get('hostname')))
self.stderr += 'user: "{0}"\n'.format(str(host.get('user')))
self.stderr += 'identityfile: "{0}"\n'.format(str(host.get('identityfile')))
self.remote_client.close() | [
"def",
"remote_ssh",
"(",
"self",
",",
"host",
")",
":",
"logger",
".",
"info",
"(",
"'Starting remote execution of task {0} on host {1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"host",
"[",
"'hostname'",
"]",
")",
")",
"try",
":",
"self",
".",
"re... | Execute a command on SSH. Takes a paramiko host dict | [
"Execute",
"a",
"command",
"on",
"SSH",
".",
"Takes",
"a",
"paramiko",
"host",
"dict"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L813-L841 | train | 34,534 |
thieman/dagobah | dagobah/core/core.py | Task.check_complete | def check_complete(self):
""" Runs completion flow for this task if it's finished. """
logger.debug('Running check_complete for task {0}'.format(self.name))
# Tasks not completed
if self.remote_not_complete() or self.local_not_complete():
self._start_check_timer()
return
return_code = self.completed_task()
# Handle task errors
if self.terminate_sent:
self.stderr += '\nDAGOBAH SENT SIGTERM TO THIS PROCESS\n'
if self.kill_sent:
self.stderr += '\nDAGOBAH SENT SIGKILL TO THIS PROCESS\n'
if self.remote_failure:
return_code = -1
self.stderr += '\nAn error occurred with the remote machine.\n'
self.stdout_file = None
self.stderr_file = None
self._task_complete(success=True if return_code == 0 else False,
return_code=return_code,
stdout=self.stdout,
stderr=self.stderr,
start_time=self.started_at,
complete_time=datetime.utcnow()) | python | def check_complete(self):
""" Runs completion flow for this task if it's finished. """
logger.debug('Running check_complete for task {0}'.format(self.name))
# Tasks not completed
if self.remote_not_complete() or self.local_not_complete():
self._start_check_timer()
return
return_code = self.completed_task()
# Handle task errors
if self.terminate_sent:
self.stderr += '\nDAGOBAH SENT SIGTERM TO THIS PROCESS\n'
if self.kill_sent:
self.stderr += '\nDAGOBAH SENT SIGKILL TO THIS PROCESS\n'
if self.remote_failure:
return_code = -1
self.stderr += '\nAn error occurred with the remote machine.\n'
self.stdout_file = None
self.stderr_file = None
self._task_complete(success=True if return_code == 0 else False,
return_code=return_code,
stdout=self.stdout,
stderr=self.stderr,
start_time=self.started_at,
complete_time=datetime.utcnow()) | [
"def",
"check_complete",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Running check_complete for task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"# Tasks not completed",
"if",
"self",
".",
"remote_not_complete",
"(",
")",
"or",
"self",
... | Runs completion flow for this task if it's finished. | [
"Runs",
"completion",
"flow",
"for",
"this",
"task",
"if",
"it",
"s",
"finished",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L843-L871 | train | 34,535 |
thieman/dagobah | dagobah/core/core.py | Task.remote_not_complete | def remote_not_complete(self):
"""
Returns True if this task is on a remote channel, and on a remote
machine, False if it is either not remote or not completed
"""
if self.remote_channel and not self.remote_channel.exit_status_ready():
self._timeout_check()
# Get some stdout/std error
if self.remote_channel.recv_ready():
self.stdout += self.remote_channel.recv(1024)
if self.remote_channel.recv_stderr_ready():
self.stderr += self.remote_channel.recv_stderr(1024)
return True
return False | python | def remote_not_complete(self):
"""
Returns True if this task is on a remote channel, and on a remote
machine, False if it is either not remote or not completed
"""
if self.remote_channel and not self.remote_channel.exit_status_ready():
self._timeout_check()
# Get some stdout/std error
if self.remote_channel.recv_ready():
self.stdout += self.remote_channel.recv(1024)
if self.remote_channel.recv_stderr_ready():
self.stderr += self.remote_channel.recv_stderr(1024)
return True
return False | [
"def",
"remote_not_complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"remote_channel",
"and",
"not",
"self",
".",
"remote_channel",
".",
"exit_status_ready",
"(",
")",
":",
"self",
".",
"_timeout_check",
"(",
")",
"# Get some stdout/std error",
"if",
"self",
... | Returns True if this task is on a remote channel, and on a remote
machine, False if it is either not remote or not completed | [
"Returns",
"True",
"if",
"this",
"task",
"is",
"on",
"a",
"remote",
"channel",
"and",
"on",
"a",
"remote",
"machine",
"False",
"if",
"it",
"is",
"either",
"not",
"remote",
"or",
"not",
"completed"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L873-L886 | train | 34,536 |
thieman/dagobah | dagobah/core/core.py | Task.local_not_complete | def local_not_complete(self):
""" Returns True if task is local and not completed"""
if self.process and self.process.poll() is None:
self._timeout_check()
return True
return False | python | def local_not_complete(self):
""" Returns True if task is local and not completed"""
if self.process and self.process.poll() is None:
self._timeout_check()
return True
return False | [
"def",
"local_not_complete",
"(",
"self",
")",
":",
"if",
"self",
".",
"process",
"and",
"self",
".",
"process",
".",
"poll",
"(",
")",
"is",
"None",
":",
"self",
".",
"_timeout_check",
"(",
")",
"return",
"True",
"return",
"False"
] | Returns True if task is local and not completed | [
"Returns",
"True",
"if",
"task",
"is",
"local",
"and",
"not",
"completed"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L888-L893 | train | 34,537 |
thieman/dagobah | dagobah/core/core.py | Task.completed_task | def completed_task(self):
""" Handle wrapping up a completed task, local or remote"""
# If its remote and finished running
if self.remote_channel and self.remote_channel.exit_status_ready():
# Collect all remaining stdout/stderr
while self.remote_channel.recv_ready():
self.stdout += self.remote_channel.recv(1024)
while self.remote_channel.recv_stderr_ready():
self.stderr += self.remote_channel.recv_stderr(1024)
return self.remote_channel.recv_exit_status()
# Otherwise check for finished local command
elif self.process:
self.stdout, self.stderr = (self._read_temp_file(self.stdout_file),
self._read_temp_file(self.stderr_file))
for temp_file in [self.stdout_file, self.stderr_file]:
temp_file.close()
return self.process.returncode | python | def completed_task(self):
""" Handle wrapping up a completed task, local or remote"""
# If its remote and finished running
if self.remote_channel and self.remote_channel.exit_status_ready():
# Collect all remaining stdout/stderr
while self.remote_channel.recv_ready():
self.stdout += self.remote_channel.recv(1024)
while self.remote_channel.recv_stderr_ready():
self.stderr += self.remote_channel.recv_stderr(1024)
return self.remote_channel.recv_exit_status()
# Otherwise check for finished local command
elif self.process:
self.stdout, self.stderr = (self._read_temp_file(self.stdout_file),
self._read_temp_file(self.stderr_file))
for temp_file in [self.stdout_file, self.stderr_file]:
temp_file.close()
return self.process.returncode | [
"def",
"completed_task",
"(",
"self",
")",
":",
"# If its remote and finished running",
"if",
"self",
".",
"remote_channel",
"and",
"self",
".",
"remote_channel",
".",
"exit_status_ready",
"(",
")",
":",
"# Collect all remaining stdout/stderr",
"while",
"self",
".",
"... | Handle wrapping up a completed task, local or remote | [
"Handle",
"wrapping",
"up",
"a",
"completed",
"task",
"local",
"or",
"remote"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L895-L911 | train | 34,538 |
thieman/dagobah | dagobah/core/core.py | Task.terminate | def terminate(self):
""" Send SIGTERM to the task's process. """
logger.info('Sending SIGTERM to task {0}'.format(self.name))
if hasattr(self, 'remote_client') and self.remote_client is not None:
self.terminate_sent = True
self.remote_client.close()
return
if not self.process:
raise DagobahError('task does not have a running process')
self.terminate_sent = True
self.process.terminate() | python | def terminate(self):
""" Send SIGTERM to the task's process. """
logger.info('Sending SIGTERM to task {0}'.format(self.name))
if hasattr(self, 'remote_client') and self.remote_client is not None:
self.terminate_sent = True
self.remote_client.close()
return
if not self.process:
raise DagobahError('task does not have a running process')
self.terminate_sent = True
self.process.terminate() | [
"def",
"terminate",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Sending SIGTERM to task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'remote_client'",
")",
"and",
"self",
".",
"remote_client",
"is",... | Send SIGTERM to the task's process. | [
"Send",
"SIGTERM",
"to",
"the",
"task",
"s",
"process",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L913-L923 | train | 34,539 |
thieman/dagobah | dagobah/core/core.py | Task.kill | def kill(self):
""" Send SIGKILL to the task's process. """
logger.info('Sending SIGKILL to task {0}'.format(self.name))
if hasattr(self, 'remote_client') and self.remote_client is not None:
self.kill_sent = True
self.remote_client.close()
return
if not self.process:
raise DagobahError('task does not have a running process')
self.kill_sent = True
self.process.kill() | python | def kill(self):
""" Send SIGKILL to the task's process. """
logger.info('Sending SIGKILL to task {0}'.format(self.name))
if hasattr(self, 'remote_client') and self.remote_client is not None:
self.kill_sent = True
self.remote_client.close()
return
if not self.process:
raise DagobahError('task does not have a running process')
self.kill_sent = True
self.process.kill() | [
"def",
"kill",
"(",
"self",
")",
":",
"logger",
".",
"info",
"(",
"'Sending SIGKILL to task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"if",
"hasattr",
"(",
"self",
",",
"'remote_client'",
")",
"and",
"self",
".",
"remote_client",
"is",
"n... | Send SIGKILL to the task's process. | [
"Send",
"SIGKILL",
"to",
"the",
"task",
"s",
"process",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L926-L936 | train | 34,540 |
thieman/dagobah | dagobah/core/core.py | Task._start_check_timer | def _start_check_timer(self):
""" Periodically checks to see if the task has completed. """
if self.timer:
self.timer.cancel()
self.timer = threading.Timer(2.5, self.check_complete)
self.timer.daemon = True
self.timer.start() | python | def _start_check_timer(self):
""" Periodically checks to see if the task has completed. """
if self.timer:
self.timer.cancel()
self.timer = threading.Timer(2.5, self.check_complete)
self.timer.daemon = True
self.timer.start() | [
"def",
"_start_check_timer",
"(",
"self",
")",
":",
"if",
"self",
".",
"timer",
":",
"self",
".",
"timer",
".",
"cancel",
"(",
")",
"self",
".",
"timer",
"=",
"threading",
".",
"Timer",
"(",
"2.5",
",",
"self",
".",
"check_complete",
")",
"self",
"."... | Periodically checks to see if the task has completed. | [
"Periodically",
"checks",
"to",
"see",
"if",
"the",
"task",
"has",
"completed",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1004-L1010 | train | 34,541 |
thieman/dagobah | dagobah/core/core.py | Task._head_temp_file | def _head_temp_file(self, temp_file, num_lines):
""" Returns a list of the first num_lines lines from a temp file. """
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer')
temp_file.seek(0)
result, curr_line = [], 0
for line in temp_file:
curr_line += 1
result.append(line.strip())
if curr_line >= num_lines:
break
return result | python | def _head_temp_file(self, temp_file, num_lines):
""" Returns a list of the first num_lines lines from a temp file. """
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer')
temp_file.seek(0)
result, curr_line = [], 0
for line in temp_file:
curr_line += 1
result.append(line.strip())
if curr_line >= num_lines:
break
return result | [
"def",
"_head_temp_file",
"(",
"self",
",",
"temp_file",
",",
"num_lines",
")",
":",
"if",
"not",
"isinstance",
"(",
"num_lines",
",",
"int",
")",
":",
"raise",
"DagobahError",
"(",
"'num_lines must be an integer'",
")",
"temp_file",
".",
"seek",
"(",
"0",
"... | Returns a list of the first num_lines lines from a temp file. | [
"Returns",
"a",
"list",
"of",
"the",
"first",
"num_lines",
"lines",
"from",
"a",
"temp",
"file",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1030-L1041 | train | 34,542 |
thieman/dagobah | dagobah/core/core.py | Task._tail_temp_file | def _tail_temp_file(self, temp_file, num_lines, seek_offset=10000):
""" Returns a list of the last num_lines lines from a temp file.
This works by first moving seek_offset chars back from the end of
the file, then attempting to tail the file from there. It is
possible that fewer than num_lines will be returned, even if the
file has more total lines than num_lines.
"""
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer')
temp_file.seek(0, os.SEEK_END)
size = temp_file.tell()
temp_file.seek(-1 * min(size, seek_offset), os.SEEK_END)
result = []
while True:
this_line = temp_file.readline()
if this_line == '':
break
result.append(this_line.strip())
if len(result) > num_lines:
result.pop(0)
return result | python | def _tail_temp_file(self, temp_file, num_lines, seek_offset=10000):
""" Returns a list of the last num_lines lines from a temp file.
This works by first moving seek_offset chars back from the end of
the file, then attempting to tail the file from there. It is
possible that fewer than num_lines will be returned, even if the
file has more total lines than num_lines.
"""
if not isinstance(num_lines, int):
raise DagobahError('num_lines must be an integer')
temp_file.seek(0, os.SEEK_END)
size = temp_file.tell()
temp_file.seek(-1 * min(size, seek_offset), os.SEEK_END)
result = []
while True:
this_line = temp_file.readline()
if this_line == '':
break
result.append(this_line.strip())
if len(result) > num_lines:
result.pop(0)
return result | [
"def",
"_tail_temp_file",
"(",
"self",
",",
"temp_file",
",",
"num_lines",
",",
"seek_offset",
"=",
"10000",
")",
":",
"if",
"not",
"isinstance",
"(",
"num_lines",
",",
"int",
")",
":",
"raise",
"DagobahError",
"(",
"'num_lines must be an integer'",
")",
"temp... | Returns a list of the last num_lines lines from a temp file.
This works by first moving seek_offset chars back from the end of
the file, then attempting to tail the file from there. It is
possible that fewer than num_lines will be returned, even if the
file has more total lines than num_lines. | [
"Returns",
"a",
"list",
"of",
"the",
"last",
"num_lines",
"lines",
"from",
"a",
"temp",
"file",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1044-L1068 | train | 34,543 |
thieman/dagobah | dagobah/core/core.py | Task._task_complete | def _task_complete(self, **kwargs):
""" Performs cleanup tasks and notifies Job that the Task finished. """
logger.debug('Running _task_complete for task {0}'.format(self.name))
with self.parent_job.completion_lock:
self.completed_at = datetime.utcnow()
self.successful = kwargs.get('success', None)
self.parent_job._complete_task(self.name, **kwargs) | python | def _task_complete(self, **kwargs):
""" Performs cleanup tasks and notifies Job that the Task finished. """
logger.debug('Running _task_complete for task {0}'.format(self.name))
with self.parent_job.completion_lock:
self.completed_at = datetime.utcnow()
self.successful = kwargs.get('success', None)
self.parent_job._complete_task(self.name, **kwargs) | [
"def",
"_task_complete",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"debug",
"(",
"'Running _task_complete for task {0}'",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"with",
"self",
".",
"parent_job",
".",
"completion_lock",
":",
... | Performs cleanup tasks and notifies Job that the Task finished. | [
"Performs",
"cleanup",
"tasks",
"and",
"notifies",
"Job",
"that",
"the",
"Task",
"finished",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1071-L1077 | train | 34,544 |
thieman/dagobah | dagobah/core/core.py | Task._serialize | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Task to a Python dict. """
result = {'command': self.command,
'name': self.name,
'started_at': self.started_at,
'completed_at': self.completed_at,
'success': self.successful,
'soft_timeout': self.soft_timeout,
'hard_timeout': self.hard_timeout,
'hostname': self.hostname}
if include_run_logs:
last_run = self.backend.get_latest_run_log(self.parent_job.job_id,
self.name)
if last_run:
run_log = last_run.get('tasks', {}).get(self.name, {})
if run_log:
result['run_log'] = run_log
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | python | def _serialize(self, include_run_logs=False, strict_json=False):
""" Serialize a representation of this Task to a Python dict. """
result = {'command': self.command,
'name': self.name,
'started_at': self.started_at,
'completed_at': self.completed_at,
'success': self.successful,
'soft_timeout': self.soft_timeout,
'hard_timeout': self.hard_timeout,
'hostname': self.hostname}
if include_run_logs:
last_run = self.backend.get_latest_run_log(self.parent_job.job_id,
self.name)
if last_run:
run_log = last_run.get('tasks', {}).get(self.name, {})
if run_log:
result['run_log'] = run_log
if strict_json:
result = json.loads(json.dumps(result, cls=StrictJSONEncoder))
return result | [
"def",
"_serialize",
"(",
"self",
",",
"include_run_logs",
"=",
"False",
",",
"strict_json",
"=",
"False",
")",
":",
"result",
"=",
"{",
"'command'",
":",
"self",
".",
"command",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'started_at'",
":",
"self",
... | Serialize a representation of this Task to a Python dict. | [
"Serialize",
"a",
"representation",
"of",
"this",
"Task",
"to",
"a",
"Python",
"dict",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/core/core.py#L1080-L1102 | train | 34,545 |
thieman/dagobah | dagobah/daemon/auth.py | do_login | def do_login():
""" Attempt to auth using single login. Rate limited at the site level. """
dt_filter = lambda x: x >= datetime.utcnow() - timedelta(seconds=60)
app.config['AUTH_ATTEMPTS'] = filter(dt_filter, app.config['AUTH_ATTEMPTS'])
if len(app.config['AUTH_ATTEMPTS']) > app.config['AUTH_RATE_LIMIT']:
return redirect(url_for('login',
alert="Rate limit exceeded. Try again in 60 seconds."))
if request.form.get('password') == app.config['APP_PASSWORD']:
login_user(SingleAuthUser)
return redirect('/')
app.config['AUTH_ATTEMPTS'].append(datetime.utcnow())
return redirect(url_for('login', alert="Incorrect password.")) | python | def do_login():
""" Attempt to auth using single login. Rate limited at the site level. """
dt_filter = lambda x: x >= datetime.utcnow() - timedelta(seconds=60)
app.config['AUTH_ATTEMPTS'] = filter(dt_filter, app.config['AUTH_ATTEMPTS'])
if len(app.config['AUTH_ATTEMPTS']) > app.config['AUTH_RATE_LIMIT']:
return redirect(url_for('login',
alert="Rate limit exceeded. Try again in 60 seconds."))
if request.form.get('password') == app.config['APP_PASSWORD']:
login_user(SingleAuthUser)
return redirect('/')
app.config['AUTH_ATTEMPTS'].append(datetime.utcnow())
return redirect(url_for('login', alert="Incorrect password.")) | [
"def",
"do_login",
"(",
")",
":",
"dt_filter",
"=",
"lambda",
"x",
":",
"x",
">=",
"datetime",
".",
"utcnow",
"(",
")",
"-",
"timedelta",
"(",
"seconds",
"=",
"60",
")",
"app",
".",
"config",
"[",
"'AUTH_ATTEMPTS'",
"]",
"=",
"filter",
"(",
"dt_filte... | Attempt to auth using single login. Rate limited at the site level. | [
"Attempt",
"to",
"auth",
"using",
"single",
"login",
".",
"Rate",
"limited",
"at",
"the",
"site",
"level",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/auth.py#L28-L43 | train | 34,546 |
thieman/dagobah | dagobah/__init__.py | return_standard_conf | def return_standard_conf():
""" Return the sample config file. """
result = resource_string(__name__, 'daemon/dagobahd.yml')
result = result % {'app_secret': os.urandom(24).encode('hex')}
return result | python | def return_standard_conf():
""" Return the sample config file. """
result = resource_string(__name__, 'daemon/dagobahd.yml')
result = result % {'app_secret': os.urandom(24).encode('hex')}
return result | [
"def",
"return_standard_conf",
"(",
")",
":",
"result",
"=",
"resource_string",
"(",
"__name__",
",",
"'daemon/dagobahd.yml'",
")",
"result",
"=",
"result",
"%",
"{",
"'app_secret'",
":",
"os",
".",
"urandom",
"(",
"24",
")",
".",
"encode",
"(",
"'hex'",
"... | Return the sample config file. | [
"Return",
"the",
"sample",
"config",
"file",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/__init__.py#L10-L14 | train | 34,547 |
thieman/dagobah | dagobah/daemon/views.py | job_detail | def job_detail(job_id=None):
""" Show a detailed description of a Job's status. """
jobs = [job for job in get_jobs() if str(job['job_id']) == job_id]
if not jobs:
abort(404)
return render_template('job_detail.html', job=jobs[0], hosts=dagobah.get_hosts()) | python | def job_detail(job_id=None):
""" Show a detailed description of a Job's status. """
jobs = [job for job in get_jobs() if str(job['job_id']) == job_id]
if not jobs:
abort(404)
return render_template('job_detail.html', job=jobs[0], hosts=dagobah.get_hosts()) | [
"def",
"job_detail",
"(",
"job_id",
"=",
"None",
")",
":",
"jobs",
"=",
"[",
"job",
"for",
"job",
"in",
"get_jobs",
"(",
")",
"if",
"str",
"(",
"job",
"[",
"'job_id'",
"]",
")",
"==",
"job_id",
"]",
"if",
"not",
"jobs",
":",
"abort",
"(",
"404",
... | Show a detailed description of a Job's status. | [
"Show",
"a",
"detailed",
"description",
"of",
"a",
"Job",
"s",
"status",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/views.py#L33-L38 | train | 34,548 |
thieman/dagobah | dagobah/daemon/views.py | task_detail | def task_detail(job_id=None, task_name=None):
""" Show a detailed description of a specific task. """
jobs = get_jobs()
job = [job for job in jobs if str(job['job_id']) == job_id][0]
return render_template('task_detail.html',
job=job,
task_name=task_name,
task=[task for task in job['tasks']
if task['name'] == task_name][0]) | python | def task_detail(job_id=None, task_name=None):
""" Show a detailed description of a specific task. """
jobs = get_jobs()
job = [job for job in jobs if str(job['job_id']) == job_id][0]
return render_template('task_detail.html',
job=job,
task_name=task_name,
task=[task for task in job['tasks']
if task['name'] == task_name][0]) | [
"def",
"task_detail",
"(",
"job_id",
"=",
"None",
",",
"task_name",
"=",
"None",
")",
":",
"jobs",
"=",
"get_jobs",
"(",
")",
"job",
"=",
"[",
"job",
"for",
"job",
"in",
"jobs",
"if",
"str",
"(",
"job",
"[",
"'job_id'",
"]",
")",
"==",
"job_id",
... | Show a detailed description of a specific task. | [
"Show",
"a",
"detailed",
"description",
"of",
"a",
"specific",
"task",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/views.py#L42-L50 | train | 34,549 |
thieman/dagobah | dagobah/daemon/views.py | log_detail | def log_detail(job_id=None, task_name=None, log_id=None):
""" Show a detailed description of a specific log. """
jobs = get_jobs()
job = [job for job in jobs if str(job['job_id']) == job_id][0]
return render_template('log_detail.html',
job=job,
task_name=task_name,
task=[task for task in job['tasks']
if task['name'] == task_name][0],
log_id=log_id) | python | def log_detail(job_id=None, task_name=None, log_id=None):
""" Show a detailed description of a specific log. """
jobs = get_jobs()
job = [job for job in jobs if str(job['job_id']) == job_id][0]
return render_template('log_detail.html',
job=job,
task_name=task_name,
task=[task for task in job['tasks']
if task['name'] == task_name][0],
log_id=log_id) | [
"def",
"log_detail",
"(",
"job_id",
"=",
"None",
",",
"task_name",
"=",
"None",
",",
"log_id",
"=",
"None",
")",
":",
"jobs",
"=",
"get_jobs",
"(",
")",
"job",
"=",
"[",
"job",
"for",
"job",
"in",
"jobs",
"if",
"str",
"(",
"job",
"[",
"'job_id'",
... | Show a detailed description of a specific log. | [
"Show",
"a",
"detailed",
"description",
"of",
"a",
"specific",
"log",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/views.py#L54-L63 | train | 34,550 |
thieman/dagobah | dagobah/email/text.py | TextEmail._task_to_text | def _task_to_text(self, task):
""" Return a standard formatting of a Task serialization. """
started = self._format_date(task.get('started_at', None))
completed = self._format_date(task.get('completed_at', None))
success = task.get('success', None)
success_lu = {None: 'Not executed', True: 'Success',
False: 'Failed'}
run_log = task.get('run_log', {})
return '\n'.join(['Task: %s' % task.get('name', None),
'Command: %s' % task.get('command', None),
'Result: %s' % success_lu[success],
'Started at: %s' % started,
'Completed at: %s' % completed,
'Return Code: %s' % run_log.get('return_code', None),
'Stdout: %s' % run_log.get('stdout', None),
'Stderr: %s' % run_log.get('stderr', None)]) | python | def _task_to_text(self, task):
""" Return a standard formatting of a Task serialization. """
started = self._format_date(task.get('started_at', None))
completed = self._format_date(task.get('completed_at', None))
success = task.get('success', None)
success_lu = {None: 'Not executed', True: 'Success',
False: 'Failed'}
run_log = task.get('run_log', {})
return '\n'.join(['Task: %s' % task.get('name', None),
'Command: %s' % task.get('command', None),
'Result: %s' % success_lu[success],
'Started at: %s' % started,
'Completed at: %s' % completed,
'Return Code: %s' % run_log.get('return_code', None),
'Stdout: %s' % run_log.get('stdout', None),
'Stderr: %s' % run_log.get('stderr', None)]) | [
"def",
"_task_to_text",
"(",
"self",
",",
"task",
")",
":",
"started",
"=",
"self",
".",
"_format_date",
"(",
"task",
".",
"get",
"(",
"'started_at'",
",",
"None",
")",
")",
"completed",
"=",
"self",
".",
"_format_date",
"(",
"task",
".",
"get",
"(",
... | Return a standard formatting of a Task serialization. | [
"Return",
"a",
"standard",
"formatting",
"of",
"a",
"Task",
"serialization",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/email/text.py#L25-L43 | train | 34,551 |
thieman/dagobah | dagobah/email/text.py | TextEmail._job_to_text | def _job_to_text(self, job):
""" Return a standard formatting of a Job serialization. """
next_run = self._format_date(job.get('next_run', None))
tasks = ''
for task in job.get('tasks', []):
tasks += self._task_to_text(task)
tasks += '\n\n'
return '\n'.join(['Job name: %s' % job.get('name', None),
'Cron schedule: %s' % job.get('cron_schedule', None),
'Next run: %s' % next_run,
'',
'Parent ID: %s' % job.get('parent_id', None),
'Job ID: %s' % job.get('job_id', None),
'',
'Tasks Detail',
'',
tasks]) | python | def _job_to_text(self, job):
""" Return a standard formatting of a Job serialization. """
next_run = self._format_date(job.get('next_run', None))
tasks = ''
for task in job.get('tasks', []):
tasks += self._task_to_text(task)
tasks += '\n\n'
return '\n'.join(['Job name: %s' % job.get('name', None),
'Cron schedule: %s' % job.get('cron_schedule', None),
'Next run: %s' % next_run,
'',
'Parent ID: %s' % job.get('parent_id', None),
'Job ID: %s' % job.get('job_id', None),
'',
'Tasks Detail',
'',
tasks]) | [
"def",
"_job_to_text",
"(",
"self",
",",
"job",
")",
":",
"next_run",
"=",
"self",
".",
"_format_date",
"(",
"job",
".",
"get",
"(",
"'next_run'",
",",
"None",
")",
")",
"tasks",
"=",
"''",
"for",
"task",
"in",
"job",
".",
"get",
"(",
"'tasks'",
",... | Return a standard formatting of a Job serialization. | [
"Return",
"a",
"standard",
"formatting",
"of",
"a",
"Job",
"serialization",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/email/text.py#L46-L65 | train | 34,552 |
thieman/dagobah | dagobah/email/common.py | EmailTemplate._get_template | def _get_template(self, template_name, template_file):
""" Returns a Jinja2 template of the specified file. """
template = os.path.join(self.location, 'templates',
template_name, template_file)
return jinja2.Template(open(template).read()) | python | def _get_template(self, template_name, template_file):
""" Returns a Jinja2 template of the specified file. """
template = os.path.join(self.location, 'templates',
template_name, template_file)
return jinja2.Template(open(template).read()) | [
"def",
"_get_template",
"(",
"self",
",",
"template_name",
",",
"template_file",
")",
":",
"template",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"location",
",",
"'templates'",
",",
"template_name",
",",
"template_file",
")",
"return",
"jinja2",... | Returns a Jinja2 template of the specified file. | [
"Returns",
"a",
"Jinja2",
"template",
"of",
"the",
"specified",
"file",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/email/common.py#L75-L79 | train | 34,553 |
thieman/dagobah | dagobah/daemon/daemon.py | replace_nones | def replace_nones(dict_or_list):
"""Update a dict or list in place to replace
'none' string values with Python None."""
def replace_none_in_value(value):
if isinstance(value, basestring) and value.lower() == "none":
return None
return value
items = dict_or_list.iteritems() if isinstance(dict_or_list, dict) else enumerate(dict_or_list)
for accessor, value in items:
if isinstance(value, (dict, list)):
replace_nones(value)
else:
dict_or_list[accessor] = replace_none_in_value(value) | python | def replace_nones(dict_or_list):
"""Update a dict or list in place to replace
'none' string values with Python None."""
def replace_none_in_value(value):
if isinstance(value, basestring) and value.lower() == "none":
return None
return value
items = dict_or_list.iteritems() if isinstance(dict_or_list, dict) else enumerate(dict_or_list)
for accessor, value in items:
if isinstance(value, (dict, list)):
replace_nones(value)
else:
dict_or_list[accessor] = replace_none_in_value(value) | [
"def",
"replace_nones",
"(",
"dict_or_list",
")",
":",
"def",
"replace_none_in_value",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"basestring",
")",
"and",
"value",
".",
"lower",
"(",
")",
"==",
"\"none\"",
":",
"return",
"None",
"retur... | Update a dict or list in place to replace
'none' string values with Python None. | [
"Update",
"a",
"dict",
"or",
"list",
"in",
"place",
"to",
"replace",
"none",
"string",
"values",
"with",
"Python",
"None",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/daemon.py#L27-L42 | train | 34,554 |
thieman/dagobah | dagobah/daemon/daemon.py | get_config_file | def get_config_file():
""" Return the loaded config file if one exists. """
# config will be created here if we can't find one
new_config_path = os.path.expanduser('~/.dagobahd.yml')
config_dirs = ['/etc',
os.path.expanduser('~')]
config_filenames = ['dagobahd.yml',
'dagobahd.yaml',
'.dagobahd.yml',
'.dagobahd.yaml']
for directory in config_dirs:
for filename in config_filenames:
try:
if os.path.isfile(os.path.join(directory, filename)):
to_load = open(os.path.join(directory, filename))
config = yaml.load(to_load.read())
to_load.close()
replace_nones(config)
return config
except:
pass
# if we made it to here, need to create a config file
# double up on notifications here to make sure first-time user sees it
print 'Creating new config file in home directory'
logging.info('Creating new config file in home directory')
new_config = open(new_config_path, 'w')
new_config.write(return_standard_conf())
new_config.close()
new_config = open(new_config_path, 'r')
config = yaml.load(new_config.read())
new_config.close()
replace_nones(config)
return config | python | def get_config_file():
""" Return the loaded config file if one exists. """
# config will be created here if we can't find one
new_config_path = os.path.expanduser('~/.dagobahd.yml')
config_dirs = ['/etc',
os.path.expanduser('~')]
config_filenames = ['dagobahd.yml',
'dagobahd.yaml',
'.dagobahd.yml',
'.dagobahd.yaml']
for directory in config_dirs:
for filename in config_filenames:
try:
if os.path.isfile(os.path.join(directory, filename)):
to_load = open(os.path.join(directory, filename))
config = yaml.load(to_load.read())
to_load.close()
replace_nones(config)
return config
except:
pass
# if we made it to here, need to create a config file
# double up on notifications here to make sure first-time user sees it
print 'Creating new config file in home directory'
logging.info('Creating new config file in home directory')
new_config = open(new_config_path, 'w')
new_config.write(return_standard_conf())
new_config.close()
new_config = open(new_config_path, 'r')
config = yaml.load(new_config.read())
new_config.close()
replace_nones(config)
return config | [
"def",
"get_config_file",
"(",
")",
":",
"# config will be created here if we can't find one",
"new_config_path",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"'~/.dagobahd.yml'",
")",
"config_dirs",
"=",
"[",
"'/etc'",
",",
"os",
".",
"path",
".",
"expanduser",
... | Return the loaded config file if one exists. | [
"Return",
"the",
"loaded",
"config",
"file",
"if",
"one",
"exists",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/daemon.py#L44-L81 | train | 34,555 |
thieman/dagobah | dagobah/daemon/daemon.py | configure_event_hooks | def configure_event_hooks(config):
""" Returns an EventHandler instance with registered hooks. """
def print_event_info(**kwargs):
print kwargs.get('event_params', {})
def job_complete_email(email_handler, **kwargs):
email_handler.send_job_completed(kwargs['event_params'])
def job_failed_email(email_handler, **kwargs):
email_handler.send_job_failed(kwargs['event_params'])
def task_failed_email(email_handler, **kwargs):
email_handler.send_task_failed(kwargs['event_params'])
handler = EventHandler()
email_handler = get_email_handler(get_conf(config, 'Dagobahd.email', None),
get_conf(config, 'Email', {}))
if (email_handler and
get_conf(config, 'Email.send_on_success', False) == True):
handler.register('job_complete', job_complete_email, email_handler)
if (email_handler and
get_conf(config, 'Email.send_on_failure', False) == True):
handler.register('job_failed', job_failed_email, email_handler)
handler.register('task_failed', task_failed_email, email_handler)
return handler | python | def configure_event_hooks(config):
""" Returns an EventHandler instance with registered hooks. """
def print_event_info(**kwargs):
print kwargs.get('event_params', {})
def job_complete_email(email_handler, **kwargs):
email_handler.send_job_completed(kwargs['event_params'])
def job_failed_email(email_handler, **kwargs):
email_handler.send_job_failed(kwargs['event_params'])
def task_failed_email(email_handler, **kwargs):
email_handler.send_task_failed(kwargs['event_params'])
handler = EventHandler()
email_handler = get_email_handler(get_conf(config, 'Dagobahd.email', None),
get_conf(config, 'Email', {}))
if (email_handler and
get_conf(config, 'Email.send_on_success', False) == True):
handler.register('job_complete', job_complete_email, email_handler)
if (email_handler and
get_conf(config, 'Email.send_on_failure', False) == True):
handler.register('job_failed', job_failed_email, email_handler)
handler.register('task_failed', task_failed_email, email_handler)
return handler | [
"def",
"configure_event_hooks",
"(",
"config",
")",
":",
"def",
"print_event_info",
"(",
"*",
"*",
"kwargs",
")",
":",
"print",
"kwargs",
".",
"get",
"(",
"'event_params'",
",",
"{",
"}",
")",
"def",
"job_complete_email",
"(",
"email_handler",
",",
"*",
"*... | Returns an EventHandler instance with registered hooks. | [
"Returns",
"an",
"EventHandler",
"instance",
"with",
"registered",
"hooks",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/daemon.py#L167-L196 | train | 34,556 |
thieman/dagobah | dagobah/daemon/daemon.py | init_core_logger | def init_core_logger(location, config):
""" Initialize the logger with settings from config. """
logger = logging.getLogger('dagobah')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if get_conf(config, 'Logging.Core.enabled', False) == False:
logger.addHandler(NullHandler())
return
config_filepath = get_conf(config, 'Logging.Core.logfile', 'default')
if config_filepath == 'default':
config_filepath = os.path.join(location, 'dagobah.log')
config_filepath = os.path.expanduser(config_filepath) if config_filepath else None
level_string = get_conf(config, 'Logging.Core.loglevel', 'info').upper()
numeric_level = getattr(logging, level_string, None)
basic_config_kwargs = {'level': numeric_level,
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
if config_filepath:
basic_config_kwargs['filename'] = config_filepath
else:
basic_config_kwargs['stream'] = open(os.devnull, 'w')
logging.basicConfig(**basic_config_kwargs)
if get_conf(config, 'Logging.Core.log_to_stdout'):
root = logging.getLogger()
stdout_logger = logging.StreamHandler(sys.stdout)
stdout_logger.setLevel(logging.DEBUG)
stdout_logger.setFormatter(formatter)
root.addHandler(stdout_logger)
if config_filepath:
print 'Logging output to %s' % config_filepath
logging.info('Core logger initialized at level %s' % level_string) | python | def init_core_logger(location, config):
""" Initialize the logger with settings from config. """
logger = logging.getLogger('dagobah')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if get_conf(config, 'Logging.Core.enabled', False) == False:
logger.addHandler(NullHandler())
return
config_filepath = get_conf(config, 'Logging.Core.logfile', 'default')
if config_filepath == 'default':
config_filepath = os.path.join(location, 'dagobah.log')
config_filepath = os.path.expanduser(config_filepath) if config_filepath else None
level_string = get_conf(config, 'Logging.Core.loglevel', 'info').upper()
numeric_level = getattr(logging, level_string, None)
basic_config_kwargs = {'level': numeric_level,
'format': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'}
if config_filepath:
basic_config_kwargs['filename'] = config_filepath
else:
basic_config_kwargs['stream'] = open(os.devnull, 'w')
logging.basicConfig(**basic_config_kwargs)
if get_conf(config, 'Logging.Core.log_to_stdout'):
root = logging.getLogger()
stdout_logger = logging.StreamHandler(sys.stdout)
stdout_logger.setLevel(logging.DEBUG)
stdout_logger.setFormatter(formatter)
root.addHandler(stdout_logger)
if config_filepath:
print 'Logging output to %s' % config_filepath
logging.info('Core logger initialized at level %s' % level_string) | [
"def",
"init_core_logger",
"(",
"location",
",",
"config",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'dagobah'",
")",
"formatter",
"=",
"logging",
".",
"Formatter",
"(",
"'%(asctime)s - %(name)s - %(levelname)s - %(message)s'",
")",
"if",
"get_conf... | Initialize the logger with settings from config. | [
"Initialize",
"the",
"logger",
"with",
"settings",
"from",
"config",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/daemon.py#L199-L234 | train | 34,557 |
thieman/dagobah | dagobah/daemon/daemon.py | get_backend | def get_backend(config):
""" Returns a backend instance based on the Daemon config file. """
backend_string = get_conf(config, 'Dagobahd.backend', None)
if backend_string is None:
from ..backend.base import BaseBackend
return BaseBackend()
elif backend_string.lower() == 'mongo':
backend_kwargs = {}
for conf_kwarg in ['host', 'port', 'db',
'dagobah_collection', 'job_collection',
'log_collection']:
backend_kwargs[conf_kwarg] = get_conf(config,
'MongoBackend.%s' % conf_kwarg)
backend_kwargs['port'] = int(backend_kwargs['port'])
try:
from ..backend.mongo import MongoBackend
except:
raise ImportError('Could not initialize the MongoDB Backend. Are you sure' +
' the optional drivers are installed? If not, try running ' +
'"pip install pymongo" to install them.')
return MongoBackend(**backend_kwargs)
raise ValueError('unknown backend type specified in conf') | python | def get_backend(config):
""" Returns a backend instance based on the Daemon config file. """
backend_string = get_conf(config, 'Dagobahd.backend', None)
if backend_string is None:
from ..backend.base import BaseBackend
return BaseBackend()
elif backend_string.lower() == 'mongo':
backend_kwargs = {}
for conf_kwarg in ['host', 'port', 'db',
'dagobah_collection', 'job_collection',
'log_collection']:
backend_kwargs[conf_kwarg] = get_conf(config,
'MongoBackend.%s' % conf_kwarg)
backend_kwargs['port'] = int(backend_kwargs['port'])
try:
from ..backend.mongo import MongoBackend
except:
raise ImportError('Could not initialize the MongoDB Backend. Are you sure' +
' the optional drivers are installed? If not, try running ' +
'"pip install pymongo" to install them.')
return MongoBackend(**backend_kwargs)
raise ValueError('unknown backend type specified in conf') | [
"def",
"get_backend",
"(",
"config",
")",
":",
"backend_string",
"=",
"get_conf",
"(",
"config",
",",
"'Dagobahd.backend'",
",",
"None",
")",
"if",
"backend_string",
"is",
"None",
":",
"from",
".",
".",
"backend",
".",
"base",
"import",
"BaseBackend",
"retur... | Returns a backend instance based on the Daemon config file. | [
"Returns",
"a",
"backend",
"instance",
"based",
"on",
"the",
"Daemon",
"config",
"file",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/daemon.py#L238-L264 | train | 34,558 |
thieman/dagobah | dagobah/daemon/util.py | api_call | def api_call(fn):
""" Returns function result in API format if requested from an API
endpoint """
@wraps(fn)
def wrapper(*args, **kwargs):
try:
result = fn(*args, **kwargs)
except (DagobahError, DAGValidationError) as e:
if request and request.endpoint == fn.__name__:
return jsonify(error_type=type(e).__name__, message=e.message), 400
raise e
except Exception as e:
logging.exception(e)
raise e
if request and request.endpoint == fn.__name__:
status_code = None
try:
if result and '_status' in result:
status_code = result['_status']
del result['_status']
except TypeError:
pass
if isinstance(result, dict):
if 'result' in result:
return jsonify(status=status_code if status_code else 200,
**result)
else:
return jsonify(status=status_code if status_code else 200,
result=result)
else:
return jsonify(status=status_code if status_code else 200,
result=result)
else:
return result
return wrapper | python | def api_call(fn):
""" Returns function result in API format if requested from an API
endpoint """
@wraps(fn)
def wrapper(*args, **kwargs):
try:
result = fn(*args, **kwargs)
except (DagobahError, DAGValidationError) as e:
if request and request.endpoint == fn.__name__:
return jsonify(error_type=type(e).__name__, message=e.message), 400
raise e
except Exception as e:
logging.exception(e)
raise e
if request and request.endpoint == fn.__name__:
status_code = None
try:
if result and '_status' in result:
status_code = result['_status']
del result['_status']
except TypeError:
pass
if isinstance(result, dict):
if 'result' in result:
return jsonify(status=status_code if status_code else 200,
**result)
else:
return jsonify(status=status_code if status_code else 200,
result=result)
else:
return jsonify(status=status_code if status_code else 200,
result=result)
else:
return result
return wrapper | [
"def",
"api_call",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"(",
"Dago... | Returns function result in API format if requested from an API
endpoint | [
"Returns",
"function",
"result",
"in",
"API",
"format",
"if",
"requested",
"from",
"an",
"API",
"endpoint"
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/util.py#L40-L79 | train | 34,559 |
thieman/dagobah | dagobah/daemon/util.py | validate_dict | def validate_dict(in_dict, **kwargs):
""" Returns Boolean of whether given dict conforms to type specifications
given in kwargs. """
if not isinstance(in_dict, dict):
raise ValueError('requires a dictionary')
for key, value in kwargs.iteritems():
if key == 'required':
for required_key in value:
if required_key not in in_dict:
return False
elif key not in in_dict:
continue
elif value == bool:
in_dict[key] = (True
if str(in_dict[key]).lower() == 'true'
else False)
else:
if (isinstance(in_dict[key], list) and
len(in_dict[key]) == 1 and
value != list):
in_dict[key] = in_dict[key][0]
try:
if key in in_dict:
in_dict[key] = value(in_dict[key])
except ValueError:
return False
return True | python | def validate_dict(in_dict, **kwargs):
""" Returns Boolean of whether given dict conforms to type specifications
given in kwargs. """
if not isinstance(in_dict, dict):
raise ValueError('requires a dictionary')
for key, value in kwargs.iteritems():
if key == 'required':
for required_key in value:
if required_key not in in_dict:
return False
elif key not in in_dict:
continue
elif value == bool:
in_dict[key] = (True
if str(in_dict[key]).lower() == 'true'
else False)
else:
if (isinstance(in_dict[key], list) and
len(in_dict[key]) == 1 and
value != list):
in_dict[key] = in_dict[key][0]
try:
if key in in_dict:
in_dict[key] = value(in_dict[key])
except ValueError:
return False
return True | [
"def",
"validate_dict",
"(",
"in_dict",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"in_dict",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'requires a dictionary'",
")",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"ite... | Returns Boolean of whether given dict conforms to type specifications
given in kwargs. | [
"Returns",
"Boolean",
"of",
"whether",
"given",
"dict",
"conforms",
"to",
"type",
"specifications",
"given",
"in",
"kwargs",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/daemon/util.py#L82-L118 | train | 34,560 |
thieman/dagobah | dagobah/backend/mongo.py | MongoBackend.delete_dagobah | def delete_dagobah(self, dagobah_id):
""" Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well.
"""
rec = self.dagobah_coll.find_one({'_id': dagobah_id})
for job in rec.get('jobs', []):
if 'job_id' in job:
self.delete_job(job['job_id'])
self.log_coll.remove({'parent_id': dagobah_id})
self.dagobah_coll.remove({'_id': dagobah_id}) | python | def delete_dagobah(self, dagobah_id):
""" Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well.
"""
rec = self.dagobah_coll.find_one({'_id': dagobah_id})
for job in rec.get('jobs', []):
if 'job_id' in job:
self.delete_job(job['job_id'])
self.log_coll.remove({'parent_id': dagobah_id})
self.dagobah_coll.remove({'_id': dagobah_id}) | [
"def",
"delete_dagobah",
"(",
"self",
",",
"dagobah_id",
")",
":",
"rec",
"=",
"self",
".",
"dagobah_coll",
".",
"find_one",
"(",
"{",
"'_id'",
":",
"dagobah_id",
"}",
")",
"for",
"job",
"in",
"rec",
".",
"get",
"(",
"'jobs'",
",",
"[",
"]",
")",
"... | Deletes the Dagobah and all child Jobs from the database.
Related run logs are deleted as well. | [
"Deletes",
"the",
"Dagobah",
"and",
"all",
"child",
"Jobs",
"from",
"the",
"database",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/backend/mongo.py#L96-L107 | train | 34,561 |
thieman/dagobah | dagobah/backend/mongo.py | MongoBackend.commit_log | def commit_log(self, log_json):
""" Commits a run log to the Mongo backend.
Due to limitations of maximum document size in Mongo,
stdout and stderr logs are truncated to a maximum size for
each task.
"""
log_json['_id'] = log_json['log_id']
append = {'save_date': datetime.utcnow()}
for task_name, values in log_json.get('tasks', {}).items():
for key, size in TRUNCATE_LOG_SIZES_CHAR.iteritems():
if isinstance(values.get(key, None), str):
if len(values[key]) > size:
values[key] = '\n'.join([values[key][:size/2],
'DAGOBAH STREAM SPLIT',
values[key][-1 * (size/2):]])
self.log_coll.save(dict(log_json.items() + append.items())) | python | def commit_log(self, log_json):
""" Commits a run log to the Mongo backend.
Due to limitations of maximum document size in Mongo,
stdout and stderr logs are truncated to a maximum size for
each task.
"""
log_json['_id'] = log_json['log_id']
append = {'save_date': datetime.utcnow()}
for task_name, values in log_json.get('tasks', {}).items():
for key, size in TRUNCATE_LOG_SIZES_CHAR.iteritems():
if isinstance(values.get(key, None), str):
if len(values[key]) > size:
values[key] = '\n'.join([values[key][:size/2],
'DAGOBAH STREAM SPLIT',
values[key][-1 * (size/2):]])
self.log_coll.save(dict(log_json.items() + append.items())) | [
"def",
"commit_log",
"(",
"self",
",",
"log_json",
")",
":",
"log_json",
"[",
"'_id'",
"]",
"=",
"log_json",
"[",
"'log_id'",
"]",
"append",
"=",
"{",
"'save_date'",
":",
"datetime",
".",
"utcnow",
"(",
")",
"}",
"for",
"task_name",
",",
"values",
"in"... | Commits a run log to the Mongo backend.
Due to limitations of maximum document size in Mongo,
stdout and stderr logs are truncated to a maximum size for
each task. | [
"Commits",
"a",
"run",
"log",
"to",
"the",
"Mongo",
"backend",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/backend/mongo.py#L117-L135 | train | 34,562 |
thieman/dagobah | dagobah/backend/base.py | BaseBackend.decode_import_json | def decode_import_json(self, json_doc, transformers=None):
""" Decode a JSON string based on a list of transformers.
Each transformer is a pair of ([conditional], transformer). If
all conditionals are met on each non-list, non-dict object,
the transformer tries to apply itself.
conditional: Callable that returns a Bool.
transformer: Callable transformer on non-dict, non-list objects.
"""
def custom_decoder(dct):
def transform(o):
if not transformers:
return o
for conditionals, transformer in transformers:
conditions_met = True
for conditional in conditionals:
try:
condition_met = conditional(o)
except:
condition_met = False
if not condition_met:
conditions_met = False
break
if not conditions_met:
continue
try:
return transformer(o)
except:
pass
return o
for key in dct.iterkeys():
if isinstance(key, dict):
custom_decoder(dct[key])
elif isinstance(key, list):
[custom_decoder[elem] for elem in dct[key]]
else:
dct[key] = transform(dct[key])
return dct
return json.loads(json_doc, object_hook=custom_decoder) | python | def decode_import_json(self, json_doc, transformers=None):
""" Decode a JSON string based on a list of transformers.
Each transformer is a pair of ([conditional], transformer). If
all conditionals are met on each non-list, non-dict object,
the transformer tries to apply itself.
conditional: Callable that returns a Bool.
transformer: Callable transformer on non-dict, non-list objects.
"""
def custom_decoder(dct):
def transform(o):
if not transformers:
return o
for conditionals, transformer in transformers:
conditions_met = True
for conditional in conditionals:
try:
condition_met = conditional(o)
except:
condition_met = False
if not condition_met:
conditions_met = False
break
if not conditions_met:
continue
try:
return transformer(o)
except:
pass
return o
for key in dct.iterkeys():
if isinstance(key, dict):
custom_decoder(dct[key])
elif isinstance(key, list):
[custom_decoder[elem] for elem in dct[key]]
else:
dct[key] = transform(dct[key])
return dct
return json.loads(json_doc, object_hook=custom_decoder) | [
"def",
"decode_import_json",
"(",
"self",
",",
"json_doc",
",",
"transformers",
"=",
"None",
")",
":",
"def",
"custom_decoder",
"(",
"dct",
")",
":",
"def",
"transform",
"(",
"o",
")",
":",
"if",
"not",
"transformers",
":",
"return",
"o",
"for",
"conditi... | Decode a JSON string based on a list of transformers.
Each transformer is a pair of ([conditional], transformer). If
all conditionals are met on each non-list, non-dict object,
the transformer tries to apply itself.
conditional: Callable that returns a Bool.
transformer: Callable transformer on non-dict, non-list objects. | [
"Decode",
"a",
"JSON",
"string",
"based",
"on",
"a",
"list",
"of",
"transformers",
"."
] | e624180c2291034960302c9e0b818b65b5a7ee11 | https://github.com/thieman/dagobah/blob/e624180c2291034960302c9e0b818b65b5a7ee11/dagobah/backend/base.py#L82-L132 | train | 34,563 |
singingwolfboy/flask-sse | flask_sse.py | ServerSentEventsBlueprint.publish | def publish(self, data, type=None, id=None, retry=None, channel='sse'):
"""
Publish data as a server-sent event.
:param data: The event data. If it is not a string, it will be
serialized to JSON using the Flask application's
:class:`~flask.json.JSONEncoder`.
:param type: An optional event type.
:param id: An optional event ID.
:param retry: An optional integer, to specify the reconnect time for
disconnected clients of this stream.
:param channel: If you want to direct different events to different
clients, you may specify a channel for this event to go to.
Only clients listening to the same channel will receive this event.
Defaults to "sse".
"""
message = Message(data, type=type, id=id, retry=retry)
msg_json = json.dumps(message.to_dict())
return self.redis.publish(channel=channel, message=msg_json) | python | def publish(self, data, type=None, id=None, retry=None, channel='sse'):
"""
Publish data as a server-sent event.
:param data: The event data. If it is not a string, it will be
serialized to JSON using the Flask application's
:class:`~flask.json.JSONEncoder`.
:param type: An optional event type.
:param id: An optional event ID.
:param retry: An optional integer, to specify the reconnect time for
disconnected clients of this stream.
:param channel: If you want to direct different events to different
clients, you may specify a channel for this event to go to.
Only clients listening to the same channel will receive this event.
Defaults to "sse".
"""
message = Message(data, type=type, id=id, retry=retry)
msg_json = json.dumps(message.to_dict())
return self.redis.publish(channel=channel, message=msg_json) | [
"def",
"publish",
"(",
"self",
",",
"data",
",",
"type",
"=",
"None",
",",
"id",
"=",
"None",
",",
"retry",
"=",
"None",
",",
"channel",
"=",
"'sse'",
")",
":",
"message",
"=",
"Message",
"(",
"data",
",",
"type",
"=",
"type",
",",
"id",
"=",
"... | Publish data as a server-sent event.
:param data: The event data. If it is not a string, it will be
serialized to JSON using the Flask application's
:class:`~flask.json.JSONEncoder`.
:param type: An optional event type.
:param id: An optional event ID.
:param retry: An optional integer, to specify the reconnect time for
disconnected clients of this stream.
:param channel: If you want to direct different events to different
clients, you may specify a channel for this event to go to.
Only clients listening to the same channel will receive this event.
Defaults to "sse". | [
"Publish",
"data",
"as",
"a",
"server",
"-",
"sent",
"event",
"."
] | a5c6afe12cd3c29c90588ad8a2c698c829af6572 | https://github.com/singingwolfboy/flask-sse/blob/a5c6afe12cd3c29c90588ad8a2c698c829af6572/flask_sse.py#L112-L130 | train | 34,564 |
rconradharris/envparse | envparse.py | Env.cast | def cast(cls, value, cast=str, subcast=None):
"""
Parse and cast provided value.
:param value: Stringed value.
:param cast: Type or callable to cast return value as.
:param subcast: Subtype or callable to cast return values as (used for
nested structures).
:returns: Value of type `cast`.
"""
if cast is bool:
value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
elif cast is float:
# Clean string
float_str = re.sub(r'[^\d,\.]', '', value)
# Split to handle thousand separator for different locales, i.e.
# comma or dot being the placeholder.
parts = re.split(r'[,\.]', float_str)
if len(parts) == 1:
float_str = parts[0]
else:
float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1])
value = float(float_str)
elif type(cast) is type and (issubclass(cast, list) or
issubclass(cast, tuple)):
value = (subcast(i.strip()) if subcast else i.strip() for i in
value.split(',') if i)
elif cast is dict:
value = {k.strip(): subcast(v.strip()) if subcast else v.strip()
for k, v in (i.split('=') for i in value.split(',') if
value)}
try:
return cast(value)
except ValueError as error:
raise ConfigurationError(*error.args) | python | def cast(cls, value, cast=str, subcast=None):
"""
Parse and cast provided value.
:param value: Stringed value.
:param cast: Type or callable to cast return value as.
:param subcast: Subtype or callable to cast return values as (used for
nested structures).
:returns: Value of type `cast`.
"""
if cast is bool:
value = value.lower() in cls.BOOLEAN_TRUE_STRINGS
elif cast is float:
# Clean string
float_str = re.sub(r'[^\d,\.]', '', value)
# Split to handle thousand separator for different locales, i.e.
# comma or dot being the placeholder.
parts = re.split(r'[,\.]', float_str)
if len(parts) == 1:
float_str = parts[0]
else:
float_str = "{0}.{1}".format(''.join(parts[0:-1]), parts[-1])
value = float(float_str)
elif type(cast) is type and (issubclass(cast, list) or
issubclass(cast, tuple)):
value = (subcast(i.strip()) if subcast else i.strip() for i in
value.split(',') if i)
elif cast is dict:
value = {k.strip(): subcast(v.strip()) if subcast else v.strip()
for k, v in (i.split('=') for i in value.split(',') if
value)}
try:
return cast(value)
except ValueError as error:
raise ConfigurationError(*error.args) | [
"def",
"cast",
"(",
"cls",
",",
"value",
",",
"cast",
"=",
"str",
",",
"subcast",
"=",
"None",
")",
":",
"if",
"cast",
"is",
"bool",
":",
"value",
"=",
"value",
".",
"lower",
"(",
")",
"in",
"cls",
".",
"BOOLEAN_TRUE_STRINGS",
"elif",
"cast",
"is",... | Parse and cast provided value.
:param value: Stringed value.
:param cast: Type or callable to cast return value as.
:param subcast: Subtype or callable to cast return values as (used for
nested structures).
:returns: Value of type `cast`. | [
"Parse",
"and",
"cast",
"provided",
"value",
"."
] | e67e70307af19d925e194b2a163e0608dae7eb55 | https://github.com/rconradharris/envparse/blob/e67e70307af19d925e194b2a163e0608dae7eb55/envparse.py#L117-L152 | train | 34,565 |
chishui/terminal-leetcode | leetcode/terminal.py | Terminal.reload_list | def reload_list(self):
'''Press R in home view to retrieve quiz list'''
self.leetcode.load()
if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0:
self.home_view = self.make_listview(self.leetcode.quizzes)
self.view_stack = []
self.goto_view(self.home_view) | python | def reload_list(self):
'''Press R in home view to retrieve quiz list'''
self.leetcode.load()
if self.leetcode.quizzes and len(self.leetcode.quizzes) > 0:
self.home_view = self.make_listview(self.leetcode.quizzes)
self.view_stack = []
self.goto_view(self.home_view) | [
"def",
"reload_list",
"(",
"self",
")",
":",
"self",
".",
"leetcode",
".",
"load",
"(",
")",
"if",
"self",
".",
"leetcode",
".",
"quizzes",
"and",
"len",
"(",
"self",
".",
"leetcode",
".",
"quizzes",
")",
">",
"0",
":",
"self",
".",
"home_view",
"=... | Press R in home view to retrieve quiz list | [
"Press",
"R",
"in",
"home",
"view",
"to",
"retrieve",
"quiz",
"list"
] | ad81924dbcac13da736f89a3b693ba13f2361906 | https://github.com/chishui/terminal-leetcode/blob/ad81924dbcac13da736f89a3b693ba13f2361906/leetcode/terminal.py#L116-L122 | train | 34,566 |
materialsvirtuallab/pyhull | pyhull/delaunay.py | DelaunayTri.simplices | def simplices(self):
"""
Returns the simplices of the triangulation.
"""
return [Simplex([self.points[i] for i in v]) for v in self.vertices] | python | def simplices(self):
"""
Returns the simplices of the triangulation.
"""
return [Simplex([self.points[i] for i in v]) for v in self.vertices] | [
"def",
"simplices",
"(",
"self",
")",
":",
"return",
"[",
"Simplex",
"(",
"[",
"self",
".",
"points",
"[",
"i",
"]",
"for",
"i",
"in",
"v",
"]",
")",
"for",
"v",
"in",
"self",
".",
"vertices",
"]"
] | Returns the simplices of the triangulation. | [
"Returns",
"the",
"simplices",
"of",
"the",
"triangulation",
"."
] | 01d4ee2c108ab3d8faa9b9ff476290ffee90073f | https://github.com/materialsvirtuallab/pyhull/blob/01d4ee2c108ab3d8faa9b9ff476290ffee90073f/pyhull/delaunay.py#L62-L66 | train | 34,567 |
materialsvirtuallab/pyhull | pyhull/__init__.py | qhull_cmd | def qhull_cmd(cmd, options, points):
"""
Generalized helper method to perform a qhull based command.
Args:
cmd:
Command to perform. Supported commands are qconvex,
qdelaunay and qvoronoi.
options:
Options to be provided for qhull command. See specific methods for
info on supported options. Up to two options separated by spaces
are supported.
points:
Sequence of points as input to qhull command.
Returns:
Output as a list of strings. E.g., ['4', '0 2', '1 0', '2 3 ', '3 1']
"""
prep_str = [str(len(points[0])), str(len(points))]
prep_str.extend([' '.join(map(repr, row)) for row in points])
output = getattr(hull, cmd)(options, "\n".join(prep_str))
return list(map(str.strip, output.strip().split("\n"))) | python | def qhull_cmd(cmd, options, points):
"""
Generalized helper method to perform a qhull based command.
Args:
cmd:
Command to perform. Supported commands are qconvex,
qdelaunay and qvoronoi.
options:
Options to be provided for qhull command. See specific methods for
info on supported options. Up to two options separated by spaces
are supported.
points:
Sequence of points as input to qhull command.
Returns:
Output as a list of strings. E.g., ['4', '0 2', '1 0', '2 3 ', '3 1']
"""
prep_str = [str(len(points[0])), str(len(points))]
prep_str.extend([' '.join(map(repr, row)) for row in points])
output = getattr(hull, cmd)(options, "\n".join(prep_str))
return list(map(str.strip, output.strip().split("\n"))) | [
"def",
"qhull_cmd",
"(",
"cmd",
",",
"options",
",",
"points",
")",
":",
"prep_str",
"=",
"[",
"str",
"(",
"len",
"(",
"points",
"[",
"0",
"]",
")",
")",
",",
"str",
"(",
"len",
"(",
"points",
")",
")",
"]",
"prep_str",
".",
"extend",
"(",
"[",... | Generalized helper method to perform a qhull based command.
Args:
cmd:
Command to perform. Supported commands are qconvex,
qdelaunay and qvoronoi.
options:
Options to be provided for qhull command. See specific methods for
info on supported options. Up to two options separated by spaces
are supported.
points:
Sequence of points as input to qhull command.
Returns:
Output as a list of strings. E.g., ['4', '0 2', '1 0', '2 3 ', '3 1'] | [
"Generalized",
"helper",
"method",
"to",
"perform",
"a",
"qhull",
"based",
"command",
"."
] | 01d4ee2c108ab3d8faa9b9ff476290ffee90073f | https://github.com/materialsvirtuallab/pyhull/blob/01d4ee2c108ab3d8faa9b9ff476290ffee90073f/pyhull/__init__.py#L19-L40 | train | 34,568 |
materialsvirtuallab/pyhull | pyhull/__init__.py | qhalf | def qhalf(options, halfspaces, interior_point):
"""
Similar to qvoronoi command in command-line qhull.
Args:
option:
An options string. Up to two options separated by spaces
are supported. See Qhull's qhalf help for info. Typically
used options are:
Fp
halfspaces:
List of Halfspaces as input.
interior_point:
An interior point (see qhalf documentation)
Returns:
Output as a list of strings.
E.g., ['3', '4', ' 1 1 0 ', ' 1 -1 2 ',
' -1 1 2 ', ' 1 1 2 ']
"""
points = [list(h.normal) + [h.offset] for h in halfspaces]
data = [[len(interior_point), 1]]
data.append(map(repr, interior_point))
data.append([len(points[0])])
data.append([len(points)])
data.extend([map(repr, row) for row in points])
prep_str = [" ".join(map(str, line)) for line in data]
output = getattr(hull, "qhalf")(options, "\n".join(prep_str))
return list(map(str.strip, output.strip().split("\n"))) | python | def qhalf(options, halfspaces, interior_point):
"""
Similar to qvoronoi command in command-line qhull.
Args:
option:
An options string. Up to two options separated by spaces
are supported. See Qhull's qhalf help for info. Typically
used options are:
Fp
halfspaces:
List of Halfspaces as input.
interior_point:
An interior point (see qhalf documentation)
Returns:
Output as a list of strings.
E.g., ['3', '4', ' 1 1 0 ', ' 1 -1 2 ',
' -1 1 2 ', ' 1 1 2 ']
"""
points = [list(h.normal) + [h.offset] for h in halfspaces]
data = [[len(interior_point), 1]]
data.append(map(repr, interior_point))
data.append([len(points[0])])
data.append([len(points)])
data.extend([map(repr, row) for row in points])
prep_str = [" ".join(map(str, line)) for line in data]
output = getattr(hull, "qhalf")(options, "\n".join(prep_str))
return list(map(str.strip, output.strip().split("\n"))) | [
"def",
"qhalf",
"(",
"options",
",",
"halfspaces",
",",
"interior_point",
")",
":",
"points",
"=",
"[",
"list",
"(",
"h",
".",
"normal",
")",
"+",
"[",
"h",
".",
"offset",
"]",
"for",
"h",
"in",
"halfspaces",
"]",
"data",
"=",
"[",
"[",
"len",
"(... | Similar to qvoronoi command in command-line qhull.
Args:
option:
An options string. Up to two options separated by spaces
are supported. See Qhull's qhalf help for info. Typically
used options are:
Fp
halfspaces:
List of Halfspaces as input.
interior_point:
An interior point (see qhalf documentation)
Returns:
Output as a list of strings.
E.g., ['3', '4', ' 1 1 0 ', ' 1 -1 2 ',
' -1 1 2 ', ' 1 1 2 '] | [
"Similar",
"to",
"qvoronoi",
"command",
"in",
"command",
"-",
"line",
"qhull",
"."
] | 01d4ee2c108ab3d8faa9b9ff476290ffee90073f | https://github.com/materialsvirtuallab/pyhull/blob/01d4ee2c108ab3d8faa9b9ff476290ffee90073f/pyhull/__init__.py#L111-L139 | train | 34,569 |
materialsvirtuallab/pyhull | pyhull/halfspace.py | Halfspace.from_hyperplane | def from_hyperplane(basis, origin, point, internal = True):
"""
Returns a Halfspace defined by a list of vectors parallel to the
bounding hyperplane.
Args:
basis: basis for the hyperplane (array with vector rows)
origin: point on the hyperplane
point: point not on the hyperplane
internal: whether point is inside the halfspace
"""
basis = np.array(basis)
assert basis.shape[0] + 1 == basis.shape[1]
big_basis = np.zeros((basis.shape[1], basis.shape[1]))
big_basis[:basis.shape[0],:basis.shape[1]] = basis
u, s, vh = np.linalg.svd(big_basis)
null_mask = (s <= 1e-8)
normal = np.compress(null_mask, vh, axis=0)[0]
if np.inner(np.array(point)-np.array(origin), normal) > 0:
if internal:
normal *= -1
else:
if not internal:
normal *= -1
offset = -np.dot(origin, normal)
return Halfspace(normal, offset) | python | def from_hyperplane(basis, origin, point, internal = True):
"""
Returns a Halfspace defined by a list of vectors parallel to the
bounding hyperplane.
Args:
basis: basis for the hyperplane (array with vector rows)
origin: point on the hyperplane
point: point not on the hyperplane
internal: whether point is inside the halfspace
"""
basis = np.array(basis)
assert basis.shape[0] + 1 == basis.shape[1]
big_basis = np.zeros((basis.shape[1], basis.shape[1]))
big_basis[:basis.shape[0],:basis.shape[1]] = basis
u, s, vh = np.linalg.svd(big_basis)
null_mask = (s <= 1e-8)
normal = np.compress(null_mask, vh, axis=0)[0]
if np.inner(np.array(point)-np.array(origin), normal) > 0:
if internal:
normal *= -1
else:
if not internal:
normal *= -1
offset = -np.dot(origin, normal)
return Halfspace(normal, offset) | [
"def",
"from_hyperplane",
"(",
"basis",
",",
"origin",
",",
"point",
",",
"internal",
"=",
"True",
")",
":",
"basis",
"=",
"np",
".",
"array",
"(",
"basis",
")",
"assert",
"basis",
".",
"shape",
"[",
"0",
"]",
"+",
"1",
"==",
"basis",
".",
"shape",... | Returns a Halfspace defined by a list of vectors parallel to the
bounding hyperplane.
Args:
basis: basis for the hyperplane (array with vector rows)
origin: point on the hyperplane
point: point not on the hyperplane
internal: whether point is inside the halfspace | [
"Returns",
"a",
"Halfspace",
"defined",
"by",
"a",
"list",
"of",
"vectors",
"parallel",
"to",
"the",
"bounding",
"hyperplane",
"."
] | 01d4ee2c108ab3d8faa9b9ff476290ffee90073f | https://github.com/materialsvirtuallab/pyhull/blob/01d4ee2c108ab3d8faa9b9ff476290ffee90073f/pyhull/halfspace.py#L36-L64 | train | 34,570 |
materialsvirtuallab/pyhull | pyhull/halfspace.py | HalfspaceIntersection.vertices | def vertices(self):
"""
Returns the vertices of the halfspace intersection
"""
if self._v_out is None:
output = qhalf('Fp', self.halfspaces, self.interior_point)
pts = []
for l in output[2:]:
pt = []
for c in l.split():
c = float(c)
if c != 10.101 and c != -10.101:
pt.append(c)
else:
pt.append(np.inf)
pts.append(pt)
self._v_out = np.array(pts)
return self._v_out | python | def vertices(self):
"""
Returns the vertices of the halfspace intersection
"""
if self._v_out is None:
output = qhalf('Fp', self.halfspaces, self.interior_point)
pts = []
for l in output[2:]:
pt = []
for c in l.split():
c = float(c)
if c != 10.101 and c != -10.101:
pt.append(c)
else:
pt.append(np.inf)
pts.append(pt)
self._v_out = np.array(pts)
return self._v_out | [
"def",
"vertices",
"(",
"self",
")",
":",
"if",
"self",
".",
"_v_out",
"is",
"None",
":",
"output",
"=",
"qhalf",
"(",
"'Fp'",
",",
"self",
".",
"halfspaces",
",",
"self",
".",
"interior_point",
")",
"pts",
"=",
"[",
"]",
"for",
"l",
"in",
"output"... | Returns the vertices of the halfspace intersection | [
"Returns",
"the",
"vertices",
"of",
"the",
"halfspace",
"intersection"
] | 01d4ee2c108ab3d8faa9b9ff476290ffee90073f | https://github.com/materialsvirtuallab/pyhull/blob/01d4ee2c108ab3d8faa9b9ff476290ffee90073f/pyhull/halfspace.py#L80-L97 | train | 34,571 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore._extract_player_stats | def _extract_player_stats(self, table, player_dict, home_or_away):
"""
Combine all player stats into a single object.
Since each player generally has a couple of rows worth of stats (one
for basic stats and another for advanced stats) on the boxscore page,
both rows should be combined into a single string object to easily
query all fields from a single object instead of determining which row
to pull metrics from.
Parameters
----------
table : PyQuery object
A PyQuery object of a single boxscore table, such as the home
team's advanced stats or the away team's basic stats.
player_dict : dictionary
A dictionary where each key is a string of the player's ID and each
value is a dictionary where the values contain the player's name,
HTML data, and a string constant indicating which team the player
is a member of.
home_or_away : string constant
A string constant indicating whether the player plays for the home
or away team.
Returns
-------
dictionary
Returns a ``dictionary`` where each key is a string of the player's
ID and each value is a dictionary where the values contain the
player's name, HTML data, and a string constant indicating which
team the player is a member of.
"""
for row in table('tbody tr').items():
player_id = self._find_player_id(row)
# Occurs when a header row is identified instead of a player.
if not player_id:
continue
name = self._find_player_name(row)
try:
player_dict[player_id]['data'] += str(row).strip()
except KeyError:
player_dict[player_id] = {
'name': name,
'data': str(row).strip(),
'team': home_or_away
}
return player_dict | python | def _extract_player_stats(self, table, player_dict, home_or_away):
"""
Combine all player stats into a single object.
Since each player generally has a couple of rows worth of stats (one
for basic stats and another for advanced stats) on the boxscore page,
both rows should be combined into a single string object to easily
query all fields from a single object instead of determining which row
to pull metrics from.
Parameters
----------
table : PyQuery object
A PyQuery object of a single boxscore table, such as the home
team's advanced stats or the away team's basic stats.
player_dict : dictionary
A dictionary where each key is a string of the player's ID and each
value is a dictionary where the values contain the player's name,
HTML data, and a string constant indicating which team the player
is a member of.
home_or_away : string constant
A string constant indicating whether the player plays for the home
or away team.
Returns
-------
dictionary
Returns a ``dictionary`` where each key is a string of the player's
ID and each value is a dictionary where the values contain the
player's name, HTML data, and a string constant indicating which
team the player is a member of.
"""
for row in table('tbody tr').items():
player_id = self._find_player_id(row)
# Occurs when a header row is identified instead of a player.
if not player_id:
continue
name = self._find_player_name(row)
try:
player_dict[player_id]['data'] += str(row).strip()
except KeyError:
player_dict[player_id] = {
'name': name,
'data': str(row).strip(),
'team': home_or_away
}
return player_dict | [
"def",
"_extract_player_stats",
"(",
"self",
",",
"table",
",",
"player_dict",
",",
"home_or_away",
")",
":",
"for",
"row",
"in",
"table",
"(",
"'tbody tr'",
")",
".",
"items",
"(",
")",
":",
"player_id",
"=",
"self",
".",
"_find_player_id",
"(",
"row",
... | Combine all player stats into a single object.
Since each player generally has a couple of rows worth of stats (one
for basic stats and another for advanced stats) on the boxscore page,
both rows should be combined into a single string object to easily
query all fields from a single object instead of determining which row
to pull metrics from.
Parameters
----------
table : PyQuery object
A PyQuery object of a single boxscore table, such as the home
team's advanced stats or the away team's basic stats.
player_dict : dictionary
A dictionary where each key is a string of the player's ID and each
value is a dictionary where the values contain the player's name,
HTML data, and a string constant indicating which team the player
is a member of.
home_or_away : string constant
A string constant indicating whether the player plays for the home
or away team.
Returns
-------
dictionary
Returns a ``dictionary`` where each key is a string of the player's
ID and each value is a dictionary where the values contain the
player's name, HTML data, and a string constant indicating which
team the player is a member of. | [
"Combine",
"all",
"player",
"stats",
"into",
"a",
"single",
"object",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L601-L647 | train | 34,572 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore._instantiate_players | def _instantiate_players(self, player_dict):
"""
Create a list of player instances for both the home and away teams.
For every player listed on the boxscores page, create an instance of
the BoxscorePlayer class for that player and add them to a list of
players for their respective team.
Parameters
----------
player_dict : dictionary
A dictionary containing information for every player on the
boxscores page. Each key is a string containing the player's ID
and each value is a dictionary with the player's full name, a
string representation of their HTML stats, and a string constant
denoting which team they play for as the values.
Returns
-------
tuple
Returns a ``tuple`` in the format (away_players, home_players)
where each element is a list of player instances for the away and
home teams, respectively.
"""
home_players = []
away_players = []
for player_id, details in player_dict.items():
player = BoxscorePlayer(player_id,
details['name'],
details['data'])
if details['team'] == HOME:
home_players.append(player)
else:
away_players.append(player)
return away_players, home_players | python | def _instantiate_players(self, player_dict):
"""
Create a list of player instances for both the home and away teams.
For every player listed on the boxscores page, create an instance of
the BoxscorePlayer class for that player and add them to a list of
players for their respective team.
Parameters
----------
player_dict : dictionary
A dictionary containing information for every player on the
boxscores page. Each key is a string containing the player's ID
and each value is a dictionary with the player's full name, a
string representation of their HTML stats, and a string constant
denoting which team they play for as the values.
Returns
-------
tuple
Returns a ``tuple`` in the format (away_players, home_players)
where each element is a list of player instances for the away and
home teams, respectively.
"""
home_players = []
away_players = []
for player_id, details in player_dict.items():
player = BoxscorePlayer(player_id,
details['name'],
details['data'])
if details['team'] == HOME:
home_players.append(player)
else:
away_players.append(player)
return away_players, home_players | [
"def",
"_instantiate_players",
"(",
"self",
",",
"player_dict",
")",
":",
"home_players",
"=",
"[",
"]",
"away_players",
"=",
"[",
"]",
"for",
"player_id",
",",
"details",
"in",
"player_dict",
".",
"items",
"(",
")",
":",
"player",
"=",
"BoxscorePlayer",
"... | Create a list of player instances for both the home and away teams.
For every player listed on the boxscores page, create an instance of
the BoxscorePlayer class for that player and add them to a list of
players for their respective team.
Parameters
----------
player_dict : dictionary
A dictionary containing information for every player on the
boxscores page. Each key is a string containing the player's ID
and each value is a dictionary with the player's full name, a
string representation of their HTML stats, and a string constant
denoting which team they play for as the values.
Returns
-------
tuple
Returns a ``tuple`` in the format (away_players, home_players)
where each element is a list of player instances for the away and
home teams, respectively. | [
"Create",
"a",
"list",
"of",
"player",
"instances",
"for",
"both",
"the",
"home",
"and",
"away",
"teams",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L649-L683 | train | 34,573 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore.winning_name | def winning_name(self):
"""
Returns a ``string`` of the winning team's name, such as 'Houston
Astros'.
"""
if self.winner == HOME:
return self._home_name.text()
return self._away_name.text() | python | def winning_name(self):
"""
Returns a ``string`` of the winning team's name, such as 'Houston
Astros'.
"""
if self.winner == HOME:
return self._home_name.text()
return self._away_name.text() | [
"def",
"winning_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"return",
"self",
".",
"_home_name",
".",
"text",
"(",
")",
"return",
"self",
".",
"_away_name",
".",
"text",
"(",
")"
] | Returns a ``string`` of the winning team's name, such as 'Houston
Astros'. | [
"Returns",
"a",
"string",
"of",
"the",
"winning",
"team",
"s",
"name",
"such",
"as",
"Houston",
"Astros",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L953-L960 | train | 34,574 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore.winning_abbr | def winning_abbr(self):
"""
Returns a ``string`` of the winning team's abbreviation, such as 'HOU'
for the Houston Astros.
"""
if self.winner == HOME:
return utils._parse_abbreviation(self._home_name)
return utils._parse_abbreviation(self._away_name) | python | def winning_abbr(self):
"""
Returns a ``string`` of the winning team's abbreviation, such as 'HOU'
for the Houston Astros.
"""
if self.winner == HOME:
return utils._parse_abbreviation(self._home_name)
return utils._parse_abbreviation(self._away_name) | [
"def",
"winning_abbr",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"return",
"utils",
".",
"_parse_abbreviation",
"(",
"self",
".",
"_home_name",
")",
"return",
"utils",
".",
"_parse_abbreviation",
"(",
"self",
".",
"_away_name",
... | Returns a ``string`` of the winning team's abbreviation, such as 'HOU'
for the Houston Astros. | [
"Returns",
"a",
"string",
"of",
"the",
"winning",
"team",
"s",
"abbreviation",
"such",
"as",
"HOU",
"for",
"the",
"Houston",
"Astros",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L963-L970 | train | 34,575 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore.losing_name | def losing_name(self):
"""
Returns a ``string`` of the losing team's name, such as 'Los Angeles
Dodgers'.
"""
if self.winner == HOME:
return self._away_name.text()
return self._home_name.text() | python | def losing_name(self):
"""
Returns a ``string`` of the losing team's name, such as 'Los Angeles
Dodgers'.
"""
if self.winner == HOME:
return self._away_name.text()
return self._home_name.text() | [
"def",
"losing_name",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"return",
"self",
".",
"_away_name",
".",
"text",
"(",
")",
"return",
"self",
".",
"_home_name",
".",
"text",
"(",
")"
] | Returns a ``string`` of the losing team's name, such as 'Los Angeles
Dodgers'. | [
"Returns",
"a",
"string",
"of",
"the",
"losing",
"team",
"s",
"name",
"such",
"as",
"Los",
"Angeles",
"Dodgers",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L973-L980 | train | 34,576 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscore.losing_abbr | def losing_abbr(self):
"""
Returns a ``string`` of the losing team's abbreviation, such as 'LAD'
for the Los Angeles Dodgers.
"""
if self.winner == HOME:
return utils._parse_abbreviation(self._away_name)
return utils._parse_abbreviation(self._home_name) | python | def losing_abbr(self):
"""
Returns a ``string`` of the losing team's abbreviation, such as 'LAD'
for the Los Angeles Dodgers.
"""
if self.winner == HOME:
return utils._parse_abbreviation(self._away_name)
return utils._parse_abbreviation(self._home_name) | [
"def",
"losing_abbr",
"(",
"self",
")",
":",
"if",
"self",
".",
"winner",
"==",
"HOME",
":",
"return",
"utils",
".",
"_parse_abbreviation",
"(",
"self",
".",
"_away_name",
")",
"return",
"utils",
".",
"_parse_abbreviation",
"(",
"self",
".",
"_home_name",
... | Returns a ``string`` of the losing team's abbreviation, such as 'LAD'
for the Los Angeles Dodgers. | [
"Returns",
"a",
"string",
"of",
"the",
"losing",
"team",
"s",
"abbreviation",
"such",
"as",
"LAD",
"for",
"the",
"Los",
"Angeles",
"Dodgers",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L983-L990 | train | 34,577 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscores._create_url | def _create_url(self, date):
"""
Build the URL based on the passed datetime object.
In order to get the proper boxscore page, the URL needs to include the
requested month, day, and year.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
Returns
-------
string
Returns a ``string`` of the boxscore URL including the requested
date.
"""
return BOXSCORES_URL % (date.year, date.month, date.day) | python | def _create_url(self, date):
"""
Build the URL based on the passed datetime object.
In order to get the proper boxscore page, the URL needs to include the
requested month, day, and year.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
Returns
-------
string
Returns a ``string`` of the boxscore URL including the requested
date.
"""
return BOXSCORES_URL % (date.year, date.month, date.day) | [
"def",
"_create_url",
"(",
"self",
",",
"date",
")",
":",
"return",
"BOXSCORES_URL",
"%",
"(",
"date",
".",
"year",
",",
"date",
".",
"month",
",",
"date",
".",
"day",
")"
] | Build the URL based on the passed datetime object.
In order to get the proper boxscore page, the URL needs to include the
requested month, day, and year.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
Returns
-------
string
Returns a ``string`` of the boxscore URL including the requested
date. | [
"Build",
"the",
"URL",
"based",
"on",
"the",
"passed",
"datetime",
"object",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L1606-L1625 | train | 34,578 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscores._get_score | def _get_score(self, score_link):
"""
Find a team's final score.
Given an HTML string of a team's boxscore, extract the integer
representing the final score and return the number.
Parameters
----------
score_link : string
An HTML string representing a team's final score in the format
'<td class="right">NN</td>' where 'NN' is the team's score.
Returns
-------
int
Returns an int representing the team's final score in runs.
"""
score = score_link.replace('<td class="right">', '')
score = score.replace('</td>', '')
return int(score) | python | def _get_score(self, score_link):
"""
Find a team's final score.
Given an HTML string of a team's boxscore, extract the integer
representing the final score and return the number.
Parameters
----------
score_link : string
An HTML string representing a team's final score in the format
'<td class="right">NN</td>' where 'NN' is the team's score.
Returns
-------
int
Returns an int representing the team's final score in runs.
"""
score = score_link.replace('<td class="right">', '')
score = score.replace('</td>', '')
return int(score) | [
"def",
"_get_score",
"(",
"self",
",",
"score_link",
")",
":",
"score",
"=",
"score_link",
".",
"replace",
"(",
"'<td class=\"right\">'",
",",
"''",
")",
"score",
"=",
"score",
".",
"replace",
"(",
"'</td>'",
",",
"''",
")",
"return",
"int",
"(",
"score"... | Find a team's final score.
Given an HTML string of a team's boxscore, extract the integer
representing the final score and return the number.
Parameters
----------
score_link : string
An HTML string representing a team's final score in the format
'<td class="right">NN</td>' where 'NN' is the team's score.
Returns
-------
int
Returns an int representing the team's final score in runs. | [
"Find",
"a",
"team",
"s",
"final",
"score",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L1711-L1731 | train | 34,579 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscores._get_team_results | def _get_team_results(self, team_result_html):
"""
Extract the winning or losing team's name and abbreviation.
Depending on which team's data field is passed (either the winner or
loser), return the name and abbreviation of that team to denote which
team won and which lost the game.
Parameters
----------
team_result_html : PyQuery object
A PyQuery object representing either the winning or losing team's
data field within the boxscore.
Returns
-------
tuple
Returns a tuple of the team's name followed by the abbreviation.
"""
link = [i for i in team_result_html('td a').items()]
# If there are no links, the boxscore is likely misformed and can't be
# parsed. In this case, the boxscore should be skipped.
if len(link) < 1:
return None
name, abbreviation = self._get_name(link[0])
return name, abbreviation | python | def _get_team_results(self, team_result_html):
"""
Extract the winning or losing team's name and abbreviation.
Depending on which team's data field is passed (either the winner or
loser), return the name and abbreviation of that team to denote which
team won and which lost the game.
Parameters
----------
team_result_html : PyQuery object
A PyQuery object representing either the winning or losing team's
data field within the boxscore.
Returns
-------
tuple
Returns a tuple of the team's name followed by the abbreviation.
"""
link = [i for i in team_result_html('td a').items()]
# If there are no links, the boxscore is likely misformed and can't be
# parsed. In this case, the boxscore should be skipped.
if len(link) < 1:
return None
name, abbreviation = self._get_name(link[0])
return name, abbreviation | [
"def",
"_get_team_results",
"(",
"self",
",",
"team_result_html",
")",
":",
"link",
"=",
"[",
"i",
"for",
"i",
"in",
"team_result_html",
"(",
"'td a'",
")",
".",
"items",
"(",
")",
"]",
"# If there are no links, the boxscore is likely misformed and can't be",
"# par... | Extract the winning or losing team's name and abbreviation.
Depending on which team's data field is passed (either the winner or
loser), return the name and abbreviation of that team to denote which
team won and which lost the game.
Parameters
----------
team_result_html : PyQuery object
A PyQuery object representing either the winning or losing team's
data field within the boxscore.
Returns
-------
tuple
Returns a tuple of the team's name followed by the abbreviation. | [
"Extract",
"the",
"winning",
"or",
"losing",
"team",
"s",
"name",
"and",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L1771-L1796 | train | 34,580 |
roclark/sportsreference | sportsreference/mlb/boxscore.py | Boxscores._find_games | def _find_games(self, date, end_date):
"""
Retrieve all major games played on a given day.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that day. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
end_date : datetime object (optional)
Optionally specify an end date to iterate until. All boxscores
starting from the date specified in the 'date' parameter up to and
including the boxscores specified in the 'end_date' parameter will
be pulled. If left empty, or if 'end_date' is prior to 'date', only
the games from the day specified in the 'date' parameter will be
saved.
"""
# Set the end date to the start date if the end date is before the
# start date.
if not end_date or date > end_date:
end_date = date
date_step = date
while date_step <= end_date:
url = self._create_url(date_step)
page = self._get_requested_page(url)
games = page('table[class="teams"]').items()
boxscores = self._extract_game_info(games)
timestamp = '%s-%s-%s' % (date_step.month, date_step.day,
date_step.year)
self._boxscores[timestamp] = boxscores
date_step += timedelta(days=1) | python | def _find_games(self, date, end_date):
"""
Retrieve all major games played on a given day.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that day. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
end_date : datetime object (optional)
Optionally specify an end date to iterate until. All boxscores
starting from the date specified in the 'date' parameter up to and
including the boxscores specified in the 'end_date' parameter will
be pulled. If left empty, or if 'end_date' is prior to 'date', only
the games from the day specified in the 'date' parameter will be
saved.
"""
# Set the end date to the start date if the end date is before the
# start date.
if not end_date or date > end_date:
end_date = date
date_step = date
while date_step <= end_date:
url = self._create_url(date_step)
page = self._get_requested_page(url)
games = page('table[class="teams"]').items()
boxscores = self._extract_game_info(games)
timestamp = '%s-%s-%s' % (date_step.month, date_step.day,
date_step.year)
self._boxscores[timestamp] = boxscores
date_step += timedelta(days=1) | [
"def",
"_find_games",
"(",
"self",
",",
"date",
",",
"end_date",
")",
":",
"# Set the end date to the start date if the end date is before the",
"# start date.",
"if",
"not",
"end_date",
"or",
"date",
">",
"end_date",
":",
"end_date",
"=",
"date",
"date_step",
"=",
... | Retrieve all major games played on a given day.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that day. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
date : datetime object
The date to search for any matches. The month, day, and year are
required for the search, but time is not factored into the search.
end_date : datetime object (optional)
Optionally specify an end date to iterate until. All boxscores
starting from the date specified in the 'date' parameter up to and
including the boxscores specified in the 'end_date' parameter will
be pulled. If left empty, or if 'end_date' is prior to 'date', only
the games from the day specified in the 'date' parameter will be
saved. | [
"Retrieve",
"all",
"major",
"games",
"played",
"on",
"a",
"given",
"day",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/mlb/boxscore.py#L1866-L1902 | train | 34,581 |
roclark/sportsreference | sportsreference/nfl/roster.py | Player._parse_season | def _parse_season(self, row):
"""
Parse the season string from the table.
The season is generally located in the first column of the stats tables
and should be parsed to detonate which season metrics are being pulled
from.
Parameters
----------
row : PyQuery object
A PyQuery object of a single row in a stats table.
Returns
-------
string
A string representation of the season in the format 'YYYY', such as
'2017'.
"""
season = utils._parse_field(PLAYER_SCHEME, row, 'season')
return season.replace('*', '').replace('+', '') | python | def _parse_season(self, row):
"""
Parse the season string from the table.
The season is generally located in the first column of the stats tables
and should be parsed to detonate which season metrics are being pulled
from.
Parameters
----------
row : PyQuery object
A PyQuery object of a single row in a stats table.
Returns
-------
string
A string representation of the season in the format 'YYYY', such as
'2017'.
"""
season = utils._parse_field(PLAYER_SCHEME, row, 'season')
return season.replace('*', '').replace('+', '') | [
"def",
"_parse_season",
"(",
"self",
",",
"row",
")",
":",
"season",
"=",
"utils",
".",
"_parse_field",
"(",
"PLAYER_SCHEME",
",",
"row",
",",
"'season'",
")",
"return",
"season",
".",
"replace",
"(",
"'*'",
",",
"''",
")",
".",
"replace",
"(",
"'+'",
... | Parse the season string from the table.
The season is generally located in the first column of the stats tables
and should be parsed to detonate which season metrics are being pulled
from.
Parameters
----------
row : PyQuery object
A PyQuery object of a single row in a stats table.
Returns
-------
string
A string representation of the season in the format 'YYYY', such as
'2017'. | [
"Parse",
"the",
"season",
"string",
"from",
"the",
"table",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L249-L269 | train | 34,582 |
roclark/sportsreference | sportsreference/nfl/roster.py | Player._combine_season_stats | def _combine_season_stats(self, table_rows, career_stats, all_stats_dict):
"""
Combine all stats for each season.
Since all of the stats are spread across multiple tables, they should
be combined into a single field which can be used to easily query stats
at once.
Parameters
----------
table_rows : generator
A generator where each element is a row in a stats table.
career_stats : generator
A generator where each element is a row in the footer of a stats
table. Career stats are kept in the footer, hence the usage.
all_stats_dict : dictionary
A dictionary of all stats separated by season where each key is the
season ``string``, such as '2017', and the value is a
``dictionary`` with a ``string`` of 'data' and ``string``
containing all of the data.
Returns
-------
dictionary
Returns an updated version of the passed all_stats_dict which
includes more metrics from the provided table.
"""
most_recent_season = self._most_recent_season
if not table_rows:
table_rows = []
for row in table_rows:
season = self._parse_season(row)
try:
all_stats_dict[season]['data'] += str(row)
except KeyError:
all_stats_dict[season] = {'data': str(row)}
most_recent_season = season
self._most_recent_season = most_recent_season
if not career_stats:
return all_stats_dict
try:
all_stats_dict['Career']['data'] += str(next(career_stats))
except KeyError:
try:
all_stats_dict['Career'] = {'data': str(next(career_stats))}
# Occurs when the player doesn't have any career stats listed on
# their page in error.
except StopIteration:
return all_stats_dict
return all_stats_dict | python | def _combine_season_stats(self, table_rows, career_stats, all_stats_dict):
"""
Combine all stats for each season.
Since all of the stats are spread across multiple tables, they should
be combined into a single field which can be used to easily query stats
at once.
Parameters
----------
table_rows : generator
A generator where each element is a row in a stats table.
career_stats : generator
A generator where each element is a row in the footer of a stats
table. Career stats are kept in the footer, hence the usage.
all_stats_dict : dictionary
A dictionary of all stats separated by season where each key is the
season ``string``, such as '2017', and the value is a
``dictionary`` with a ``string`` of 'data' and ``string``
containing all of the data.
Returns
-------
dictionary
Returns an updated version of the passed all_stats_dict which
includes more metrics from the provided table.
"""
most_recent_season = self._most_recent_season
if not table_rows:
table_rows = []
for row in table_rows:
season = self._parse_season(row)
try:
all_stats_dict[season]['data'] += str(row)
except KeyError:
all_stats_dict[season] = {'data': str(row)}
most_recent_season = season
self._most_recent_season = most_recent_season
if not career_stats:
return all_stats_dict
try:
all_stats_dict['Career']['data'] += str(next(career_stats))
except KeyError:
try:
all_stats_dict['Career'] = {'data': str(next(career_stats))}
# Occurs when the player doesn't have any career stats listed on
# their page in error.
except StopIteration:
return all_stats_dict
return all_stats_dict | [
"def",
"_combine_season_stats",
"(",
"self",
",",
"table_rows",
",",
"career_stats",
",",
"all_stats_dict",
")",
":",
"most_recent_season",
"=",
"self",
".",
"_most_recent_season",
"if",
"not",
"table_rows",
":",
"table_rows",
"=",
"[",
"]",
"for",
"row",
"in",
... | Combine all stats for each season.
Since all of the stats are spread across multiple tables, they should
be combined into a single field which can be used to easily query stats
at once.
Parameters
----------
table_rows : generator
A generator where each element is a row in a stats table.
career_stats : generator
A generator where each element is a row in the footer of a stats
table. Career stats are kept in the footer, hence the usage.
all_stats_dict : dictionary
A dictionary of all stats separated by season where each key is the
season ``string``, such as '2017', and the value is a
``dictionary`` with a ``string`` of 'data' and ``string``
containing all of the data.
Returns
-------
dictionary
Returns an updated version of the passed all_stats_dict which
includes more metrics from the provided table. | [
"Combine",
"all",
"stats",
"for",
"each",
"season",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L271-L320 | train | 34,583 |
roclark/sportsreference | sportsreference/nfl/roster.py | Player._parse_player_information | def _parse_player_information(self, player_info):
"""
Parse general player information.
Parse general player information such as height, weight, and name. The
attribute for the requested field will be set with the value prior to
returning.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
"""
for field in ['_height', '_weight', '_name']:
short_field = str(field)[1:]
value = utils._parse_field(PLAYER_SCHEME, player_info, short_field)
setattr(self, field, value) | python | def _parse_player_information(self, player_info):
"""
Parse general player information.
Parse general player information such as height, weight, and name. The
attribute for the requested field will be set with the value prior to
returning.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page.
"""
for field in ['_height', '_weight', '_name']:
short_field = str(field)[1:]
value = utils._parse_field(PLAYER_SCHEME, player_info, short_field)
setattr(self, field, value) | [
"def",
"_parse_player_information",
"(",
"self",
",",
"player_info",
")",
":",
"for",
"field",
"in",
"[",
"'_height'",
",",
"'_weight'",
",",
"'_name'",
"]",
":",
"short_field",
"=",
"str",
"(",
"field",
")",
"[",
"1",
":",
"]",
"value",
"=",
"utils",
... | Parse general player information.
Parse general player information such as height, weight, and name. The
attribute for the requested field will be set with the value prior to
returning.
Parameters
----------
player_info : PyQuery object
A PyQuery object containing the HTML from the player's stats page. | [
"Parse",
"general",
"player",
"information",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L357-L373 | train | 34,584 |
roclark/sportsreference | sportsreference/nfl/roster.py | Player.dataframe | def dataframe(self):
"""
Returns a ``pandas DataFrame`` containing all other relevant class
properties and values where each index is a different season plus the
career stats.
"""
temp_index = self._index
rows = []
indices = []
if not self._season:
return None
for season in self._season:
self._index = self._season.index(season)
rows.append(self._dataframe_fields())
indices.append(season)
self._index = temp_index
return pd.DataFrame(rows, index=[indices]) | python | def dataframe(self):
"""
Returns a ``pandas DataFrame`` containing all other relevant class
properties and values where each index is a different season plus the
career stats.
"""
temp_index = self._index
rows = []
indices = []
if not self._season:
return None
for season in self._season:
self._index = self._season.index(season)
rows.append(self._dataframe_fields())
indices.append(season)
self._index = temp_index
return pd.DataFrame(rows, index=[indices]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"temp_index",
"=",
"self",
".",
"_index",
"rows",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"_season",
":",
"return",
"None",
"for",
"season",
"in",
"self",
".",
"_season",
":",
"s... | Returns a ``pandas DataFrame`` containing all other relevant class
properties and values where each index is a different season plus the
career stats. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"relevant",
"class",
"properties",
"and",
"values",
"where",
"each",
"index",
"is",
"a",
"different",
"season",
"plus",
"the",
"career",
"stats",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/roster.py#L611-L627 | train | 34,585 |
roclark/sportsreference | sportsreference/utils.py | _find_year_for_season | def _find_year_for_season(league):
"""
Return the necessary seaons's year based on the current date.
Since all sports start and end at different times throughout the year,
simply using the current year is not sufficient to describe a season. For
example, the NCAA Men's Basketball season begins in November every year.
However, for the November and December months, the following year is used
to denote the season (ie. November 2017 marks the start of the '2018'
season) on sports-reference.com. This rule does not apply to all sports.
Baseball begins and ends in one single calendar year, so the year never
needs to be incremented.
Additionally, since information for future seasons is generally not
finalized until a month before the season begins, the year will default to
the most recent season until the month prior to the season start date. For
example, the 2018 MLB season begins in April. In January 2018, however, not
all of the season's information is present in the system, so the default
year will be '2017'.
Parameters
----------
league : string
A string pertaining to the league start information as listed in
SEASON_START_MONTH (ie. 'mlb', 'nba', 'nfl', etc.). League must be
present in SEASON_START_MONTH.
Returns
-------
int
The respective season's year.
Raises
------
ValueError
If the passed 'league' is not a key in SEASON_START_MONTH.
"""
today = _todays_date()
if league not in SEASON_START_MONTH:
raise ValueError('"%s" league cannot be found!')
start = SEASON_START_MONTH[league]['start']
wrap = SEASON_START_MONTH[league]['wrap']
if wrap and start - 1 <= today.month <= 12:
return today.year + 1
elif not wrap and start == 1 and today.month == 12:
return today.year + 1
elif not wrap and not start - 1 <= today.month <= 12:
return today.year - 1
else:
return today.year | python | def _find_year_for_season(league):
"""
Return the necessary seaons's year based on the current date.
Since all sports start and end at different times throughout the year,
simply using the current year is not sufficient to describe a season. For
example, the NCAA Men's Basketball season begins in November every year.
However, for the November and December months, the following year is used
to denote the season (ie. November 2017 marks the start of the '2018'
season) on sports-reference.com. This rule does not apply to all sports.
Baseball begins and ends in one single calendar year, so the year never
needs to be incremented.
Additionally, since information for future seasons is generally not
finalized until a month before the season begins, the year will default to
the most recent season until the month prior to the season start date. For
example, the 2018 MLB season begins in April. In January 2018, however, not
all of the season's information is present in the system, so the default
year will be '2017'.
Parameters
----------
league : string
A string pertaining to the league start information as listed in
SEASON_START_MONTH (ie. 'mlb', 'nba', 'nfl', etc.). League must be
present in SEASON_START_MONTH.
Returns
-------
int
The respective season's year.
Raises
------
ValueError
If the passed 'league' is not a key in SEASON_START_MONTH.
"""
today = _todays_date()
if league not in SEASON_START_MONTH:
raise ValueError('"%s" league cannot be found!')
start = SEASON_START_MONTH[league]['start']
wrap = SEASON_START_MONTH[league]['wrap']
if wrap and start - 1 <= today.month <= 12:
return today.year + 1
elif not wrap and start == 1 and today.month == 12:
return today.year + 1
elif not wrap and not start - 1 <= today.month <= 12:
return today.year - 1
else:
return today.year | [
"def",
"_find_year_for_season",
"(",
"league",
")",
":",
"today",
"=",
"_todays_date",
"(",
")",
"if",
"league",
"not",
"in",
"SEASON_START_MONTH",
":",
"raise",
"ValueError",
"(",
"'\"%s\" league cannot be found!'",
")",
"start",
"=",
"SEASON_START_MONTH",
"[",
"... | Return the necessary seaons's year based on the current date.
Since all sports start and end at different times throughout the year,
simply using the current year is not sufficient to describe a season. For
example, the NCAA Men's Basketball season begins in November every year.
However, for the November and December months, the following year is used
to denote the season (ie. November 2017 marks the start of the '2018'
season) on sports-reference.com. This rule does not apply to all sports.
Baseball begins and ends in one single calendar year, so the year never
needs to be incremented.
Additionally, since information for future seasons is generally not
finalized until a month before the season begins, the year will default to
the most recent season until the month prior to the season start date. For
example, the 2018 MLB season begins in April. In January 2018, however, not
all of the season's information is present in the system, so the default
year will be '2017'.
Parameters
----------
league : string
A string pertaining to the league start information as listed in
SEASON_START_MONTH (ie. 'mlb', 'nba', 'nfl', etc.). League must be
present in SEASON_START_MONTH.
Returns
-------
int
The respective season's year.
Raises
------
ValueError
If the passed 'league' is not a key in SEASON_START_MONTH. | [
"Return",
"the",
"necessary",
"seaons",
"s",
"year",
"based",
"on",
"the",
"current",
"date",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/utils.py#L41-L90 | train | 34,586 |
roclark/sportsreference | sportsreference/utils.py | _parse_abbreviation | def _parse_abbreviation(uri_link):
"""
Returns a team's abbreviation.
A school or team's abbreviation is generally embedded in a URI link which
contains other relative link information. For example, the URI for the
New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This
function strips all of the contents before and after "nwe" and converts it
to uppercase and returns "NWE".
Parameters
----------
uri_link : string
A URI link which contains a team's abbreviation within other link
contents.
Returns
-------
string
The shortened uppercase abbreviation for a given team.
"""
abbr = re.sub(r'/[0-9]+\..*htm.*', '', uri_link('a').attr('href'))
abbr = re.sub(r'/.*/schools/', '', abbr)
abbr = re.sub(r'/teams/', '', abbr)
return abbr.upper() | python | def _parse_abbreviation(uri_link):
"""
Returns a team's abbreviation.
A school or team's abbreviation is generally embedded in a URI link which
contains other relative link information. For example, the URI for the
New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This
function strips all of the contents before and after "nwe" and converts it
to uppercase and returns "NWE".
Parameters
----------
uri_link : string
A URI link which contains a team's abbreviation within other link
contents.
Returns
-------
string
The shortened uppercase abbreviation for a given team.
"""
abbr = re.sub(r'/[0-9]+\..*htm.*', '', uri_link('a').attr('href'))
abbr = re.sub(r'/.*/schools/', '', abbr)
abbr = re.sub(r'/teams/', '', abbr)
return abbr.upper() | [
"def",
"_parse_abbreviation",
"(",
"uri_link",
")",
":",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'/[0-9]+\\..*htm.*'",
",",
"''",
",",
"uri_link",
"(",
"'a'",
")",
".",
"attr",
"(",
"'href'",
")",
")",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'/.*/schools/'... | Returns a team's abbreviation.
A school or team's abbreviation is generally embedded in a URI link which
contains other relative link information. For example, the URI for the
New England Patriots for the 2017 season is "/teams/nwe/2017.htm". This
function strips all of the contents before and after "nwe" and converts it
to uppercase and returns "NWE".
Parameters
----------
uri_link : string
A URI link which contains a team's abbreviation within other link
contents.
Returns
-------
string
The shortened uppercase abbreviation for a given team. | [
"Returns",
"a",
"team",
"s",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/utils.py#L93-L117 | train | 34,587 |
roclark/sportsreference | sportsreference/utils.py | _parse_field | def _parse_field(parsing_scheme, html_data, field, index=0):
"""
Parse an HTML table to find the requested field's value.
All of the values are passed in an HTML table row instead of as individual
items. The values need to be parsed by matching the requested attribute
with a parsing scheme that sports-reference uses to differentiate stats.
This function returns a single value for the given attribute.
Parameters
----------
parsing_scheme : dict
A dictionary of the parsing scheme to be used to find the desired
field. The key corresponds to the attribute name to parse, and the
value is a PyQuery-readable parsing scheme as a string (such as
'td[data-stat="wins"]').
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in
parsing_scheme.
index : int (optional)
An optional index if multiple fields have the same attribute name. For
example, 'HR' may stand for the number of home runs a baseball team has
hit, or the number of home runs a pitcher has given up. The index
aligns with the order in which the attributes are recevied in the
html_data parameter.
Returns
-------
string
The value at the specified index for the requested field. If no value
could be found, returns None.
"""
if field == 'abbreviation':
return _parse_abbreviation(html_data)
scheme = parsing_scheme[field]
items = [i.text() for i in html_data(scheme).items()]
# Stats can be added and removed on a yearly basis. If not stats are found,
# return None and have the be the value.
if len(items) == 0:
return None
# Default to returning the first element. Optionally return another element
# if multiple fields have the same tag attribute.
try:
return items[index]
except IndexError:
return None | python | def _parse_field(parsing_scheme, html_data, field, index=0):
"""
Parse an HTML table to find the requested field's value.
All of the values are passed in an HTML table row instead of as individual
items. The values need to be parsed by matching the requested attribute
with a parsing scheme that sports-reference uses to differentiate stats.
This function returns a single value for the given attribute.
Parameters
----------
parsing_scheme : dict
A dictionary of the parsing scheme to be used to find the desired
field. The key corresponds to the attribute name to parse, and the
value is a PyQuery-readable parsing scheme as a string (such as
'td[data-stat="wins"]').
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in
parsing_scheme.
index : int (optional)
An optional index if multiple fields have the same attribute name. For
example, 'HR' may stand for the number of home runs a baseball team has
hit, or the number of home runs a pitcher has given up. The index
aligns with the order in which the attributes are recevied in the
html_data parameter.
Returns
-------
string
The value at the specified index for the requested field. If no value
could be found, returns None.
"""
if field == 'abbreviation':
return _parse_abbreviation(html_data)
scheme = parsing_scheme[field]
items = [i.text() for i in html_data(scheme).items()]
# Stats can be added and removed on a yearly basis. If not stats are found,
# return None and have the be the value.
if len(items) == 0:
return None
# Default to returning the first element. Optionally return another element
# if multiple fields have the same tag attribute.
try:
return items[index]
except IndexError:
return None | [
"def",
"_parse_field",
"(",
"parsing_scheme",
",",
"html_data",
",",
"field",
",",
"index",
"=",
"0",
")",
":",
"if",
"field",
"==",
"'abbreviation'",
":",
"return",
"_parse_abbreviation",
"(",
"html_data",
")",
"scheme",
"=",
"parsing_scheme",
"[",
"field",
... | Parse an HTML table to find the requested field's value.
All of the values are passed in an HTML table row instead of as individual
items. The values need to be parsed by matching the requested attribute
with a parsing scheme that sports-reference uses to differentiate stats.
This function returns a single value for the given attribute.
Parameters
----------
parsing_scheme : dict
A dictionary of the parsing scheme to be used to find the desired
field. The key corresponds to the attribute name to parse, and the
value is a PyQuery-readable parsing scheme as a string (such as
'td[data-stat="wins"]').
html_data : string
A string containing all of the rows of stats for a given team. If
multiple tables are being referenced, this will be comprised of
multiple rows in a single string.
field : string
The name of the attribute to match. Field must be a key in
parsing_scheme.
index : int (optional)
An optional index if multiple fields have the same attribute name. For
example, 'HR' may stand for the number of home runs a baseball team has
hit, or the number of home runs a pitcher has given up. The index
aligns with the order in which the attributes are recevied in the
html_data parameter.
Returns
-------
string
The value at the specified index for the requested field. If no value
could be found, returns None. | [
"Parse",
"an",
"HTML",
"table",
"to",
"find",
"the",
"requested",
"field",
"s",
"value",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/utils.py#L120-L169 | train | 34,588 |
roclark/sportsreference | sportsreference/utils.py | _get_stats_table | def _get_stats_table(html_page, div, footer=False):
"""
Returns a generator of all rows in a requested table.
When given a PyQuery HTML object and a requested div, this function creates
a generator where every item is a PyQuery object pertaining to every row in
the table. Generally, each row will contain multiple stats for a given
player or team.
Parameters
----------
html_page : PyQuery object
A PyQuery object which contains the requested HTML page contents.
div : string
The requested tag type and id string in the format "<tag>#<id name>"
which aligns to the desired table in the passed HTML page. For example,
"div#all_stats_table" or "table#conference_standings".
footer : boolean (optional)
Optionally return the table footer rows instead of the table header.
Returns
-------
generator
A generator of all row items in a given table.
"""
stats_html = html_page(div)
try:
stats_table = pq(_remove_html_comment_tags(stats_html))
except (ParserError, XMLSyntaxError):
return None
if footer:
teams_list = stats_table('tfoot tr').items()
else:
teams_list = stats_table('tbody tr').items()
return teams_list | python | def _get_stats_table(html_page, div, footer=False):
"""
Returns a generator of all rows in a requested table.
When given a PyQuery HTML object and a requested div, this function creates
a generator where every item is a PyQuery object pertaining to every row in
the table. Generally, each row will contain multiple stats for a given
player or team.
Parameters
----------
html_page : PyQuery object
A PyQuery object which contains the requested HTML page contents.
div : string
The requested tag type and id string in the format "<tag>#<id name>"
which aligns to the desired table in the passed HTML page. For example,
"div#all_stats_table" or "table#conference_standings".
footer : boolean (optional)
Optionally return the table footer rows instead of the table header.
Returns
-------
generator
A generator of all row items in a given table.
"""
stats_html = html_page(div)
try:
stats_table = pq(_remove_html_comment_tags(stats_html))
except (ParserError, XMLSyntaxError):
return None
if footer:
teams_list = stats_table('tfoot tr').items()
else:
teams_list = stats_table('tbody tr').items()
return teams_list | [
"def",
"_get_stats_table",
"(",
"html_page",
",",
"div",
",",
"footer",
"=",
"False",
")",
":",
"stats_html",
"=",
"html_page",
"(",
"div",
")",
"try",
":",
"stats_table",
"=",
"pq",
"(",
"_remove_html_comment_tags",
"(",
"stats_html",
")",
")",
"except",
... | Returns a generator of all rows in a requested table.
When given a PyQuery HTML object and a requested div, this function creates
a generator where every item is a PyQuery object pertaining to every row in
the table. Generally, each row will contain multiple stats for a given
player or team.
Parameters
----------
html_page : PyQuery object
A PyQuery object which contains the requested HTML page contents.
div : string
The requested tag type and id string in the format "<tag>#<id name>"
which aligns to the desired table in the passed HTML page. For example,
"div#all_stats_table" or "table#conference_standings".
footer : boolean (optional)
Optionally return the table footer rows instead of the table header.
Returns
-------
generator
A generator of all row items in a given table. | [
"Returns",
"a",
"generator",
"of",
"all",
"rows",
"in",
"a",
"requested",
"table",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/utils.py#L194-L228 | train | 34,589 |
roclark/sportsreference | sportsreference/nhl/teams.py | Teams.dataframes | def dataframes(self):
"""
Returns a pandas DataFrame where each row is a representation of the
Team class. Rows are indexed by the team abbreviation.
"""
frames = []
for team in self.__iter__():
frames.append(team.dataframe)
return pd.concat(frames) | python | def dataframes(self):
"""
Returns a pandas DataFrame where each row is a representation of the
Team class. Rows are indexed by the team abbreviation.
"""
frames = []
for team in self.__iter__():
frames.append(team.dataframe)
return pd.concat(frames) | [
"def",
"dataframes",
"(",
"self",
")",
":",
"frames",
"=",
"[",
"]",
"for",
"team",
"in",
"self",
".",
"__iter__",
"(",
")",
":",
"frames",
".",
"append",
"(",
"team",
".",
"dataframe",
")",
"return",
"pd",
".",
"concat",
"(",
"frames",
")"
] | Returns a pandas DataFrame where each row is a representation of the
Team class. Rows are indexed by the team abbreviation. | [
"Returns",
"a",
"pandas",
"DataFrame",
"where",
"each",
"row",
"is",
"a",
"representation",
"of",
"the",
"Team",
"class",
".",
"Rows",
"are",
"indexed",
"by",
"the",
"team",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/teams.py#L486-L494 | train | 34,590 |
roclark/sportsreference | sportsreference/ncaaf/rankings.py | Rankings._get_team | def _get_team(self, team):
"""
Retrieve team's name and abbreviation.
The team's name and abbreviation are embedded within the 'school_name'
tag and, in the case of the abbreviation, require special parsing as it
is located in the middle of a URI. The name and abbreviation are
returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
rankings page.
Returns
-------
tuple (string, string)
Returns a tuple of two strings where the first string is the team's
abbreviation, such as 'PURDUE' and the second string is the team's
name, such as 'Purdue'.
"""
name_tag = team('td[data-stat="school_name"]')
abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a')))
abbreviation = re.sub(r'/.*', '', abbreviation)
name = team('td[data-stat="school_name"] a').text()
return abbreviation, name | python | def _get_team(self, team):
"""
Retrieve team's name and abbreviation.
The team's name and abbreviation are embedded within the 'school_name'
tag and, in the case of the abbreviation, require special parsing as it
is located in the middle of a URI. The name and abbreviation are
returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
rankings page.
Returns
-------
tuple (string, string)
Returns a tuple of two strings where the first string is the team's
abbreviation, such as 'PURDUE' and the second string is the team's
name, such as 'Purdue'.
"""
name_tag = team('td[data-stat="school_name"]')
abbreviation = re.sub(r'.*/cfb/schools/', '', str(name_tag('a')))
abbreviation = re.sub(r'/.*', '', abbreviation)
name = team('td[data-stat="school_name"] a').text()
return abbreviation, name | [
"def",
"_get_team",
"(",
"self",
",",
"team",
")",
":",
"name_tag",
"=",
"team",
"(",
"'td[data-stat=\"school_name\"]'",
")",
"abbreviation",
"=",
"re",
".",
"sub",
"(",
"r'.*/cfb/schools/'",
",",
"''",
",",
"str",
"(",
"name_tag",
"(",
"'a'",
")",
")",
... | Retrieve team's name and abbreviation.
The team's name and abbreviation are embedded within the 'school_name'
tag and, in the case of the abbreviation, require special parsing as it
is located in the middle of a URI. The name and abbreviation are
returned for the requested school.
Parameters
----------
team : PyQuery object
A PyQuery object representing a single row in a table on the
rankings page.
Returns
-------
tuple (string, string)
Returns a tuple of two strings where the first string is the team's
abbreviation, such as 'PURDUE' and the second string is the team's
name, such as 'Purdue'. | [
"Retrieve",
"team",
"s",
"name",
"and",
"abbreviation",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/rankings.py#L49-L75 | train | 34,591 |
roclark/sportsreference | sportsreference/ncaaf/rankings.py | Rankings._find_rankings | def _find_rankings(self, year):
"""
Retrieve the rankings for each week.
Find and retrieve all AP rankings for the requested year and combine
them on a per-week basis. Each week contains information about the
name, abbreviation, rank, movement, and previous rank for each team
as well as the date and week number the results were published on.
Parameters
----------
year : string
A string of the requested year to pull rankings from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_rankings_page(year)
if not page:
output = ("Can't pull rankings page. Ensure the following URL "
"exists: %s" % RANKINGS_URL)
raise ValueError(output)
rankings = page('table#ap tbody tr').items()
weekly_rankings = []
week = 0
for team in rankings:
if 'class="thead"' in str(team):
self._rankings[int(week)] = weekly_rankings
weekly_rankings = []
continue
abbreviation, name = self._get_team(team)
rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank')
week = utils._parse_field(RANKINGS_SCHEME, team, 'week')
date = utils._parse_field(RANKINGS_SCHEME, team, 'date')
previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous')
change = utils._parse_field(RANKINGS_SCHEME, team, 'change')
if 'decrease' in str(team(RANKINGS_SCHEME['change'])):
change = int(change) * -1
elif 'increase' in str(team(RANKINGS_SCHEME['change'])):
try:
change = int(change)
except ValueError:
change = 0
else:
change = 0
rank_details = {
'abbreviation': abbreviation,
'name': name,
'rank': int(rank),
'week': int(week),
'date': date,
'previous': previous,
'change': change
}
weekly_rankings.append(rank_details)
# Add the final rankings which is not terminated with another header
# row and hence will not hit the first if statement in the loop above.
self._rankings[int(week)] = weekly_rankings | python | def _find_rankings(self, year):
"""
Retrieve the rankings for each week.
Find and retrieve all AP rankings for the requested year and combine
them on a per-week basis. Each week contains information about the
name, abbreviation, rank, movement, and previous rank for each team
as well as the date and week number the results were published on.
Parameters
----------
year : string
A string of the requested year to pull rankings from.
"""
if not year:
year = utils._find_year_for_season('ncaaf')
page = self._pull_rankings_page(year)
if not page:
output = ("Can't pull rankings page. Ensure the following URL "
"exists: %s" % RANKINGS_URL)
raise ValueError(output)
rankings = page('table#ap tbody tr').items()
weekly_rankings = []
week = 0
for team in rankings:
if 'class="thead"' in str(team):
self._rankings[int(week)] = weekly_rankings
weekly_rankings = []
continue
abbreviation, name = self._get_team(team)
rank = utils._parse_field(RANKINGS_SCHEME, team, 'rank')
week = utils._parse_field(RANKINGS_SCHEME, team, 'week')
date = utils._parse_field(RANKINGS_SCHEME, team, 'date')
previous = utils._parse_field(RANKINGS_SCHEME, team, 'previous')
change = utils._parse_field(RANKINGS_SCHEME, team, 'change')
if 'decrease' in str(team(RANKINGS_SCHEME['change'])):
change = int(change) * -1
elif 'increase' in str(team(RANKINGS_SCHEME['change'])):
try:
change = int(change)
except ValueError:
change = 0
else:
change = 0
rank_details = {
'abbreviation': abbreviation,
'name': name,
'rank': int(rank),
'week': int(week),
'date': date,
'previous': previous,
'change': change
}
weekly_rankings.append(rank_details)
# Add the final rankings which is not terminated with another header
# row and hence will not hit the first if statement in the loop above.
self._rankings[int(week)] = weekly_rankings | [
"def",
"_find_rankings",
"(",
"self",
",",
"year",
")",
":",
"if",
"not",
"year",
":",
"year",
"=",
"utils",
".",
"_find_year_for_season",
"(",
"'ncaaf'",
")",
"page",
"=",
"self",
".",
"_pull_rankings_page",
"(",
"year",
")",
"if",
"not",
"page",
":",
... | Retrieve the rankings for each week.
Find and retrieve all AP rankings for the requested year and combine
them on a per-week basis. Each week contains information about the
name, abbreviation, rank, movement, and previous rank for each team
as well as the date and week number the results were published on.
Parameters
----------
year : string
A string of the requested year to pull rankings from. | [
"Retrieve",
"the",
"rankings",
"for",
"each",
"week",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/rankings.py#L77-L133 | train | 34,592 |
roclark/sportsreference | sportsreference/ncaaf/rankings.py | Rankings.current | def current(self):
"""
Returns a ``dictionary`` of the most recent rankings from the
Associated Press where each key is a ``string`` of the team's
abbreviation and each value is an ``int`` of the team's rank for the
current week.
"""
rankings_dict = {}
for team in self.current_extended:
rankings_dict[team['abbreviation']] = team['rank']
return rankings_dict | python | def current(self):
"""
Returns a ``dictionary`` of the most recent rankings from the
Associated Press where each key is a ``string`` of the team's
abbreviation and each value is an ``int`` of the team's rank for the
current week.
"""
rankings_dict = {}
for team in self.current_extended:
rankings_dict[team['abbreviation']] = team['rank']
return rankings_dict | [
"def",
"current",
"(",
"self",
")",
":",
"rankings_dict",
"=",
"{",
"}",
"for",
"team",
"in",
"self",
".",
"current_extended",
":",
"rankings_dict",
"[",
"team",
"[",
"'abbreviation'",
"]",
"]",
"=",
"team",
"[",
"'rank'",
"]",
"return",
"rankings_dict"
] | Returns a ``dictionary`` of the most recent rankings from the
Associated Press where each key is a ``string`` of the team's
abbreviation and each value is an ``int`` of the team's rank for the
current week. | [
"Returns",
"a",
"dictionary",
"of",
"the",
"most",
"recent",
"rankings",
"from",
"the",
"Associated",
"Press",
"where",
"each",
"key",
"is",
"a",
"string",
"of",
"the",
"team",
"s",
"abbreviation",
"and",
"each",
"value",
"is",
"an",
"int",
"of",
"the",
... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/ncaaf/rankings.py#L164-L175 | train | 34,593 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | Boxscore._retrieve_html_page | def _retrieve_html_page(self, uri):
"""
Download the requested HTML page.
Given a relative link, download the requested page and strip it of all
comment tags before returning a pyquery object which will be used to
parse the data.
Parameters
----------
uri : string
The relative link to the boxscore HTML page, such as
'201802040nwe'.
Returns
-------
PyQuery object
The requested page is returned as a queriable PyQuery object with
the comment tags removed.
"""
url = BOXSCORE_URL % uri
try:
url_data = pq(url)
except HTTPError:
return None
# For NFL, a 404 page doesn't actually raise a 404 error, so it needs
# to be manually checked.
if '404 error' in str(url_data):
return None
return pq(utils._remove_html_comment_tags(url_data)) | python | def _retrieve_html_page(self, uri):
"""
Download the requested HTML page.
Given a relative link, download the requested page and strip it of all
comment tags before returning a pyquery object which will be used to
parse the data.
Parameters
----------
uri : string
The relative link to the boxscore HTML page, such as
'201802040nwe'.
Returns
-------
PyQuery object
The requested page is returned as a queriable PyQuery object with
the comment tags removed.
"""
url = BOXSCORE_URL % uri
try:
url_data = pq(url)
except HTTPError:
return None
# For NFL, a 404 page doesn't actually raise a 404 error, so it needs
# to be manually checked.
if '404 error' in str(url_data):
return None
return pq(utils._remove_html_comment_tags(url_data)) | [
"def",
"_retrieve_html_page",
"(",
"self",
",",
"uri",
")",
":",
"url",
"=",
"BOXSCORE_URL",
"%",
"uri",
"try",
":",
"url_data",
"=",
"pq",
"(",
"url",
")",
"except",
"HTTPError",
":",
"return",
"None",
"# For NFL, a 404 page doesn't actually raise a 404 error, so... | Download the requested HTML page.
Given a relative link, download the requested page and strip it of all
comment tags before returning a pyquery object which will be used to
parse the data.
Parameters
----------
uri : string
The relative link to the boxscore HTML page, such as
'201802040nwe'.
Returns
-------
PyQuery object
The requested page is returned as a queriable PyQuery object with
the comment tags removed. | [
"Download",
"the",
"requested",
"HTML",
"page",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L292-L321 | train | 34,594 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | Boxscore.dataframe | def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '201802040nwe'.
"""
if self._away_points is None and self._home_points is None:
return None
fields_to_include = {
'attendance': self.attendance,
'away_first_downs': self.away_first_downs,
'away_fourth_down_attempts': self.away_fourth_down_attempts,
'away_fourth_down_conversions': self.away_fourth_down_conversions,
'away_fumbles': self.away_fumbles,
'away_fumbles_lost': self.away_fumbles_lost,
'away_interceptions': self.away_interceptions,
'away_net_pass_yards': self.away_net_pass_yards,
'away_pass_attempts': self.away_pass_attempts,
'away_pass_completions': self.away_pass_completions,
'away_pass_touchdowns': self.away_pass_touchdowns,
'away_pass_yards': self.away_pass_yards,
'away_penalties': self.away_penalties,
'away_points': self.away_points,
'away_rush_attempts': self.away_rush_attempts,
'away_rush_touchdowns': self.away_rush_touchdowns,
'away_rush_yards': self.away_rush_yards,
'away_third_down_attempts': self.away_third_down_attempts,
'away_third_down_conversions': self.away_third_down_conversions,
'away_time_of_possession': self.away_time_of_possession,
'away_times_sacked': self.away_times_sacked,
'away_total_yards': self.away_total_yards,
'away_turnovers': self.away_turnovers,
'away_yards_from_penalties': self.away_yards_from_penalties,
'away_yards_lost_from_sacks': self.away_yards_lost_from_sacks,
'date': self.date,
'duration': self.duration,
'home_first_downs': self.home_first_downs,
'home_fourth_down_attempts': self.home_fourth_down_attempts,
'home_fourth_down_conversions': self.home_fourth_down_conversions,
'home_fumbles': self.home_fumbles,
'home_fumbles_lost': self.home_fumbles_lost,
'home_interceptions': self.home_interceptions,
'home_net_pass_yards': self.home_net_pass_yards,
'home_pass_attempts': self.home_pass_attempts,
'home_pass_completions': self.home_pass_completions,
'home_pass_touchdowns': self.home_pass_touchdowns,
'home_pass_yards': self.home_pass_yards,
'home_penalties': self.home_penalties,
'home_points': self.home_points,
'home_rush_attempts': self.home_rush_attempts,
'home_rush_touchdowns': self.home_rush_touchdowns,
'home_rush_yards': self.home_rush_yards,
'home_third_down_attempts': self.home_third_down_attempts,
'home_third_down_conversions': self.home_third_down_conversions,
'home_time_of_possession': self.home_time_of_possession,
'home_times_sacked': self.home_times_sacked,
'home_total_yards': self.home_total_yards,
'home_turnovers': self.home_turnovers,
'home_yards_from_penalties': self.home_yards_from_penalties,
'home_yards_lost_from_sacks': self.home_yards_lost_from_sacks,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'stadium': self.stadium,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | python | def dataframe(self):
"""
Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '201802040nwe'.
"""
if self._away_points is None and self._home_points is None:
return None
fields_to_include = {
'attendance': self.attendance,
'away_first_downs': self.away_first_downs,
'away_fourth_down_attempts': self.away_fourth_down_attempts,
'away_fourth_down_conversions': self.away_fourth_down_conversions,
'away_fumbles': self.away_fumbles,
'away_fumbles_lost': self.away_fumbles_lost,
'away_interceptions': self.away_interceptions,
'away_net_pass_yards': self.away_net_pass_yards,
'away_pass_attempts': self.away_pass_attempts,
'away_pass_completions': self.away_pass_completions,
'away_pass_touchdowns': self.away_pass_touchdowns,
'away_pass_yards': self.away_pass_yards,
'away_penalties': self.away_penalties,
'away_points': self.away_points,
'away_rush_attempts': self.away_rush_attempts,
'away_rush_touchdowns': self.away_rush_touchdowns,
'away_rush_yards': self.away_rush_yards,
'away_third_down_attempts': self.away_third_down_attempts,
'away_third_down_conversions': self.away_third_down_conversions,
'away_time_of_possession': self.away_time_of_possession,
'away_times_sacked': self.away_times_sacked,
'away_total_yards': self.away_total_yards,
'away_turnovers': self.away_turnovers,
'away_yards_from_penalties': self.away_yards_from_penalties,
'away_yards_lost_from_sacks': self.away_yards_lost_from_sacks,
'date': self.date,
'duration': self.duration,
'home_first_downs': self.home_first_downs,
'home_fourth_down_attempts': self.home_fourth_down_attempts,
'home_fourth_down_conversions': self.home_fourth_down_conversions,
'home_fumbles': self.home_fumbles,
'home_fumbles_lost': self.home_fumbles_lost,
'home_interceptions': self.home_interceptions,
'home_net_pass_yards': self.home_net_pass_yards,
'home_pass_attempts': self.home_pass_attempts,
'home_pass_completions': self.home_pass_completions,
'home_pass_touchdowns': self.home_pass_touchdowns,
'home_pass_yards': self.home_pass_yards,
'home_penalties': self.home_penalties,
'home_points': self.home_points,
'home_rush_attempts': self.home_rush_attempts,
'home_rush_touchdowns': self.home_rush_touchdowns,
'home_rush_yards': self.home_rush_yards,
'home_third_down_attempts': self.home_third_down_attempts,
'home_third_down_conversions': self.home_third_down_conversions,
'home_time_of_possession': self.home_time_of_possession,
'home_times_sacked': self.home_times_sacked,
'home_total_yards': self.home_total_yards,
'home_turnovers': self.home_turnovers,
'home_yards_from_penalties': self.home_yards_from_penalties,
'home_yards_lost_from_sacks': self.home_yards_lost_from_sacks,
'losing_abbr': self.losing_abbr,
'losing_name': self.losing_name,
'stadium': self.stadium,
'time': self.time,
'winner': self.winner,
'winning_abbr': self.winning_abbr,
'winning_name': self.winning_name
}
return pd.DataFrame([fields_to_include], index=[self._uri]) | [
"def",
"dataframe",
"(",
"self",
")",
":",
"if",
"self",
".",
"_away_points",
"is",
"None",
"and",
"self",
".",
"_home_points",
"is",
"None",
":",
"return",
"None",
"fields_to_include",
"=",
"{",
"'attendance'",
":",
"self",
".",
"attendance",
",",
"'away_... | Returns a pandas DataFrame containing all other class properties and
values. The index for the DataFrame is the string URI that is used to
instantiate the class, such as '201802040nwe'. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"all",
"other",
"class",
"properties",
"and",
"values",
".",
"The",
"index",
"for",
"the",
"DataFrame",
"is",
"the",
"string",
"URI",
"that",
"is",
"used",
"to",
"instantiate",
"the",
"class",
"such",
"as"... | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L650-L718 | train | 34,595 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | Boxscore.away_abbreviation | def away_abbreviation(self):
"""
Returns a ``string`` of the away team's abbreviation, such as 'NWE'.
"""
abbr = re.sub(r'.*/teams/', '', str(self._away_name))
abbr = re.sub(r'/.*', '', abbr)
return abbr | python | def away_abbreviation(self):
"""
Returns a ``string`` of the away team's abbreviation, such as 'NWE'.
"""
abbr = re.sub(r'.*/teams/', '', str(self._away_name))
abbr = re.sub(r'/.*', '', abbr)
return abbr | [
"def",
"away_abbreviation",
"(",
"self",
")",
":",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'.*/teams/'",
",",
"''",
",",
"str",
"(",
"self",
".",
"_away_name",
")",
")",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'/.*'",
",",
"''",
",",
"abbr",
")",
"re... | Returns a ``string`` of the away team's abbreviation, such as 'NWE'. | [
"Returns",
"a",
"string",
"of",
"the",
"away",
"team",
"s",
"abbreviation",
"such",
"as",
"NWE",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L737-L743 | train | 34,596 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | Boxscore.home_abbreviation | def home_abbreviation(self):
"""
Returns a ``string`` of the home team's abbreviation, such as 'KAN'.
"""
abbr = re.sub(r'.*/teams/', '', str(self._home_name))
abbr = re.sub(r'/.*', '', abbr)
return abbr | python | def home_abbreviation(self):
"""
Returns a ``string`` of the home team's abbreviation, such as 'KAN'.
"""
abbr = re.sub(r'.*/teams/', '', str(self._home_name))
abbr = re.sub(r'/.*', '', abbr)
return abbr | [
"def",
"home_abbreviation",
"(",
"self",
")",
":",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'.*/teams/'",
",",
"''",
",",
"str",
"(",
"self",
".",
"_home_name",
")",
")",
"abbr",
"=",
"re",
".",
"sub",
"(",
"r'/.*'",
",",
"''",
",",
"abbr",
")",
"re... | Returns a ``string`` of the home team's abbreviation, such as 'KAN'. | [
"Returns",
"a",
"string",
"of",
"the",
"home",
"team",
"s",
"abbreviation",
"such",
"as",
"KAN",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L746-L752 | train | 34,597 |
roclark/sportsreference | sportsreference/nfl/boxscore.py | Boxscores._find_games | def _find_games(self, week, year, end_week):
"""
Retrieve all major games played for a given week.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that week. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
week : int
The week number to pull games from.
year : int
The 4-digit year to pull games from.
end_week : int (optional)
Optionally specify an end week to iterate until. All boxscores
starting from the week specified in the 'week' parameter up to and
including the boxscores specified in the 'end_week' parameter will
be pulled. If left empty, or if 'end_week' is prior to 'week', only
the games from the day specified in the 'date' parameter will be
saved.
"""
if not end_week or week > end_week:
end_week = week
while week <= end_week:
url = self._create_url(week, year)
page = self._get_requested_page(url)
games = page('table[class="teams"]').items()
boxscores = self._extract_game_info(games)
timestamp = '%s-%s' % (week, year)
self._boxscores[timestamp] = boxscores
week += 1 | python | def _find_games(self, week, year, end_week):
"""
Retrieve all major games played for a given week.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that week. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
week : int
The week number to pull games from.
year : int
The 4-digit year to pull games from.
end_week : int (optional)
Optionally specify an end week to iterate until. All boxscores
starting from the week specified in the 'week' parameter up to and
including the boxscores specified in the 'end_week' parameter will
be pulled. If left empty, or if 'end_week' is prior to 'week', only
the games from the day specified in the 'date' parameter will be
saved.
"""
if not end_week or week > end_week:
end_week = week
while week <= end_week:
url = self._create_url(week, year)
page = self._get_requested_page(url)
games = page('table[class="teams"]').items()
boxscores = self._extract_game_info(games)
timestamp = '%s-%s' % (week, year)
self._boxscores[timestamp] = boxscores
week += 1 | [
"def",
"_find_games",
"(",
"self",
",",
"week",
",",
"year",
",",
"end_week",
")",
":",
"if",
"not",
"end_week",
"or",
"week",
">",
"end_week",
":",
"end_week",
"=",
"week",
"while",
"week",
"<=",
"end_week",
":",
"url",
"=",
"self",
".",
"_create_url"... | Retrieve all major games played for a given week.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that week. Any
games that are found are added to the boxscores dictionary with
high-level game information such as the home and away team names and a
link to the boxscore page.
Parameters
----------
week : int
The week number to pull games from.
year : int
The 4-digit year to pull games from.
end_week : int (optional)
Optionally specify an end week to iterate until. All boxscores
starting from the week specified in the 'week' parameter up to and
including the boxscores specified in the 'end_week' parameter will
be pulled. If left empty, or if 'end_week' is prior to 'week', only
the games from the day specified in the 'date' parameter will be
saved. | [
"Retrieve",
"all",
"major",
"games",
"played",
"for",
"a",
"given",
"week",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nfl/boxscore.py#L1531-L1564 | train | 34,598 |
roclark/sportsreference | sportsreference/nhl/schedule.py | Game.result | def result(self):
"""
Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won.
"""
if self._result.lower() == 'w':
return WIN
if self._result.lower() == 'l' and \
self.overtime != 0:
return OVERTIME_LOSS
return LOSS | python | def result(self):
"""
Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won.
"""
if self._result.lower() == 'w':
return WIN
if self._result.lower() == 'l' and \
self.overtime != 0:
return OVERTIME_LOSS
return LOSS | [
"def",
"result",
"(",
"self",
")",
":",
"if",
"self",
".",
"_result",
".",
"lower",
"(",
")",
"==",
"'w'",
":",
"return",
"WIN",
"if",
"self",
".",
"_result",
".",
"lower",
"(",
")",
"==",
"'l'",
"and",
"self",
".",
"overtime",
"!=",
"0",
":",
... | Returns a ``string`` constant to indicate whether the team lost in
regulation, lost in overtime, or won. | [
"Returns",
"a",
"string",
"constant",
"to",
"indicate",
"whether",
"the",
"team",
"lost",
"in",
"regulation",
"lost",
"in",
"overtime",
"or",
"won",
"."
] | ea0bae432be76450e137671d2998eb38f962dffd | https://github.com/roclark/sportsreference/blob/ea0bae432be76450e137671d2998eb38f962dffd/sportsreference/nhl/schedule.py#L271-L281 | train | 34,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.