repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow._got_request_exception | python | def _got_request_exception(self, sender, exception, **extra):
extra = self.summary_extra()
extra['errno'] = 500
self.summary_logger.error(str(exception), extra=extra)
g._has_exception = True | The signal handler for the got_request_exception signal. | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L194-L201 | null | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow.user_id | python | def user_id(self):
# This needs flask-login to be installed
if not has_flask_login:
return
# and the actual login manager installed
if not hasattr(current_app, 'login_manager'):
return
# fail if no current_user was attached to the request context
... | Return the ID of the current request's user | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L203-L230 | null | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow.summary_extra | python | def summary_extra(self):
out = {
'errno': 0,
'agent': request.headers.get('User-Agent', ''),
'lang': request.headers.get('Accept-Language', ''),
'method': request.method,
'path': request.path,
}
# set the uid value to the current user ... | Build the extra data for the summary logger. | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L232-L261 | [
"def user_id(self):\n \"\"\"\n Return the ID of the current request's user\n \"\"\"\n # This needs flask-login to be installed\n if not has_flask_login:\n return\n\n # and the actual login manager installed\n if not hasattr(current_app, 'login_manager'):\n return\n\n # fail if ... | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow._version_view | python | def _version_view(self):
version_json = self._version_callback(self.version_path)
if version_json is None:
return 'version.json not found', 404
else:
return jsonify(version_json) | View that returns the contents of version.json or a 404. | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L263-L271 | null | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow._heartbeat_view | python | def _heartbeat_view(self):
details = {}
statuses = {}
level = 0
for name, check in self.checks.items():
detail = self._heartbeat_check_detail(check)
statuses[name] = detail['status']
level = max(level, detail['level'])
if detail['level'] >... | Runs all the registered checks and returns a JSON response with either
a status code of 200 or 500 depending on the results of the checks.
Any check that returns a warning or worse (error, critical) will
return a 500 response. | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L291-L326 | null | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/app.py | Dockerflow.check | python | def check(self, func=None, name=None):
if func is None:
return functools.partial(self.check, name=name)
if name is None:
name = func.__name__
self.logger.info('Registered Dockerflow check %s', name)
@functools.wraps(func)
def decorated_function(*args, *... | A decorator to register a new Dockerflow check to be run
when the /__heartbeat__ endpoint is called., e.g.::
from dockerflow.flask import checks
@dockerflow.check
def storage_reachable():
try:
acme.storage.ping()
except Sl... | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/app.py#L354-L391 | null | class Dockerflow(object):
"""
The Dockerflow Flask extension. Set it up like this:
.. code-block:: python
:caption: ``myproject.py``
from flask import Flask
from dockerflow.flask import Dockerflow
app = Flask(__name__)
dockerflow = Dockerflow(app)
Or if you use the... |
mozilla-services/python-dockerflow | src/dockerflow/flask/checks/__init__.py | check_database_connected | python | def check_database_connected(db):
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
errors = []
try:
with db.engine.connect() as connection:
connection.execute('SELECT 1;')
except DBAPIError as e:
msg = 'DB-API error: {!s}'.format(e)
errors.append(Error(msg, id=... | A built-in check to see if connecting to the configured default
database backend succeeds.
It's automatically added to the list of Dockerflow checks if a
:class:`~flask_sqlalchemy.SQLAlchemy` object is passed
to the :class:`~dockerflow.flask.app.Dockerflow` class during
instantiation, e.g.::
... | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/checks/__init__.py#L14-L46 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
"""
This module contains a few built-in checks for the Flask integration.
"""
from ... import health
from .messages impor... |
mozilla-services/python-dockerflow | src/dockerflow/flask/checks/__init__.py | check_migrations_applied | python | def check_migrations_applied(migrate):
errors = []
from alembic.migration import MigrationContext
from alembic.script import ScriptDirectory
from sqlalchemy.exc import DBAPIError, SQLAlchemyError
# pass in Migrate.directory here explicitly to be compatible with
# older versions of Flask-Migrat... | A built-in check to see if all migrations have been applied correctly.
It's automatically added to the list of Dockerflow checks if a
`flask_migrate.Migrate <https://flask-migrate.readthedocs.io/>`_ object
is passed to the :class:`~dockerflow.flask.app.Dockerflow` class during
instantiation, e.g.::
... | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/checks/__init__.py#L49-L93 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
"""
This module contains a few built-in checks for the Flask integration.
"""
from ... import health
from .messages impor... |
mozilla-services/python-dockerflow | src/dockerflow/flask/checks/__init__.py | check_redis_connected | python | def check_redis_connected(client):
import redis
errors = []
try:
result = client.ping()
except redis.ConnectionError as e:
msg = 'Could not connect to redis: {!s}'.format(e)
errors.append(Error(msg, id=health.ERROR_CANNOT_CONNECT_REDIS))
except redis.RedisError as e:
... | A built-in check to connect to Redis using the given client and see
if it responds to the ``PING`` command.
It's automatically added to the list of Dockerflow checks if a
:class:`~redis.StrictRedis` instances is passed
to the :class:`~dockerflow.flask.app.Dockerflow` class during
instantiation, e.g... | train | https://github.com/mozilla-services/python-dockerflow/blob/43703c5e8934ba6901b0a1520d6da4ed6457208c/src/dockerflow/flask/checks/__init__.py#L96-L145 | null | # This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, you can obtain one at http://mozilla.org/MPL/2.0/.
"""
This module contains a few built-in checks for the Flask integration.
"""
from ... import health
from .messages impor... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData.reset | python | def reset(self):
self.current_table = None
self.tables = []
self.data = [{}]
self.additional_data = {}
self.lines = []
self.set_state('document')
self.current_file = None
self.set_of_energies = set() | Clean any processing data, and prepare object for reuse | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L34-L44 | [
"def set_state(self, state):\n if state not in OldHEPData.states:\n raise ValueError(\"unknown state\")\n self.current_state = state\n"
] | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._parse_line | python | def _parse_line(self, file):
line = self._strip_comments(file.readline())
# check if the file ended
if not line:
return False
# line was empty or it was a comment, continue
if line.strip() == '':
return True
# retrieve keyword and its value
... | Parse single line (or more if particular keyword actually demands it)
:param file:
:type file: file | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L136-L165 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._set_table | python | def _set_table(self, data):
self.set_state('table')
self.current_table = HEPTable(index=len(self.tables) + 1)
self.tables.append(self.current_table)
self.data.append(self.current_table.metadata) | Set current parsing state to 'table',
create new table object and add it to tables collection | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L183-L190 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._parse_table_data | python | def _parse_table_data(self, data):
header = data.split(':')
self.current_table.data_header = header
for i, h in enumerate(header):
header[i] = h.strip()
x_count = header.count('x')
y_count = header.count('y')
if not self.current_table.xheaders:
... | Parse dataset data of the original HEPData format
:param data: header of the table to be parsed
:raise ValueError: | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L204-L406 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._reformat_matrix | python | def _reformat_matrix(self):
nxax = len(self.current_table.data['independent_variables'])
nyax = len(self.current_table.data['dependent_variables'])
npts = len(self.current_table.data['dependent_variables'][0]['values'])
# check if 1 x-axis, and npts (>=2) equals number of y-axes
... | Transform a square matrix into a format with two independent variables and one dependent variable. | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L408-L454 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._parse_qual | python | def _parse_qual(self, data):
list = []
headers = data.split(':')
name = headers[0].strip()
name = re.split(' IN ', name, flags=re.I) # ignore case
units = None
if len(name) > 1:
units = name[1].strip()
name = name[0].strip()
if len(headers) <... | Parse qual attribute of the old HEPData format
example qual:
*qual: RE : P P --> Z0 Z0 X
:param data: data to be parsed
:type data: str | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L510-L550 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._parse_header | python | def _parse_header(self, data):
return_list = []
headers = data.split(':')
for header in headers:
header = re.split(' IN ', header, flags=re.I) # ignore case
xheader = {'name': header[0].strip()}
if len(header) > 1:
xheader['units'] = header[1... | Parse header (xheader or yheader)
:param data: data to be parsed
:type data: str
:return: list with header's data
:rtype: list | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L552-L571 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._strip_comments | python | def _strip_comments(line):
if line == '':
return line
r = re.search('(?P<line>[^#]*)(#(?P<comment>.*))?', line)
if r:
line = r.group('line')
if not line.endswith('\n'):
line += '\n'
return line
return '\n' | Processes line stripping any comments from it
:param line: line to be processed
:type line: str
:return: line with removed comments
:rtype: str | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L590-L606 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._read_multiline | python | def _read_multiline(self, init_data):
result = init_data
first = True
while True:
last_index = self.current_file.tell()
line_raw = self.current_file.readline()
# don't add newlines from full line comments
if line_raw[0] == '#':
co... | Reads multiline symbols (ususally comments)
:param init_data: initial data (parsed from the line containing keyword)
:return: parsed value of the multiline symbol
:rtype: str | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L608-L648 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._bind_set_table_metadata | python | def _bind_set_table_metadata(self, key, multiline=False):
def set_table_metadata(self, data):
if multiline:
data = self._read_multiline(data)
if key == 'location' and data:
data = 'Data from ' + data
self.current_table.metadata[key] = data.str... | Returns parsing function which will parse data as text, and add it to the table metatadata dictionary
with the provided key
:param key: dictionary key under which parsed data will be added to table.metadata
:type key: str
:param multiline: if True this attribute will be treated as multi... | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L653-L672 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/parsers/oldhepdata_parser.py | OldHEPData._bind_parse_additional_data | python | def _bind_parse_additional_data(self, key, multiline=False):
def _set_additional_data_bound(self, data):
"""Concrete method for setting additional data
:param self:
:type self: OldHEPData
"""
# if it's multiline, parse it
if multiline:
... | Returns parsing function which will parse data as text, and add it to the table additional data dictionary
with the provided key
:param key: dictionary key under which parsed data will be added to table.metadata
:type key: str
:param multiline: if True this attribute will be treated as ... | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/oldhepdata_parser.py#L689-L715 | null | class OldHEPData(Parser):
"""Parser for Old HEPData format
"""
help = 'Parses OLD HepData format - example OLD HepData input format: http://hepdata.cedar.ac.uk/resource/sample.input'
@classmethod
def options(cls):
options = Parser.options()
options['strict'] = Option('strict', defau... |
HEPData/hepdata-converter | hepdata_converter/writers/utils.py | error_value_processor | python | def error_value_processor(value, error):
if isinstance(error, (str, unicode)):
try:
if "%" in error:
error_float = float(error.replace("%", ""))
error_abs = (value/100) * error_float
return error_abs
elif error == "":
er... | If an error is a percentage, we convert to a float, then
calculate the percentage of the supplied value.
:param value: base value, e.g. 10
:param error: e.g. 20.0%
:return: the absolute error, e.g. 12 for the above case. | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/utils.py#L2-L24 | null | |
HEPData/hepdata-converter | hepdata_converter/__init__.py | convert | python | def convert(input, output=None, options={}):
if 'input_format' not in options and 'output_format' not in options:
raise ValueError("no input_format and output_format specified!")
input_format = options.get('input_format', 'yaml')
output_format = options.get('output_format', 'yaml')
parser = P... | Converts a supported ``input_format`` (*oldhepdata*, *yaml*)
to a supported ``output_format`` (*csv*, *root*, *yaml*, *yoda*).
:param input: location of input file for *oldhepdata* format or input directory for *yaml* format
:param output: location of output directory to which converted files will be writt... | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/__init__.py#L9-L43 | [
"def get_concrete_class(cls, class_name):\n \"\"\"This method provides easier access to all writers inheriting Writer class\n\n :param class_name: name of the parser (name of the parser class which should be used)\n :type class_name: str\n :return: Writer subclass specified by parser_name\n :rtype: W... | import StringIO
import argparse
import sys
import version
from parsers import Parser
from writers import Writer
def make_exit(message='', code=0):
return code, message
def generate_help_epilogue():
margin = ' '
r = 'Parsers:\n'
r += '[use them as --input-format parameter]\n'
r += '\n'
f... |
HEPData/hepdata-converter | hepdata_converter/writers/csv_writer.py | CSV._write_packed_data | python | def _write_packed_data(self, data_out, table):
headers = []
data = []
qualifiers_marks = []
qualifiers = {}
self._extract_independent_variables(table, headers, data, qualifiers_marks)
for dependent_variable in table.dependent_variables:
self._parse_dependent... | This is kind of legacy function - this functionality may be useful for some people, so even though
now the default of writing CSV is writing unpacked data (divided by independent variable) this method is
still available and accessible if ```pack``` flag is specified in Writer's options
:param o... | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/csv_writer.py#L82-L102 | null | class CSV(ArrayWriter):
help = 'Writes to CSV format, it can write either one table (specified by --table parameter) or all tables from the ' \
'input file. In the case of one table output must be filepath to the new csv file, in the case of multiple tables ' \
'the output must be specified to... |
HEPData/hepdata-converter | hepdata_converter/common.py | GetConcreteSubclassMixin.get_concrete_class | python | def get_concrete_class(cls, class_name):
def recurrent_class_lookup(cls):
for cls in cls.__subclasses__():
if lower(cls.__name__) == lower(class_name):
return cls
elif len(cls.__subclasses__()) > 0:
r = recurrent_class_lookup(cl... | This method provides easier access to all writers inheriting Writer class
:param class_name: name of the parser (name of the parser class which should be used)
:type class_name: str
:return: Writer subclass specified by parser_name
:rtype: Writer subclass
:raise ValueError: | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/common.py#L92-L115 | [
"def recurrent_class_lookup(cls):\n for cls in cls.__subclasses__():\n if lower(cls.__name__) == lower(class_name):\n return cls\n elif len(cls.__subclasses__()) > 0:\n r = recurrent_class_lookup(cls)\n if r is not None:\n return r\n return None\n"... | class GetConcreteSubclassMixin(object):
@classmethod
@classmethod
def get_all_subclasses(cls, include_abstract=False):
def recurrent_class_list(cls):
r = []
for cls in cls.__subclasses__():
if include_abstract or not inspect.isabstract(cls):
... |
HEPData/hepdata-converter | hepdata_converter/writers/root_writer.py | ROOT._prepare_outputs | python | def _prepare_outputs(self, data_out, outputs):
compress = ROOTModule.ROOT.CompressionSettings(ROOTModule.ROOT.kZLIB, 1)
if isinstance(data_out, (str, unicode)):
self.file_emulation = True
outputs.append(ROOTModule.TFile.Open(data_out, 'RECREATE', '', compress))
# multiple... | Open a ROOT file with option 'RECREATE' to create a new file (the file will
be overwritten if it already exists), and using the ZLIB compression algorithm
(with compression level 1) for better compatibility with older ROOT versions
(see https://root.cern.ch/doc/v614/release-notes.html#important-... | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/root_writer.py#L405-L425 | null | class ROOT(ArrayWriter):
help = 'Writes to ROOT format (binary) converts tables into files containing TH1 objects'
class_list = [TH3FRootClass, TH2FRootClass, TH1FRootClass, TGraph2DErrorsClass, TGraphAsymmErrorsRootClass]
def __init__(self, *args, **kwargs):
super(ROOT, self).__init__(*args, **kwa... |
HEPData/hepdata-converter | hepdata_converter/writers/root_writer.py | ROOT.write | python | def write(self, data_in, data_out, *args, **kwargs):
self._get_tables(data_in)
self.file_emulation = False
outputs = []
self._prepare_outputs(data_out, outputs)
output = outputs[0]
for i in xrange(len(self.tables)):
table = self.tables[i]
self._w... | :param data_in:
:type data_in: hepconverter.parsers.ParsedData
:param data_out: filelike object
:type data_out: file
:param args:
:param kwargs: | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/root_writer.py#L427-L457 | [
"def _get_tables(self, data_in):\n # get table to work on\n if self.table_id is not None:\n if isinstance(self.table_id, int):\n self.tables.append(data_in.get_table(id=self.table_id))\n else:\n try:\n tab = data_in.get_table(file=self.table_id)\n ... | class ROOT(ArrayWriter):
help = 'Writes to ROOT format (binary) converts tables into files containing TH1 objects'
class_list = [TH3FRootClass, TH2FRootClass, TH1FRootClass, TGraph2DErrorsClass, TGraphAsymmErrorsRootClass]
def __init__(self, *args, **kwargs):
super(ROOT, self).__init__(*args, **kwa... |
HEPData/hepdata-converter | hepdata_converter/writers/array_writer.py | ArrayWriter.process_error_labels | python | def process_error_labels(value):
observed_error_labels = {}
for error in value.get('errors', []):
label = error.get('label', 'error')
if label not in observed_error_labels:
observed_error_labels[label] = 0
observed_error_labels[label] += 1
... | Process the error labels of a dependent variable 'value' to ensure uniqueness. | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/writers/array_writer.py#L140-L160 | null | class ArrayWriter(Writer):
__metaclass__ = abc.ABCMeta
@staticmethod
@staticmethod
def calculate_total_errors(variable, is_number_list, min_errs, max_errs, values, err_breakdown={}):
for i, entry in enumerate(variable['values']):
if not is_number_list[i]: continue # skip non-numer... |
HEPData/hepdata-converter | hepdata_converter/parsers/yaml_parser.py | YAML.parse | python | def parse(self, data_in, *args, **kwargs):
if not os.path.exists(data_in):
raise ValueError("File / Directory does not exist: %s" % data_in)
if os.path.isdir(data_in):
submission_filepath = os.path.join(data_in, 'submission.yaml')
if not os.path.exists(submission_fil... | :param data_in: path to submission.yaml
:param args:
:param kwargs:
:raise ValueError: | train | https://github.com/HEPData/hepdata-converter/blob/354271448980efba86f2f3d27b99d818e75fd90d/hepdata_converter/parsers/yaml_parser.py#L42-L109 | null | class YAML(Parser):
help = 'Parses New HEPData YAML format. Input parameter should be path to ' \
'the directory where submission.yaml file ' \
'is present (or direct filepath to the submission.yaml file)'
pool = Pool()
def __init__(self, *args, **kwargs):
super(YAML, self)._... |
ryukinix/decorating | decorating/decorator.py | Decorator.default_arguments | python | def default_arguments(cls):
func = cls.__init__
args = func.__code__.co_varnames
defaults = func.__defaults__
index = -len(defaults)
return {k: v for k, v in zip(args[index:], defaults)} | Returns the available kwargs of the called class | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/decorator.py#L134-L140 | null | class Decorator(DecoratorManager):
"""Decorator base class to keep easy creating more decorators
triggers:
self.start
self.stop
context_manager:
self.__enter__
self.__exit__
Only this is in generall necessary to implement the class you are writing,
like this:
... |
ryukinix/decorating | decorating/decorator.py | Decorator.recreate | python | def recreate(cls, *args, **kwargs):
cls.check_arguments(kwargs)
first_is_callable = True if any(args) and callable(args[0]) else False
signature = cls.default_arguments()
allowed_arguments = {k: v for k, v in kwargs.items() if k in signature}
if (any(allowed_arguments) or any(arg... | Recreate the class based in your args, multiple uses | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/decorator.py#L143-L155 | null | class Decorator(DecoratorManager):
"""Decorator base class to keep easy creating more decorators
triggers:
self.start
self.stop
context_manager:
self.__enter__
self.__exit__
Only this is in generall necessary to implement the class you are writing,
like this:
... |
ryukinix/decorating | decorating/decorator.py | Decorator.check_arguments | python | def check_arguments(cls, passed):
defaults = list(cls.default_arguments().keys())
template = ("Pass arg {argument:!r} in {cname:!r}, can be a typo? "
"Supported key arguments: {defaults}")
fails = []
for arg in passed:
if arg not in defaults:
... | Put warnings of arguments whose can't be handle by the class | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/decorator.py#L158-L171 | null | class Decorator(DecoratorManager):
"""Decorator base class to keep easy creating more decorators
triggers:
self.start
self.stop
context_manager:
self.__enter__
self.__exit__
Only this is in generall necessary to implement the class you are writing,
like this:
... |
ryukinix/decorating | decorating/color.py | colorize | python | def colorize(printable, color, style='normal', autoreset=True):
if not COLORED: # disable color
return printable
if color not in COLOR_MAP:
raise RuntimeError('invalid color set, no {}'.format(color))
return '{color}{printable}{reset}'.format(
printable=printable,
color=COL... | Colorize some message with ANSI colors specification
:param printable: interface whose has __str__ or __repr__ method
:param color: the colors defined in COLOR_MAP to colorize the text
:style: can be 'normal', 'bold' or 'underline'
:returns: the 'printable' colorized with style | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/color.py#L45-L63 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
"""
Module focused in termcolor operations
If the exection is not attatched in any tty,
so colored is disabled
"""
from ... |
ryukinix/decorating | decorating/general.py | cache | python | def cache(function):
memory = {}
miss = object()
@wraps(function)
def _wrapper(*args):
result = memory.get(args, miss)
if result is miss:
_wrapper.call += 1
result = function(*args)
memory[args] = result
return result
_wrapper.call = 0
... | Function: cache
Summary: Decorator used to cache the input->output
Examples: An fib memoized executes at O(1) time
instead O(e^n)
Attributes:
@param (function): function
Returns: wrapped function
TODO: Give support to functions with kwargs | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/general.py#L50-L75 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
# pylint: disable=redefined-builtin
# pylint: disable=invalid-name
"""
An collection of usefull decorators for debug
and time... |
ryukinix/decorating | decorating/animation.py | space_wave | python | def space_wave(phase, amplitude=12, frequency=0.1):
wave = cycle(horizontal)
return ''.join((next(wave) for x in range
(int((amplitude + 1) * abs(sin(frequency * (phase))))))) | Function: space_wave
Summary: This function is used to generate a wave-like padding
spacement based on the variable lambda
Examples: >>> print('\n'.join(space_wave(x) for x in range(100))
█
███
████
██████
███████
█... | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L114-L151 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
# pylint: disable=no-member
# pylint: disable=C0103
# pylint: disable=too-few-public-methods
"""
This module was be done to hand... |
ryukinix/decorating | decorating/animation.py | AnimatedDecorator.start | python | def start(self, autopush=True):
if self.enabled:
if autopush:
self.push_message(self.message)
self.spinner.message = ' - '.join(self.animation.messages)
if not self.spinner.running:
self.animation.thread = threading.Thread(target=_spinner,
... | Start a new animation instance | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L235-L246 | [
"def push_message(cls, message):\n \"\"\"Push a new message for the public messages stack\"\"\"\n return cls.animation.messages.append(message)\n"
] | class AnimatedDecorator(decorator.Decorator):
"""The animated decorator from hell
You can use this these way:
@animated
def slow():
heavy_stuff()
As well with custom messages
@animated('WOOOOW')
def download_the_universe():
while True:
... |
ryukinix/decorating | decorating/animation.py | AnimatedDecorator.stop | python | def stop(cls):
if AnimatedDecorator._enabled:
if cls.spinner.running:
cls.spinner.running = False
cls.animation.thread.join()
if any(cls.animation.messages):
cls.pop_message()
sys.stdout = sys.__stdout__ | Stop the thread animation gracefully and reset_message | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L249-L259 | [
"def pop_message(cls):\n \"\"\"Pop a new message (last) from the public message stack\"\"\"\n return cls.animation.messages.pop(-1)\n"
] | class AnimatedDecorator(decorator.Decorator):
"""The animated decorator from hell
You can use this these way:
@animated
def slow():
heavy_stuff()
As well with custom messages
@animated('WOOOOW')
def download_the_universe():
while True:
... |
ryukinix/decorating | decorating/animation.py | AnimatedDecorator.auto_message | python | def auto_message(self, args):
if any(args) and callable(args[0]) and not self.message:
return args[0].__name__
elif not self.message:
return self.default_message
else:
return self.message | Try guess the message by the args passed
args: a set of args passed on the wrapper __call__ in
the definition above.
if the object already have some message (defined in __init__),
we don't change that. If the first arg is a function, so is decorated
without argument, use ... | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L296-L315 | null | class AnimatedDecorator(decorator.Decorator):
"""The animated decorator from hell
You can use this these way:
@animated
def slow():
heavy_stuff()
As well with custom messages
@animated('WOOOOW')
def download_the_universe():
while True:
... |
ryukinix/decorating | decorating/animation.py | WritingDecorator.start | python | def start(self):
self.streams.append(sys.stdout)
sys.stdout = self.stream | Activate the TypingStream on stdout | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L353-L356 | null | class WritingDecorator(decorator.Decorator):
"""A writing class context to simulate a delayed stream
You can do something like that:
with writing(delay=0.3):
print('LOL!!! This is so awesome!')
Or, as expected for this lib, using as decorator!
@writing
def somebody_talking():
... |
ryukinix/decorating | decorating/animation.py | WritingDecorator.stop | python | def stop(cls):
if any(cls.streams):
sys.stdout = cls.streams.pop(-1)
else:
sys.stdout = sys.__stdout__ | Change back the normal stdout after the end | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/animation.py#L359-L364 | null | class WritingDecorator(decorator.Decorator):
"""A writing class context to simulate a delayed stream
You can do something like that:
with writing(delay=0.3):
print('LOL!!! This is so awesome!')
Or, as expected for this lib, using as decorator!
@writing
def somebody_talking():
... |
ryukinix/decorating | decorating/stream.py | Unbuffered.write | python | def write(self, message, flush=True):
self.stream.write(message)
if flush:
self.stream.flush() | Function: write
Summary: write method on the default stream
Examples: >>> stream.write('message')
'message'
Attributes:
@param (message): str-like content to send on stream
@param (flush) default=True: flush the stdout after write
Returns: None | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/stream.py#L45-L58 | null | class Unbuffered(Stream):
"""Unbuffered whose flush automaticly
That way we don't need flush after a write.
"""
lock = Lock()
def __init__(self, stream):
super(Unbuffered, self).__init__(stream)
self.stream = stream
def __getattr__(self, attr):
return getattr(self.... |
ryukinix/decorating | decorating/stream.py | Animation.write | python | def write(self, message, autoerase=True):
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) | Send something for stdout and erased after delay | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/stream.py#L82-L88 | [
"def write(self, message, flush=True):\n \"\"\"\n Function: write\n Summary: write method on the default stream\n Examples: >>> stream.write('message')\n 'message'\n Attributes:\n @param (message): str-like content to send on stream\n @param (flush) default=True: flush the ... | class Animation(Unbuffered):
"""A stream unbuffered whose write & erase at interval
After you write something, you can easily clean the buffer
and restart the points of the older message.
stream = Animation(stream, delay=0.5)
self.write('message')
"""
last_message = ''
ansi_escape = ... |
ryukinix/decorating | decorating/stream.py | Animation.erase | python | def erase(self, message=None):
if not message:
message = self.last_message
# Move cursor to the beginning of line
super(Animation, self).write("\033[G")
# Erase in line from cursor
super(Animation, self).write("\033[K") | Erase something whose you write before: message | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/stream.py#L90-L97 | [
"def write(self, message, flush=True):\n \"\"\"\n Function: write\n Summary: write method on the default stream\n Examples: >>> stream.write('message')\n 'message'\n Attributes:\n @param (message): str-like content to send on stream\n @param (flush) default=True: flush the ... | class Animation(Unbuffered):
"""A stream unbuffered whose write & erase at interval
After you write something, you can easily clean the buffer
and restart the points of the older message.
stream = Animation(stream, delay=0.5)
self.write('message')
"""
last_message = ''
ansi_escape = ... |
ryukinix/decorating | decorating/stream.py | Clean.write | python | def write(self, message, flush=False):
# this need be threadsafe because the concurrent spinning running on
# the stderr
with self.lock:
self.paralell_stream.erase()
super(Clean, self).write(message, flush) | Write something on the default stream with a prefixed message | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/stream.py#L120-L126 | [
"def write(self, message, flush=True):\n \"\"\"\n Function: write\n Summary: write method on the default stream\n Examples: >>> stream.write('message')\n 'message'\n Attributes:\n @param (message): str-like content to send on stream\n @param (flush) default=True: flush the ... | class Clean(Unbuffered):
"""A stream wrapper to prepend '\n' in each write
This is used to not break the animations when he is activated
So in the start_animation we do:
sys.stdout = Clean(sys.stdout, <paralell-stream>)
In the stop_animation we do:
sys.stdout = sys.__stdout__Whose par... |
ryukinix/decorating | decorating/stream.py | Writting.write | python | def write(self, message, flush=True):
if isinstance(message, bytes): # pragma: no cover
message = message.decode('utf-8')
for char in message:
time.sleep(self.delay * (4 if char == '\n' else 1))
super(Writting, self).write(char, flush) | A Writting like write method, delayed at each char | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/stream.py#L148-L155 | [
"def write(self, message, flush=True):\n \"\"\"\n Function: write\n Summary: write method on the default stream\n Examples: >>> stream.write('message')\n 'message'\n Attributes:\n @param (message): str-like content to send on stream\n @param (flush) default=True: flush the ... | class Writting(Unbuffered):
"""
The Writting stream is a delayed stream whose
simulate an user Writting something.
The base class is the AnimationStream
"""
def __init__(self, stream, delay=0.08):
super(Writting, self).__init__(stream)
self.delay = delay
|
ryukinix/decorating | decorating/debugging.py | debug | python | def debug(function):
@wraps(function)
def _wrapper(*args, **kwargs):
result = function(*args, **kwargs)
for key, value in kwargs.items():
args += tuple(['{}={!r}'.format(key, value)])
if len(args) == 1:
args = '({})'.format(args[0])
print('@{0}{1} -> {2}'... | Function: debug
Summary: decorator to debug a function
Examples: at the execution of the function wrapped,
the decorator will allows to print the
input and output of each execution
Attributes:
@param (function): function
Returns: wrapped function | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/debugging.py#L20-L43 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
"""
An collection of usefull decorators for debug
and time evaluation of functions flow
"""
from __future__ import unicode_lit... |
ryukinix/decorating | decorating/debugging.py | counter | python | def counter(function):
@wraps(function)
def _wrapper(*args, **kwargs):
_wrapper.count += 1
res = function(*args, **kwargs)
funcname = function.__name__
count = _wrapper.count
print("{} has been used: {}x".format(funcname, count))
return res
_wrapper.count = 0... | Function: counter
Summary: Decorator to count the number of a function is executed each time
Examples: You can use that to had a progress of heally heavy
computation without progress feedback
Attributes:
@param (function): function
Returns: wrapped function | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/debugging.py#L46-L66 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
"""
An collection of usefull decorators for debug
and time evaluation of functions flow
"""
from __future__ import unicode_lit... |
ryukinix/decorating | decorating/debugging.py | count_time | python | def count_time(function):
@wraps(function)
def _wrapper(*args, **kwargs):
before = time()
result = function(*args, **kwargs)
diff = time() - before
funcname = function.__name__
print("{!r} func leave it {:.2f} ms to finish".format(funcname, diff))
_wrapper.time = ... | Function: count_time
Summary: get the time to finish a function
print at the end that time to stdout
Examples: <NONE>
Attributes:
@param (function): function
Returns: wrapped function | train | https://github.com/ryukinix/decorating/blob/df78c3f87800205701704c0bc0fb9b6bb908ba7e/decorating/debugging.py#L69-L90 | null | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright © Manoel Vilela 2016
#
# @project: Decorating
# @author: Manoel Vilela
# @email: manoel_vilela@engineer.com
#
"""
An collection of usefull decorators for debug
and time evaluation of functions flow
"""
from __future__ import unicode_lit... |
inveniosoftware/invenio-indexer | examples/app.py | records | python | def records():
with db.session.begin_nested():
for idx in range(20):
# create the record
id_ = uuid.uuid4()
Record.create({
'title': 'LHC experiment {}'.format(idx),
'description': 'Data from experiment {}.'.format(idx),
'ty... | Load test data fixture. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/examples/app.py#L84-L104 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
r"""Minimal Flask application example for development.
SPHINX-START
Run ElasticSea... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | Producer.publish | python | def publish(self, data, **kwargs):
assert data.get('op') in {'index', 'create', 'delete', 'update'}
return super(Producer, self).publish(data, **kwargs) | Validate operation type. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L36-L39 | null | class Producer(KombuProducer):
"""Producer validating published messages.
For more information visit :class:`kombu:kombu.Producer`.
"""
|
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer.index | python | def index(self, record):
index, doc_type = self.record_to_index(record)
return self.client.index(
id=str(record.id),
version=record.revision_id,
version_type=self._version_type,
index=index,
doc_type=doc_type,
body=self._prepare_re... | Index a record.
The caller is responsible for ensuring that the record has already been
committed to the database. If a newer version of a record has already
been indexed then the provided record will not be indexed. This
behavior can be controlled by providing a different ``version_typ... | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L106-L126 | [
"def record_to_index(self, record):\n \"\"\"Get index/doc_type given a record.\n\n :param record: The record where to look for the information.\n :returns: A tuple (index, doc_type).\n \"\"\"\n return self._record_to_index(record)\n",
"def _prepare_record(record, index, doc_type):\n \"\"\"Prepar... | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer.delete | python | def delete(self, record):
index, doc_type = self.record_to_index(record)
return self.client.delete(
id=str(record.id),
index=index,
doc_type=doc_type,
) | Delete a record.
:param record: Record instance. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L135-L146 | [
"def record_to_index(self, record):\n \"\"\"Get index/doc_type given a record.\n\n :param record: The record where to look for the information.\n :returns: A tuple (index, doc_type).\n \"\"\"\n return self._record_to_index(record)\n"
] | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer.process_bulk_queue | python | def process_bulk_queue(self, es_bulk_kwargs=None):
with current_celery_app.pool.acquire(block=True) as conn:
consumer = Consumer(
connection=conn,
queue=self.mq_queue.name,
exchange=self.mq_exchange.name,
routing_key=self.mq_routing_key... | Process bulk indexing queue.
:param dict es_bulk_kwargs: Passed to
:func:`elasticsearch:elasticsearch.helpers.bulk`. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L166-L193 | [
"def _actionsiter(self, message_iterator):\n \"\"\"Iterate bulk actions.\n\n :param message_iterator: Iterator yielding messages from a queue.\n \"\"\"\n for message in message_iterator:\n payload = message.decode()\n try:\n if payload['op'] == 'delete':\n yield s... | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer.create_producer | python | def create_producer(self):
with current_celery_app.pool.acquire(block=True) as conn:
yield Producer(
conn,
exchange=self.mq_exchange,
routing_key=self.mq_routing_key,
auto_declare=True,
) | Context manager that yields an instance of ``Producer``. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L196-L204 | null | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer._bulk_op | python | def _bulk_op(self, record_id_iterator, op_type, index=None, doc_type=None):
with self.create_producer() as producer:
for rec in record_id_iterator:
producer.publish(dict(
id=str(rec),
op=op_type,
index=index,
... | Index record in Elasticsearch asynchronously.
:param record_id_iterator: Iterator that yields record UUIDs.
:param op_type: Indexing operation (one of ``index``, ``create``,
``delete`` or ``update``).
:param index: The Elasticsearch index. (Default: ``None``)
:param doc_type... | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L209-L225 | null | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer._actionsiter | python | def _actionsiter(self, message_iterator):
for message in message_iterator:
payload = message.decode()
try:
if payload['op'] == 'delete':
yield self._delete_action(payload)
else:
yield self._index_action(payload)
... | Iterate bulk actions.
:param message_iterator: Iterator yielding messages from a queue. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L227-L246 | [
"def _delete_action(self, payload):\n \"\"\"Bulk delete action.\n\n :param payload: Decoded message body.\n :returns: Dictionary defining an Elasticsearch bulk 'delete' action.\n \"\"\"\n index, doc_type = payload.get('index'), payload.get('doc_type')\n if not (index and doc_type):\n record... | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer._delete_action | python | def _delete_action(self, payload):
index, doc_type = payload.get('index'), payload.get('doc_type')
if not (index and doc_type):
record = Record.get_record(payload['id'])
index, doc_type = self.record_to_index(record)
return {
'_op_type': 'delete',
... | Bulk delete action.
:param payload: Decoded message body.
:returns: Dictionary defining an Elasticsearch bulk 'delete' action. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L248-L264 | [
"def record_to_index(self, record):\n \"\"\"Get index/doc_type given a record.\n\n :param record: The record where to look for the information.\n :returns: A tuple (index, doc_type).\n \"\"\"\n return self._record_to_index(record)\n"
] | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer._index_action | python | def _index_action(self, payload):
record = Record.get_record(payload['id'])
index, doc_type = self.record_to_index(record)
return {
'_op_type': 'index',
'_index': index,
'_type': doc_type,
'_id': str(record.id),
'_version': record.revi... | Bulk index action.
:param payload: Decoded message body.
:returns: Dictionary defining an Elasticsearch bulk 'index' action. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L266-L283 | [
"def record_to_index(self, record):\n \"\"\"Get index/doc_type given a record.\n\n :param record: The record where to look for the information.\n :returns: A tuple (index, doc_type).\n \"\"\"\n return self._record_to_index(record)\n",
"def _prepare_record(record, index, doc_type):\n \"\"\"Prepar... | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/api.py | RecordIndexer._prepare_record | python | def _prepare_record(record, index, doc_type):
if current_app.config['INDEXER_REPLACE_REFS']:
data = copy.deepcopy(record.replace_refs())
else:
data = record.dumps()
data['_created'] = pytz.utc.localize(record.created).isoformat() \
if record.created else None... | Prepare record data for indexing.
:param record: The record to prepare.
:param index: The Elasticsearch index.
:param doc_type: The Elasticsearch document type.
:returns: The record metadata. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/api.py#L286-L313 | null | class RecordIndexer(object):
r"""Provide an interface for indexing records in Elasticsearch.
Bulk indexing works by queuing requests for indexing records and processing
these requests in bulk.
"""
def __init__(self, search_client=None, exchange=None, queue=None,
routing_key=None, ... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | run | python | def run(delayed, concurrency, version_type=None, queue=None,
raise_on_error=True):
if delayed:
celery_kwargs = {
'kwargs': {
'version_type': version_type,
'es_bulk_kwargs': {'raise_on_error': raise_on_error},
}
}
click.secho(
... | Run bulk record indexing. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L43-L63 | [
"def process_bulk_queue(self, es_bulk_kwargs=None):\n \"\"\"Process bulk indexing queue.\n\n :param dict es_bulk_kwargs: Passed to\n :func:`elasticsearch:elasticsearch.helpers.bulk`.\n \"\"\"\n with current_celery_app.pool.acquire(block=True) as conn:\n consumer = Consumer(\n co... | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | reindex | python | def reindex(pid_type):
click.secho('Sending records to indexing queue ...', fg='green')
query = (x[0] for x in PersistentIdentifier.query.filter_by(
object_type='rec', status=PIDStatus.REGISTERED
).filter(
PersistentIdentifier.pid_type.in_(pid_type)
).values(
PersistentIdentifie... | Reindex all records.
:param pid_type: Pid type. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L72-L88 | [
"def bulk_index(self, record_id_iterator):\n \"\"\"Bulk index records.\n\n :param record_id_iterator: Iterator yielding record UUIDs.\n \"\"\"\n self._bulk_op(record_id_iterator, 'index')\n"
] | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | process_actions | python | def process_actions(actions):
queue = current_app.config['INDEXER_MQ_QUEUE']
with establish_connection() as c:
q = queue(c)
for action in actions:
q = action(q) | Process queue actions. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L98-L104 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | init_queue | python | def init_queue():
def action(queue):
queue.declare()
click.secho('Indexing queue has been initialized.', fg='green')
return queue
return action | Initialize indexing queue. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L108-L114 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | purge_queue | python | def purge_queue():
def action(queue):
queue.purge()
click.secho('Indexing queue has been purged.', fg='green')
return queue
return action | Purge indexing queue. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L118-L124 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/cli.py | delete_queue | python | def delete_queue():
def action(queue):
queue.delete()
click.secho('Indexing queue has been deleted.', fg='green')
return queue
return action | Delete indexing queue. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/cli.py#L128-L134 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""CLI for indexer."""
from __future__ import absolute_import, print_function
impor... |
inveniosoftware/invenio-indexer | invenio_indexer/utils.py | default_record_to_index | python | def default_record_to_index(record):
index_names = current_search.mappings.keys()
schema = record.get('$schema', '')
if isinstance(schema, dict):
schema = schema.get('$ref', '')
index, doc_type = schema_to_index(schema, index_names=index_names)
if index and doc_type:
return index, ... | Get index/doc_type given a record.
It tries to extract from `record['$schema']` the index and doc_type.
If it fails, return the default values.
:param record: The record object.
:returns: Tuple (index, doc_type). | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/utils.py#L16-L36 | null | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2016-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Utility functions for data processing."""
from flask import current_app
from inve... |
inveniosoftware/invenio-indexer | invenio_indexer/ext.py | InvenioIndexer.init_app | python | def init_app(self, app):
self.init_config(app)
app.extensions['invenio-indexer'] = self
hooks = app.config.get('INDEXER_BEFORE_INDEX_HOOKS', [])
for hook in hooks:
if isinstance(hook, six.string_types):
hook = import_string(hook)
before_record_ind... | Flask application initialization.
:param app: The Flask application. | train | https://github.com/inveniosoftware/invenio-indexer/blob/1460aa8976b449d9a3a99d356322b158e9be6f80/invenio_indexer/ext.py#L34-L46 | [
"def init_config(self, app):\n \"\"\"Initialize configuration.\n\n :param app: The Flask application.\n \"\"\"\n for k in dir(config):\n if k.startswith('INDEXER_'):\n app.config.setdefault(k, getattr(config, k))\n"
] | class InvenioIndexer(object):
"""Invenio-Indexer extension."""
def __init__(self, app=None):
"""Extension initialization.
:param app: The Flask application. (Default: ``None``)
"""
if app:
self.init_app(app)
def init_config(self, app):
"""Initialize co... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.register_event | python | def register_event(self, *names):
for name in names:
if name in self.__events:
continue
self.__events[name] = Event(name) | Registers new events after instance creation
Args:
*names (str): Name or names of the events to register | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L125-L134 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.bind | python | def bind(self, **kwargs):
aio_loop = kwargs.pop('__aio_loop__', None)
props = self.__property_events
events = self.__events
for name, cb in kwargs.items():
if name in props:
e = props[name]
else:
e = events[name]
e.add_l... | Subscribes to events or to :class:`~pydispatch.properties.Property` updates
Keyword arguments are used with the Event or Property names as keys
and the callbacks as values::
class Foo(Dispatcher):
name = Property()
foo = Foo()
foo.bind(name=my_list... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L135-L198 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.unbind | python | def unbind(self, *args):
props = self.__property_events.values()
events = self.__events.values()
for arg in args:
for prop in props:
prop.remove_listener(arg)
for e in events:
e.remove_listener(arg) | Unsubscribes from events or :class:`~pydispatch.properties.Property` updates
Multiple arguments can be given. Each of which can be either the method
that was used for the original call to :meth:`bind` or an instance
object.
If an instance of an object is supplied, any previously bound ... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L199-L215 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.emit | python | def emit(self, name, *args, **kwargs):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e(*args, **kwargs) | Dispatches an event to any subscribed listeners
Note:
If a listener returns :obj:`False`, the event will stop dispatching to
other listeners. Any other return value is ignored.
Args:
name (str): The name of the :class:`Event` to dispatch
*args (Optional)... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L236-L251 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.get_dispatcher_event | python | def get_dispatcher_event(self, name):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e | Retrieves an Event object by name
Args:
name (str): The name of the :class:`Event` or
:class:`~pydispatch.properties.Property` object to retrieve
Returns:
The :class:`Event` instance for the event or property definition
.. versionadded:: 0.1.0 | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L252-L267 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/dispatch.py | Dispatcher.emission_lock | python | def emission_lock(self, name):
e = self.__property_events.get(name)
if e is None:
e = self.__events[name]
return e.emission_lock | Holds emission of events and dispatches the last event on release
The context manager returned will store the last event data called by
:meth:`emit` and prevent callbacks until it exits. On exit, it will
dispatch the last event captured (if any)::
class Foo(Dispatcher):
... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/dispatch.py#L268-L309 | null | class Dispatcher(object):
"""Core class used to enable all functionality in the library
Interfaces with :class:`Event` and :class:`~pydispatch.properties.Property`
objects upon instance creation.
Events can be created by calling :meth:`register_event` or by the subclass
definition::
class... |
nocarryr/python-dispatch | pydispatch/properties.py | Property._on_change | python | def _on_change(self, obj, old, value, **kwargs):
kwargs['property'] = self
obj.emit(self.name, obj, value, old=old, **kwargs) | Called internally to emit changes from the instance object
The keyword arguments here will be passed to callbacks through the
instance object's :meth:`~pydispatch.dispatch.Dispatcher.emit` method.
Keyword Args:
property: The :class:`Property` instance. This is useful if multiple
... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/properties.py#L96-L114 | null | class Property(object):
"""Defined on the class level to create an observable attribute
Args:
default (Optional): If supplied, this will be the default value of the
Property for all instances of the class. Otherwise :obj:`None`
Attributes:
name (str): The name of the Property a... |
nocarryr/python-dispatch | pydispatch/utils.py | WeakMethodContainer.add_method | python | def add_method(self, m, **kwargs):
if isinstance(m, types.FunctionType):
self['function', id(m)] = m
else:
f, obj = get_method_vars(m)
wrkey = (f, id(obj))
self[wrkey] = obj | Add an instance method or function
Args:
m: The instance method or function to store | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L49-L60 | [
"def get_method_vars(m):\n if PY2:\n f = m.im_func\n obj = m.im_self\n else:\n f = m.__func__\n obj = m.__self__\n return f, obj\n"
] | class WeakMethodContainer(weakref.WeakValueDictionary):
"""Container to store weak references to callbacks
Instance methods are stored using the underlying :term:`function` object
and the instance id (using :func:`id(obj) <id>`) as the key (a two-tuple)
and the object itself as the value. This ensures ... |
nocarryr/python-dispatch | pydispatch/utils.py | WeakMethodContainer.del_method | python | def del_method(self, m):
if isinstance(m, types.FunctionType) and not iscoroutinefunction(m):
wrkey = ('function', id(m))
else:
f, obj = get_method_vars(m)
wrkey = (f, id(obj))
if wrkey in self:
del self[wrkey] | Remove an instance method or function if it exists
Args:
m: The instance method or function to remove | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L61-L73 | [
"def get_method_vars(m):\n if PY2:\n f = m.im_func\n obj = m.im_self\n else:\n f = m.__func__\n obj = m.__self__\n return f, obj\n",
"def iscoroutinefunction(obj):\n if AIO_AVAILABLE:\n return asyncio.iscoroutinefunction(obj)\n return False\n"
] | class WeakMethodContainer(weakref.WeakValueDictionary):
"""Container to store weak references to callbacks
Instance methods are stored using the underlying :term:`function` object
and the instance id (using :func:`id(obj) <id>`) as the key (a two-tuple)
and the object itself as the value. This ensures ... |
nocarryr/python-dispatch | pydispatch/utils.py | WeakMethodContainer.del_instance | python | def del_instance(self, obj):
to_remove = set()
for wrkey, _obj in self.iter_instances():
if obj is _obj:
to_remove.add(wrkey)
for wrkey in to_remove:
del self[wrkey] | Remove any stored instance methods that belong to an object
Args:
obj: The instance object to remove | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L74-L85 | [
"def iter_instances(self):\n \"\"\"Iterate over the stored objects\n\n Yields:\n wrkey: The two-tuple key used to store the object\n obj: The instance or function object\n \"\"\"\n for wrkey in set(self.keys()):\n obj = self.get(wrkey)\n if obj is None:\n continue\... | class WeakMethodContainer(weakref.WeakValueDictionary):
"""Container to store weak references to callbacks
Instance methods are stored using the underlying :term:`function` object
and the instance id (using :func:`id(obj) <id>`) as the key (a two-tuple)
and the object itself as the value. This ensures ... |
nocarryr/python-dispatch | pydispatch/utils.py | WeakMethodContainer.iter_instances | python | def iter_instances(self):
for wrkey in set(self.keys()):
obj = self.get(wrkey)
if obj is None:
continue
yield wrkey, obj | Iterate over the stored objects
Yields:
wrkey: The two-tuple key used to store the object
obj: The instance or function object | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L86-L97 | [
"def keys(self):\n if PY2:\n return self.iterkeys()\n return super(WeakMethodContainer, self).keys()\n"
] | class WeakMethodContainer(weakref.WeakValueDictionary):
"""Container to store weak references to callbacks
Instance methods are stored using the underlying :term:`function` object
and the instance id (using :func:`id(obj) <id>`) as the key (a two-tuple)
and the object itself as the value. This ensures ... |
nocarryr/python-dispatch | pydispatch/utils.py | WeakMethodContainer.iter_methods | python | def iter_methods(self):
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
if f == 'function':
yield self[wrkey]
else:
yield getattr(obj, f.__name__) | Iterate over stored functions and instance methods
Yields:
Instance methods or function objects | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/utils.py#L98-L109 | [
"def iter_instances(self):\n \"\"\"Iterate over the stored objects\n\n Yields:\n wrkey: The two-tuple key used to store the object\n obj: The instance or function object\n \"\"\"\n for wrkey in set(self.keys()):\n obj = self.get(wrkey)\n if obj is None:\n continue\... | class WeakMethodContainer(weakref.WeakValueDictionary):
"""Container to store weak references to callbacks
Instance methods are stored using the underlying :term:`function` object
and the instance id (using :func:`id(obj) <id>`) as the key (a two-tuple)
and the object itself as the value. This ensures ... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioSimpleLock.acquire | python | def acquire(self, blocking=True, timeout=-1):
result = self.lock.acquire(blocking, timeout)
return result | Acquire the :attr:`lock`
Args:
blocking (bool): See :meth:`threading.Lock.acquire`
timeout (float): See :meth:`threading.Lock.acquire`
Returns:
bool: :obj:`True` if the lock was acquired, otherwise :obj:`False` | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L61-L73 | null | class AioSimpleLock(object):
""":class:`asyncio.Lock` alternative backed by a :class:`threading.Lock`
This is a context manager that supports use in both :keyword:`with` and
:keyword:`async with` context blocks.
Attributes:
lock: Instance of :class:`threading.Lock`
.. versionadded:: 0.1.0... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioSimpleLock.acquire_async | python | async def acquire_async(self):
r = self.acquire(blocking=False)
while not r:
await asyncio.sleep(.01)
r = self.acquire(blocking=False) | Acquire the :attr:`lock` asynchronously | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L83-L90 | [
"def acquire(self, blocking=True, timeout=-1):\n \"\"\"Acquire the :attr:`lock`\n\n Args:\n blocking (bool): See :meth:`threading.Lock.acquire`\n timeout (float): See :meth:`threading.Lock.acquire`\n\n Returns:\n bool: :obj:`True` if the lock was acquired, otherwise :obj:`False`\n\n ... | class AioSimpleLock(object):
""":class:`asyncio.Lock` alternative backed by a :class:`threading.Lock`
This is a context manager that supports use in both :keyword:`with` and
:keyword:`async with` context blocks.
Attributes:
lock: Instance of :class:`threading.Lock`
.. versionadded:: 0.1.0... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioEventWaiter.trigger | python | def trigger(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
self.aio_event.set() | Called on event emission and notifies the :meth:`wait` method
Called by :class:`AioEventWaiters` when the
:class:`~pydispatch.dispatch.Event` instance is dispatched.
Positional and keyword arguments are stored as instance attributes for
use in the :meth:`wait` method and :attr:`aio_eve... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L118-L129 | null | class AioEventWaiter(object):
"""Stores necessary information for a single "waiter"
Used by :class:`AioEventWaiters` to handle :keyword:`awaiting <await>`
an :class:`~pydispatch.dispatch.Event` on a specific
:class:`event loop <asyncio.BaseEventLoop>`
Attributes:
loop: The :class:`EventLoo... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioEventWaiters.add_waiter | python | async def add_waiter(self):
loop = asyncio.get_event_loop()
async with self.lock:
waiter = AioEventWaiter(loop)
self.waiters.add(waiter)
return waiter | Add a :class:`AioEventWaiter` to the :attr:`waiters` container
The event loop to use for :attr:`AioEventWaiter.loop` is found in the
current context using :func:`asyncio.get_event_loop`
Returns:
waiter: The created :class:`AioEventWaiter` instance | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L162-L176 | null | class AioEventWaiters(object):
"""Container used to manage :keyword:`await` use with events
Used by :class:`pydispatch.dispatch.Event` when it is
:keyword:`awaited <await>`
Attributes:
waiters (set): Instances of :class:`AioEventWaiter` currently "awaiting"
the event
lock (... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioWeakMethodContainer.add_method | python | def add_method(self, loop, callback):
f, obj = get_method_vars(callback)
wrkey = (f, id(obj))
self[wrkey] = obj
self.event_loop_map[wrkey] = loop | Add a coroutine function
Args:
loop: The :class:`event loop <asyncio.BaseEventLoop>` instance
on which to schedule callbacks
callback: The :term:`coroutine function` to add | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L229-L240 | [
"def get_method_vars(m):\n if PY2:\n f = m.im_func\n obj = m.im_self\n else:\n f = m.__func__\n obj = m.__self__\n return f, obj\n"
] | class AioWeakMethodContainer(WeakMethodContainer):
"""Storage for coroutine functions as weak references
.. versionadded:: 0.1.0
"""
def __init__(self):
super().__init__()
def remove(wr, selfref=ref(self)):
self = selfref()
if self is not None:
if... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioWeakMethodContainer.iter_methods | python | def iter_methods(self):
for wrkey, obj in self.iter_instances():
f, obj_id = wrkey
loop = self.event_loop_map[wrkey]
m = getattr(obj, f.__name__)
yield loop, m | Iterate over stored coroutine functions
Yields:
Stored :term:`coroutine function` objects
.. seealso:: :meth:`pydispatch.utils.WeakMethodContainer.iter_instances` | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L248-L260 | [
"def iter_instances(self):\n \"\"\"Iterate over the stored objects\n\n .. seealso:: :meth:`pydispatch.utils.WeakMethodContainer.iter_instances`\n \"\"\"\n with _IterationGuard(self):\n yield from super().iter_instances()\n"
] | class AioWeakMethodContainer(WeakMethodContainer):
"""Storage for coroutine functions as weak references
.. versionadded:: 0.1.0
"""
def __init__(self):
super().__init__()
def remove(wr, selfref=ref(self)):
self = selfref()
if self is not None:
if... |
nocarryr/python-dispatch | pydispatch/aioutils.py | AioWeakMethodContainer.submit_coroutine | python | def submit_coroutine(self, coro, loop):
async def _do_call(_coro):
with _IterationGuard(self):
await _coro
asyncio.run_coroutine_threadsafe(_do_call(coro), loop=loop) | Schedule and await a coroutine on the specified loop
The coroutine is wrapped and scheduled using
:func:`asyncio.run_coroutine_threadsafe`. While the coroutine is
"awaited", the result is not available as method returns immediately.
Args:
coro: The :term:`coroutine` to sche... | train | https://github.com/nocarryr/python-dispatch/blob/7c5ca03835c922cbfdfd62772c9e560062c954c7/pydispatch/aioutils.py#L264-L283 | [
"async def _do_call(_coro):\n with _IterationGuard(self):\n await _coro\n"
] | class AioWeakMethodContainer(WeakMethodContainer):
"""Storage for coroutine functions as weak references
.. versionadded:: 0.1.0
"""
def __init__(self):
super().__init__()
def remove(wr, selfref=ref(self)):
self = selfref()
if self is not None:
if... |
wroberts/fsed | fsed/utils.py | open_file | python | def open_file(filename, mode='rb'):
if (('r' not in mode or hasattr(filename, 'read')) and
(('a' not in mode and 'w' not in mode) or hasattr(filename, 'write')) and
hasattr(filename, '__iter__')):
return filename
elif isinstance(filename, string_type):
if filename == '-' and 'r' ... | Opens a file for access with the given mode. This function
transparently wraps gzip and xz files as well as normal files.
You can also open zip files using syntax like:
f = utils.open_file('../semcor-parsed.zip:semcor000.txt') | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/utils.py#L15-L55 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
utils.py
(c) Will Roberts 12 December, 2015
Utility functions.
'''
from __future__ import absolute_import
from fsed.compat import PY3, string_type
import sys
|
wroberts/fsed | fsed/ahocorasick.py | boundary_transform | python | def boundary_transform(seq, force_edges = True):
'''
Wraps all word transitions with a boundary token character (\x00).
If desired (with ``force_edges`` set to ``True``), this inserts
the boundary character at the beginning and end of the string.
Arguments:
- `seq`:
- `force_edges = True`:
... | Wraps all word transitions with a boundary token character (\x00).
If desired (with ``force_edges`` set to ``True``), this inserts
the boundary character at the beginning and end of the string.
Arguments:
- `seq`:
- `force_edges = True`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L404-L419 | [
"def boundary_words(seq):\n '''\n Wraps all word transitions with a boundary token character (\\x00).\n\n Arguments:\n - `seq`:\n '''\n in_word = None\n for char in seq:\n if char == '\\x00' and in_word is not None:\n in_word = not in_word\n elif char in WHITESPACE_CHAR... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
ahocorasick.py
(c) Will Roberts 18 June, 2015
Second attempt writing Aho-Corasick string matching in Python.
'''
from __future__ import absolute_import, print_function, unicode_literals
from collections import deque
# ==============================================... |
wroberts/fsed | fsed/ahocorasick.py | boundary_words | python | def boundary_words(seq):
'''
Wraps all word transitions with a boundary token character (\x00).
Arguments:
- `seq`:
'''
in_word = None
for char in seq:
if char == '\x00' and in_word is not None:
in_word = not in_word
elif char in WHITESPACE_CHARS:
if ... | Wraps all word transitions with a boundary token character (\x00).
Arguments:
- `seq`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L421-L440 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
ahocorasick.py
(c) Will Roberts 18 June, 2015
Second attempt writing Aho-Corasick string matching in Python.
'''
from __future__ import absolute_import, print_function, unicode_literals
from collections import deque
# ==============================================... |
wroberts/fsed | fsed/ahocorasick.py | remove_duplicates | python | def remove_duplicates(seq):
'''
Removes duplicate boundary token characters from the given
character iterable.
Arguments:
- `seq`:
'''
last_boundary = False
for char in seq:
if char == '\x00':
if not last_boundary:
last_boundary = True
... | Removes duplicate boundary token characters from the given
character iterable.
Arguments:
- `seq`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L455-L471 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
ahocorasick.py
(c) Will Roberts 18 June, 2015
Second attempt writing Aho-Corasick string matching in Python.
'''
from __future__ import absolute_import, print_function, unicode_literals
from collections import deque
# ==============================================... |
wroberts/fsed | fsed/ahocorasick.py | Trie.dfs | python | def dfs(self):
'''
Depth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`.
'''
yield (self.root, None)
todo = [(self.root[char], self.root) for char in self.root]
while todo:
current, paren... | Depth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L121-L132 | null | class Trie(object):
'''A Trie which stores values.'''
def __init__(self):
'''Constructor.'''
self.root = TrieNode()
def __contains__(self, seq):
current = self.root
for char in seq:
if char not in current:
return False
current = curre... |
wroberts/fsed | fsed/ahocorasick.py | Trie.bfs | python | def bfs(self):
'''
Breadth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`.
'''
yield (self.root, None)
todo = deque([(self.root[char], self.root) for char in self.root])
while todo:
curre... | Breadth-first search generator. Yields `(node, parent)` for every
node in the tree, beginning with `(self.root, None)`. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L134-L145 | null | class Trie(object):
'''A Trie which stores values.'''
def __init__(self):
'''Constructor.'''
self.root = TrieNode()
def __contains__(self, seq):
current = self.root
for char in seq:
if char not in current:
return False
current = curre... |
wroberts/fsed | fsed/ahocorasick.py | Trie.pretty_print_str | python | def pretty_print_str(self):
'''
Create a string to pretty-print this trie to standard output.
'''
retval = ''
# dfs
todo = [self.root]
while todo:
current = todo.pop()
for char in reversed(sorted(current.keys())):
todo.appen... | Create a string to pretty-print this trie to standard output. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L147-L160 | null | class Trie(object):
'''A Trie which stores values.'''
def __init__(self):
'''Constructor.'''
self.root = TrieNode()
def __contains__(self, seq):
current = self.root
for char in seq:
if char not in current:
return False
current = curre... |
wroberts/fsed | fsed/ahocorasick.py | AhoCorasickTrie._reset_suffix_links | python | def _reset_suffix_links(self):
'''
Reset all suffix links in all nodes in this trie.
'''
self._suffix_links_set = False
for current, _parent in self.dfs():
current.suffix = None
current.dict_suffix = None
current.longest_prefix = None | Reset all suffix links in all nodes in this trie. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L185-L193 | [
"def dfs(self):\n '''\n Depth-first search generator. Yields `(node, parent)` for every\n node in the tree, beginning with `(self.root, None)`.\n '''\n yield (self.root, None)\n todo = [(self.root[char], self.root) for char in self.root]\n while todo:\n current, parent = todo.pop()\n ... | class AhoCorasickTrie(Trie):
'''A Trie object for performing Aho-Corasick string matching.'''
def __init__(self):
'''Constructor.'''
super(AhoCorasickTrie, self).__init__()
self._suffix_links_set = False
def __setitem__(self, seq, value):
super(AhoCorasickTrie, self).__seti... |
wroberts/fsed | fsed/ahocorasick.py | AhoCorasickTrie._set_suffix_links | python | def _set_suffix_links(self):
'''
Sets all suffix links in all nodes in this trie.
'''
self._suffix_links_set = True
for current, parent in self.bfs():
# skip the root node
if parent is None:
continue
current.longest_prefix = par... | Sets all suffix links in all nodes in this trie. | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L195-L228 | [
"def bfs(self):\n '''\n Breadth-first search generator. Yields `(node, parent)` for every\n node in the tree, beginning with `(self.root, None)`.\n '''\n yield (self.root, None)\n todo = deque([(self.root[char], self.root) for char in self.root])\n while todo:\n current, parent = todo.p... | class AhoCorasickTrie(Trie):
'''A Trie object for performing Aho-Corasick string matching.'''
def __init__(self):
'''Constructor.'''
super(AhoCorasickTrie, self).__init__()
self._suffix_links_set = False
def __setitem__(self, seq, value):
super(AhoCorasickTrie, self).__seti... |
wroberts/fsed | fsed/ahocorasick.py | AhoCorasickTrie.find_all | python | def find_all(self, seq):
'''
Generator expression. Yields tuples of `(begin, length, value)`,
where:
- `begin` is an integer identifying the character index where
the match begins (0-based)
- `length` is an integer indicating the length of the match (1
or mo... | Generator expression. Yields tuples of `(begin, length, value)`,
where:
- `begin` is an integer identifying the character index where
the match begins (0-based)
- `length` is an integer indicating the length of the match (1
or more characters)
- `value` is the value... | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L230-L262 | [
"def _set_suffix_links(self):\n '''\n Sets all suffix links in all nodes in this trie.\n '''\n self._suffix_links_set = True\n for current, parent in self.bfs():\n # skip the root node\n if parent is None:\n continue\n current.longest_prefix = parent.longest_prefix\n ... | class AhoCorasickTrie(Trie):
'''A Trie object for performing Aho-Corasick string matching.'''
def __init__(self):
'''Constructor.'''
super(AhoCorasickTrie, self).__init__()
self._suffix_links_set = False
def __setitem__(self, seq, value):
super(AhoCorasickTrie, self).__seti... |
wroberts/fsed | fsed/ahocorasick.py | AhoCorasickTrie.replace | python | def replace(self, seq):
'''
Performs search and replace on the given input string `seq` using
the values stored in this trie. This method uses a O(n**2)
chart-parsing algorithm to find the optimal way of replacing
matches in the input.
Arguments:
- `seq`:
... | Performs search and replace on the given input string `seq` using
the values stored in this trie. This method uses a O(n**2)
chart-parsing algorithm to find the optimal way of replacing
matches in the input.
Arguments:
- `seq`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L264-L338 | [
"def find_all(self, seq):\n '''\n Generator expression. Yields tuples of `(begin, length, value)`,\n where:\n\n - `begin` is an integer identifying the character index where\n the match begins (0-based)\n - `length` is an integer indicating the length of the match (1\n or more characters)\... | class AhoCorasickTrie(Trie):
'''A Trie object for performing Aho-Corasick string matching.'''
def __init__(self):
'''Constructor.'''
super(AhoCorasickTrie, self).__init__()
self._suffix_links_set = False
def __setitem__(self, seq, value):
super(AhoCorasickTrie, self).__seti... |
wroberts/fsed | fsed/ahocorasick.py | AhoCorasickTrie.greedy_replace | python | def greedy_replace(self, seq):
'''
Greedily matches strings in ``seq``, and replaces them with their
node values.
Arguments:
- `seq`: an iterable of characters to perform search-and-replace on
'''
if not self._suffix_links_set:
self._set_suffix_links(... | Greedily matches strings in ``seq``, and replaces them with their
node values.
Arguments:
- `seq`: an iterable of characters to perform search-and-replace on | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/ahocorasick.py#L340-L395 | [
"def _set_suffix_links(self):\n '''\n Sets all suffix links in all nodes in this trie.\n '''\n self._suffix_links_set = True\n for current, parent in self.bfs():\n # skip the root node\n if parent is None:\n continue\n current.longest_prefix = parent.longest_prefix\n ... | class AhoCorasickTrie(Trie):
'''A Trie object for performing Aho-Corasick string matching.'''
def __init__(self):
'''Constructor.'''
super(AhoCorasickTrie, self).__init__()
self._suffix_links_set = False
def __setitem__(self, seq, value):
super(AhoCorasickTrie, self).__seti... |
wroberts/fsed | fsed/fsed.py | set_log_level | python | def set_log_level(verbose, quiet):
'''
Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`:
'''
if quiet:
verbose = -1
if verbose < 0:
verbose = logging.CRITICAL
elif verbose == 0:
verbose = logging.WARNING
... | Ses the logging level of the script based on command line options.
Arguments:
- `verbose`:
- `quiet`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L23-L41 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
wroberts/fsed | fsed/fsed.py | detect_pattern_format | python | def detect_pattern_format(pattern_filename, encoding, on_word_boundaries):
'''
Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word... | Automatically detects the pattern file format, and determines
whether the Aho-Corasick string matching should pay attention to
word boundaries or not.
Arguments:
- `pattern_filename`:
- `encoding`:
- `on_word_boundaries`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L43-L65 | [
"def open_file(filename, mode='rb'):\n \"\"\"\n Opens a file for access with the given mode. This function\n transparently wraps gzip and xz files as well as normal files.\n You can also open zip files using syntax like:\n\n f = utils.open_file('../semcor-parsed.zip:semcor000.txt')\n \"\"\"\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
wroberts/fsed | fsed/fsed.py | sub_escapes | python | def sub_escapes(sval):
'''
Process escaped characters in ``sval``.
Arguments:
- `sval`:
'''
sval = sval.replace('\\a', '\a')
sval = sval.replace('\\b', '\x00')
sval = sval.replace('\\f', '\f')
sval = sval.replace('\\n', '\n')
sval = sval.replace('\\r', '\r')
sval = sval.repl... | Process escaped characters in ``sval``.
Arguments:
- `sval`: | train | https://github.com/wroberts/fsed/blob/c0c1c5e0ea3a413ef679fdf71635f7f2e5d79ca2/fsed/fsed.py#L67-L82 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
fsed.py
(c) Will Roberts 12 December, 2015
Main module for the ``fsed`` command line utility.
'''
from __future__ import absolute_import, print_function, unicode_literals
from fsed.utils import open_file
import click
import fsed.ahocorasick
import logging
import re
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.