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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FileObject.dumps | def dumps(self):
"""Create a dump of the metadata associated to the record."""
self.data.update({
'bucket': str(self.obj.bucket_id),
'checksum': self.obj.file.checksum,
'key': self.obj.key, # IMPORTANT it must stay here!
'size': self.obj.file.size,
'version_id': str(self.obj.version_id),
})
return self.data | python | def dumps(self):
"""Create a dump of the metadata associated to the record."""
self.data.update({
'bucket': str(self.obj.bucket_id),
'checksum': self.obj.file.checksum,
'key': self.obj.key, # IMPORTANT it must stay here!
'size': self.obj.file.size,
'version_id': str(self.obj.version_id),
})
return self.data | [
"def",
"dumps",
"(",
"self",
")",
":",
"self",
".",
"data",
".",
"update",
"(",
"{",
"'bucket'",
":",
"str",
"(",
"self",
".",
"obj",
".",
"bucket_id",
")",
",",
"'checksum'",
":",
"self",
".",
"obj",
".",
"file",
".",
"checksum",
",",
"'key'",
"... | Create a dump of the metadata associated to the record. | [
"Create",
"a",
"dump",
"of",
"the",
"metadata",
"associated",
"to",
"the",
"record",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L68-L77 | train | 42,000 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FilesIterator.flush | def flush(self):
"""Flush changes to record."""
files = self.dumps()
# Do not create `_files` when there has not been `_files` field before
# and the record still has no files attached.
if files or '_files' in self.record:
self.record['_files'] = files | python | def flush(self):
"""Flush changes to record."""
files = self.dumps()
# Do not create `_files` when there has not been `_files` field before
# and the record still has no files attached.
if files or '_files' in self.record:
self.record['_files'] = files | [
"def",
"flush",
"(",
"self",
")",
":",
"files",
"=",
"self",
".",
"dumps",
"(",
")",
"# Do not create `_files` when there has not been `_files` field before",
"# and the record still has no files attached.",
"if",
"files",
"or",
"'_files'",
"in",
"self",
".",
"record",
... | Flush changes to record. | [
"Flush",
"changes",
"to",
"record",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L150-L156 | train | 42,001 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FilesIterator.sort_by | def sort_by(self, *ids):
"""Update files order.
:param ids: List of ids specifying the final status of the list.
"""
# Support sorting by file_ids or keys.
files = {str(f_.file_id): f_.key for f_ in self}
# self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids]
self.filesmap = OrderedDict([
(files.get(id_, id_), self[files.get(id_, id_)].dumps())
for id_ in ids
])
self.flush() | python | def sort_by(self, *ids):
"""Update files order.
:param ids: List of ids specifying the final status of the list.
"""
# Support sorting by file_ids or keys.
files = {str(f_.file_id): f_.key for f_ in self}
# self.record['_files'] = [{'key': files.get(id_, id_)} for id_ in ids]
self.filesmap = OrderedDict([
(files.get(id_, id_), self[files.get(id_, id_)].dumps())
for id_ in ids
])
self.flush() | [
"def",
"sort_by",
"(",
"self",
",",
"*",
"ids",
")",
":",
"# Support sorting by file_ids or keys.",
"files",
"=",
"{",
"str",
"(",
"f_",
".",
"file_id",
")",
":",
"f_",
".",
"key",
"for",
"f_",
"in",
"self",
"}",
"# self.record['_files'] = [{'key': files.get(i... | Update files order.
:param ids: List of ids specifying the final status of the list. | [
"Update",
"files",
"order",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L180-L192 | train | 42,002 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FilesIterator.dumps | def dumps(self, bucket=None):
"""Serialize files from a bucket.
:param bucket: Instance of files
:class:`invenio_files_rest.models.Bucket`. (Default:
``self.bucket``)
:returns: List of serialized files.
"""
return [
self.file_cls(o, self.filesmap.get(o.key, {})).dumps()
for o in sorted_files_from_bucket(bucket or self.bucket, self.keys)
] | python | def dumps(self, bucket=None):
"""Serialize files from a bucket.
:param bucket: Instance of files
:class:`invenio_files_rest.models.Bucket`. (Default:
``self.bucket``)
:returns: List of serialized files.
"""
return [
self.file_cls(o, self.filesmap.get(o.key, {})).dumps()
for o in sorted_files_from_bucket(bucket or self.bucket, self.keys)
] | [
"def",
"dumps",
"(",
"self",
",",
"bucket",
"=",
"None",
")",
":",
"return",
"[",
"self",
".",
"file_cls",
"(",
"o",
",",
"self",
".",
"filesmap",
".",
"get",
"(",
"o",
".",
"key",
",",
"{",
"}",
")",
")",
".",
"dumps",
"(",
")",
"for",
"o",
... | Serialize files from a bucket.
:param bucket: Instance of files
:class:`invenio_files_rest.models.Bucket`. (Default:
``self.bucket``)
:returns: List of serialized files. | [
"Serialize",
"files",
"from",
"a",
"bucket",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L220-L231 | train | 42,003 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FilesMixin.files | def files(self):
"""Get files iterator.
:returns: Files iterator.
"""
if self.model is None:
raise MissingModelError()
records_buckets = RecordsBuckets.query.filter_by(
record_id=self.id).first()
if not records_buckets:
bucket = self._create_bucket()
if not bucket:
return None
RecordsBuckets.create(record=self.model, bucket=bucket)
else:
bucket = records_buckets.bucket
return self.files_iter_cls(self, bucket=bucket, file_cls=self.file_cls) | python | def files(self):
"""Get files iterator.
:returns: Files iterator.
"""
if self.model is None:
raise MissingModelError()
records_buckets = RecordsBuckets.query.filter_by(
record_id=self.id).first()
if not records_buckets:
bucket = self._create_bucket()
if not bucket:
return None
RecordsBuckets.create(record=self.model, bucket=bucket)
else:
bucket = records_buckets.bucket
return self.files_iter_cls(self, bucket=bucket, file_cls=self.file_cls) | [
"def",
"files",
"(",
"self",
")",
":",
"if",
"self",
".",
"model",
"is",
"None",
":",
"raise",
"MissingModelError",
"(",
")",
"records_buckets",
"=",
"RecordsBuckets",
".",
"query",
".",
"filter_by",
"(",
"record_id",
"=",
"self",
".",
"id",
")",
".",
... | Get files iterator.
:returns: Files iterator. | [
"Get",
"files",
"iterator",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L263-L282 | train | 42,004 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | FilesMixin.files | def files(self, data):
"""Set files from data."""
current_files = self.files
if current_files:
raise RuntimeError('Can not update existing files.')
for key in data:
current_files[key] = data[key] | python | def files(self, data):
"""Set files from data."""
current_files = self.files
if current_files:
raise RuntimeError('Can not update existing files.')
for key in data:
current_files[key] = data[key] | [
"def",
"files",
"(",
"self",
",",
"data",
")",
":",
"current_files",
"=",
"self",
".",
"files",
"if",
"current_files",
":",
"raise",
"RuntimeError",
"(",
"'Can not update existing files.'",
")",
"for",
"key",
"in",
"data",
":",
"current_files",
"[",
"key",
"... | Set files from data. | [
"Set",
"files",
"from",
"data",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L285-L291 | train | 42,005 |
inveniosoftware/invenio-records-files | invenio_records_files/api.py | Record.delete | def delete(self, force=False):
"""Delete a record and also remove the RecordsBuckets if necessary.
:param force: True to remove also the
:class:`~invenio_records_files.models.RecordsBuckets` object.
:returns: Deleted record.
"""
if force:
RecordsBuckets.query.filter_by(
record=self.model,
bucket=self.files.bucket
).delete()
return super(Record, self).delete(force) | python | def delete(self, force=False):
"""Delete a record and also remove the RecordsBuckets if necessary.
:param force: True to remove also the
:class:`~invenio_records_files.models.RecordsBuckets` object.
:returns: Deleted record.
"""
if force:
RecordsBuckets.query.filter_by(
record=self.model,
bucket=self.files.bucket
).delete()
return super(Record, self).delete(force) | [
"def",
"delete",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
":",
"RecordsBuckets",
".",
"query",
".",
"filter_by",
"(",
"record",
"=",
"self",
".",
"model",
",",
"bucket",
"=",
"self",
".",
"files",
".",
"bucket",
")",
".",
"... | Delete a record and also remove the RecordsBuckets if necessary.
:param force: True to remove also the
:class:`~invenio_records_files.models.RecordsBuckets` object.
:returns: Deleted record. | [
"Delete",
"a",
"record",
"and",
"also",
"remove",
"the",
"RecordsBuckets",
"if",
"necessary",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/api.py#L297-L309 | train | 42,006 |
inveniosoftware/invenio-records-files | invenio_records_files/models.py | RecordsBuckets.create | def create(cls, record, bucket):
"""Create a new RecordsBuckets and adds it to the session.
:param record: Record used to relate with the ``Bucket``.
:param bucket: Bucket used to relate with the ``Record``.
:returns: The :class:`~invenio_records_files.models.RecordsBuckets`
object created.
"""
rb = cls(record=record, bucket=bucket)
db.session.add(rb)
return rb | python | def create(cls, record, bucket):
"""Create a new RecordsBuckets and adds it to the session.
:param record: Record used to relate with the ``Bucket``.
:param bucket: Bucket used to relate with the ``Record``.
:returns: The :class:`~invenio_records_files.models.RecordsBuckets`
object created.
"""
rb = cls(record=record, bucket=bucket)
db.session.add(rb)
return rb | [
"def",
"create",
"(",
"cls",
",",
"record",
",",
"bucket",
")",
":",
"rb",
"=",
"cls",
"(",
"record",
"=",
"record",
",",
"bucket",
"=",
"bucket",
")",
"db",
".",
"session",
".",
"add",
"(",
"rb",
")",
"return",
"rb"
] | Create a new RecordsBuckets and adds it to the session.
:param record: Record used to relate with the ``Bucket``.
:param bucket: Bucket used to relate with the ``Record``.
:returns: The :class:`~invenio_records_files.models.RecordsBuckets`
object created. | [
"Create",
"a",
"new",
"RecordsBuckets",
"and",
"adds",
"it",
"to",
"the",
"session",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/models.py#L48-L58 | train | 42,007 |
inveniosoftware/invenio-records-files | invenio_records_files/utils.py | sorted_files_from_bucket | def sorted_files_from_bucket(bucket, keys=None):
"""Return files from bucket sorted by given keys.
:param bucket: :class:`~invenio_files_rest.models.Bucket` containing the
files.
:param keys: Keys order to be used.
:returns: Sorted list of bucket items.
"""
keys = keys or []
total = len(keys)
sortby = dict(zip(keys, range(total)))
values = ObjectVersion.get_by_bucket(bucket).all()
return sorted(values, key=lambda x: sortby.get(x.key, total)) | python | def sorted_files_from_bucket(bucket, keys=None):
"""Return files from bucket sorted by given keys.
:param bucket: :class:`~invenio_files_rest.models.Bucket` containing the
files.
:param keys: Keys order to be used.
:returns: Sorted list of bucket items.
"""
keys = keys or []
total = len(keys)
sortby = dict(zip(keys, range(total)))
values = ObjectVersion.get_by_bucket(bucket).all()
return sorted(values, key=lambda x: sortby.get(x.key, total)) | [
"def",
"sorted_files_from_bucket",
"(",
"bucket",
",",
"keys",
"=",
"None",
")",
":",
"keys",
"=",
"keys",
"or",
"[",
"]",
"total",
"=",
"len",
"(",
"keys",
")",
"sortby",
"=",
"dict",
"(",
"zip",
"(",
"keys",
",",
"range",
"(",
"total",
")",
")",
... | Return files from bucket sorted by given keys.
:param bucket: :class:`~invenio_files_rest.models.Bucket` containing the
files.
:param keys: Keys order to be used.
:returns: Sorted list of bucket items. | [
"Return",
"files",
"from",
"bucket",
"sorted",
"by",
"given",
"keys",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L19-L31 | train | 42,008 |
inveniosoftware/invenio-records-files | invenio_records_files/utils.py | record_file_factory | def record_file_factory(pid, record, filename):
"""Get file from a record.
:param pid: Not used. It keeps the function signature.
:param record: Record which contains the files.
:param filename: Name of the file to be returned.
:returns: File object or ``None`` if not found.
"""
try:
if not (hasattr(record, 'files') and record.files):
return None
except MissingModelError:
return None
try:
return record.files[filename]
except KeyError:
return None | python | def record_file_factory(pid, record, filename):
"""Get file from a record.
:param pid: Not used. It keeps the function signature.
:param record: Record which contains the files.
:param filename: Name of the file to be returned.
:returns: File object or ``None`` if not found.
"""
try:
if not (hasattr(record, 'files') and record.files):
return None
except MissingModelError:
return None
try:
return record.files[filename]
except KeyError:
return None | [
"def",
"record_file_factory",
"(",
"pid",
",",
"record",
",",
"filename",
")",
":",
"try",
":",
"if",
"not",
"(",
"hasattr",
"(",
"record",
",",
"'files'",
")",
"and",
"record",
".",
"files",
")",
":",
"return",
"None",
"except",
"MissingModelError",
":"... | Get file from a record.
:param pid: Not used. It keeps the function signature.
:param record: Record which contains the files.
:param filename: Name of the file to be returned.
:returns: File object or ``None`` if not found. | [
"Get",
"file",
"from",
"a",
"record",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L34-L51 | train | 42,009 |
inveniosoftware/invenio-records-files | invenio_records_files/utils.py | file_download_ui | def file_download_ui(pid, record, _record_file_factory=None, **kwargs):
"""File download view for a given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/files/<filename>',
view_imp='invenio_records_files.utils:file_download_ui',
record_class='invenio_records_files.api:Record',
)
)
If ``download`` is passed as a querystring argument, the file is sent as an
attachment.
:param pid: The :class:`invenio_pidstore.models.PersistentIdentifier`
instance.
:param record: The record metadata.
"""
_record_file_factory = _record_file_factory or record_file_factory
# Extract file from record.
fileobj = _record_file_factory(
pid, record, kwargs.get('filename')
)
if not fileobj:
abort(404)
obj = fileobj.obj
# Check permissions
ObjectResource.check_object_permission(obj)
# Send file.
return ObjectResource.send_object(
obj.bucket, obj,
expected_chksum=fileobj.get('checksum'),
logger_data={
'bucket_id': obj.bucket_id,
'pid_type': pid.pid_type,
'pid_value': pid.pid_value,
},
as_attachment=('download' in request.args)
) | python | def file_download_ui(pid, record, _record_file_factory=None, **kwargs):
"""File download view for a given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/files/<filename>',
view_imp='invenio_records_files.utils:file_download_ui',
record_class='invenio_records_files.api:Record',
)
)
If ``download`` is passed as a querystring argument, the file is sent as an
attachment.
:param pid: The :class:`invenio_pidstore.models.PersistentIdentifier`
instance.
:param record: The record metadata.
"""
_record_file_factory = _record_file_factory or record_file_factory
# Extract file from record.
fileobj = _record_file_factory(
pid, record, kwargs.get('filename')
)
if not fileobj:
abort(404)
obj = fileobj.obj
# Check permissions
ObjectResource.check_object_permission(obj)
# Send file.
return ObjectResource.send_object(
obj.bucket, obj,
expected_chksum=fileobj.get('checksum'),
logger_data={
'bucket_id': obj.bucket_id,
'pid_type': pid.pid_type,
'pid_value': pid.pid_value,
},
as_attachment=('download' in request.args)
) | [
"def",
"file_download_ui",
"(",
"pid",
",",
"record",
",",
"_record_file_factory",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_record_file_factory",
"=",
"_record_file_factory",
"or",
"record_file_factory",
"# Extract file from record.",
"fileobj",
"=",
"_record... | File download view for a given record.
Plug this method into your ``RECORDS_UI_ENDPOINTS`` configuration:
.. code-block:: python
RECORDS_UI_ENDPOINTS = dict(
recid=dict(
# ...
route='/records/<pid_value/files/<filename>',
view_imp='invenio_records_files.utils:file_download_ui',
record_class='invenio_records_files.api:Record',
)
)
If ``download`` is passed as a querystring argument, the file is sent as an
attachment.
:param pid: The :class:`invenio_pidstore.models.PersistentIdentifier`
instance.
:param record: The record metadata. | [
"File",
"download",
"view",
"for",
"a",
"given",
"record",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/utils.py#L54-L101 | train | 42,010 |
inveniosoftware/invenio-records-files | invenio_records_files/links.py | default_bucket_link_factory | def default_bucket_link_factory(pid):
"""Factory for record bucket generation."""
try:
record = Record.get_record(pid.get_assigned_object())
bucket = record.files.bucket
return url_for('invenio_files_rest.bucket_api',
bucket_id=bucket.id, _external=True)
except AttributeError:
return None | python | def default_bucket_link_factory(pid):
"""Factory for record bucket generation."""
try:
record = Record.get_record(pid.get_assigned_object())
bucket = record.files.bucket
return url_for('invenio_files_rest.bucket_api',
bucket_id=bucket.id, _external=True)
except AttributeError:
return None | [
"def",
"default_bucket_link_factory",
"(",
"pid",
")",
":",
"try",
":",
"record",
"=",
"Record",
".",
"get_record",
"(",
"pid",
".",
"get_assigned_object",
"(",
")",
")",
"bucket",
"=",
"record",
".",
"files",
".",
"bucket",
"return",
"url_for",
"(",
"'inv... | Factory for record bucket generation. | [
"Factory",
"for",
"record",
"bucket",
"generation",
"."
] | c410eba986ea43be7e97082d5dcbbdc19ccec39c | https://github.com/inveniosoftware/invenio-records-files/blob/c410eba986ea43be7e97082d5dcbbdc19ccec39c/invenio_records_files/links.py#L16-L25 | train | 42,011 |
timothycrosley/deprecated.frosted | frosted/reporter.py | Reporter.flake | def flake(self, message):
"""Print an error message to stdout."""
self.stdout.write(str(message))
self.stdout.write('\n') | python | def flake(self, message):
"""Print an error message to stdout."""
self.stdout.write(str(message))
self.stdout.write('\n') | [
"def",
"flake",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"str",
"(",
"message",
")",
")",
"self",
".",
"stdout",
".",
"write",
"(",
"'\\n'",
")"
] | Print an error message to stdout. | [
"Print",
"an",
"error",
"message",
"to",
"stdout",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/reporter.py#L34-L37 | train | 42,012 |
timothycrosley/deprecated.frosted | frosted/checker.py | ExportBinding.names | def names(self):
"""Return a list of the names referenced by this binding."""
names = []
if isinstance(self.source, ast.List):
for node in self.source.elts:
if isinstance(node, ast.Str):
names.append(node.s)
return names | python | def names(self):
"""Return a list of the names referenced by this binding."""
names = []
if isinstance(self.source, ast.List):
for node in self.source.elts:
if isinstance(node, ast.Str):
names.append(node.s)
return names | [
"def",
"names",
"(",
"self",
")",
":",
"names",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"self",
".",
"source",
",",
"ast",
".",
"List",
")",
":",
"for",
"node",
"in",
"self",
".",
"source",
".",
"elts",
":",
"if",
"isinstance",
"(",
"node",
",",
... | Return a list of the names referenced by this binding. | [
"Return",
"a",
"list",
"of",
"the",
"names",
"referenced",
"by",
"this",
"binding",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L128-L135 | train | 42,013 |
timothycrosley/deprecated.frosted | frosted/checker.py | FunctionScope.unusedAssignments | def unusedAssignments(self):
"""Return a generator for the assignments which have not been used."""
for name, binding in self.items():
if (not binding.used and name not in self.globals
and not self.uses_locals
and isinstance(binding, Assignment)):
yield name, binding | python | def unusedAssignments(self):
"""Return a generator for the assignments which have not been used."""
for name, binding in self.items():
if (not binding.used and name not in self.globals
and not self.uses_locals
and isinstance(binding, Assignment)):
yield name, binding | [
"def",
"unusedAssignments",
"(",
"self",
")",
":",
"for",
"name",
",",
"binding",
"in",
"self",
".",
"items",
"(",
")",
":",
"if",
"(",
"not",
"binding",
".",
"used",
"and",
"name",
"not",
"in",
"self",
".",
"globals",
"and",
"not",
"self",
".",
"u... | Return a generator for the assignments which have not been used. | [
"Return",
"a",
"generator",
"for",
"the",
"assignments",
"which",
"have",
"not",
"been",
"used",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L159-L165 | train | 42,014 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.check_plugins | def check_plugins(self):
""" collect plugins from entry point 'frosted.plugins'
and run their check() method, passing the filename
"""
checkers = {}
for ep in pkg_resources.iter_entry_points(group='frosted.plugins'):
checkers.update({ep.name: ep.load()})
for plugin_name, plugin in checkers.items():
if self.filename != '(none)':
messages = plugin.check(self.filename)
for message, loc, args, kwargs in messages:
self.report(message, loc, *args, **kwargs) | python | def check_plugins(self):
""" collect plugins from entry point 'frosted.plugins'
and run their check() method, passing the filename
"""
checkers = {}
for ep in pkg_resources.iter_entry_points(group='frosted.plugins'):
checkers.update({ep.name: ep.load()})
for plugin_name, plugin in checkers.items():
if self.filename != '(none)':
messages = plugin.check(self.filename)
for message, loc, args, kwargs in messages:
self.report(message, loc, *args, **kwargs) | [
"def",
"check_plugins",
"(",
"self",
")",
":",
"checkers",
"=",
"{",
"}",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"group",
"=",
"'frosted.plugins'",
")",
":",
"checkers",
".",
"update",
"(",
"{",
"ep",
".",
"name",
":",
"ep",
... | collect plugins from entry point 'frosted.plugins'
and run their check() method, passing the filename | [
"collect",
"plugins",
"from",
"entry",
"point",
"frosted",
".",
"plugins"
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L276-L289 | train | 42,015 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.run_deferred | def run_deferred(self, deferred):
"""Run the callables in deferred using their associated scope stack."""
for handler, scope, offset in deferred:
self.scope_stack = scope
self.offset = offset
handler() | python | def run_deferred(self, deferred):
"""Run the callables in deferred using their associated scope stack."""
for handler, scope, offset in deferred:
self.scope_stack = scope
self.offset = offset
handler() | [
"def",
"run_deferred",
"(",
"self",
",",
"deferred",
")",
":",
"for",
"handler",
",",
"scope",
",",
"offset",
"in",
"deferred",
":",
"self",
".",
"scope_stack",
"=",
"scope",
"self",
".",
"offset",
"=",
"offset",
"handler",
"(",
")"
] | Run the callables in deferred using their associated scope stack. | [
"Run",
"the",
"callables",
"in",
"deferred",
"using",
"their",
"associated",
"scope",
"stack",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L306-L311 | train | 42,016 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.find_return_with_argument | def find_return_with_argument(self, node):
"""Finds and returns a return statment that has an argument.
Note that we should use node.returns in Python 3, but this method is never called in Python 3 so we don't bother
checking.
"""
for item in node.body:
if isinstance(item, ast.Return) and item.value:
return item
elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'):
return_with_argument = self.find_return_with_argument(item)
if return_with_argument:
return return_with_argument | python | def find_return_with_argument(self, node):
"""Finds and returns a return statment that has an argument.
Note that we should use node.returns in Python 3, but this method is never called in Python 3 so we don't bother
checking.
"""
for item in node.body:
if isinstance(item, ast.Return) and item.value:
return item
elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'):
return_with_argument = self.find_return_with_argument(item)
if return_with_argument:
return return_with_argument | [
"def",
"find_return_with_argument",
"(",
"self",
",",
"node",
")",
":",
"for",
"item",
"in",
"node",
".",
"body",
":",
"if",
"isinstance",
"(",
"item",
",",
"ast",
".",
"Return",
")",
"and",
"item",
".",
"value",
":",
"return",
"item",
"elif",
"not",
... | Finds and returns a return statment that has an argument.
Note that we should use node.returns in Python 3, but this method is never called in Python 3 so we don't bother
checking. | [
"Finds",
"and",
"returns",
"a",
"return",
"statment",
"that",
"has",
"an",
"argument",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L605-L618 | train | 42,017 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.is_generator | def is_generator(self, node):
"""Checks whether a function is a generator by looking for a yield
statement or expression."""
if not isinstance(node.body, list):
# lambdas can not be generators
return False
for item in node.body:
if isinstance(item, (ast.Assign, ast.Expr)):
if isinstance(item.value, ast.Yield):
return True
elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'):
if self.is_generator(item):
return True
return False | python | def is_generator(self, node):
"""Checks whether a function is a generator by looking for a yield
statement or expression."""
if not isinstance(node.body, list):
# lambdas can not be generators
return False
for item in node.body:
if isinstance(item, (ast.Assign, ast.Expr)):
if isinstance(item.value, ast.Yield):
return True
elif not isinstance(item, ast.FunctionDef) and hasattr(item, 'body'):
if self.is_generator(item):
return True
return False | [
"def",
"is_generator",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"isinstance",
"(",
"node",
".",
"body",
",",
"list",
")",
":",
"# lambdas can not be generators",
"return",
"False",
"for",
"item",
"in",
"node",
".",
"body",
":",
"if",
"isinstance",
... | Checks whether a function is a generator by looking for a yield
statement or expression. | [
"Checks",
"whether",
"a",
"function",
"is",
"a",
"generator",
"by",
"looking",
"for",
"a",
"yield",
"statement",
"or",
"expression",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L620-L633 | train | 42,018 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.FOR | def FOR(self, node):
"""Process bindings for loop variables."""
vars = []
def collectLoopVars(n):
if isinstance(n, ast.Name):
vars.append(n.id)
elif isinstance(n, ast.expr_context):
return
else:
for c in ast.iter_child_nodes(n):
collectLoopVars(c)
collectLoopVars(node.target)
for varn in vars:
if (isinstance(self.scope.get(varn), Importation)
# unused ones will get an unused import warning
and self.scope[varn].used):
self.report(messages.ImportShadowedByLoopVar,
node, varn, self.scope[varn].source)
self.handle_children(node) | python | def FOR(self, node):
"""Process bindings for loop variables."""
vars = []
def collectLoopVars(n):
if isinstance(n, ast.Name):
vars.append(n.id)
elif isinstance(n, ast.expr_context):
return
else:
for c in ast.iter_child_nodes(n):
collectLoopVars(c)
collectLoopVars(node.target)
for varn in vars:
if (isinstance(self.scope.get(varn), Importation)
# unused ones will get an unused import warning
and self.scope[varn].used):
self.report(messages.ImportShadowedByLoopVar,
node, varn, self.scope[varn].source)
self.handle_children(node) | [
"def",
"FOR",
"(",
"self",
",",
"node",
")",
":",
"vars",
"=",
"[",
"]",
"def",
"collectLoopVars",
"(",
"n",
")",
":",
"if",
"isinstance",
"(",
"n",
",",
"ast",
".",
"Name",
")",
":",
"vars",
".",
"append",
"(",
"n",
".",
"id",
")",
"elif",
"... | Process bindings for loop variables. | [
"Process",
"bindings",
"for",
"loop",
"variables",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L693-L714 | train | 42,019 |
timothycrosley/deprecated.frosted | frosted/checker.py | Checker.CLASSDEF | def CLASSDEF(self, node):
"""Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.push_scope(ClassScope)
if self.settings.get('run_doctests', False):
self.defer_function(lambda: self.handle_doctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.pop_scope()
self.add_binding(node, ClassDefinition(node.name, node)) | python | def CLASSDEF(self, node):
"""Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope.
"""
for deco in node.decorator_list:
self.handleNode(deco, node)
for baseNode in node.bases:
self.handleNode(baseNode, node)
if not PY2:
for keywordNode in node.keywords:
self.handleNode(keywordNode, node)
self.push_scope(ClassScope)
if self.settings.get('run_doctests', False):
self.defer_function(lambda: self.handle_doctests(node))
for stmt in node.body:
self.handleNode(stmt, node)
self.pop_scope()
self.add_binding(node, ClassDefinition(node.name, node)) | [
"def",
"CLASSDEF",
"(",
"self",
",",
"node",
")",
":",
"for",
"deco",
"in",
"node",
".",
"decorator_list",
":",
"self",
".",
"handleNode",
"(",
"deco",
",",
"node",
")",
"for",
"baseNode",
"in",
"node",
".",
"bases",
":",
"self",
".",
"handleNode",
"... | Check names used in a class definition, including its decorators,
base classes, and the body of its definition.
Additionally, add its name to the current scope. | [
"Check",
"names",
"used",
"in",
"a",
"class",
"definition",
"including",
"its",
"decorators",
"base",
"classes",
"and",
"the",
"body",
"of",
"its",
"definition",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/checker.py#L837-L857 | train | 42,020 |
timothycrosley/deprecated.frosted | frosted/api.py | check | def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the Python source given by codeString for unfrosted flakes."""
if not settings_path and filename:
settings_path = os.path.dirname(os.path.abspath(filename))
settings_path = settings_path or os.getcwd()
active_settings = settings.from_path(settings_path).copy()
for key, value in itemsview(setting_overrides):
access_key = key.replace('not_', '').lower()
if type(active_settings.get(access_key)) in (list, tuple):
if key.startswith('not_'):
active_settings[access_key] = list(set(active_settings[access_key]).difference(value))
else:
active_settings[access_key] = list(set(active_settings[access_key]).union(value))
else:
active_settings[key] = value
active_settings.update(setting_overrides)
if _should_skip(filename, active_settings.get('skip', [])):
if active_settings.get('directly_being_checked', None) == 1:
reporter.flake(FileSkipped(filename))
return 1
elif active_settings.get('verbose', False):
ignore = active_settings.get('ignore_frosted_errors', [])
if(not "W200" in ignore and not "W201" in ignore):
reporter.flake(FileSkipped(filename, None, verbose=active_settings.get('verbose')))
return 0
# First, compile into an AST and handle syntax errors.
try:
tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpected_error(filename, 'problem decoding source')
else:
reporter.flake(PythonSyntaxError(filename, msg, lineno, offset, text,
verbose=active_settings.get('verbose')))
return 1
except Exception:
reporter.unexpected_error(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
w = checker.Checker(tree, filename, None, ignore_lines=_noqa_lines(codeString), **active_settings)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages) | python | def check(codeString, filename, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Check the Python source given by codeString for unfrosted flakes."""
if not settings_path and filename:
settings_path = os.path.dirname(os.path.abspath(filename))
settings_path = settings_path or os.getcwd()
active_settings = settings.from_path(settings_path).copy()
for key, value in itemsview(setting_overrides):
access_key = key.replace('not_', '').lower()
if type(active_settings.get(access_key)) in (list, tuple):
if key.startswith('not_'):
active_settings[access_key] = list(set(active_settings[access_key]).difference(value))
else:
active_settings[access_key] = list(set(active_settings[access_key]).union(value))
else:
active_settings[key] = value
active_settings.update(setting_overrides)
if _should_skip(filename, active_settings.get('skip', [])):
if active_settings.get('directly_being_checked', None) == 1:
reporter.flake(FileSkipped(filename))
return 1
elif active_settings.get('verbose', False):
ignore = active_settings.get('ignore_frosted_errors', [])
if(not "W200" in ignore and not "W201" in ignore):
reporter.flake(FileSkipped(filename, None, verbose=active_settings.get('verbose')))
return 0
# First, compile into an AST and handle syntax errors.
try:
tree = compile(codeString, filename, "exec", _ast.PyCF_ONLY_AST)
except SyntaxError:
value = sys.exc_info()[1]
msg = value.args[0]
(lineno, offset, text) = value.lineno, value.offset, value.text
# If there's an encoding problem with the file, the text is None.
if text is None:
# Avoid using msg, since for the only known case, it contains a
# bogus message that claims the encoding the file declared was
# unknown.
reporter.unexpected_error(filename, 'problem decoding source')
else:
reporter.flake(PythonSyntaxError(filename, msg, lineno, offset, text,
verbose=active_settings.get('verbose')))
return 1
except Exception:
reporter.unexpected_error(filename, 'problem decoding source')
return 1
# Okay, it's syntactically valid. Now check it.
w = checker.Checker(tree, filename, None, ignore_lines=_noqa_lines(codeString), **active_settings)
w.messages.sort(key=lambda m: m.lineno)
for warning in w.messages:
reporter.flake(warning)
return len(w.messages) | [
"def",
"check",
"(",
"codeString",
",",
"filename",
",",
"reporter",
"=",
"modReporter",
".",
"Default",
",",
"settings_path",
"=",
"None",
",",
"*",
"*",
"setting_overrides",
")",
":",
"if",
"not",
"settings_path",
"and",
"filename",
":",
"settings_path",
"... | Check the Python source given by codeString for unfrosted flakes. | [
"Check",
"the",
"Python",
"source",
"given",
"by",
"codeString",
"for",
"unfrosted",
"flakes",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/api.py#L62-L118 | train | 42,021 |
timothycrosley/deprecated.frosted | frosted/api.py | check_recursive | def check_recursive(paths, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Recursively check all source files defined in paths."""
warnings = 0
for source_path in iter_source_code(paths):
warnings += check_path(source_path, reporter, settings_path=None, **setting_overrides)
return warnings | python | def check_recursive(paths, reporter=modReporter.Default, settings_path=None, **setting_overrides):
"""Recursively check all source files defined in paths."""
warnings = 0
for source_path in iter_source_code(paths):
warnings += check_path(source_path, reporter, settings_path=None, **setting_overrides)
return warnings | [
"def",
"check_recursive",
"(",
"paths",
",",
"reporter",
"=",
"modReporter",
".",
"Default",
",",
"settings_path",
"=",
"None",
",",
"*",
"*",
"setting_overrides",
")",
":",
"warnings",
"=",
"0",
"for",
"source_path",
"in",
"iter_source_code",
"(",
"paths",
... | Recursively check all source files defined in paths. | [
"Recursively",
"check",
"all",
"source",
"files",
"defined",
"in",
"paths",
"."
] | 61ba7f341fc55676c3580c8c4e52117986cd5e12 | https://github.com/timothycrosley/deprecated.frosted/blob/61ba7f341fc55676c3580c8c4e52117986cd5e12/frosted/api.py#L148-L153 | train | 42,022 |
codingjoe/django-s3file | s3file/middleware.py | S3FileMiddleware.get_files_from_storage | def get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
f = default_storage.open(path)
f.name = os.path.basename(path)
try:
yield f
except ClientError:
logger.exception("File not found: %s", path) | python | def get_files_from_storage(paths):
"""Return S3 file where the name does not include the path."""
for path in paths:
f = default_storage.open(path)
f.name = os.path.basename(path)
try:
yield f
except ClientError:
logger.exception("File not found: %s", path) | [
"def",
"get_files_from_storage",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"f",
"=",
"default_storage",
".",
"open",
"(",
"path",
")",
"f",
".",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")",
"try",
":",
"yield",
... | Return S3 file where the name does not include the path. | [
"Return",
"S3",
"file",
"where",
"the",
"name",
"does",
"not",
"include",
"the",
"path",
"."
] | 53c55543a6589bd906d2c28c683f8f182b33d2fa | https://github.com/codingjoe/django-s3file/blob/53c55543a6589bd906d2c28c683f8f182b33d2fa/s3file/middleware.py#L24-L32 | train | 42,023 |
balemessenger/bale-bot-python | examples/echobot.py | echo | def echo(bot, update):
"""Echo the user message."""
message = update.get_effective_message()
bot.reply(update, message) | python | def echo(bot, update):
"""Echo the user message."""
message = update.get_effective_message()
bot.reply(update, message) | [
"def",
"echo",
"(",
"bot",
",",
"update",
")",
":",
"message",
"=",
"update",
".",
"get_effective_message",
"(",
")",
"bot",
".",
"reply",
"(",
"update",
",",
"message",
")"
] | Echo the user message. | [
"Echo",
"the",
"user",
"message",
"."
] | 92bfd60016b075179f16c212fc3fc20a4e5f16f4 | https://github.com/balemessenger/bale-bot-python/blob/92bfd60016b075179f16c212fc3fc20a4e5f16f4/examples/echobot.py#L38-L41 | train | 42,024 |
balemessenger/bale-bot-python | examples/echobot.py | error | def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | python | def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.error('Update {} caused error {}'.format(update, error), extra={"tag": "err"}) | [
"def",
"error",
"(",
"bot",
",",
"update",
",",
"error",
")",
":",
"logger",
".",
"error",
"(",
"'Update {} caused error {}'",
".",
"format",
"(",
"update",
",",
"error",
")",
",",
"extra",
"=",
"{",
"\"tag\"",
":",
"\"err\"",
"}",
")"
] | Log Errors caused by Updates. | [
"Log",
"Errors",
"caused",
"by",
"Updates",
"."
] | 92bfd60016b075179f16c212fc3fc20a4e5f16f4 | https://github.com/balemessenger/bale-bot-python/blob/92bfd60016b075179f16c212fc3fc20a4e5f16f4/examples/echobot.py#L44-L46 | train | 42,025 |
balemessenger/bale-bot-python | examples/echobot.py | main | def main():
"""Start the bot."""
# Bale Bot Authorization Token
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Bale
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Bale
dp.add_handler(MessageHandler(DefaultFilter(), echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.run() | python | def main():
"""Start the bot."""
# Bale Bot Authorization Token
updater = Updater("TOKEN")
# Get the dispatcher to register handlers
dp = updater.dispatcher
# on different commands - answer in Bale
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("help", help))
# on noncommand i.e message - echo the message on Bale
dp.add_handler(MessageHandler(DefaultFilter(), echo))
# log all errors
dp.add_error_handler(error)
# Start the Bot
updater.run() | [
"def",
"main",
"(",
")",
":",
"# Bale Bot Authorization Token",
"updater",
"=",
"Updater",
"(",
"\"TOKEN\"",
")",
"# Get the dispatcher to register handlers",
"dp",
"=",
"updater",
".",
"dispatcher",
"# on different commands - answer in Bale",
"dp",
".",
"add_handler",
"(... | Start the bot. | [
"Start",
"the",
"bot",
"."
] | 92bfd60016b075179f16c212fc3fc20a4e5f16f4 | https://github.com/balemessenger/bale-bot-python/blob/92bfd60016b075179f16c212fc3fc20a4e5f16f4/examples/echobot.py#L49-L68 | train | 42,026 |
hozn/coilmq | coilmq/start.py | main | def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will be started.
"""
_main(**locals()) | python | def main(config, host, port, logfile, debug, daemon, uid, gid, pidfile, umask, rundir):
"""
Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will be started.
"""
_main(**locals()) | [
"def",
"main",
"(",
"config",
",",
"host",
",",
"port",
",",
"logfile",
",",
"debug",
",",
"daemon",
",",
"uid",
",",
"gid",
",",
"pidfile",
",",
"umask",
",",
"rundir",
")",
":",
"_main",
"(",
"*",
"*",
"locals",
"(",
")",
")"
] | Main entry point for running a socket server from the commandline.
This method will read in options from the commandline and call the L{config.init_config} method
to get everything setup. Then, depending on whether deamon mode was specified or not,
the process may be forked (or not) and the server will be started. | [
"Main",
"entry",
"point",
"for",
"running",
"a",
"socket",
"server",
"from",
"the",
"commandline",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/start.py#L207-L216 | train | 42,027 |
hozn/coilmq | coilmq/store/sa/__init__.py | make_sa | def make_sa():
"""
Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration.
"""
configuration = dict(config.items('coilmq'))
engine = engine_from_config(configuration, 'qstore.sqlalchemy.')
init_model(engine)
store = SAQueue()
return store | python | def make_sa():
"""
Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration.
"""
configuration = dict(config.items('coilmq'))
engine = engine_from_config(configuration, 'qstore.sqlalchemy.')
init_model(engine)
store = SAQueue()
return store | [
"def",
"make_sa",
"(",
")",
":",
"configuration",
"=",
"dict",
"(",
"config",
".",
"items",
"(",
"'coilmq'",
")",
")",
"engine",
"=",
"engine_from_config",
"(",
"configuration",
",",
"'qstore.sqlalchemy.'",
")",
"init_model",
"(",
"engine",
")",
"store",
"="... | Factory to creates a SQLAlchemy queue store, pulling config values from the CoilMQ configuration. | [
"Factory",
"to",
"creates",
"a",
"SQLAlchemy",
"queue",
"store",
"pulling",
"config",
"values",
"from",
"the",
"CoilMQ",
"configuration",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/store/sa/__init__.py#L44-L52 | train | 42,028 |
hozn/coilmq | coilmq/topic.py | TopicManager.subscribe | def subscribe(self, connection, destination):
"""
Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._topics[destination].add(connection) | python | def subscribe(self, connection, destination):
"""
Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Subscribing %s to %s" % (connection, destination))
self._topics[destination].add(connection) | [
"def",
"subscribe",
"(",
"self",
",",
"connection",
",",
"destination",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Subscribing %s to %s\"",
"%",
"(",
"connection",
",",
"destination",
")",
")",
"self",
".",
"_topics",
"[",
"destination",
"]",
".",... | Subscribes a connection to the specified topic destination.
@param connection: The client connection to subscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | [
"Subscribes",
"a",
"connection",
"to",
"the",
"specified",
"topic",
"destination",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/topic.py#L67-L78 | train | 42,029 |
hozn/coilmq | coilmq/topic.py | TopicManager.unsubscribe | def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._topics[destination]:
self._topics[destination].remove(connection)
if not self._topics[destination]:
del self._topics[destination] | python | def unsubscribe(self, connection, destination):
"""
Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str}
"""
self.log.debug("Unsubscribing %s from %s" % (connection, destination))
if connection in self._topics[destination]:
self._topics[destination].remove(connection)
if not self._topics[destination]:
del self._topics[destination] | [
"def",
"unsubscribe",
"(",
"self",
",",
"connection",
",",
"destination",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Unsubscribing %s from %s\"",
"%",
"(",
"connection",
",",
"destination",
")",
")",
"if",
"connection",
"in",
"self",
".",
"_topics",... | Unsubscribes a connection from the specified topic destination.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
@param destination: The topic destination (e.g. '/topic/foo')
@type destination: C{str} | [
"Unsubscribes",
"a",
"connection",
"from",
"the",
"specified",
"topic",
"destination",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/topic.py#L81-L96 | train | 42,030 |
hozn/coilmq | coilmq/topic.py | TopicManager.disconnect | def disconnect(self, connection):
"""
Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
for dest in list(self._topics.keys()):
if connection in self._topics[dest]:
self._topics[dest].remove(connection)
if not self._topics[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._topics[dest] | python | def disconnect(self, connection):
"""
Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
for dest in list(self._topics.keys()):
if connection in self._topics[dest]:
self._topics[dest].remove(connection)
if not self._topics[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._topics[dest] | [
"def",
"disconnect",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Disconnecting %s\"",
"%",
"connection",
")",
"for",
"dest",
"in",
"list",
"(",
"self",
".",
"_topics",
".",
"keys",
"(",
")",
")",
":",
"if",
"co... | Removes a subscriber connection.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | [
"Removes",
"a",
"subscriber",
"connection",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/topic.py#L99-L112 | train | 42,031 |
hozn/coilmq | coilmq/topic.py | TopicManager.send | def send(self, message):
"""
Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
bad_subscribers = set()
for subscriber in self._topics[dest]:
try:
subscriber.send_frame(message)
except:
self.log.exception(
"Error delivering message to subscriber %s; client will be disconnected." % subscriber)
# We queue for deletion so we are not modifying the topics dict
# while iterating over it.
bad_subscribers.add(subscriber)
for subscriber in bad_subscribers:
self.disconnect(subscriber) | python | def send(self, message):
"""
Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
bad_subscribers = set()
for subscriber in self._topics[dest]:
try:
subscriber.send_frame(message)
except:
self.log.exception(
"Error delivering message to subscriber %s; client will be disconnected." % subscriber)
# We queue for deletion so we are not modifying the topics dict
# while iterating over it.
bad_subscribers.add(subscriber)
for subscriber in bad_subscribers:
self.disconnect(subscriber) | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"dest",
"=",
"message",
".",
"headers",
".",
"get",
"(",
"'destination'",
")",
"if",
"not",
"dest",
":",
"raise",
"ValueError",
"(",
"\"Cannot send frame with no destination: %s\"",
"%",
"message",
")",
"... | Sends a message to all subscribers of destination.
@param message: The message frame. (The frame will be modified to set command
to MESSAGE and set a message id.)
@type message: L{stompclient.frame.Frame} | [
"Sends",
"a",
"message",
"to",
"all",
"subscribers",
"of",
"destination",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/topic.py#L115-L144 | train | 42,032 |
hozn/coilmq | coilmq/queue.py | QueueManager.subscriber_count | def subscriber_count(self, destination=None):
"""
Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
"""
if destination:
return len(self._queues[destination])
else:
# total them up
total = 0
for k in self._queues.keys():
total += len(self._queues[k])
return total | python | def subscriber_count(self, destination=None):
"""
Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str}
"""
if destination:
return len(self._queues[destination])
else:
# total them up
total = 0
for k in self._queues.keys():
total += len(self._queues[k])
return total | [
"def",
"subscriber_count",
"(",
"self",
",",
"destination",
"=",
"None",
")",
":",
"if",
"destination",
":",
"return",
"len",
"(",
"self",
".",
"_queues",
"[",
"destination",
"]",
")",
"else",
":",
"# total them up",
"total",
"=",
"0",
"for",
"k",
"in",
... | Returns a count of the number of subscribers.
If destination is specified then it only returns count of subscribers
for that specific destination.
@param destination: The optional topic/queue destination (e.g. '/queue/foo')
@type destination: C{str} | [
"Returns",
"a",
"count",
"of",
"the",
"number",
"of",
"subscribers",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L114-L131 | train | 42,033 |
hozn/coilmq | coilmq/queue.py | QueueManager.disconnect | def disconnect(self, connection):
"""
Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
if connection in self._pending:
pending_frame = self._pending[connection]
self.store.requeue(pending_frame.headers.get(
'destination'), pending_frame)
del self._pending[connection]
for dest in list(self._queues.keys()):
if connection in self._queues[dest]:
self._queues[dest].remove(connection)
if not self._queues[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._queues[dest] | python | def disconnect(self, connection):
"""
Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection}
"""
self.log.debug("Disconnecting %s" % connection)
if connection in self._pending:
pending_frame = self._pending[connection]
self.store.requeue(pending_frame.headers.get(
'destination'), pending_frame)
del self._pending[connection]
for dest in list(self._queues.keys()):
if connection in self._queues[dest]:
self._queues[dest].remove(connection)
if not self._queues[dest]:
# This won't trigger RuntimeError, since we're using keys()
del self._queues[dest] | [
"def",
"disconnect",
"(",
"self",
",",
"connection",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Disconnecting %s\"",
"%",
"connection",
")",
"if",
"connection",
"in",
"self",
".",
"_pending",
":",
"pending_frame",
"=",
"self",
".",
"_pending",
"["... | Removes a subscriber connection, ensuring that any pending commands get requeued.
@param connection: The client connection to unsubscribe.
@type connection: L{coilmq.server.StompConnection} | [
"Removes",
"a",
"subscriber",
"connection",
"ensuring",
"that",
"any",
"pending",
"commands",
"get",
"requeued",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L167-L186 | train | 42,034 |
hozn/coilmq | coilmq/queue.py | QueueManager.send | def send(self, message):
"""
Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
# Grab all subscribers for this destination that do not have pending
# frames
subscribers = [s for s in self._queues[dest]
if s not in self._pending]
if not subscribers:
self.log.debug(
"No eligible subscribers; adding message %s to queue %s" % (message, dest))
self.store.enqueue(dest, message)
else:
selected = self.subscriber_scheduler.choice(subscribers, message)
self.log.debug("Delivering message %s to subscriber %s" %
(message, selected))
self._send_frame(selected, message) | python | def send(self, message):
"""
Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stompclient.frame.Frame}
"""
dest = message.headers.get('destination')
if not dest:
raise ValueError(
"Cannot send frame with no destination: %s" % message)
message.cmd = 'message'
message.headers.setdefault('message-id', str(uuid.uuid4()))
# Grab all subscribers for this destination that do not have pending
# frames
subscribers = [s for s in self._queues[dest]
if s not in self._pending]
if not subscribers:
self.log.debug(
"No eligible subscribers; adding message %s to queue %s" % (message, dest))
self.store.enqueue(dest, message)
else:
selected = self.subscriber_scheduler.choice(subscribers, message)
self.log.debug("Delivering message %s to subscriber %s" %
(message, selected))
self._send_frame(selected, message) | [
"def",
"send",
"(",
"self",
",",
"message",
")",
":",
"dest",
"=",
"message",
".",
"headers",
".",
"get",
"(",
"'destination'",
")",
"if",
"not",
"dest",
":",
"raise",
"ValueError",
"(",
"\"Cannot send frame with no destination: %s\"",
"%",
"message",
")",
"... | Sends a MESSAGE frame to an eligible subscriber connection.
Note that this method will modify the incoming message object to
add a message-id header (if not present) and to change the command
to 'MESSAGE' (if it is not).
@param message: The message frame.
@type message: C{stompclient.frame.Frame} | [
"Sends",
"a",
"MESSAGE",
"frame",
"to",
"an",
"eligible",
"subscriber",
"connection",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L189-L222 | train | 42,035 |
hozn/coilmq | coilmq/queue.py | QueueManager.ack | def ack(self, connection, frame, transaction=None):
"""
Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame being acknowledged.
"""
self.log.debug("ACK %s for %s" % (frame, connection))
if connection in self._pending:
pending_frame = self._pending[connection]
# Make sure that the frame being acknowledged matches
# the expected frame
if pending_frame.headers.get('message-id') != frame.headers.get('message-id'):
self.log.warning(
"Got a ACK for unexpected message-id: %s" % frame.message_id)
self.store.requeue(pending_frame.destination, pending_frame)
# (The pending frame will be removed further down)
if transaction is not None:
self._transaction_frames[connection][
transaction].append(pending_frame)
del self._pending[connection]
self._send_backlog(connection)
else:
self.log.debug("No pending messages for %s" % connection) | python | def ack(self, connection, frame, transaction=None):
"""
Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame being acknowledged.
"""
self.log.debug("ACK %s for %s" % (frame, connection))
if connection in self._pending:
pending_frame = self._pending[connection]
# Make sure that the frame being acknowledged matches
# the expected frame
if pending_frame.headers.get('message-id') != frame.headers.get('message-id'):
self.log.warning(
"Got a ACK for unexpected message-id: %s" % frame.message_id)
self.store.requeue(pending_frame.destination, pending_frame)
# (The pending frame will be removed further down)
if transaction is not None:
self._transaction_frames[connection][
transaction].append(pending_frame)
del self._pending[connection]
self._send_backlog(connection)
else:
self.log.debug("No pending messages for %s" % connection) | [
"def",
"ack",
"(",
"self",
",",
"connection",
",",
"frame",
",",
"transaction",
"=",
"None",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"ACK %s for %s\"",
"%",
"(",
"frame",
",",
"connection",
")",
")",
"if",
"connection",
"in",
"self",
".",
... | Acknowledge receipt of a message.
If the `transaction` parameter is non-null, the frame being ack'd
will be queued so that it can be requeued if the transaction
is rolled back.
@param connection: The connection that is acknowledging the frame.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame being acknowledged. | [
"Acknowledge",
"receipt",
"of",
"a",
"message",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L225-L259 | train | 42,036 |
hozn/coilmq | coilmq/queue.py | QueueManager.resend_transaction_frames | def resend_transaction_frames(self, connection, transaction):
"""
Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (which was aborted).
@type transaction: C{str}
"""
for frame in self._transaction_frames[connection][transaction]:
self.send(frame) | python | def resend_transaction_frames(self, connection, transaction):
"""
Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (which was aborted).
@type transaction: C{str}
"""
for frame in self._transaction_frames[connection][transaction]:
self.send(frame) | [
"def",
"resend_transaction_frames",
"(",
"self",
",",
"connection",
",",
"transaction",
")",
":",
"for",
"frame",
"in",
"self",
".",
"_transaction_frames",
"[",
"connection",
"]",
"[",
"transaction",
"]",
":",
"self",
".",
"send",
"(",
"frame",
")"
] | Resend the messages that were ACK'd in specified transaction.
This is called by the engine when there is an abort command.
@param connection: The client connection that aborted the transaction.
@type connection: L{coilmq.server.StompConnection}
@param transaction: The transaction id (which was aborted).
@type transaction: C{str} | [
"Resend",
"the",
"messages",
"that",
"were",
"ACK",
"d",
"in",
"specified",
"transaction",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L262-L275 | train | 42,037 |
hozn/coilmq | coilmq/queue.py | QueueManager._send_frame | def _send_frame(self, connection, frame):
"""
Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to send.
@type frame: L{stompclient.frame.Frame}
"""
assert connection is not None
assert frame is not None
self.log.debug("Delivering frame %s to connection %s" %
(frame, connection))
if connection.reliable_subscriber:
if connection in self._pending:
raise RuntimeError("Connection already has a pending frame.")
self.log.debug(
"Tracking frame %s as pending for connection %s" % (frame, connection))
self._pending[connection] = frame
connection.send_frame(frame) | python | def _send_frame(self, connection, frame):
"""
Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to send.
@type frame: L{stompclient.frame.Frame}
"""
assert connection is not None
assert frame is not None
self.log.debug("Delivering frame %s to connection %s" %
(frame, connection))
if connection.reliable_subscriber:
if connection in self._pending:
raise RuntimeError("Connection already has a pending frame.")
self.log.debug(
"Tracking frame %s as pending for connection %s" % (frame, connection))
self._pending[connection] = frame
connection.send_frame(frame) | [
"def",
"_send_frame",
"(",
"self",
",",
"connection",
",",
"frame",
")",
":",
"assert",
"connection",
"is",
"not",
"None",
"assert",
"frame",
"is",
"not",
"None",
"self",
".",
"log",
".",
"debug",
"(",
"\"Delivering frame %s to connection %s\"",
"%",
"(",
"f... | Sends a frame to a specific subscriber connection.
(This method assumes it is being called from within a lock-guarded public
method.)
@param connection: The subscriber connection object to send to.
@type connection: L{coilmq.server.StompConnection}
@param frame: The frame to send.
@type frame: L{stompclient.frame.Frame} | [
"Sends",
"a",
"frame",
"to",
"a",
"specific",
"subscriber",
"connection",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/queue.py#L350-L376 | train | 42,038 |
hozn/coilmq | coilmq/store/dbm.py | make_dbm | def make_dbm():
"""
Creates a DBM queue store, pulling config values from the CoilMQ configuration.
"""
try:
data_dir = config.get('coilmq', 'qstore.dbm.data_dir')
cp_ops = config.getint('coilmq', 'qstore.dbm.checkpoint_operations')
cp_timeout = config.getint('coilmq', 'qstore.dbm.checkpoint_timeout')
except ConfigParser.NoOptionError as e:
raise ConfigError('Missing configuration parameter: %s' % e)
if not os.path.exists(data_dir):
raise ConfigError('DBM directory does not exist: %s' % data_dir)
# FIXME: how do these get applied? Is OR appropriate?
if not os.access(data_dir, os.W_OK | os.R_OK):
raise ConfigError('Cannot read and write DBM directory: %s' % data_dir)
store = DbmQueue(data_dir, checkpoint_operations=cp_ops,
checkpoint_timeout=cp_timeout)
return store | python | def make_dbm():
"""
Creates a DBM queue store, pulling config values from the CoilMQ configuration.
"""
try:
data_dir = config.get('coilmq', 'qstore.dbm.data_dir')
cp_ops = config.getint('coilmq', 'qstore.dbm.checkpoint_operations')
cp_timeout = config.getint('coilmq', 'qstore.dbm.checkpoint_timeout')
except ConfigParser.NoOptionError as e:
raise ConfigError('Missing configuration parameter: %s' % e)
if not os.path.exists(data_dir):
raise ConfigError('DBM directory does not exist: %s' % data_dir)
# FIXME: how do these get applied? Is OR appropriate?
if not os.access(data_dir, os.W_OK | os.R_OK):
raise ConfigError('Cannot read and write DBM directory: %s' % data_dir)
store = DbmQueue(data_dir, checkpoint_operations=cp_ops,
checkpoint_timeout=cp_timeout)
return store | [
"def",
"make_dbm",
"(",
")",
":",
"try",
":",
"data_dir",
"=",
"config",
".",
"get",
"(",
"'coilmq'",
",",
"'qstore.dbm.data_dir'",
")",
"cp_ops",
"=",
"config",
".",
"getint",
"(",
"'coilmq'",
",",
"'qstore.dbm.checkpoint_operations'",
")",
"cp_timeout",
"=",... | Creates a DBM queue store, pulling config values from the CoilMQ configuration. | [
"Creates",
"a",
"DBM",
"queue",
"store",
"pulling",
"config",
"values",
"from",
"the",
"CoilMQ",
"configuration",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/store/dbm.py#L47-L66 | train | 42,039 |
hozn/coilmq | coilmq/store/dbm.py | DbmQueue._sync | def _sync(self):
"""
Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}.
"""
if (self._opcount > self.checkpoint_operations or
datetime.now() > self._last_sync + self.checkpoint_timeout):
self.log.debug("Synchronizing queue metadata.")
self.queue_metadata.sync()
self._last_sync = datetime.now()
self._opcount = 0
else:
self.log.debug("NOT synchronizing queue metadata.") | python | def _sync(self):
"""
Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}.
"""
if (self._opcount > self.checkpoint_operations or
datetime.now() > self._last_sync + self.checkpoint_timeout):
self.log.debug("Synchronizing queue metadata.")
self.queue_metadata.sync()
self._last_sync = datetime.now()
self._opcount = 0
else:
self.log.debug("NOT synchronizing queue metadata.") | [
"def",
"_sync",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"_opcount",
">",
"self",
".",
"checkpoint_operations",
"or",
"datetime",
".",
"now",
"(",
")",
">",
"self",
".",
"_last_sync",
"+",
"self",
".",
"checkpoint_timeout",
")",
":",
"self",
".",... | Synchronize the cached data with the underlyind database.
Uses an internal transaction counter and compares to the checkpoint_operations
and checkpoint_timeout paramters to determine whether to persist the memory store.
In this implementation, this method wraps calls to C{shelve.Shelf#sync}. | [
"Synchronize",
"the",
"cached",
"data",
"with",
"the",
"underlyind",
"database",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/store/dbm.py#L246-L262 | train | 42,040 |
polyaxon/rhea | rhea/reader.py | read | def read(config_values):
"""Reads an ordered list of configuration values and deep merge the values in reverse order."""
if not config_values:
raise RheaError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for config_value in config_values:
config_value = ConfigSpec.get_from(value=config_value)
config_value.check_type()
config_results = config_value.read()
if config_results and isinstance(config_results, Mapping):
config = deep_update(config, config_results)
elif config_value.check_if_exists:
raise RheaError('Cannot read config_value: `{}`'.format(config_value))
return config | python | def read(config_values):
"""Reads an ordered list of configuration values and deep merge the values in reverse order."""
if not config_values:
raise RheaError('Cannot read config_value: `{}`'.format(config_values))
config_values = to_list(config_values)
config = {}
for config_value in config_values:
config_value = ConfigSpec.get_from(value=config_value)
config_value.check_type()
config_results = config_value.read()
if config_results and isinstance(config_results, Mapping):
config = deep_update(config, config_results)
elif config_value.check_if_exists:
raise RheaError('Cannot read config_value: `{}`'.format(config_value))
return config | [
"def",
"read",
"(",
"config_values",
")",
":",
"if",
"not",
"config_values",
":",
"raise",
"RheaError",
"(",
"'Cannot read config_value: `{}`'",
".",
"format",
"(",
"config_values",
")",
")",
"config_values",
"=",
"to_list",
"(",
"config_values",
")",
"config",
... | Reads an ordered list of configuration values and deep merge the values in reverse order. | [
"Reads",
"an",
"ordered",
"list",
"of",
"configuration",
"values",
"and",
"deep",
"merge",
"the",
"values",
"in",
"reverse",
"order",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/reader.py#L11-L28 | train | 42,041 |
hozn/coilmq | coilmq/util/frames.py | parse_headers | def parse_headers(buff):
"""
Parses buffer and returns command and headers as strings
"""
preamble_lines = list(map(
lambda x: six.u(x).decode(),
iter(lambda: buff.readline().strip(), b''))
)
if not preamble_lines:
raise EmptyBuffer()
return preamble_lines[0], OrderedDict([l.split(':') for l in preamble_lines[1:]]) | python | def parse_headers(buff):
"""
Parses buffer and returns command and headers as strings
"""
preamble_lines = list(map(
lambda x: six.u(x).decode(),
iter(lambda: buff.readline().strip(), b''))
)
if not preamble_lines:
raise EmptyBuffer()
return preamble_lines[0], OrderedDict([l.split(':') for l in preamble_lines[1:]]) | [
"def",
"parse_headers",
"(",
"buff",
")",
":",
"preamble_lines",
"=",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"six",
".",
"u",
"(",
"x",
")",
".",
"decode",
"(",
")",
",",
"iter",
"(",
"lambda",
":",
"buff",
".",
"readline",
"(",
")",
".",
... | Parses buffer and returns command and headers as strings | [
"Parses",
"buffer",
"and",
"returns",
"command",
"and",
"headers",
"as",
"strings"
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/util/frames.py#L41-L51 | train | 42,042 |
hozn/coilmq | coilmq/util/frames.py | Frame.pack | def pack(self):
"""
Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str}
"""
self.headers.setdefault('content-length', len(self.body))
# Convert and append any existing headers to a string as the
# protocol describes.
headerparts = ("{0}:{1}\n".format(key, value)
for key, value in self.headers.items())
# Frame is Command + Header + EOF marker.
return six.b("{0}\n{1}\n".format(self.cmd, "".join(headerparts))) + (self.body if isinstance(self.body, six.binary_type) else six.b(self.body)) + six.b('\x00') | python | def pack(self):
"""
Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str}
"""
self.headers.setdefault('content-length', len(self.body))
# Convert and append any existing headers to a string as the
# protocol describes.
headerparts = ("{0}:{1}\n".format(key, value)
for key, value in self.headers.items())
# Frame is Command + Header + EOF marker.
return six.b("{0}\n{1}\n".format(self.cmd, "".join(headerparts))) + (self.body if isinstance(self.body, six.binary_type) else six.b(self.body)) + six.b('\x00') | [
"def",
"pack",
"(",
"self",
")",
":",
"self",
".",
"headers",
".",
"setdefault",
"(",
"'content-length'",
",",
"len",
"(",
"self",
".",
"body",
")",
")",
"# Convert and append any existing headers to a string as the",
"# protocol describes.",
"headerparts",
"=",
"("... | Create a string representation from object state.
@return: The string (bytes) for this stomp frame.
@rtype: C{str} | [
"Create",
"a",
"string",
"representation",
"from",
"object",
"state",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/util/frames.py#L113-L129 | train | 42,043 |
hozn/coilmq | coilmq/util/frames.py | FrameBuffer.extract_frame | def extract_frame(self):
"""
Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame}
"""
# (mbytes, hbytes) = self._find_message_bytes(self.buffer)
# if not mbytes:
# return None
#
# msgdata = self.buffer[:mbytes]
# self.buffer = self.buffer[mbytes:]
# hdata = msgdata[:hbytes]
# # Strip off any leading whitespace from headers; this is necessary, because
# # we do not (any longer) expect a trailing \n after the \x00 byte (which means
# # it will become a leading \n to the next frame).
# hdata = hdata.lstrip()
# elems = hdata.split('\n')
# cmd = elems.pop(0)
# headers = {}
#
# for e in elems:
# try:
# (k,v) = e.split(':', 1) # header values may contain ':' so specify maxsplit
# except ValueError:
# continue
# headers[k.strip()] = v.strip()
#
# # hbytes points to the start of the '\n\n' at the end of the header,
# # so 2 bytes beyond this is the start of the body. The body EXCLUDES
# # the final byte, which is '\x00'.
# body = msgdata[hbytes + 2:-1]
self._buffer.seek(self._pointer, 0)
try:
f = Frame.from_buffer(self._buffer)
self._pointer = self._buffer.tell()
except (IncompleteFrame, EmptyBuffer):
self._buffer.seek(self._pointer, 0)
return None
return f | python | def extract_frame(self):
"""
Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame}
"""
# (mbytes, hbytes) = self._find_message_bytes(self.buffer)
# if not mbytes:
# return None
#
# msgdata = self.buffer[:mbytes]
# self.buffer = self.buffer[mbytes:]
# hdata = msgdata[:hbytes]
# # Strip off any leading whitespace from headers; this is necessary, because
# # we do not (any longer) expect a trailing \n after the \x00 byte (which means
# # it will become a leading \n to the next frame).
# hdata = hdata.lstrip()
# elems = hdata.split('\n')
# cmd = elems.pop(0)
# headers = {}
#
# for e in elems:
# try:
# (k,v) = e.split(':', 1) # header values may contain ':' so specify maxsplit
# except ValueError:
# continue
# headers[k.strip()] = v.strip()
#
# # hbytes points to the start of the '\n\n' at the end of the header,
# # so 2 bytes beyond this is the start of the body. The body EXCLUDES
# # the final byte, which is '\x00'.
# body = msgdata[hbytes + 2:-1]
self._buffer.seek(self._pointer, 0)
try:
f = Frame.from_buffer(self._buffer)
self._pointer = self._buffer.tell()
except (IncompleteFrame, EmptyBuffer):
self._buffer.seek(self._pointer, 0)
return None
return f | [
"def",
"extract_frame",
"(",
"self",
")",
":",
"# (mbytes, hbytes) = self._find_message_bytes(self.buffer)",
"# if not mbytes:",
"# return None",
"#",
"# msgdata = self.buffer[:mbytes]",
"# self.buffer = self.buffer[mbytes:]",
"# hdata = msgdata[:hbytes]",
"# # Strip off any leading wh... | Pulls one complete frame off the buffer and returns it.
If there is no complete message in the buffer, returns None.
Note that the buffer can contain more than once message. You
should therefore call this method in a loop (or use iterator
functionality exposed by class) until None returned.
@return: The next complete frame in the buffer.
@rtype: L{stomp.frame.Frame} | [
"Pulls",
"one",
"complete",
"frame",
"off",
"the",
"buffer",
"and",
"returns",
"it",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/util/frames.py#L292-L339 | train | 42,044 |
hozn/coilmq | coilmq/scheduler.py | FavorReliableSubscriberScheduler.choice | def choice(self, subscribers, message):
"""
Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be delivered.
@type message: L{stompclient.frame.Frame}
@return: A random subscriber from the list or None if list is empty.
@rtype: L{coilmq.server.StompConnection}
"""
if not subscribers:
return None
reliable_subscribers = [
s for s in subscribers if s.reliable_subscriber]
if reliable_subscribers:
return random.choice(reliable_subscribers)
else:
return random.choice(subscribers) | python | def choice(self, subscribers, message):
"""
Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be delivered.
@type message: L{stompclient.frame.Frame}
@return: A random subscriber from the list or None if list is empty.
@rtype: L{coilmq.server.StompConnection}
"""
if not subscribers:
return None
reliable_subscribers = [
s for s in subscribers if s.reliable_subscriber]
if reliable_subscribers:
return random.choice(reliable_subscribers)
else:
return random.choice(subscribers) | [
"def",
"choice",
"(",
"self",
",",
"subscribers",
",",
"message",
")",
":",
"if",
"not",
"subscribers",
":",
"return",
"None",
"reliable_subscribers",
"=",
"[",
"s",
"for",
"s",
"in",
"subscribers",
"if",
"s",
".",
"reliable_subscriber",
"]",
"if",
"reliab... | Choose a random connection, favoring those that are reliable from
subscriber pool to deliver specified message.
@param subscribers: Collection of subscribed connections to destination.
@type subscribers: C{list} of L{coilmq.server.StompConnection}
@param message: The message to be delivered.
@type message: L{stompclient.frame.Frame}
@return: A random subscriber from the list or None if list is empty.
@rtype: L{coilmq.server.StompConnection} | [
"Choose",
"a",
"random",
"connection",
"favoring",
"those",
"that",
"are",
"reliable",
"from",
"subscriber",
"pool",
"to",
"deliver",
"specified",
"message",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/scheduler.py#L96-L117 | train | 42,045 |
hozn/coilmq | coilmq/scheduler.py | RandomQueueScheduler.choice | def choice(self, queues, connection):
"""
Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: The connection that is going to be delivered the frame(s).
@type connection: L{coilmq.server.StompConnection}
@return: A random queue destination or None if list is empty.
@rtype: C{str}
"""
if not queues:
return None
return random.choice(list(queues.keys())) | python | def choice(self, queues, connection):
"""
Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: The connection that is going to be delivered the frame(s).
@type connection: L{coilmq.server.StompConnection}
@return: A random queue destination or None if list is empty.
@rtype: C{str}
"""
if not queues:
return None
return random.choice(list(queues.keys())) | [
"def",
"choice",
"(",
"self",
",",
"queues",
",",
"connection",
")",
":",
"if",
"not",
"queues",
":",
"return",
"None",
"return",
"random",
".",
"choice",
"(",
"list",
"(",
"queues",
".",
"keys",
"(",
")",
")",
")"
] | Chooses a random queue for messages to specified connection.
@param queues: A C{dict} mapping queue name to queues (sets of frames) to which
specified connection is subscribed.
@type queues: C{dict} of C{str} to C{set} of L{stompclient.frame.Frame}
@param connection: The connection that is going to be delivered the frame(s).
@type connection: L{coilmq.server.StompConnection}
@return: A random queue destination or None if list is empty.
@rtype: C{str} | [
"Chooses",
"a",
"random",
"queue",
"for",
"messages",
"to",
"specified",
"connection",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/scheduler.py#L125-L141 | train | 42,046 |
polyaxon/rhea | rhea/manager.py | Rhea.get_uri | def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | python | def get_uri(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=UriSpec,
type_convert=self.parse_uri_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | [
"def",
"get_uri",
"(",
"self",
",",
"key",
",",
"is_list",
"=",
"False",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"is_li... | Get a the value corresponding to the key and converts it to `UriSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | [
"Get",
"a",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"and",
"converts",
"it",
"to",
"UriSpec",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L329-L369 | train | 42,047 |
polyaxon/rhea | rhea/manager.py | Rhea.get_auth | def get_auth(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | python | def get_auth(self,
key,
is_list=False,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
if is_list:
return self._get_typed_list_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
return self._get_typed_value(key=key,
target_type=AuthSpec,
type_convert=self.parse_auth_spec,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | [
"def",
"get_auth",
"(",
"self",
",",
"key",
",",
"is_list",
"=",
"False",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"if",
"is_l... | Get a the value corresponding to the key and converts it to `AuthSpec`.
Args
key: the dict key.
is_list: If this is one element or a list of elements.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | [
"Get",
"a",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"and",
"converts",
"it",
"to",
"AuthSpec",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L371-L411 | train | 42,048 |
polyaxon/rhea | rhea/manager.py | Rhea.get_list | def get_list(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
def parse_list(v):
parts = v.split(',')
results = []
for part in parts:
part = part.strip()
if part:
results.append(part)
return results
return self._get_typed_value(key=key,
target_type=list,
type_convert=parse_list,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | python | def get_list(self,
key,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key.
"""
def parse_list(v):
parts = v.split(',')
results = []
for part in parts:
part = part.strip()
if part:
results.append(part)
return results
return self._get_typed_value(key=key,
target_type=list,
type_convert=parse_list,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options) | [
"def",
"get_list",
"(",
"self",
",",
"key",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")",
":",
"def",
"parse_list",
"(",
"v",
")",
":",
... | Get a the value corresponding to the key and converts comma separated values to a list.
Args:
key: the dict key.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
`str`: value corresponding to the key. | [
"Get",
"a",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"and",
"converts",
"comma",
"separated",
"values",
"to",
"a",
"list",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L413-L451 | train | 42,049 |
polyaxon/rhea | rhea/manager.py | Rhea._get_typed_value | def _get_typed_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
The corresponding value of the key converted.
"""
try:
value = self._get(key)
except KeyError:
if not is_optional:
raise RheaError(
'No value was provided for the non optional key `{}`.'.format(key))
return default
if isinstance(value, six.string_types):
try:
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return type_convert(value)
except ValueError:
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type))
if isinstance(value, target_type):
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return value
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type)) | python | def _get_typed_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
The corresponding value of the key converted.
"""
try:
value = self._get(key)
except KeyError:
if not is_optional:
raise RheaError(
'No value was provided for the non optional key `{}`.'.format(key))
return default
if isinstance(value, six.string_types):
try:
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return type_convert(value)
except ValueError:
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type))
if isinstance(value, target_type):
self._add_key(key, is_secret=is_secret, is_local=is_local)
self._check_options(key=key, value=value, options=options)
return value
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, target_type)) | [
"def",
"_get_typed_value",
"(",
"self",
",",
"key",
",",
"target_type",
",",
"type_convert",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")",
"... | Return the value corresponding to the key converted to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
Returns:
The corresponding value of the key converted. | [
"Return",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"converted",
"to",
"the",
"given",
"type",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L482-L529 | train | 42,050 |
polyaxon/rhea | rhea/manager.py | Rhea._get_typed_list_value | def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
"""
value = self._get_typed_value(key=key,
target_type=list,
type_convert=json.loads,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
if not value:
return default
raise_type = 'dict' if target_type == Mapping else target_type
if not isinstance(value, list):
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, raise_type))
# If we are here the value must be a list
result = []
for v in value:
if isinstance(v, six.string_types):
try:
result.append(type_convert(v))
except ValueError:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
elif isinstance(v, target_type):
result.append(v)
else:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
return result | python | def _get_typed_list_value(self,
key,
target_type,
type_convert,
is_optional=False,
is_secret=False,
is_local=False,
default=None,
options=None):
"""
Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values.
"""
value = self._get_typed_value(key=key,
target_type=list,
type_convert=json.loads,
is_optional=is_optional,
is_secret=is_secret,
is_local=is_local,
default=default,
options=options)
if not value:
return default
raise_type = 'dict' if target_type == Mapping else target_type
if not isinstance(value, list):
raise RheaError("Cannot convert value `{}` (key: `{}`) "
"to `{}`".format(value, key, raise_type))
# If we are here the value must be a list
result = []
for v in value:
if isinstance(v, six.string_types):
try:
result.append(type_convert(v))
except ValueError:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
elif isinstance(v, target_type):
result.append(v)
else:
raise RheaError("Cannot convert value `{}` (found in list key: `{}`) "
"to `{}`".format(v, key, raise_type))
return result | [
"def",
"_get_typed_list_value",
"(",
"self",
",",
"key",
",",
"target_type",
",",
"type_convert",
",",
"is_optional",
"=",
"False",
",",
"is_secret",
"=",
"False",
",",
"is_local",
"=",
"False",
",",
"default",
"=",
"None",
",",
"options",
"=",
"None",
")"... | Return the value corresponding to the key converted first to list
than each element to the given type.
Args:
key: the dict key.
target_type: The type we expect the variable or key to be in.
type_convert: A lambda expression that converts the key to the desired type.
is_optional: To raise an error if key was not found.
is_secret: If the key is a secret.
is_local: If the key is a local to this service.
default: default value if is_optional is True.
options: list/tuple if provided, the value must be one of these values. | [
"Return",
"the",
"value",
"corresponding",
"to",
"the",
"key",
"converted",
"first",
"to",
"list",
"than",
"each",
"element",
"to",
"the",
"given",
"type",
"."
] | f47b59777cd996d834a0497a1ab442541aaa8a62 | https://github.com/polyaxon/rhea/blob/f47b59777cd996d834a0497a1ab442541aaa8a62/rhea/manager.py#L531-L587 | train | 42,051 |
hozn/coilmq | coilmq/auth/simple.py | SimpleAuthenticator.from_configfile | def from_configfile(self, configfile):
"""
Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepass
anotheruser = anotherpass
@param configfile: Path to config file or file-like object.
@type configfile: C{any}
@raise ValueError: If file could not be read or does not contain [auth] section.
"""
cfg = ConfigParser()
if hasattr(configfile, 'read'):
cfg.read_file(configfile)
else:
filesread = cfg.read(configfile)
if not filesread:
raise ValueError('Could not parse auth file: %s' % configfile)
if not cfg.has_section('auth'):
raise ValueError('Config file contains no [auth] section.')
self.store = dict(cfg.items('auth')) | python | def from_configfile(self, configfile):
"""
Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepass
anotheruser = anotherpass
@param configfile: Path to config file or file-like object.
@type configfile: C{any}
@raise ValueError: If file could not be read or does not contain [auth] section.
"""
cfg = ConfigParser()
if hasattr(configfile, 'read'):
cfg.read_file(configfile)
else:
filesread = cfg.read(configfile)
if not filesread:
raise ValueError('Could not parse auth file: %s' % configfile)
if not cfg.has_section('auth'):
raise ValueError('Config file contains no [auth] section.')
self.store = dict(cfg.items('auth')) | [
"def",
"from_configfile",
"(",
"self",
",",
"configfile",
")",
":",
"cfg",
"=",
"ConfigParser",
"(",
")",
"if",
"hasattr",
"(",
"configfile",
",",
"'read'",
")",
":",
"cfg",
".",
"read_file",
"(",
"configfile",
")",
"else",
":",
"filesread",
"=",
"cfg",
... | Initialize the authentication store from a "config"-style file.
Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain
an [auth] section which contains the usernames (keys) and passwords (values).
Example auth file::
[auth]
someuser = somepass
anotheruser = anotherpass
@param configfile: Path to config file or file-like object.
@type configfile: C{any}
@raise ValueError: If file could not be read or does not contain [auth] section. | [
"Initialize",
"the",
"authentication",
"store",
"from",
"a",
"config",
"-",
"style",
"file",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/auth/simple.py#L64-L92 | train | 42,052 |
hozn/coilmq | coilmq/auth/simple.py | SimpleAuthenticator.authenticate | def authenticate(self, login, passcode):
"""
Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool}
"""
return login in self.store and self.store[login] == passcode | python | def authenticate(self, login, passcode):
"""
Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool}
"""
return login in self.store and self.store[login] == passcode | [
"def",
"authenticate",
"(",
"self",
",",
"login",
",",
"passcode",
")",
":",
"return",
"login",
"in",
"self",
".",
"store",
"and",
"self",
".",
"store",
"[",
"login",
"]",
"==",
"passcode"
] | Authenticate the login and passcode.
@return: Whether provided login and password match values in store.
@rtype: C{bool} | [
"Authenticate",
"the",
"login",
"and",
"passcode",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/auth/simple.py#L94-L101 | train | 42,053 |
hozn/coilmq | coilmq/protocol/__init__.py | STOMP10.process_frame | def process_frame(self, frame):
"""
Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame}
"""
cmd_method = frame.cmd.lower()
if not cmd_method in VALID_COMMANDS:
raise ProtocolError("Invalid STOMP command: {}".format(frame.cmd))
method = getattr(self, cmd_method, None)
if not self.engine.connected and method not in (self.connect, self.stomp):
raise ProtocolError("Not connected.")
try:
transaction = frame.headers.get('transaction')
if not transaction or method in (self.begin, self.commit, self.abort):
method(frame)
else:
if not transaction in self.engine.transactions:
raise ProtocolError(
"Invalid transaction specified: %s" % transaction)
self.engine.transactions[transaction].append(frame)
except Exception as e:
self.engine.log.error("Error processing STOMP frame: %s" % e)
self.engine.log.exception(e)
try:
self.engine.connection.send_frame(ErrorFrame(str(e), str(e)))
except Exception as e: # pragma: no cover
self.engine.log.error("Could not send error frame: %s" % e)
self.engine.log.exception(e)
else:
# The protocol is not especially clear here (not sure why I'm surprised)
# about the expected behavior WRT receipts and errors. We will assume that
# the RECEIPT frame should not be sent if there is an error frame.
# Also we'll assume that a transaction should not preclude sending the receipt
# frame.
# import pdb; pdb.set_trace()
if frame.headers.get('receipt') and method != self.connect:
self.engine.connection.send_frame(ReceiptFrame(
receipt=frame.headers.get('receipt'))) | python | def process_frame(self, frame):
"""
Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame}
"""
cmd_method = frame.cmd.lower()
if not cmd_method in VALID_COMMANDS:
raise ProtocolError("Invalid STOMP command: {}".format(frame.cmd))
method = getattr(self, cmd_method, None)
if not self.engine.connected and method not in (self.connect, self.stomp):
raise ProtocolError("Not connected.")
try:
transaction = frame.headers.get('transaction')
if not transaction or method in (self.begin, self.commit, self.abort):
method(frame)
else:
if not transaction in self.engine.transactions:
raise ProtocolError(
"Invalid transaction specified: %s" % transaction)
self.engine.transactions[transaction].append(frame)
except Exception as e:
self.engine.log.error("Error processing STOMP frame: %s" % e)
self.engine.log.exception(e)
try:
self.engine.connection.send_frame(ErrorFrame(str(e), str(e)))
except Exception as e: # pragma: no cover
self.engine.log.error("Could not send error frame: %s" % e)
self.engine.log.exception(e)
else:
# The protocol is not especially clear here (not sure why I'm surprised)
# about the expected behavior WRT receipts and errors. We will assume that
# the RECEIPT frame should not be sent if there is an error frame.
# Also we'll assume that a transaction should not preclude sending the receipt
# frame.
# import pdb; pdb.set_trace()
if frame.headers.get('receipt') and method != self.connect:
self.engine.connection.send_frame(ReceiptFrame(
receipt=frame.headers.get('receipt'))) | [
"def",
"process_frame",
"(",
"self",
",",
"frame",
")",
":",
"cmd_method",
"=",
"frame",
".",
"cmd",
".",
"lower",
"(",
")",
"if",
"not",
"cmd_method",
"in",
"VALID_COMMANDS",
":",
"raise",
"ProtocolError",
"(",
"\"Invalid STOMP command: {}\"",
".",
"format",
... | Dispatches a received frame to the appropriate internal method.
@param frame: The frame that was received.
@type frame: C{stompclient.frame.Frame} | [
"Dispatches",
"a",
"received",
"frame",
"to",
"the",
"appropriate",
"internal",
"method",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/protocol/__init__.py#L81-L124 | train | 42,054 |
hozn/coilmq | coilmq/config/__init__.py | init_config | def init_config(config_file=None):
"""
Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}
@raise ValueError: if the specified config_file could not be read.
@see: L{init_logging}
"""
global config
if config_file and os.path.exists(config_file):
read = config.read([config_file])
if not read:
raise ValueError(
"Could not read configuration from file: %s" % config_file) | python | def init_config(config_file=None):
"""
Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}
@raise ValueError: if the specified config_file could not be read.
@see: L{init_logging}
"""
global config
if config_file and os.path.exists(config_file):
read = config.read([config_file])
if not read:
raise ValueError(
"Could not read configuration from file: %s" % config_file) | [
"def",
"init_config",
"(",
"config_file",
"=",
"None",
")",
":",
"global",
"config",
"if",
"config_file",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"config_file",
")",
":",
"read",
"=",
"config",
".",
"read",
"(",
"[",
"config_file",
"]",
")",
"if"... | Initialize the configuration from a config file.
The values in config_file will override those already loaded from the default
configuration file (defaults.cfg, in current package).
This method does not setup logging.
@param config_file: The path to a configuration file.
@type config_file: C{str}
@raise ValueError: if the specified config_file could not be read.
@see: L{init_logging} | [
"Initialize",
"the",
"configuration",
"from",
"a",
"config",
"file",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/config/__init__.py#L45-L66 | train | 42,055 |
hozn/coilmq | coilmq/config/__init__.py | init_logging | def init_logging(logfile=None, loglevel=logging.INFO, configfile=None):
"""
Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging may need to be initialized within a daemon
context.
@param logfile: An explicitly specified logfile destination. If this is specified in addition
to default logging, a warning will be issued.
@type logfile: C{str}
@param loglevel: Which level to use when logging to explicitly specified file or stdout.
@type loglevel: C{int}
@param configfile: The path to a configuration file. This takes precedence over any explicitly
specified logfile/loglevel (but a warning will be logged if both are specified).
If the file is not specified or does not exist annd no logfile was specified,
then the default.cfg configuration file will be used to initialize logging.
@type configfile: C{str}
"""
# If a config file was specified, we will use that in place of the
# explicitly
use_configfile = False
if configfile and os.path.exists(configfile):
testcfg = ConfigParser()
read = testcfg.read(configfile)
use_configfile = (read and testcfg.has_section('loggers'))
if use_configfile:
logging.config.fileConfig(configfile)
if logfile:
msg = "Config file conflicts with explicitly specified logfile; config file takes precedence."
logging.warn(msg)
else:
format = '%(asctime)s [%(threadName)s] %(name)s - %(levelname)s - %(message)s'
if logfile:
logging.basicConfig(
filename=logfile, level=loglevel, format=format)
else:
logging.basicConfig(level=loglevel, format=format) | python | def init_logging(logfile=None, loglevel=logging.INFO, configfile=None):
"""
Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging may need to be initialized within a daemon
context.
@param logfile: An explicitly specified logfile destination. If this is specified in addition
to default logging, a warning will be issued.
@type logfile: C{str}
@param loglevel: Which level to use when logging to explicitly specified file or stdout.
@type loglevel: C{int}
@param configfile: The path to a configuration file. This takes precedence over any explicitly
specified logfile/loglevel (but a warning will be logged if both are specified).
If the file is not specified or does not exist annd no logfile was specified,
then the default.cfg configuration file will be used to initialize logging.
@type configfile: C{str}
"""
# If a config file was specified, we will use that in place of the
# explicitly
use_configfile = False
if configfile and os.path.exists(configfile):
testcfg = ConfigParser()
read = testcfg.read(configfile)
use_configfile = (read and testcfg.has_section('loggers'))
if use_configfile:
logging.config.fileConfig(configfile)
if logfile:
msg = "Config file conflicts with explicitly specified logfile; config file takes precedence."
logging.warn(msg)
else:
format = '%(asctime)s [%(threadName)s] %(name)s - %(levelname)s - %(message)s'
if logfile:
logging.basicConfig(
filename=logfile, level=loglevel, format=format)
else:
logging.basicConfig(level=loglevel, format=format) | [
"def",
"init_logging",
"(",
"logfile",
"=",
"None",
",",
"loglevel",
"=",
"logging",
".",
"INFO",
",",
"configfile",
"=",
"None",
")",
":",
"# If a config file was specified, we will use that in place of the",
"# explicitly",
"use_configfile",
"=",
"False",
"if",
"con... | Configures the logging using either basic filename + loglevel or passed config file path.
This is performed separately from L{init_config()} in order to support the case where
logging should happen independent of (usu. *after*) other aspects of the configuration
initialization. For example, if logging may need to be initialized within a daemon
context.
@param logfile: An explicitly specified logfile destination. If this is specified in addition
to default logging, a warning will be issued.
@type logfile: C{str}
@param loglevel: Which level to use when logging to explicitly specified file or stdout.
@type loglevel: C{int}
@param configfile: The path to a configuration file. This takes precedence over any explicitly
specified logfile/loglevel (but a warning will be logged if both are specified).
If the file is not specified or does not exist annd no logfile was specified,
then the default.cfg configuration file will be used to initialize logging.
@type configfile: C{str} | [
"Configures",
"the",
"logging",
"using",
"either",
"basic",
"filename",
"+",
"loglevel",
"or",
"passed",
"config",
"file",
"path",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/config/__init__.py#L69-L110 | train | 42,056 |
hozn/coilmq | coilmq/server/socket_server.py | StompRequestHandler.send_frame | def send_frame(self, frame):
""" Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame}
"""
packed = frame.pack()
if self.debug: # pragma: no cover
self.log.debug("SEND: %r" % packed)
self.request.sendall(packed) | python | def send_frame(self, frame):
""" Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame}
"""
packed = frame.pack()
if self.debug: # pragma: no cover
self.log.debug("SEND: %r" % packed)
self.request.sendall(packed) | [
"def",
"send_frame",
"(",
"self",
",",
"frame",
")",
":",
"packed",
"=",
"frame",
".",
"pack",
"(",
")",
"if",
"self",
".",
"debug",
":",
"# pragma: no cover",
"self",
".",
"log",
".",
"debug",
"(",
"\"SEND: %r\"",
"%",
"packed",
")",
"self",
".",
"r... | Sends a frame to connected socket client.
@param frame: The frame to send.
@type frame: C{stompclient.frame.Frame} | [
"Sends",
"a",
"frame",
"to",
"connected",
"socket",
"client",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/server/socket_server.py#L104-L113 | train | 42,057 |
hozn/coilmq | coilmq/server/socket_server.py | StompServer.server_close | def server_close(self):
"""
Closes the socket server and any associated resources.
"""
self.log.debug("Closing the socket server connection.")
TCPServer.server_close(self)
self.queue_manager.close()
self.topic_manager.close()
if hasattr(self.authenticator, 'close'):
self.authenticator.close()
self.shutdown() | python | def server_close(self):
"""
Closes the socket server and any associated resources.
"""
self.log.debug("Closing the socket server connection.")
TCPServer.server_close(self)
self.queue_manager.close()
self.topic_manager.close()
if hasattr(self.authenticator, 'close'):
self.authenticator.close()
self.shutdown() | [
"def",
"server_close",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Closing the socket server connection.\"",
")",
"TCPServer",
".",
"server_close",
"(",
"self",
")",
"self",
".",
"queue_manager",
".",
"close",
"(",
")",
"self",
".",
"top... | Closes the socket server and any associated resources. | [
"Closes",
"the",
"socket",
"server",
"and",
"any",
"associated",
"resources",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/server/socket_server.py#L161-L171 | train | 42,058 |
hozn/coilmq | coilmq/server/socket_server.py | StompServer.serve_forever | def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self._serving_event.set()
self._shutdown_request_event.clear()
TCPServer.serve_forever(self, poll_interval=poll_interval) | python | def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self._serving_event.set()
self._shutdown_request_event.clear()
TCPServer.serve_forever(self, poll_interval=poll_interval) | [
"def",
"serve_forever",
"(",
"self",
",",
"poll_interval",
"=",
"0.5",
")",
":",
"self",
".",
"_serving_event",
".",
"set",
"(",
")",
"self",
".",
"_shutdown_request_event",
".",
"clear",
"(",
")",
"TCPServer",
".",
"serve_forever",
"(",
"self",
",",
"poll... | Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread. | [
"Handle",
"one",
"request",
"at",
"a",
"time",
"until",
"shutdown",
"."
] | 76b7fcf347144b3a5746423a228bed121dc564b5 | https://github.com/hozn/coilmq/blob/76b7fcf347144b3a5746423a228bed121dc564b5/coilmq/server/socket_server.py#L179-L188 | train | 42,059 |
caseman/noise | perlin.py | BaseNoise.randomize | def randomize(self, period=None):
"""Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs.
"""
if period is not None:
self.period = period
perm = list(range(self.period))
perm_right = self.period - 1
for i in list(perm):
j = self.randint_function(0, perm_right)
perm[i], perm[j] = perm[j], perm[i]
self.permutation = tuple(perm) * 2 | python | def randomize(self, period=None):
"""Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs.
"""
if period is not None:
self.period = period
perm = list(range(self.period))
perm_right = self.period - 1
for i in list(perm):
j = self.randint_function(0, perm_right)
perm[i], perm[j] = perm[j], perm[i]
self.permutation = tuple(perm) * 2 | [
"def",
"randomize",
"(",
"self",
",",
"period",
"=",
"None",
")",
":",
"if",
"period",
"is",
"not",
"None",
":",
"self",
".",
"period",
"=",
"period",
"perm",
"=",
"list",
"(",
"range",
"(",
"self",
".",
"period",
")",
")",
"perm_right",
"=",
"self... | Randomize the permutation table used by the noise functions. This
makes them generate a different noise pattern for the same inputs. | [
"Randomize",
"the",
"permutation",
"table",
"used",
"by",
"the",
"noise",
"functions",
".",
"This",
"makes",
"them",
"generate",
"a",
"different",
"noise",
"pattern",
"for",
"the",
"same",
"inputs",
"."
] | bb32991ab97e90882d0e46e578060717c5b90dc5 | https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/perlin.py#L113-L124 | train | 42,060 |
caseman/noise | perlin.py | TileableNoise.noise3 | def noise3(self, x, y, z, repeat, base=0.0):
"""Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval.
"""
i = int(fmod(floor(x), repeat))
j = int(fmod(floor(y), repeat))
k = int(fmod(floor(z), repeat))
ii = (i + 1) % repeat
jj = (j + 1) % repeat
kk = (k + 1) % repeat
if base:
i += base; j += base; k += base
ii += base; jj += base; kk += base
x -= floor(x); y -= floor(y); z -= floor(z)
fx = x**3 * (x * (x * 6 - 15) + 10)
fy = y**3 * (y * (y * 6 - 15) + 10)
fz = z**3 * (z * (z * 6 - 15) + 10)
perm = self.permutation
A = perm[i]
AA = perm[A + j]
AB = perm[A + jj]
B = perm[ii]
BA = perm[B + j]
BB = perm[B + jj]
return lerp(fz, lerp(fy, lerp(fx, grad3(perm[AA + k], x, y, z),
grad3(perm[BA + k], x - 1, y, z)),
lerp(fx, grad3(perm[AB + k], x, y - 1, z),
grad3(perm[BB + k], x - 1, y - 1, z))),
lerp(fy, lerp(fx, grad3(perm[AA + kk], x, y, z - 1),
grad3(perm[BA + kk], x - 1, y, z - 1)),
lerp(fx, grad3(perm[AB + kk], x, y - 1, z - 1),
grad3(perm[BB + kk], x - 1, y - 1, z - 1)))) | python | def noise3(self, x, y, z, repeat, base=0.0):
"""Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval.
"""
i = int(fmod(floor(x), repeat))
j = int(fmod(floor(y), repeat))
k = int(fmod(floor(z), repeat))
ii = (i + 1) % repeat
jj = (j + 1) % repeat
kk = (k + 1) % repeat
if base:
i += base; j += base; k += base
ii += base; jj += base; kk += base
x -= floor(x); y -= floor(y); z -= floor(z)
fx = x**3 * (x * (x * 6 - 15) + 10)
fy = y**3 * (y * (y * 6 - 15) + 10)
fz = z**3 * (z * (z * 6 - 15) + 10)
perm = self.permutation
A = perm[i]
AA = perm[A + j]
AB = perm[A + jj]
B = perm[ii]
BA = perm[B + j]
BB = perm[B + jj]
return lerp(fz, lerp(fy, lerp(fx, grad3(perm[AA + k], x, y, z),
grad3(perm[BA + k], x - 1, y, z)),
lerp(fx, grad3(perm[AB + k], x, y - 1, z),
grad3(perm[BB + k], x - 1, y - 1, z))),
lerp(fy, lerp(fx, grad3(perm[AA + kk], x, y, z - 1),
grad3(perm[BA + kk], x - 1, y, z - 1)),
lerp(fx, grad3(perm[AB + kk], x, y - 1, z - 1),
grad3(perm[BB + kk], x - 1, y - 1, z - 1)))) | [
"def",
"noise3",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
",",
"repeat",
",",
"base",
"=",
"0.0",
")",
":",
"i",
"=",
"int",
"(",
"fmod",
"(",
"floor",
"(",
"x",
")",
",",
"repeat",
")",
")",
"j",
"=",
"int",
"(",
"fmod",
"(",
"floor",
... | Tileable 3D noise.
repeat specifies the integer interval in each dimension
when the noise pattern repeats.
base allows a different texture to be generated for
the same repeat interval. | [
"Tileable",
"3D",
"noise",
".",
"repeat",
"specifies",
"the",
"integer",
"interval",
"in",
"each",
"dimension",
"when",
"the",
"noise",
"pattern",
"repeats",
".",
"base",
"allows",
"a",
"different",
"texture",
"to",
"be",
"generated",
"for",
"the",
"same",
"... | bb32991ab97e90882d0e46e578060717c5b90dc5 | https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/perlin.py#L311-L350 | train | 42,061 |
caseman/noise | shader_noise.py | ShaderNoiseTexture.load | def load(self):
"""Load the noise texture data into the current texture unit"""
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_SHORT, ctypes.byref(self.data)) | python | def load(self):
"""Load the noise texture data into the current texture unit"""
glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
GL_UNSIGNED_SHORT, ctypes.byref(self.data)) | [
"def",
"load",
"(",
"self",
")",
":",
"glTexImage3D",
"(",
"GL_TEXTURE_3D",
",",
"0",
",",
"GL_LUMINANCE16_ALPHA16",
",",
"self",
".",
"width",
",",
"self",
".",
"width",
",",
"self",
".",
"width",
",",
"0",
",",
"GL_LUMINANCE_ALPHA",
",",
"GL_UNSIGNED_SHO... | Load the noise texture data into the current texture unit | [
"Load",
"the",
"noise",
"texture",
"data",
"into",
"the",
"current",
"texture",
"unit"
] | bb32991ab97e90882d0e46e578060717c5b90dc5 | https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/shader_noise.py#L46-L50 | train | 42,062 |
caseman/noise | shader_noise.py | ShaderNoiseTexture.enable | def enable(self):
"""Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function
"""
glEnable(GL_TEXTURE_3D)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) | python | def enable(self):
"""Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function
"""
glEnable(GL_TEXTURE_3D)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) | [
"def",
"enable",
"(",
"self",
")",
":",
"glEnable",
"(",
"GL_TEXTURE_3D",
")",
"glTexParameteri",
"(",
"GL_TEXTURE_3D",
",",
"GL_TEXTURE_WRAP_S",
",",
"GL_REPEAT",
")",
"glTexParameteri",
"(",
"GL_TEXTURE_3D",
",",
"GL_TEXTURE_WRAP_T",
",",
"GL_REPEAT",
")",
"glTe... | Convenience method to enable 3D texturing state so the texture may be used by the
ffpnoise shader function | [
"Convenience",
"method",
"to",
"enable",
"3D",
"texturing",
"state",
"so",
"the",
"texture",
"may",
"be",
"used",
"by",
"the",
"ffpnoise",
"shader",
"function"
] | bb32991ab97e90882d0e46e578060717c5b90dc5 | https://github.com/caseman/noise/blob/bb32991ab97e90882d0e46e578060717c5b90dc5/shader_noise.py#L52-L61 | train | 42,063 |
openstack/monasca-common | monasca_common/expression_parser/alarm_expr_parser.py | main | def main():
"""Used for development and testing."""
expr_list = [
"max(-_.千幸福的笑脸{घोड़ा=馬, "
"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 "
"times 3 && "
"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and "
"count(fizzle) lt 0or count(baz) > 1)".decode('utf8'),
"max(foo{hostname=mini-mon,千=千}, 120) > 100 and (max(bar)>100 "
" or max(biz)>100)".decode('utf8'),
"max(foo)>=100",
"test_metric{this=that, that = this} < 1",
"max ( 3test_metric5 { this = that }) lt 5 times 3",
"3test_metric5 lt 3",
"ntp.offset > 1 or ntp.offset < -5",
"max(3test_metric5{it's this=that's it}) lt 5 times 3",
"count(log.error{test=1}, deterministic) > 1.0",
"count(log.error{test=1}, deterministic, 120) > 1.0",
"last(test_metric{hold=here}) < 13",
"count(log.error{test=1}, deterministic, 130) > 1.0",
"count(log.error{test=1}, deterministic) > 1.0 times 0",
]
for expr in expr_list:
print('orig expr: {}'.format(expr.encode('utf8')))
sub_exprs = []
try:
alarm_expr_parser = AlarmExprParser(expr)
sub_exprs = alarm_expr_parser.sub_expr_list
except Exception as ex:
print("Parse failed: {}".format(ex))
for sub_expr in sub_exprs:
print('sub expr: {}'.format(
sub_expr.fmtd_sub_expr_str.encode('utf8')))
print('sub_expr dimensions: {}'.format(
sub_expr.dimensions_str.encode('utf8')))
print('sub_expr deterministic: {}'.format(
sub_expr.deterministic))
print('sub_expr period: {}'.format(
sub_expr.period))
print("")
print("") | python | def main():
"""Used for development and testing."""
expr_list = [
"max(-_.千幸福的笑脸{घोड़ा=馬, "
"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 "
"times 3 && "
"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and "
"count(fizzle) lt 0or count(baz) > 1)".decode('utf8'),
"max(foo{hostname=mini-mon,千=千}, 120) > 100 and (max(bar)>100 "
" or max(biz)>100)".decode('utf8'),
"max(foo)>=100",
"test_metric{this=that, that = this} < 1",
"max ( 3test_metric5 { this = that }) lt 5 times 3",
"3test_metric5 lt 3",
"ntp.offset > 1 or ntp.offset < -5",
"max(3test_metric5{it's this=that's it}) lt 5 times 3",
"count(log.error{test=1}, deterministic) > 1.0",
"count(log.error{test=1}, deterministic, 120) > 1.0",
"last(test_metric{hold=here}) < 13",
"count(log.error{test=1}, deterministic, 130) > 1.0",
"count(log.error{test=1}, deterministic) > 1.0 times 0",
]
for expr in expr_list:
print('orig expr: {}'.format(expr.encode('utf8')))
sub_exprs = []
try:
alarm_expr_parser = AlarmExprParser(expr)
sub_exprs = alarm_expr_parser.sub_expr_list
except Exception as ex:
print("Parse failed: {}".format(ex))
for sub_expr in sub_exprs:
print('sub expr: {}'.format(
sub_expr.fmtd_sub_expr_str.encode('utf8')))
print('sub_expr dimensions: {}'.format(
sub_expr.dimensions_str.encode('utf8')))
print('sub_expr deterministic: {}'.format(
sub_expr.deterministic))
print('sub_expr period: {}'.format(
sub_expr.period))
print("")
print("") | [
"def",
"main",
"(",
")",
":",
"expr_list",
"=",
"[",
"\"max(-_.千幸福的笑脸{घोड़ा=馬, \"",
"\"dn2=dv2,千幸福的笑脸घ=千幸福的笑脸घ}) gte 100 \"",
"\"times 3 && \"",
"\"(min(ເຮືອນ{dn3=dv3,家=дом}) < 10 or sum(biz{dn5=dv5}) >99 and \"",
"\"count(fizzle) lt 0or count(baz) > 1)\"",
".",
"decode",
"(",
"'utf... | Used for development and testing. | [
"Used",
"for",
"development",
"and",
"testing",
"."
] | 61e2e00454734e2881611abec8df0d85bf7655ac | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/expression_parser/alarm_expr_parser.py#L321-L375 | train | 42,064 |
openstack/monasca-common | monasca_common/expression_parser/alarm_expr_parser.py | SubExpr.fmtd_sub_expr_str | def fmtd_sub_expr_str(self):
"""Get the entire sub expressions as a string with spaces."""
result = u"{}({}".format(self.normalized_func,
self._metric_name)
if self._dimensions is not None:
result += "{" + self.dimensions_str + "}"
if self._period != _DEFAULT_PERIOD:
result += ", {}".format(self._period)
result += ")"
result += " {} {}".format(self._operator,
self._threshold)
if self._periods != _DEFAULT_PERIODS:
result += " times {}".format(self._periods)
return result | python | def fmtd_sub_expr_str(self):
"""Get the entire sub expressions as a string with spaces."""
result = u"{}({}".format(self.normalized_func,
self._metric_name)
if self._dimensions is not None:
result += "{" + self.dimensions_str + "}"
if self._period != _DEFAULT_PERIOD:
result += ", {}".format(self._period)
result += ")"
result += " {} {}".format(self._operator,
self._threshold)
if self._periods != _DEFAULT_PERIODS:
result += " times {}".format(self._periods)
return result | [
"def",
"fmtd_sub_expr_str",
"(",
"self",
")",
":",
"result",
"=",
"u\"{}({}\"",
".",
"format",
"(",
"self",
".",
"normalized_func",
",",
"self",
".",
"_metric_name",
")",
"if",
"self",
".",
"_dimensions",
"is",
"not",
"None",
":",
"result",
"+=",
"\"{\"",
... | Get the entire sub expressions as a string with spaces. | [
"Get",
"the",
"entire",
"sub",
"expressions",
"as",
"a",
"string",
"with",
"spaces",
"."
] | 61e2e00454734e2881611abec8df0d85bf7655ac | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/expression_parser/alarm_expr_parser.py#L55-L74 | train | 42,065 |
openstack/monasca-common | monasca_common/expression_parser/alarm_expr_parser.py | SubExpr.normalized_operator | def normalized_operator(self):
"""Get the operator as one of LT, GT, LTE, or GTE."""
if self._operator.lower() == "lt" or self._operator == "<":
return u"LT"
elif self._operator.lower() == "gt" or self._operator == ">":
return u"GT"
elif self._operator.lower() == "lte" or self._operator == "<=":
return u"LTE"
elif self._operator.lower() == "gte" or self._operator == ">=":
return u"GTE" | python | def normalized_operator(self):
"""Get the operator as one of LT, GT, LTE, or GTE."""
if self._operator.lower() == "lt" or self._operator == "<":
return u"LT"
elif self._operator.lower() == "gt" or self._operator == ">":
return u"GT"
elif self._operator.lower() == "lte" or self._operator == "<=":
return u"LTE"
elif self._operator.lower() == "gte" or self._operator == ">=":
return u"GTE" | [
"def",
"normalized_operator",
"(",
"self",
")",
":",
"if",
"self",
".",
"_operator",
".",
"lower",
"(",
")",
"==",
"\"lt\"",
"or",
"self",
".",
"_operator",
"==",
"\"<\"",
":",
"return",
"u\"LT\"",
"elif",
"self",
".",
"_operator",
".",
"lower",
"(",
"... | Get the operator as one of LT, GT, LTE, or GTE. | [
"Get",
"the",
"operator",
"as",
"one",
"of",
"LT",
"GT",
"LTE",
"or",
"GTE",
"."
] | 61e2e00454734e2881611abec8df0d85bf7655ac | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/expression_parser/alarm_expr_parser.py#L150-L159 | train | 42,066 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_basic_smoother | def validate_basic_smoother():
"""Run Friedman's test from Figure 2b."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
# plt.plot(x, y, '.', label='Data')
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
friedman_smooth, _resids = run_friedman_smooth(x, y, span)
plt.plot(x, my_smoother.smooth_result, '.-', label='pyace span = {0}'.format(span))
plt.plot(x, friedman_smooth, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | python | def validate_basic_smoother():
"""Run Friedman's test from Figure 2b."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
# plt.plot(x, y, '.', label='Data')
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
friedman_smooth, _resids = run_friedman_smooth(x, y, span)
plt.plot(x, my_smoother.smooth_result, '.-', label='pyace span = {0}'.format(span))
plt.plot(x, friedman_smooth, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | [
"def",
"validate_basic_smoother",
"(",
")",
":",
"x",
",",
"y",
"=",
"sort_data",
"(",
"*",
"smoother_friedman82",
".",
"build_sample_smoother_problem_friedman82",
"(",
")",
")",
"plt",
".",
"figure",
"(",
")",
"# plt.plot(x, y, '.', label='Data')",
"for",
"span",
... | Run Friedman's test from Figure 2b. | [
"Run",
"Friedman",
"s",
"test",
"from",
"Figure",
"2b",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L23-L33 | train | 42,067 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_basic_smoother_resid | def validate_basic_smoother_resid():
"""Compare residuals."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
_friedman_smooth, resids = run_friedman_smooth(x, y, span) # pylint: disable=unused-variable
plt.plot(x, my_smoother.cross_validated_residual, '.-',
label='pyace span = {0}'.format(span))
plt.plot(x, resids, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | python | def validate_basic_smoother_resid():
"""Compare residuals."""
x, y = sort_data(*smoother_friedman82.build_sample_smoother_problem_friedman82())
plt.figure()
for span in smoother.DEFAULT_SPANS:
my_smoother = smoother.perform_smooth(x, y, span)
_friedman_smooth, resids = run_friedman_smooth(x, y, span) # pylint: disable=unused-variable
plt.plot(x, my_smoother.cross_validated_residual, '.-',
label='pyace span = {0}'.format(span))
plt.plot(x, resids, '.-', label='Friedman span = {0}'.format(span))
finish_plot() | [
"def",
"validate_basic_smoother_resid",
"(",
")",
":",
"x",
",",
"y",
"=",
"sort_data",
"(",
"*",
"smoother_friedman82",
".",
"build_sample_smoother_problem_friedman82",
"(",
")",
")",
"plt",
".",
"figure",
"(",
")",
"for",
"span",
"in",
"smoother",
".",
"DEFA... | Compare residuals. | [
"Compare",
"residuals",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L36-L46 | train | 42,068 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_supersmoother | def validate_supersmoother():
"""Validate the supersmoother."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
x, y = sort_data(x, y)
my_smoother = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmootherWithPlots)
# smoother.DEFAULT_BASIC_SMOOTHER = BasicFixedSpanSmootherBreiman
supsmu_result = run_freidman_supsmu(x, y, bass_enhancement=0.0)
mace_result = run_mace_smothr(x, y, bass_enhancement=0.0)
plt.plot(x, y, '.', label='Data')
plt.plot(x, my_smoother.smooth_result, '-', label='pyace')
plt.plot(x, supsmu_result, '--', label='SUPSMU')
plt.plot(x, mace_result, ':', label='SMOOTH')
plt.legend()
plt.savefig('supersmoother_validation.png') | python | def validate_supersmoother():
"""Validate the supersmoother."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
x, y = sort_data(x, y)
my_smoother = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmootherWithPlots)
# smoother.DEFAULT_BASIC_SMOOTHER = BasicFixedSpanSmootherBreiman
supsmu_result = run_freidman_supsmu(x, y, bass_enhancement=0.0)
mace_result = run_mace_smothr(x, y, bass_enhancement=0.0)
plt.plot(x, y, '.', label='Data')
plt.plot(x, my_smoother.smooth_result, '-', label='pyace')
plt.plot(x, supsmu_result, '--', label='SUPSMU')
plt.plot(x, mace_result, ':', label='SMOOTH')
plt.legend()
plt.savefig('supersmoother_validation.png') | [
"def",
"validate_supersmoother",
"(",
")",
":",
"x",
",",
"y",
"=",
"smoother_friedman82",
".",
"build_sample_smoother_problem_friedman82",
"(",
")",
"x",
",",
"y",
"=",
"sort_data",
"(",
"x",
",",
"y",
")",
"my_smoother",
"=",
"smoother",
".",
"perform_smooth... | Validate the supersmoother. | [
"Validate",
"the",
"supersmoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L48-L61 | train | 42,069 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_supersmoother_bass | def validate_supersmoother_bass():
"""Validate the supersmoother with extra bass."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
plt.plot(x, y, '.', label='Data')
for bass in range(0, 10, 3):
smooth = supersmoother.SuperSmoother()
smooth.set_bass_enhancement(bass)
smooth.specify_data_set(x, y)
smooth.compute()
plt.plot(x, smooth.smooth_result, '.', label='Bass = {0}'.format(bass))
# pylab.plot(self.x, smoother.smooth_result, label='Bass = {0}'.format(bass))
finish_plot() | python | def validate_supersmoother_bass():
"""Validate the supersmoother with extra bass."""
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82()
plt.figure()
plt.plot(x, y, '.', label='Data')
for bass in range(0, 10, 3):
smooth = supersmoother.SuperSmoother()
smooth.set_bass_enhancement(bass)
smooth.specify_data_set(x, y)
smooth.compute()
plt.plot(x, smooth.smooth_result, '.', label='Bass = {0}'.format(bass))
# pylab.plot(self.x, smoother.smooth_result, label='Bass = {0}'.format(bass))
finish_plot() | [
"def",
"validate_supersmoother_bass",
"(",
")",
":",
"x",
",",
"y",
"=",
"smoother_friedman82",
".",
"build_sample_smoother_problem_friedman82",
"(",
")",
"plt",
".",
"figure",
"(",
")",
"plt",
".",
"plot",
"(",
"x",
",",
"y",
",",
"'.'",
",",
"label",
"="... | Validate the supersmoother with extra bass. | [
"Validate",
"the",
"supersmoother",
"with",
"extra",
"bass",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L63-L75 | train | 42,070 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_average_best_span | def validate_average_best_span():
"""Figure 2d? from Friedman."""
N = 200
num_trials = 400
avg = numpy.zeros(N)
for i in range(num_trials):
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N)
my_smoother = smoother.perform_smooth(
x, y, smoother_cls=supersmoother.SuperSmoother
)
avg += my_smoother._smoothed_best_spans.smooth_result
if not (i + 1) % 20:
print(i + 1)
avg /= num_trials
plt.plot(my_smoother.x, avg, '.', label='Average JCV')
finish_plot() | python | def validate_average_best_span():
"""Figure 2d? from Friedman."""
N = 200
num_trials = 400
avg = numpy.zeros(N)
for i in range(num_trials):
x, y = smoother_friedman82.build_sample_smoother_problem_friedman82(N=N)
my_smoother = smoother.perform_smooth(
x, y, smoother_cls=supersmoother.SuperSmoother
)
avg += my_smoother._smoothed_best_spans.smooth_result
if not (i + 1) % 20:
print(i + 1)
avg /= num_trials
plt.plot(my_smoother.x, avg, '.', label='Average JCV')
finish_plot() | [
"def",
"validate_average_best_span",
"(",
")",
":",
"N",
"=",
"200",
"num_trials",
"=",
"400",
"avg",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"for",
"i",
"in",
"range",
"(",
"num_trials",
")",
":",
"x",
",",
"y",
"=",
"smoother_friedman82",
".",
"... | Figure 2d? from Friedman. | [
"Figure",
"2d?",
"from",
"Friedman",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L77-L92 | train | 42,071 |
partofthething/ace | ace/validation/validate_smoothers.py | validate_known_curve | def validate_known_curve():
"""Validate on a sin function."""
plt.figure()
N = 100
x = numpy.linspace(-1, 1, N)
y = numpy.sin(4 * x)
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmootherSlowUpdate
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Slow')
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmoother
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Fast')
plt.plot(x, y, '.', label='data')
plt.legend()
plt.show() | python | def validate_known_curve():
"""Validate on a sin function."""
plt.figure()
N = 100
x = numpy.linspace(-1, 1, N)
y = numpy.sin(4 * x)
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmootherSlowUpdate
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Slow')
smoother.DEFAULT_BASIC_SMOOTHER = smoother.BasicFixedSpanSmoother
smooth = smoother.perform_smooth(x, y, smoother_cls=supersmoother.SuperSmoother)
plt.plot(x, smooth.smooth_result, label='Fast')
plt.plot(x, y, '.', label='data')
plt.legend()
plt.show() | [
"def",
"validate_known_curve",
"(",
")",
":",
"plt",
".",
"figure",
"(",
")",
"N",
"=",
"100",
"x",
"=",
"numpy",
".",
"linspace",
"(",
"-",
"1",
",",
"1",
",",
"N",
")",
"y",
"=",
"numpy",
".",
"sin",
"(",
"4",
"*",
"x",
")",
"smoother",
"."... | Validate on a sin function. | [
"Validate",
"on",
"a",
"sin",
"function",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L94-L108 | train | 42,072 |
partofthething/ace | ace/validation/validate_smoothers.py | finish_plot | def finish_plot():
"""Helper for plotting."""
plt.legend()
plt.grid(color='0.7')
plt.xlabel('x')
plt.ylabel('y')
plt.show() | python | def finish_plot():
"""Helper for plotting."""
plt.legend()
plt.grid(color='0.7')
plt.xlabel('x')
plt.ylabel('y')
plt.show() | [
"def",
"finish_plot",
"(",
")",
":",
"plt",
".",
"legend",
"(",
")",
"plt",
".",
"grid",
"(",
"color",
"=",
"'0.7'",
")",
"plt",
".",
"xlabel",
"(",
"'x'",
")",
"plt",
".",
"ylabel",
"(",
"'y'",
")",
"plt",
".",
"show",
"(",
")"
] | Helper for plotting. | [
"Helper",
"for",
"plotting",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L110-L116 | train | 42,073 |
partofthething/ace | ace/validation/validate_smoothers.py | run_freidman_supsmu | def run_freidman_supsmu(x, y, bass_enhancement=0.0):
"""Run the FORTRAN supersmoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.supsmu(x, y, weight, 1, 0.0, bass_enhancement, results, flags)
return results | python | def run_freidman_supsmu(x, y, bass_enhancement=0.0):
"""Run the FORTRAN supersmoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.supsmu(x, y, weight, 1, 0.0, bass_enhancement, results, flags)
return results | [
"def",
"run_freidman_supsmu",
"(",
"x",
",",
"y",
",",
"bass_enhancement",
"=",
"0.0",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"weight",
"=",
"numpy",
".",
"ones",
"(",
"N",
")",
"results",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"flags",
"=... | Run the FORTRAN supersmoother. | [
"Run",
"the",
"FORTRAN",
"supersmoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L118-L125 | train | 42,074 |
partofthething/ace | ace/validation/validate_smoothers.py | run_friedman_smooth | def run_friedman_smooth(x, y, span):
"""Run the FORTRAN smoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | python | def run_friedman_smooth(x, y, span):
"""Run the FORTRAN smoother."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
residuals = numpy.zeros(N)
mace.smooth(x, y, weight, span, 1, 1e-7, results, residuals)
return results, residuals | [
"def",
"run_friedman_smooth",
"(",
"x",
",",
"y",
",",
"span",
")",
":",
"N",
"=",
"len",
"(",
"x",
")",
"weight",
"=",
"numpy",
".",
"ones",
"(",
"N",
")",
"results",
"=",
"numpy",
".",
"zeros",
"(",
"N",
")",
"residuals",
"=",
"numpy",
".",
"... | Run the FORTRAN smoother. | [
"Run",
"the",
"FORTRAN",
"smoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L127-L134 | train | 42,075 |
partofthething/ace | ace/validation/validate_smoothers.py | run_mace_smothr | def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument
"""Run the FORTRAN SMOTHR."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.smothr(1, x, y, weight, results, flags)
return results | python | def run_mace_smothr(x, y, bass_enhancement=0.0): # pylint: disable=unused-argument
"""Run the FORTRAN SMOTHR."""
N = len(x)
weight = numpy.ones(N)
results = numpy.zeros(N)
flags = numpy.zeros((N, 7))
mace.smothr(1, x, y, weight, results, flags)
return results | [
"def",
"run_mace_smothr",
"(",
"x",
",",
"y",
",",
"bass_enhancement",
"=",
"0.0",
")",
":",
"# pylint: disable=unused-argument",
"N",
"=",
"len",
"(",
"x",
")",
"weight",
"=",
"numpy",
".",
"ones",
"(",
"N",
")",
"results",
"=",
"numpy",
".",
"zeros",
... | Run the FORTRAN SMOTHR. | [
"Run",
"the",
"FORTRAN",
"SMOTHR",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L136-L143 | train | 42,076 |
partofthething/ace | ace/validation/validate_smoothers.py | sort_data | def sort_data(x, y):
"""Sort the data."""
xy = sorted(zip(x, y))
x, y = zip(*xy)
return x, y | python | def sort_data(x, y):
"""Sort the data."""
xy = sorted(zip(x, y))
x, y = zip(*xy)
return x, y | [
"def",
"sort_data",
"(",
"x",
",",
"y",
")",
":",
"xy",
"=",
"sorted",
"(",
"zip",
"(",
"x",
",",
"y",
")",
")",
"x",
",",
"y",
"=",
"zip",
"(",
"*",
"xy",
")",
"return",
"x",
",",
"y"
] | Sort the data. | [
"Sort",
"the",
"data",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L162-L166 | train | 42,077 |
partofthething/ace | ace/validation/validate_smoothers.py | BasicFixedSpanSmootherBreiman.compute | def compute(self):
"""Run smoother."""
self.smooth_result, self.cross_validated_residual = run_friedman_smooth(
self.x, self.y, self._span
) | python | def compute(self):
"""Run smoother."""
self.smooth_result, self.cross_validated_residual = run_friedman_smooth(
self.x, self.y, self._span
) | [
"def",
"compute",
"(",
"self",
")",
":",
"self",
".",
"smooth_result",
",",
"self",
".",
"cross_validated_residual",
"=",
"run_friedman_smooth",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
",",
"self",
".",
"_span",
")"
] | Run smoother. | [
"Run",
"smoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L148-L152 | train | 42,078 |
partofthething/ace | ace/validation/validate_smoothers.py | SuperSmootherBreiman.compute | def compute(self):
"""Run SuperSmoother."""
self.smooth_result = run_freidman_supsmu(self.x, self.y)
self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result))) | python | def compute(self):
"""Run SuperSmoother."""
self.smooth_result = run_freidman_supsmu(self.x, self.y)
self._store_unsorted_results(self.smooth_result, numpy.zeros(len(self.smooth_result))) | [
"def",
"compute",
"(",
"self",
")",
":",
"self",
".",
"smooth_result",
"=",
"run_freidman_supsmu",
"(",
"self",
".",
"x",
",",
"self",
".",
"y",
")",
"self",
".",
"_store_unsorted_results",
"(",
"self",
".",
"smooth_result",
",",
"numpy",
".",
"zeros",
"... | Run SuperSmoother. | [
"Run",
"SuperSmoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/validation/validate_smoothers.py#L157-L160 | train | 42,079 |
openstack/monasca-common | monasca_common/kafka/consumer.py | KafkaConsumer._partition | def _partition(self):
"""Consume messages from kafka
Consume messages from kafka using the Kazoo SetPartitioner to
allow multiple consumer processes to negotiate access to the kafka
partitions
"""
# KazooClient and SetPartitioner objects need to be instantiated after
# the consumer process has forked. Instantiating prior to forking
# gives the appearance that things are working but after forking the
# connection to zookeeper is lost and no state changes are visible
if not self._kazoo_client:
self._kazoo_client = KazooClient(hosts=self._zookeeper_url)
self._kazoo_client.start()
state_change_event = threading.Event()
self._set_partitioner = (
SetPartitioner(self._kazoo_client,
path=self._zookeeper_path,
set=self._consumer.fetch_offsets.keys(),
state_change_event=state_change_event,
identifier=str(datetime.datetime.now())))
try:
while 1:
if self._set_partitioner.failed:
raise Exception("Failed to acquire partition")
elif self._set_partitioner.release:
log.info("Releasing locks on partition set {} "
"for topic {}".format(self._partitions,
self._kafka_topic))
self._set_partitioner.release_set()
self._partitions = []
elif self._set_partitioner.acquired:
if not self._partitions:
self._partitions = [p for p in self._set_partitioner]
if not self._partitions:
log.info("Not assigned any partitions on topic {},"
" waiting for a Partitioner state change"
.format(self._kafka_topic))
state_change_event.wait()
state_change_event.clear()
continue
log.info("Acquired locks on partition set {} "
"for topic {}".format(self._partitions, self._kafka_topic))
# Reconstruct the kafka consumer object because the
# consumer has no API that allows the set of partitons
# to be updated outside of construction.
self._consumer.stop()
self._consumer = self._create_kafka_consumer(self._partitions)
return
elif self._set_partitioner.allocating:
log.info("Waiting to acquire locks on partition set")
self._set_partitioner.wait_for_acquire()
except Exception:
log.exception('KafkaConsumer encountered fatal exception '
'processing messages.')
raise | python | def _partition(self):
"""Consume messages from kafka
Consume messages from kafka using the Kazoo SetPartitioner to
allow multiple consumer processes to negotiate access to the kafka
partitions
"""
# KazooClient and SetPartitioner objects need to be instantiated after
# the consumer process has forked. Instantiating prior to forking
# gives the appearance that things are working but after forking the
# connection to zookeeper is lost and no state changes are visible
if not self._kazoo_client:
self._kazoo_client = KazooClient(hosts=self._zookeeper_url)
self._kazoo_client.start()
state_change_event = threading.Event()
self._set_partitioner = (
SetPartitioner(self._kazoo_client,
path=self._zookeeper_path,
set=self._consumer.fetch_offsets.keys(),
state_change_event=state_change_event,
identifier=str(datetime.datetime.now())))
try:
while 1:
if self._set_partitioner.failed:
raise Exception("Failed to acquire partition")
elif self._set_partitioner.release:
log.info("Releasing locks on partition set {} "
"for topic {}".format(self._partitions,
self._kafka_topic))
self._set_partitioner.release_set()
self._partitions = []
elif self._set_partitioner.acquired:
if not self._partitions:
self._partitions = [p for p in self._set_partitioner]
if not self._partitions:
log.info("Not assigned any partitions on topic {},"
" waiting for a Partitioner state change"
.format(self._kafka_topic))
state_change_event.wait()
state_change_event.clear()
continue
log.info("Acquired locks on partition set {} "
"for topic {}".format(self._partitions, self._kafka_topic))
# Reconstruct the kafka consumer object because the
# consumer has no API that allows the set of partitons
# to be updated outside of construction.
self._consumer.stop()
self._consumer = self._create_kafka_consumer(self._partitions)
return
elif self._set_partitioner.allocating:
log.info("Waiting to acquire locks on partition set")
self._set_partitioner.wait_for_acquire()
except Exception:
log.exception('KafkaConsumer encountered fatal exception '
'processing messages.')
raise | [
"def",
"_partition",
"(",
"self",
")",
":",
"# KazooClient and SetPartitioner objects need to be instantiated after",
"# the consumer process has forked. Instantiating prior to forking",
"# gives the appearance that things are working but after forking the",
"# connection to zookeeper is lost and... | Consume messages from kafka
Consume messages from kafka using the Kazoo SetPartitioner to
allow multiple consumer processes to negotiate access to the kafka
partitions | [
"Consume",
"messages",
"from",
"kafka"
] | 61e2e00454734e2881611abec8df0d85bf7655ac | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/monasca_common/kafka/consumer.py#L161-L229 | train | 42,080 |
openstack/monasca-common | docker/mysql_check.py | connect_mysql | def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
) | python | def connect_mysql(host, port, user, password, database):
"""Connect to MySQL with retries."""
return pymysql.connect(
host=host, port=port,
user=user, passwd=password,
db=database
) | [
"def",
"connect_mysql",
"(",
"host",
",",
"port",
",",
"user",
",",
"password",
",",
"database",
")",
":",
"return",
"pymysql",
".",
"connect",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"user",
"=",
"user",
",",
"passwd",
"=",
"passwor... | Connect to MySQL with retries. | [
"Connect",
"to",
"MySQL",
"with",
"retries",
"."
] | 61e2e00454734e2881611abec8df0d85bf7655ac | https://github.com/openstack/monasca-common/blob/61e2e00454734e2881611abec8df0d85bf7655ac/docker/mysql_check.py#L109-L115 | train | 42,081 |
partofthething/ace | ace/ace.py | unsort_vector | def unsort_vector(data, indices_of_increasing):
"""Upermutate 1-D data that is sorted by indices_of_increasing."""
return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))]) | python | def unsort_vector(data, indices_of_increasing):
"""Upermutate 1-D data that is sorted by indices_of_increasing."""
return numpy.array([data[indices_of_increasing.index(i)] for i in range(len(data))]) | [
"def",
"unsort_vector",
"(",
"data",
",",
"indices_of_increasing",
")",
":",
"return",
"numpy",
".",
"array",
"(",
"[",
"data",
"[",
"indices_of_increasing",
".",
"index",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"data",
")",
")"... | Upermutate 1-D data that is sorted by indices_of_increasing. | [
"Upermutate",
"1",
"-",
"D",
"data",
"that",
"is",
"sorted",
"by",
"indices_of_increasing",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L213-L215 | train | 42,082 |
partofthething/ace | ace/ace.py | ACESolver.specify_data_set | def specify_data_set(self, x_input, y_input):
"""
Define input to ACE.
Parameters
----------
x_input : list
list of iterables, one for each independent variable
y_input : array
the dependent observations
"""
self.x = x_input
self.y = y_input | python | def specify_data_set(self, x_input, y_input):
"""
Define input to ACE.
Parameters
----------
x_input : list
list of iterables, one for each independent variable
y_input : array
the dependent observations
"""
self.x = x_input
self.y = y_input | [
"def",
"specify_data_set",
"(",
"self",
",",
"x_input",
",",
"y_input",
")",
":",
"self",
".",
"x",
"=",
"x_input",
"self",
".",
"y",
"=",
"y_input"
] | Define input to ACE.
Parameters
----------
x_input : list
list of iterables, one for each independent variable
y_input : array
the dependent observations | [
"Define",
"input",
"to",
"ACE",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L50-L62 | train | 42,083 |
partofthething/ace | ace/ace.py | ACESolver.solve | def solve(self):
"""Run the ACE calculational loop."""
self._initialize()
while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS:
print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}'
''.format(self._outer_iters, self._last_outer_error))
self._iterate_to_update_x_transforms()
self._update_y_transform()
self._outer_iters += 1 | python | def solve(self):
"""Run the ACE calculational loop."""
self._initialize()
while self._outer_error_is_decreasing() and self._outer_iters < MAX_OUTERS:
print('* Starting outer iteration {0:03d}. Current err = {1:12.5E}'
''.format(self._outer_iters, self._last_outer_error))
self._iterate_to_update_x_transforms()
self._update_y_transform()
self._outer_iters += 1 | [
"def",
"solve",
"(",
"self",
")",
":",
"self",
".",
"_initialize",
"(",
")",
"while",
"self",
".",
"_outer_error_is_decreasing",
"(",
")",
"and",
"self",
".",
"_outer_iters",
"<",
"MAX_OUTERS",
":",
"print",
"(",
"'* Starting outer iteration {0:03d}. Current err =... | Run the ACE calculational loop. | [
"Run",
"the",
"ACE",
"calculational",
"loop",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L64-L72 | train | 42,084 |
partofthething/ace | ace/ace.py | ACESolver._initialize | def _initialize(self):
"""Set up and normalize initial data once input data is specified."""
self.y_transform = self.y - numpy.mean(self.y)
self.y_transform /= numpy.std(self.y_transform)
self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x]
self._compute_sorted_indices() | python | def _initialize(self):
"""Set up and normalize initial data once input data is specified."""
self.y_transform = self.y - numpy.mean(self.y)
self.y_transform /= numpy.std(self.y_transform)
self.x_transforms = [numpy.zeros(len(self.y)) for _xi in self.x]
self._compute_sorted_indices() | [
"def",
"_initialize",
"(",
"self",
")",
":",
"self",
".",
"y_transform",
"=",
"self",
".",
"y",
"-",
"numpy",
".",
"mean",
"(",
"self",
".",
"y",
")",
"self",
".",
"y_transform",
"/=",
"numpy",
".",
"std",
"(",
"self",
".",
"y_transform",
")",
"sel... | Set up and normalize initial data once input data is specified. | [
"Set",
"up",
"and",
"normalize",
"initial",
"data",
"once",
"input",
"data",
"is",
"specified",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L74-L79 | train | 42,085 |
partofthething/ace | ace/ace.py | ACESolver._compute_sorted_indices | def _compute_sorted_indices(self):
"""
The smoothers need sorted data. This sorts it from the perspective of each column.
if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8
We only have to sort the data once.
"""
sorted_indices = []
for to_sort in [self.y] + self.x:
data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)]
data_w_indices.sort()
sorted_indices.append([i for val, i in data_w_indices])
# save in meaningful variable names
self._yi_sorted = sorted_indices[0] # list (like self.y)
self._xi_sorted = sorted_indices[1:] | python | def _compute_sorted_indices(self):
"""
The smoothers need sorted data. This sorts it from the perspective of each column.
if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8
We only have to sort the data once.
"""
sorted_indices = []
for to_sort in [self.y] + self.x:
data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)]
data_w_indices.sort()
sorted_indices.append([i for val, i in data_w_indices])
# save in meaningful variable names
self._yi_sorted = sorted_indices[0] # list (like self.y)
self._xi_sorted = sorted_indices[1:] | [
"def",
"_compute_sorted_indices",
"(",
"self",
")",
":",
"sorted_indices",
"=",
"[",
"]",
"for",
"to_sort",
"in",
"[",
"self",
".",
"y",
"]",
"+",
"self",
".",
"x",
":",
"data_w_indices",
"=",
"[",
"(",
"val",
",",
"i",
")",
"for",
"(",
"i",
",",
... | The smoothers need sorted data. This sorts it from the perspective of each column.
if self._x[0][3] is the 9th-smallest value in self._x[0], then _xi_sorted[3] = 8
We only have to sort the data once. | [
"The",
"smoothers",
"need",
"sorted",
"data",
".",
"This",
"sorts",
"it",
"from",
"the",
"perspective",
"of",
"each",
"column",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L81-L96 | train | 42,086 |
partofthething/ace | ace/ace.py | ACESolver._outer_error_is_decreasing | def _outer_error_is_decreasing(self):
"""True if outer iteration error is decreasing."""
is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error)
return is_decreasing | python | def _outer_error_is_decreasing(self):
"""True if outer iteration error is decreasing."""
is_decreasing, self._last_outer_error = self._error_is_decreasing(self._last_outer_error)
return is_decreasing | [
"def",
"_outer_error_is_decreasing",
"(",
"self",
")",
":",
"is_decreasing",
",",
"self",
".",
"_last_outer_error",
"=",
"self",
".",
"_error_is_decreasing",
"(",
"self",
".",
"_last_outer_error",
")",
"return",
"is_decreasing"
] | True if outer iteration error is decreasing. | [
"True",
"if",
"outer",
"iteration",
"error",
"is",
"decreasing",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L98-L101 | train | 42,087 |
partofthething/ace | ace/ace.py | ACESolver._error_is_decreasing | def _error_is_decreasing(self, last_error):
"""True if current error is less than last_error."""
current_error = self._compute_error()
is_decreasing = current_error < last_error
return is_decreasing, current_error | python | def _error_is_decreasing(self, last_error):
"""True if current error is less than last_error."""
current_error = self._compute_error()
is_decreasing = current_error < last_error
return is_decreasing, current_error | [
"def",
"_error_is_decreasing",
"(",
"self",
",",
"last_error",
")",
":",
"current_error",
"=",
"self",
".",
"_compute_error",
"(",
")",
"is_decreasing",
"=",
"current_error",
"<",
"last_error",
"return",
"is_decreasing",
",",
"current_error"
] | True if current error is less than last_error. | [
"True",
"if",
"current",
"error",
"is",
"less",
"than",
"last_error",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L103-L107 | train | 42,088 |
partofthething/ace | ace/ace.py | ACESolver._compute_error | def _compute_error(self):
"""Compute unexplained error."""
sum_x = sum(self.x_transforms)
err = sum((self.y_transform - sum_x) ** 2) / len(sum_x)
return err | python | def _compute_error(self):
"""Compute unexplained error."""
sum_x = sum(self.x_transforms)
err = sum((self.y_transform - sum_x) ** 2) / len(sum_x)
return err | [
"def",
"_compute_error",
"(",
"self",
")",
":",
"sum_x",
"=",
"sum",
"(",
"self",
".",
"x_transforms",
")",
"err",
"=",
"sum",
"(",
"(",
"self",
".",
"y_transform",
"-",
"sum_x",
")",
"**",
"2",
")",
"/",
"len",
"(",
"sum_x",
")",
"return",
"err"
] | Compute unexplained error. | [
"Compute",
"unexplained",
"error",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L109-L113 | train | 42,089 |
partofthething/ace | ace/ace.py | ACESolver._iterate_to_update_x_transforms | def _iterate_to_update_x_transforms(self):
"""Perform the inner iteration."""
self._inner_iters = 0
self._last_inner_error = float('inf')
while self._inner_error_is_decreasing():
print(' Starting inner iteration {0:03d}. Current err = {1:12.5E}'
''.format(self._inner_iters, self._last_inner_error))
self._update_x_transforms()
self._inner_iters += 1 | python | def _iterate_to_update_x_transforms(self):
"""Perform the inner iteration."""
self._inner_iters = 0
self._last_inner_error = float('inf')
while self._inner_error_is_decreasing():
print(' Starting inner iteration {0:03d}. Current err = {1:12.5E}'
''.format(self._inner_iters, self._last_inner_error))
self._update_x_transforms()
self._inner_iters += 1 | [
"def",
"_iterate_to_update_x_transforms",
"(",
"self",
")",
":",
"self",
".",
"_inner_iters",
"=",
"0",
"self",
".",
"_last_inner_error",
"=",
"float",
"(",
"'inf'",
")",
"while",
"self",
".",
"_inner_error_is_decreasing",
"(",
")",
":",
"print",
"(",
"' Star... | Perform the inner iteration. | [
"Perform",
"the",
"inner",
"iteration",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L115-L123 | train | 42,090 |
partofthething/ace | ace/ace.py | ACESolver._update_x_transforms | def _update_x_transforms(self):
"""
Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother.
"""
# start by subtracting all transforms
theta_minus_phis = self.y_transform - numpy.sum(self.x_transforms, axis=0)
# add one transform at a time so as to exclude it from the subtracted sum
for xtransform_index in range(len(self.x_transforms)):
xtransform = self.x_transforms[xtransform_index]
sorted_data_indices = self._xi_sorted[xtransform_index]
xk_sorted = sort_vector(self.x[xtransform_index], sorted_data_indices)
xtransform_sorted = sort_vector(xtransform, sorted_data_indices)
theta_minus_phis_sorted = sort_vector(theta_minus_phis, sorted_data_indices)
# minimize sums by just adding in the phik where i!=k here.
to_smooth = theta_minus_phis_sorted + xtransform_sorted
smoother = perform_smooth(xk_sorted, to_smooth, smoother_cls=self._smoother_cls)
updated_x_transform_smooth = smoother.smooth_result
updated_x_transform_smooth -= numpy.mean(updated_x_transform_smooth)
# store updated transform in the order of the original data
unsorted_xt = unsort_vector(updated_x_transform_smooth, sorted_data_indices)
self.x_transforms[xtransform_index] = unsorted_xt
# update main expession with new smooth. This was done in the original FORTRAN
tmp_unsorted = unsort_vector(to_smooth, sorted_data_indices)
theta_minus_phis = tmp_unsorted - unsorted_xt | python | def _update_x_transforms(self):
"""
Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother.
"""
# start by subtracting all transforms
theta_minus_phis = self.y_transform - numpy.sum(self.x_transforms, axis=0)
# add one transform at a time so as to exclude it from the subtracted sum
for xtransform_index in range(len(self.x_transforms)):
xtransform = self.x_transforms[xtransform_index]
sorted_data_indices = self._xi_sorted[xtransform_index]
xk_sorted = sort_vector(self.x[xtransform_index], sorted_data_indices)
xtransform_sorted = sort_vector(xtransform, sorted_data_indices)
theta_minus_phis_sorted = sort_vector(theta_minus_phis, sorted_data_indices)
# minimize sums by just adding in the phik where i!=k here.
to_smooth = theta_minus_phis_sorted + xtransform_sorted
smoother = perform_smooth(xk_sorted, to_smooth, smoother_cls=self._smoother_cls)
updated_x_transform_smooth = smoother.smooth_result
updated_x_transform_smooth -= numpy.mean(updated_x_transform_smooth)
# store updated transform in the order of the original data
unsorted_xt = unsort_vector(updated_x_transform_smooth, sorted_data_indices)
self.x_transforms[xtransform_index] = unsorted_xt
# update main expession with new smooth. This was done in the original FORTRAN
tmp_unsorted = unsort_vector(to_smooth, sorted_data_indices)
theta_minus_phis = tmp_unsorted - unsorted_xt | [
"def",
"_update_x_transforms",
"(",
"self",
")",
":",
"# start by subtracting all transforms",
"theta_minus_phis",
"=",
"self",
".",
"y_transform",
"-",
"numpy",
".",
"sum",
"(",
"self",
".",
"x_transforms",
",",
"axis",
"=",
"0",
")",
"# add one transform at a time... | Compute a new set of x-transform functions phik.
phik(xk) = theta(y) - sum of phii(xi) over i!=k
This is the first of the eponymous conditional expectations. The conditional
expectations are computed using the SuperSmoother. | [
"Compute",
"a",
"new",
"set",
"of",
"x",
"-",
"transform",
"functions",
"phik",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L129-L162 | train | 42,091 |
partofthething/ace | ace/ace.py | ACESolver.write_input_to_file | def write_input_to_file(self, fname='ace_input.txt'):
"""Write y and x values used in this run to a space-delimited txt file."""
self._write_columns(fname, self.x, self.y) | python | def write_input_to_file(self, fname='ace_input.txt'):
"""Write y and x values used in this run to a space-delimited txt file."""
self._write_columns(fname, self.x, self.y) | [
"def",
"write_input_to_file",
"(",
"self",
",",
"fname",
"=",
"'ace_input.txt'",
")",
":",
"self",
".",
"_write_columns",
"(",
"fname",
",",
"self",
".",
"x",
",",
"self",
".",
"y",
")"
] | Write y and x values used in this run to a space-delimited txt file. | [
"Write",
"y",
"and",
"x",
"values",
"used",
"in",
"this",
"run",
"to",
"a",
"space",
"-",
"delimited",
"txt",
"file",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L191-L193 | train | 42,092 |
partofthething/ace | ace/ace.py | ACESolver.write_transforms_to_file | def write_transforms_to_file(self, fname='ace_transforms.txt'):
"""Write y and x transforms used in this run to a space-delimited txt file."""
self._write_columns(fname, self.x_transforms, self.y_transform) | python | def write_transforms_to_file(self, fname='ace_transforms.txt'):
"""Write y and x transforms used in this run to a space-delimited txt file."""
self._write_columns(fname, self.x_transforms, self.y_transform) | [
"def",
"write_transforms_to_file",
"(",
"self",
",",
"fname",
"=",
"'ace_transforms.txt'",
")",
":",
"self",
".",
"_write_columns",
"(",
"fname",
",",
"self",
".",
"x_transforms",
",",
"self",
".",
"y_transform",
")"
] | Write y and x transforms used in this run to a space-delimited txt file. | [
"Write",
"y",
"and",
"x",
"transforms",
"used",
"in",
"this",
"run",
"to",
"a",
"space",
"-",
"delimited",
"txt",
"file",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/ace.py#L195-L197 | train | 42,093 |
partofthething/ace | ace/samples/smoother_friedman82.py | build_sample_smoother_problem_friedman82 | def build_sample_smoother_problem_friedman82(N=200):
"""Sample problem from supersmoother publication."""
x = numpy.random.uniform(size=N)
err = numpy.random.standard_normal(N)
y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err
return x, y | python | def build_sample_smoother_problem_friedman82(N=200):
"""Sample problem from supersmoother publication."""
x = numpy.random.uniform(size=N)
err = numpy.random.standard_normal(N)
y = numpy.sin(2 * math.pi * (1 - x) ** 2) + x * err
return x, y | [
"def",
"build_sample_smoother_problem_friedman82",
"(",
"N",
"=",
"200",
")",
":",
"x",
"=",
"numpy",
".",
"random",
".",
"uniform",
"(",
"size",
"=",
"N",
")",
"err",
"=",
"numpy",
".",
"random",
".",
"standard_normal",
"(",
"N",
")",
"y",
"=",
"numpy... | Sample problem from supersmoother publication. | [
"Sample",
"problem",
"from",
"supersmoother",
"publication",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/samples/smoother_friedman82.py#L11-L16 | train | 42,094 |
robotpy/pyfrc | lib/pyfrc/sim/field/field.py | RobotField.add_moving_element | def add_moving_element(self, element):
"""Add elements to the board"""
element.initialize(self.canvas)
self.elements.append(element) | python | def add_moving_element(self, element):
"""Add elements to the board"""
element.initialize(self.canvas)
self.elements.append(element) | [
"def",
"add_moving_element",
"(",
"self",
",",
"element",
")",
":",
"element",
".",
"initialize",
"(",
"self",
".",
"canvas",
")",
"self",
".",
"elements",
".",
"append",
"(",
"element",
")"
] | Add elements to the board | [
"Add",
"elements",
"to",
"the",
"board"
] | 7672ea3f17c8d4b702a9f18a7372d95feee7e37d | https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/sim/field/field.py#L84-L88 | train | 42,095 |
robotpy/pyfrc | lib/pyfrc/sim/field/field.py | RobotField.on_key_pressed | def on_key_pressed(self, event):
"""
likely to take in a set of parameters to treat as up, down, left,
right, likely to actually be based on a joystick event... not sure
yet
"""
return
# TODO
if event.keysym == "Up":
self.manager.set_joystick(0.0, -1.0, 0)
elif event.keysym == "Down":
self.manager.set_joystick(0.0, 1.0, 0)
elif event.keysym == "Left":
self.manager.set_joystick(-1.0, 0.0, 0)
elif event.keysym == "Right":
self.manager.set_joystick(1.0, 0.0, 0)
elif event.char == " ":
mode = self.manager.get_mode()
if mode == self.manager.MODE_DISABLED:
self.manager.set_mode(self.manager.MODE_OPERATOR_CONTROL)
else:
self.manager.set_mode(self.manager.MODE_DISABLED) | python | def on_key_pressed(self, event):
"""
likely to take in a set of parameters to treat as up, down, left,
right, likely to actually be based on a joystick event... not sure
yet
"""
return
# TODO
if event.keysym == "Up":
self.manager.set_joystick(0.0, -1.0, 0)
elif event.keysym == "Down":
self.manager.set_joystick(0.0, 1.0, 0)
elif event.keysym == "Left":
self.manager.set_joystick(-1.0, 0.0, 0)
elif event.keysym == "Right":
self.manager.set_joystick(1.0, 0.0, 0)
elif event.char == " ":
mode = self.manager.get_mode()
if mode == self.manager.MODE_DISABLED:
self.manager.set_mode(self.manager.MODE_OPERATOR_CONTROL)
else:
self.manager.set_mode(self.manager.MODE_DISABLED) | [
"def",
"on_key_pressed",
"(",
"self",
",",
"event",
")",
":",
"return",
"# TODO",
"if",
"event",
".",
"keysym",
"==",
"\"Up\"",
":",
"self",
".",
"manager",
".",
"set_joystick",
"(",
"0.0",
",",
"-",
"1.0",
",",
"0",
")",
"elif",
"event",
".",
"keysy... | likely to take in a set of parameters to treat as up, down, left,
right, likely to actually be based on a joystick event... not sure
yet | [
"likely",
"to",
"take",
"in",
"a",
"set",
"of",
"parameters",
"to",
"treat",
"as",
"up",
"down",
"left",
"right",
"likely",
"to",
"actually",
"be",
"based",
"on",
"a",
"joystick",
"event",
"...",
"not",
"sure",
"yet"
] | 7672ea3f17c8d4b702a9f18a7372d95feee7e37d | https://github.com/robotpy/pyfrc/blob/7672ea3f17c8d4b702a9f18a7372d95feee7e37d/lib/pyfrc/sim/field/field.py#L93-L118 | train | 42,096 |
partofthething/ace | ace/smoother.py | perform_smooth | def perform_smooth(x_values, y_values, span=None, smoother_cls=None):
"""
Convenience function to run the basic smoother.
Parameters
----------
x_values : iterable
List of x value observations
y_ values : iterable
list of y value observations
span : float, optional
Fraction of data to use as the window
smoother_cls : Class
The class of smoother to use to smooth the data
Returns
-------
smoother : object
The smoother object with results stored on it.
"""
if smoother_cls is None:
smoother_cls = DEFAULT_BASIC_SMOOTHER
smoother = smoother_cls()
smoother.specify_data_set(x_values, y_values)
smoother.set_span(span)
smoother.compute()
return smoother | python | def perform_smooth(x_values, y_values, span=None, smoother_cls=None):
"""
Convenience function to run the basic smoother.
Parameters
----------
x_values : iterable
List of x value observations
y_ values : iterable
list of y value observations
span : float, optional
Fraction of data to use as the window
smoother_cls : Class
The class of smoother to use to smooth the data
Returns
-------
smoother : object
The smoother object with results stored on it.
"""
if smoother_cls is None:
smoother_cls = DEFAULT_BASIC_SMOOTHER
smoother = smoother_cls()
smoother.specify_data_set(x_values, y_values)
smoother.set_span(span)
smoother.compute()
return smoother | [
"def",
"perform_smooth",
"(",
"x_values",
",",
"y_values",
",",
"span",
"=",
"None",
",",
"smoother_cls",
"=",
"None",
")",
":",
"if",
"smoother_cls",
"is",
"None",
":",
"smoother_cls",
"=",
"DEFAULT_BASIC_SMOOTHER",
"smoother",
"=",
"smoother_cls",
"(",
")",
... | Convenience function to run the basic smoother.
Parameters
----------
x_values : iterable
List of x value observations
y_ values : iterable
list of y value observations
span : float, optional
Fraction of data to use as the window
smoother_cls : Class
The class of smoother to use to smooth the data
Returns
-------
smoother : object
The smoother object with results stored on it. | [
"Convenience",
"function",
"to",
"run",
"the",
"basic",
"smoother",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/smoother.py#L323-L349 | train | 42,097 |
partofthething/ace | ace/smoother.py | Smoother.add_data_point_xy | def add_data_point_xy(self, x, y):
"""Add a new data point to the data set to be smoothed."""
self.x.append(x)
self.y.append(y) | python | def add_data_point_xy(self, x, y):
"""Add a new data point to the data set to be smoothed."""
self.x.append(x)
self.y.append(y) | [
"def",
"add_data_point_xy",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"self",
".",
"x",
".",
"append",
"(",
"x",
")",
"self",
".",
"y",
".",
"append",
"(",
"y",
")"
] | Add a new data point to the data set to be smoothed. | [
"Add",
"a",
"new",
"data",
"point",
"to",
"the",
"data",
"set",
"to",
"be",
"smoothed",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/smoother.py#L54-L57 | train | 42,098 |
partofthething/ace | ace/smoother.py | Smoother.specify_data_set | def specify_data_set(self, x_input, y_input, sort_data=False):
"""
Fully define data by lists of x values and y values.
This will sort them by increasing x but remember how to unsort them for providing results.
Parameters
----------
x_input : iterable
list of floats that represent x
y_input : iterable
list of floats that represent y(x) for each x
sort_data : bool, optional
If true, the data will be sorted by increasing x values.
"""
if sort_data:
xy = sorted(zip(x_input, y_input))
x, y = zip(*xy)
x_input_list = list(x_input)
self._original_index_of_xvalue = [x_input_list.index(xi) for xi in x]
if len(set(self._original_index_of_xvalue)) != len(x):
raise RuntimeError('There are some non-unique x-values')
else:
x, y = x_input, y_input
self.x = x
self.y = y | python | def specify_data_set(self, x_input, y_input, sort_data=False):
"""
Fully define data by lists of x values and y values.
This will sort them by increasing x but remember how to unsort them for providing results.
Parameters
----------
x_input : iterable
list of floats that represent x
y_input : iterable
list of floats that represent y(x) for each x
sort_data : bool, optional
If true, the data will be sorted by increasing x values.
"""
if sort_data:
xy = sorted(zip(x_input, y_input))
x, y = zip(*xy)
x_input_list = list(x_input)
self._original_index_of_xvalue = [x_input_list.index(xi) for xi in x]
if len(set(self._original_index_of_xvalue)) != len(x):
raise RuntimeError('There are some non-unique x-values')
else:
x, y = x_input, y_input
self.x = x
self.y = y | [
"def",
"specify_data_set",
"(",
"self",
",",
"x_input",
",",
"y_input",
",",
"sort_data",
"=",
"False",
")",
":",
"if",
"sort_data",
":",
"xy",
"=",
"sorted",
"(",
"zip",
"(",
"x_input",
",",
"y_input",
")",
")",
"x",
",",
"y",
"=",
"zip",
"(",
"*"... | Fully define data by lists of x values and y values.
This will sort them by increasing x but remember how to unsort them for providing results.
Parameters
----------
x_input : iterable
list of floats that represent x
y_input : iterable
list of floats that represent y(x) for each x
sort_data : bool, optional
If true, the data will be sorted by increasing x values. | [
"Fully",
"define",
"data",
"by",
"lists",
"of",
"x",
"values",
"and",
"y",
"values",
"."
] | 1593a49f3c2e845514323e9c36ee253fe77bac3c | https://github.com/partofthething/ace/blob/1593a49f3c2e845514323e9c36ee253fe77bac3c/ace/smoother.py#L59-L85 | train | 42,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.