id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
44,400 | serkanyersen/underscore.py | src/underscore.py | underscore.value | def value(self):
""" returns the object instead of instance
"""
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.obj | python | def value(self):
""" returns the object instead of instance
"""
if self._wrapped is not self.Null:
return self._wrapped
else:
return self.obj | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_wrapped",
"is",
"not",
"self",
".",
"Null",
":",
"return",
"self",
".",
"_wrapped",
"else",
":",
"return",
"self",
".",
"obj"
] | returns the object instead of instance | [
"returns",
"the",
"object",
"instead",
"of",
"instance"
] | 07c25c3f0f789536e4ad47aa315faccc0da9602f | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1583-L1589 |
44,401 | serkanyersen/underscore.py | src/underscore.py | underscore.makeStatic | def makeStatic():
""" Provide static access to underscore class
"""
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspect.getmembers(underscore,
predicate=p):
m = eachMethod[0]
... | python | def makeStatic():
""" Provide static access to underscore class
"""
p = lambda value: inspect.ismethod(value) or inspect.isfunction(value)
for eachMethod in inspect.getmembers(underscore,
predicate=p):
m = eachMethod[0]
... | [
"def",
"makeStatic",
"(",
")",
":",
"p",
"=",
"lambda",
"value",
":",
"inspect",
".",
"ismethod",
"(",
"value",
")",
"or",
"inspect",
".",
"isfunction",
"(",
"value",
")",
"for",
"eachMethod",
"in",
"inspect",
".",
"getmembers",
"(",
"underscore",
",",
... | Provide static access to underscore class | [
"Provide",
"static",
"access",
"to",
"underscore",
"class"
] | 07c25c3f0f789536e4ad47aa315faccc0da9602f | https://github.com/serkanyersen/underscore.py/blob/07c25c3f0f789536e4ad47aa315faccc0da9602f/src/underscore.py#L1592-L1614 |
44,402 | ckan/ckan-service-provider | ckanserviceprovider/web.py | init | def init():
"""Initialise and configure the app, database, scheduler, etc.
This should be called once at application startup or at tests startup
(and not e.g. called once for each test case).
"""
global _users, _names
_configure_app(app)
_users, _names = _init_login_manager(app)
_confi... | python | def init():
"""Initialise and configure the app, database, scheduler, etc.
This should be called once at application startup or at tests startup
(and not e.g. called once for each test case).
"""
global _users, _names
_configure_app(app)
_users, _names = _init_login_manager(app)
_confi... | [
"def",
"init",
"(",
")",
":",
"global",
"_users",
",",
"_names",
"_configure_app",
"(",
"app",
")",
"_users",
",",
"_names",
"=",
"_init_login_manager",
"(",
"app",
")",
"_configure_logger",
"(",
")",
"init_scheduler",
"(",
"app",
".",
"config",
".",
"get"... | Initialise and configure the app, database, scheduler, etc.
This should be called once at application startup or at tests startup
(and not e.g. called once for each test case). | [
"Initialise",
"and",
"configure",
"the",
"app",
"database",
"scheduler",
"etc",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L40-L52 |
44,403 | ckan/ckan-service-provider | ckanserviceprovider/web.py | _configure_app | def _configure_app(app_):
"""Configure the Flask WSGI app."""
app_.url_map.strict_slashes = False
app_.config.from_object(default_settings)
app_.config.from_envvar('JOB_CONFIG', silent=True)
db_url = app_.config.get('SQLALCHEMY_DATABASE_URI')
if not db_url:
raise Exception('No db_url in ... | python | def _configure_app(app_):
"""Configure the Flask WSGI app."""
app_.url_map.strict_slashes = False
app_.config.from_object(default_settings)
app_.config.from_envvar('JOB_CONFIG', silent=True)
db_url = app_.config.get('SQLALCHEMY_DATABASE_URI')
if not db_url:
raise Exception('No db_url in ... | [
"def",
"_configure_app",
"(",
"app_",
")",
":",
"app_",
".",
"url_map",
".",
"strict_slashes",
"=",
"False",
"app_",
".",
"config",
".",
"from_object",
"(",
"default_settings",
")",
"app_",
".",
"config",
".",
"from_envvar",
"(",
"'JOB_CONFIG'",
",",
"silent... | Configure the Flask WSGI app. | [
"Configure",
"the",
"Flask",
"WSGI",
"app",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L55-L71 |
44,404 | ckan/ckan-service-provider | ckanserviceprovider/web.py | _init_login_manager | def _init_login_manager(app_):
"""Initialise and configure the login manager."""
login_manager = flogin.LoginManager()
login_manager.setup_app(app_)
login_manager.anonymous_user = Anonymous
login_manager.login_view = "login"
users = {app_.config['USERNAME']: User('Admin', 0)}
names = dict((... | python | def _init_login_manager(app_):
"""Initialise and configure the login manager."""
login_manager = flogin.LoginManager()
login_manager.setup_app(app_)
login_manager.anonymous_user = Anonymous
login_manager.login_view = "login"
users = {app_.config['USERNAME']: User('Admin', 0)}
names = dict((... | [
"def",
"_init_login_manager",
"(",
"app_",
")",
":",
"login_manager",
"=",
"flogin",
".",
"LoginManager",
"(",
")",
"login_manager",
".",
"setup_app",
"(",
"app_",
")",
"login_manager",
".",
"anonymous_user",
"=",
"Anonymous",
"login_manager",
".",
"login_view",
... | Initialise and configure the login manager. | [
"Initialise",
"and",
"configure",
"the",
"login",
"manager",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L74-L90 |
44,405 | ckan/ckan-service-provider | ckanserviceprovider/web.py | _configure_logger_for_production | def _configure_logger_for_production(logger):
"""Configure the given logger for production deployment.
Logs to stderr and file, and emails errors to admins.
"""
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(logging.INFO)
if 'STDERR' in app.config:
logger.ad... | python | def _configure_logger_for_production(logger):
"""Configure the given logger for production deployment.
Logs to stderr and file, and emails errors to admins.
"""
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setLevel(logging.INFO)
if 'STDERR' in app.config:
logger.ad... | [
"def",
"_configure_logger_for_production",
"(",
"logger",
")",
":",
"stderr_handler",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stderr",
")",
"stderr_handler",
".",
"setLevel",
"(",
"logging",
".",
"INFO",
")",
"if",
"'STDERR'",
"in",
"app",
".",... | Configure the given logger for production deployment.
Logs to stderr and file, and emails errors to admins. | [
"Configure",
"the",
"given",
"logger",
"for",
"production",
"deployment",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L93-L117 |
44,406 | ckan/ckan-service-provider | ckanserviceprovider/web.py | _configure_logger | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | python | def _configure_logger():
"""Configure the logging module."""
if not app.debug:
_configure_logger_for_production(logging.getLogger())
elif not app.testing:
_configure_logger_for_debugging(logging.getLogger()) | [
"def",
"_configure_logger",
"(",
")",
":",
"if",
"not",
"app",
".",
"debug",
":",
"_configure_logger_for_production",
"(",
"logging",
".",
"getLogger",
"(",
")",
")",
"elif",
"not",
"app",
".",
"testing",
":",
"_configure_logger_for_debugging",
"(",
"logging",
... | Configure the logging module. | [
"Configure",
"the",
"logging",
"module",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L125-L130 |
44,407 | ckan/ckan-service-provider | ckanserviceprovider/web.py | init_scheduler | def init_scheduler(db_uri):
"""Initialise and configure the scheduler."""
global scheduler
scheduler = apscheduler.Scheduler()
scheduler.misfire_grace_time = 3600
scheduler.add_jobstore(
sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default')
scheduler.add_listener(
job_liste... | python | def init_scheduler(db_uri):
"""Initialise and configure the scheduler."""
global scheduler
scheduler = apscheduler.Scheduler()
scheduler.misfire_grace_time = 3600
scheduler.add_jobstore(
sqlalchemy_store.SQLAlchemyJobStore(url=db_uri), 'default')
scheduler.add_listener(
job_liste... | [
"def",
"init_scheduler",
"(",
"db_uri",
")",
":",
"global",
"scheduler",
"scheduler",
"=",
"apscheduler",
".",
"Scheduler",
"(",
")",
"scheduler",
".",
"misfire_grace_time",
"=",
"3600",
"scheduler",
".",
"add_jobstore",
"(",
"sqlalchemy_store",
".",
"SQLAlchemyJo... | Initialise and configure the scheduler. | [
"Initialise",
"and",
"configure",
"the",
"scheduler",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L133-L144 |
44,408 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job_listener | def job_listener(event):
'''Listens to completed job'''
job_id = event.job.args[0]
if event.code == events.EVENT_JOB_MISSED:
db.mark_job_as_missed(job_id)
elif event.exception:
if isinstance(event.exception, util.JobError):
error_object = event.exception.as_dict()
el... | python | def job_listener(event):
'''Listens to completed job'''
job_id = event.job.args[0]
if event.code == events.EVENT_JOB_MISSED:
db.mark_job_as_missed(job_id)
elif event.exception:
if isinstance(event.exception, util.JobError):
error_object = event.exception.as_dict()
el... | [
"def",
"job_listener",
"(",
"event",
")",
":",
"job_id",
"=",
"event",
".",
"job",
".",
"args",
"[",
"0",
"]",
"if",
"event",
".",
"code",
"==",
"events",
".",
"EVENT_JOB_MISSED",
":",
"db",
".",
"mark_job_as_missed",
"(",
"job_id",
")",
"elif",
"event... | Listens to completed job | [
"Listens",
"to",
"completed",
"job"
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L179-L203 |
44,409 | ckan/ckan-service-provider | ckanserviceprovider/web.py | status | def status():
'''Show version, available job types and name of service.
**Results:**
:rtype: A dictionary with the following keys
:param version: Version of the service provider
:type version: float
:param job_types: Available job types
:type job_types: list of strings
:param name: Nam... | python | def status():
'''Show version, available job types and name of service.
**Results:**
:rtype: A dictionary with the following keys
:param version: Version of the service provider
:type version: float
:param job_types: Available job types
:type job_types: list of strings
:param name: Nam... | [
"def",
"status",
"(",
")",
":",
"job_types",
"=",
"async_types",
".",
"keys",
"(",
")",
"+",
"sync_types",
".",
"keys",
"(",
")",
"counts",
"=",
"{",
"}",
"for",
"job_status",
"in",
"job_statuses",
":",
"counts",
"[",
"job_status",
"]",
"=",
"db",
".... | Show version, available job types and name of service.
**Results:**
:rtype: A dictionary with the following keys
:param version: Version of the service provider
:type version: float
:param job_types: Available job types
:type job_types: list of strings
:param name: Name of the service
... | [
"Show",
"version",
"available",
"job",
"types",
"and",
"name",
"of",
"service",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L224-L253 |
44,410 | ckan/ckan-service-provider | ckanserviceprovider/web.py | login | def login():
'''Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string
'''
username = None
password = None
ne... | python | def login():
'''Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string
'''
username = None
password = None
ne... | [
"def",
"login",
"(",
")",
":",
"username",
"=",
"None",
"password",
"=",
"None",
"next",
"=",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'next'",
")",
"auth",
"=",
"flask",
".",
"request",
".",
"authorization",
"if",
"flask",
".",
"reque... | Log in as administrator
You can use wither basic auth or form based login (via POST).
:param username: The administrator's username
:type username: string
:param password: The administrator's password
:type password: string | [
"Log",
"in",
"as",
"administrator"
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L265-L307 |
44,411 | ckan/ckan-service-provider | ckanserviceprovider/web.py | user | def user():
'''Show information about the current user
:rtype: A dictionary with the following keys
:param id: User id
:type id: int
:param name: User name
:type name: string
:param is_active: Whether the user is currently active
:type is_active: bool
:param is_anonymous: The anonym... | python | def user():
'''Show information about the current user
:rtype: A dictionary with the following keys
:param id: User id
:type id: int
:param name: User name
:type name: string
:param is_active: Whether the user is currently active
:type is_active: bool
:param is_anonymous: The anonym... | [
"def",
"user",
"(",
")",
":",
"user",
"=",
"flogin",
".",
"current_user",
"return",
"flask",
".",
"jsonify",
"(",
"{",
"'id'",
":",
"user",
".",
"get_id",
"(",
")",
",",
"'name'",
":",
"user",
".",
"name",
",",
"'is_active'",
":",
"user",
".",
"is_... | Show information about the current user
:rtype: A dictionary with the following keys
:param id: User id
:type id: int
:param name: User name
:type name: string
:param is_active: Whether the user is currently active
:type is_active: bool
:param is_anonymous: The anonymous user is the def... | [
"Show",
"information",
"about",
"the",
"current",
"user"
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L311-L331 |
44,412 | ckan/ckan-service-provider | ckanserviceprovider/web.py | logout | def logout():
""" Log out the active user
"""
flogin.logout_user()
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for("user")) | python | def logout():
""" Log out the active user
"""
flogin.logout_user()
next = flask.request.args.get('next')
return flask.redirect(next or flask.url_for("user")) | [
"def",
"logout",
"(",
")",
":",
"flogin",
".",
"logout_user",
"(",
")",
"next",
"=",
"flask",
".",
"request",
".",
"args",
".",
"get",
"(",
"'next'",
")",
"return",
"flask",
".",
"redirect",
"(",
"next",
"or",
"flask",
".",
"url_for",
"(",
"\"user\""... | Log out the active user | [
"Log",
"out",
"the",
"active",
"user"
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L335-L340 |
44,413 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job_list | def job_list():
'''List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
... | python | def job_list():
'''List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
... | [
"def",
"job_list",
"(",
")",
":",
"args",
"=",
"dict",
"(",
"(",
"key",
",",
"value",
")",
"for",
"key",
",",
"value",
"in",
"flask",
".",
"request",
".",
"args",
".",
"items",
"(",
")",
")",
"limit",
"=",
"args",
".",
"pop",
"(",
"'_limit'",
"... | List all jobs.
:param _limit: maximum number of jobs to show (default 100)
:type _limit: int
:param _offset: how many jobs to skip before showin the first one (default 0)
:type _offset: int
:param _status: filter jobs by status (complete, error)
:type _status: string
Also, you can filter t... | [
"List",
"all",
"jobs",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L344-L397 |
44,414 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job_status | def job_status(job_id, show_job_key=False, ignore_auth=False):
'''Show a specific job.
**Results:**
:rtype: A dictionary with the following keys
:param status: Status of job (complete, error)
:type status: string
:param sent_data: Input data for job
:type sent_data: json encodable data
... | python | def job_status(job_id, show_job_key=False, ignore_auth=False):
'''Show a specific job.
**Results:**
:rtype: A dictionary with the following keys
:param status: Status of job (complete, error)
:type status: string
:param sent_data: Input data for job
:type sent_data: json encodable data
... | [
"def",
"job_status",
"(",
"job_id",
",",
"show_job_key",
"=",
"False",
",",
"ignore_auth",
"=",
"False",
")",
":",
"job_dict",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job_dict",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'erro... | Show a specific job.
**Results:**
:rtype: A dictionary with the following keys
:param status: Status of job (complete, error)
:type status: string
:param sent_data: Input data for job
:type sent_data: json encodable data
:param job_id: An identifier for the job
:type job_id: string
... | [
"Show",
"a",
"specific",
"job",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L410-L449 |
44,415 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job_delete | def job_delete(job_id):
'''Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error oc... | python | def job_delete(job_id):
'''Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error oc... | [
"def",
"job_delete",
"(",
"job_id",
")",
":",
"conn",
"=",
"db",
".",
"ENGINE",
".",
"connect",
"(",
")",
"job",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'j... | Deletes the job together with its logs and metadata.
:param job_id: An identifier for the job
:type job_id: string
:statuscode 200: no error
:statuscode 403: not authorized to delete the job
:statuscode 404: the job could not be found
:statuscode 409: an error occurred | [
"Deletes",
"the",
"job",
"together",
"with",
"its",
"logs",
"and",
"metadata",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L453-L480 |
44,416 | ckan/ckan-service-provider | ckanserviceprovider/web.py | clear_jobs | def clear_jobs():
'''Clear old jobs
:param days: Jobs for how many days should be kept (default: 10)
:type days: integer
:statuscode 200: no error
:statuscode 403: not authorized to delete jobs
:statuscode 409: an error occurred
'''
if not is_authorized():
return json.dumps({'e... | python | def clear_jobs():
'''Clear old jobs
:param days: Jobs for how many days should be kept (default: 10)
:type days: integer
:statuscode 200: no error
:statuscode 403: not authorized to delete jobs
:statuscode 409: an error occurred
'''
if not is_authorized():
return json.dumps({'e... | [
"def",
"clear_jobs",
"(",
")",
":",
"if",
"not",
"is_authorized",
"(",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'not authorized'",
"}",
")",
",",
"403",
",",
"headers",
"days",
"=",
"flask",
".",
"request",
".",
"args",
".... | Clear old jobs
:param days: Jobs for how many days should be kept (default: 10)
:type days: integer
:statuscode 200: no error
:statuscode 403: not authorized to delete jobs
:statuscode 409: an error occurred | [
"Clear",
"old",
"jobs"
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L484-L498 |
44,417 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job_data | def job_data(job_id):
'''Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
... | python | def job_data(job_id):
'''Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
... | [
"def",
"job_data",
"(",
"job_id",
")",
":",
"job_dict",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"if",
"not",
"job_dict",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'error'",
":",
"'job_id not found'",
"}",
")",
",",
"404",
",",
"headers",
... | Get the raw data that the job returned. The mimetype
will be the value provided in the metdata for the key ``mimetype``.
**Results:**
:rtype: string
:statuscode 200: no error
:statuscode 403: not authorized to view the job's data
:statuscode 404: job id not found
:statuscode 409: an error... | [
"Get",
"the",
"raw",
"data",
"that",
"the",
"job",
"returned",
".",
"The",
"mimetype",
"will",
"be",
"the",
"value",
"provided",
"in",
"the",
"metdata",
"for",
"the",
"key",
"mimetype",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L525-L546 |
44,418 | ckan/ckan-service-provider | ckanserviceprovider/web.py | job | def job(job_id=None):
'''Submit a job. If no id is provided, a random id will be generated.
:param job_type: Which kind of job should be run. Has to be one of the
available job types.
:type job_type: string
:param api_key: An API key that is needed to execute the job. This could
be a CK... | python | def job(job_id=None):
'''Submit a job. If no id is provided, a random id will be generated.
:param job_type: Which kind of job should be run. Has to be one of the
available job types.
:type job_type: string
:param api_key: An API key that is needed to execute the job. This could
be a CK... | [
"def",
"job",
"(",
"job_id",
"=",
"None",
")",
":",
"if",
"not",
"job_id",
":",
"job_id",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
"# key required for job administration",
"job_key",
"=",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
... | Submit a job. If no id is provided, a random id will be generated.
:param job_type: Which kind of job should be run. Has to be one of the
available job types.
:type job_type: string
:param api_key: An API key that is needed to execute the job. This could
be a CKAN API key that is needed to ... | [
"Submit",
"a",
"job",
".",
"If",
"no",
"id",
"is",
"provided",
"a",
"random",
"id",
"will",
"be",
"generated",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L551-L649 |
44,419 | ckan/ckan-service-provider | ckanserviceprovider/web.py | is_authorized | def is_authorized(job=None):
'''Returns true if the request is authorized for the job
if provided. If no job is provided, the user has to be admin
to be authorized.
'''
if flogin.current_user.is_authenticated:
return True
if job:
job_key = flask.request.headers.get('Authorization... | python | def is_authorized(job=None):
'''Returns true if the request is authorized for the job
if provided. If no job is provided, the user has to be admin
to be authorized.
'''
if flogin.current_user.is_authenticated:
return True
if job:
job_key = flask.request.headers.get('Authorization... | [
"def",
"is_authorized",
"(",
"job",
"=",
"None",
")",
":",
"if",
"flogin",
".",
"current_user",
".",
"is_authenticated",
":",
"return",
"True",
"if",
"job",
":",
"job_key",
"=",
"flask",
".",
"request",
".",
"headers",
".",
"get",
"(",
"'Authorization'",
... | Returns true if the request is authorized for the job
if provided. If no job is provided, the user has to be admin
to be authorized. | [
"Returns",
"true",
"if",
"the",
"request",
"is",
"authorized",
"for",
"the",
"job",
"if",
"provided",
".",
"If",
"no",
"job",
"is",
"provided",
"the",
"user",
"has",
"to",
"be",
"admin",
"to",
"be",
"authorized",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L697-L709 |
44,420 | ckan/ckan-service-provider | ckanserviceprovider/web.py | send_result | def send_result(job_id, api_key=None):
''' Send results to where requested.
If api_key is provided, it is used, otherwiese
the key from the job will be used.
'''
job_dict = db.get_job(job_id)
result_url = job_dict.get('result_url')
if not result_url:
# A job with an API key (for u... | python | def send_result(job_id, api_key=None):
''' Send results to where requested.
If api_key is provided, it is used, otherwiese
the key from the job will be used.
'''
job_dict = db.get_job(job_id)
result_url = job_dict.get('result_url')
if not result_url:
# A job with an API key (for u... | [
"def",
"send_result",
"(",
"job_id",
",",
"api_key",
"=",
"None",
")",
":",
"job_dict",
"=",
"db",
".",
"get_job",
"(",
"job_id",
")",
"result_url",
"=",
"job_dict",
".",
"get",
"(",
"'result_url'",
")",
"if",
"not",
"result_url",
":",
"# A job with an API... | Send results to where requested.
If api_key is provided, it is used, otherwiese
the key from the job will be used. | [
"Send",
"results",
"to",
"where",
"requested",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/web.py#L712-L751 |
44,421 | ckan/ckan-service-provider | ckanserviceprovider/db.py | init | def init(uri, echo=False):
"""Initialise the database.
Initialise the sqlalchemy engine, metadata and table objects that we use to
connect to the database.
Create the database and the database tables themselves if they don't
already exist.
:param uri: the sqlalchemy database URI
:type uri... | python | def init(uri, echo=False):
"""Initialise the database.
Initialise the sqlalchemy engine, metadata and table objects that we use to
connect to the database.
Create the database and the database tables themselves if they don't
already exist.
:param uri: the sqlalchemy database URI
:type uri... | [
"def",
"init",
"(",
"uri",
",",
"echo",
"=",
"False",
")",
":",
"global",
"ENGINE",
",",
"_METADATA",
",",
"JOBS_TABLE",
",",
"METADATA_TABLE",
",",
"LOGS_TABLE",
"ENGINE",
"=",
"sqlalchemy",
".",
"create_engine",
"(",
"uri",
",",
"echo",
"=",
"echo",
",... | Initialise the database.
Initialise the sqlalchemy engine, metadata and table objects that we use to
connect to the database.
Create the database and the database tables themselves if they don't
already exist.
:param uri: the sqlalchemy database URI
:type uri: string
:param echo: whether... | [
"Initialise",
"the",
"database",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L60-L83 |
44,422 | ckan/ckan-service-provider | ckanserviceprovider/db.py | get_job | def get_job(job_id):
"""Return the job with the given job_id as a dict.
The dict also includes any metadata or logs associated with the job.
Returns None instead of a dict if there's no job with the given job_id.
The keys of a job dict are:
"job_id": The unique identifier for the job (unicode)
... | python | def get_job(job_id):
"""Return the job with the given job_id as a dict.
The dict also includes any metadata or logs associated with the job.
Returns None instead of a dict if there's no job with the given job_id.
The keys of a job dict are:
"job_id": The unique identifier for the job (unicode)
... | [
"def",
"get_job",
"(",
"job_id",
")",
":",
"# Avoid SQLAlchemy \"Unicode type received non-unicode bind param value\"",
"# warnings.",
"if",
"job_id",
":",
"job_id",
"=",
"unicode",
"(",
"job_id",
")",
"result",
"=",
"ENGINE",
".",
"execute",
"(",
"JOBS_TABLE",
".",
... | Return the job with the given job_id as a dict.
The dict also includes any metadata or logs associated with the job.
Returns None instead of a dict if there's no job with the given job_id.
The keys of a job dict are:
"job_id": The unique identifier for the job (unicode)
"job_type": The name of ... | [
"Return",
"the",
"job",
"with",
"the",
"given",
"job_id",
"as",
"a",
"dict",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L98-L179 |
44,423 | ckan/ckan-service-provider | ckanserviceprovider/db.py | add_pending_job | def add_pending_job(job_id, job_key, job_type, api_key,
data=None, metadata=None, result_url=None):
"""Add a new job with status "pending" to the jobs table.
All code that adds jobs to the jobs table should go through this function.
Code that adds to the jobs table manually should be re... | python | def add_pending_job(job_id, job_key, job_type, api_key,
data=None, metadata=None, result_url=None):
"""Add a new job with status "pending" to the jobs table.
All code that adds jobs to the jobs table should go through this function.
Code that adds to the jobs table manually should be re... | [
"def",
"add_pending_job",
"(",
"job_id",
",",
"job_key",
",",
"job_type",
",",
"api_key",
",",
"data",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"result_url",
"=",
"None",
")",
":",
"if",
"not",
"data",
":",
"data",
"=",
"{",
"}",
"data",
"=",
... | Add a new job with status "pending" to the jobs table.
All code that adds jobs to the jobs table should go through this function.
Code that adds to the jobs table manually should be refactored to use this
function.
May raise unspecified exceptions from Python core, SQLAlchemy or JSON!
TODO: Docume... | [
"Add",
"a",
"new",
"job",
"with",
"status",
"pending",
"to",
"the",
"jobs",
"table",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L182-L282 |
44,424 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _validate_error | def _validate_error(error):
"""Validate and return the given error object.
Based on the given error object, return either None or a dict with a
"message" key whose value is a string (the dict may also have any other
keys that it wants).
The given "error" object can be:
- None, in which case N... | python | def _validate_error(error):
"""Validate and return the given error object.
Based on the given error object, return either None or a dict with a
"message" key whose value is a string (the dict may also have any other
keys that it wants).
The given "error" object can be:
- None, in which case N... | [
"def",
"_validate_error",
"(",
"error",
")",
":",
"if",
"error",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"error",
",",
"basestring",
")",
":",
"return",
"{",
"\"message\"",
":",
"error",
"}",
"else",
":",
"try",
":",
"message",
... | Validate and return the given error object.
Based on the given error object, return either None or a dict with a
"message" key whose value is a string (the dict may also have any other
keys that it wants).
The given "error" object can be:
- None, in which case None is returned
- A string, in... | [
"Validate",
"and",
"return",
"the",
"given",
"error",
"object",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L289-L326 |
44,425 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _update_job | def _update_job(job_id, job_dict):
"""Update the database row for the given job_id with the given job_dict.
All functions that update rows in the jobs table do it by calling this
helper function.
job_dict is a dict with values corresponding to the database columns that
should be updated, e.g.:
... | python | def _update_job(job_id, job_dict):
"""Update the database row for the given job_id with the given job_dict.
All functions that update rows in the jobs table do it by calling this
helper function.
job_dict is a dict with values corresponding to the database columns that
should be updated, e.g.:
... | [
"def",
"_update_job",
"(",
"job_id",
",",
"job_dict",
")",
":",
"# Avoid SQLAlchemy \"Unicode type received non-unicode bind param value\"",
"# warnings.",
"if",
"job_id",
":",
"job_id",
"=",
"unicode",
"(",
"job_id",
")",
"if",
"\"error\"",
"in",
"job_dict",
":",
"jo... | Update the database row for the given job_id with the given job_dict.
All functions that update rows in the jobs table do it by calling this
helper function.
job_dict is a dict with values corresponding to the database columns that
should be updated, e.g.:
{"status": "complete", "data": ...} | [
"Update",
"the",
"database",
"row",
"for",
"the",
"given",
"job_id",
"with",
"the",
"given",
"job_dict",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L329-L361 |
44,426 | ckan/ckan-service-provider | ckanserviceprovider/db.py | mark_job_as_completed | def mark_job_as_completed(job_id, data=None):
"""Mark a job as completed successfully.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param data: the output data returned by the job
:type data: any JSON-serializable type (including None)
"""
update_dict = {
... | python | def mark_job_as_completed(job_id, data=None):
"""Mark a job as completed successfully.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param data: the output data returned by the job
:type data: any JSON-serializable type (including None)
"""
update_dict = {
... | [
"def",
"mark_job_as_completed",
"(",
"job_id",
",",
"data",
"=",
"None",
")",
":",
"update_dict",
"=",
"{",
"\"status\"",
":",
"\"complete\"",
",",
"\"data\"",
":",
"json",
".",
"dumps",
"(",
"data",
")",
",",
"\"finished_timestamp\"",
":",
"datetime",
".",
... | Mark a job as completed successfully.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param data: the output data returned by the job
:type data: any JSON-serializable type (including None) | [
"Mark",
"a",
"job",
"as",
"completed",
"successfully",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L364-L379 |
44,427 | ckan/ckan-service-provider | ckanserviceprovider/db.py | mark_job_as_errored | def mark_job_as_errored(job_id, error_object):
"""Mark a job as failed with an error.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param error_object: the error returned by the job
:type error_object: either a string or a dict with a "message" key whose
value i... | python | def mark_job_as_errored(job_id, error_object):
"""Mark a job as failed with an error.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param error_object: the error returned by the job
:type error_object: either a string or a dict with a "message" key whose
value i... | [
"def",
"mark_job_as_errored",
"(",
"job_id",
",",
"error_object",
")",
":",
"update_dict",
"=",
"{",
"\"status\"",
":",
"\"error\"",
",",
"\"error\"",
":",
"error_object",
",",
"\"finished_timestamp\"",
":",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"... | Mark a job as failed with an error.
:param job_id: the job_id of the job to be updated
:type job_id: unicode
:param error_object: the error returned by the job
:type error_object: either a string or a dict with a "message" key whose
value is a string | [
"Mark",
"a",
"job",
"as",
"failed",
"with",
"an",
"error",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L397-L413 |
44,428 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _init_jobs_table | def _init_jobs_table():
"""Initialise the "jobs" table in the db."""
_jobs_table = sqlalchemy.Table(
'jobs', _METADATA,
sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True),
sqlalchemy.Column('job_type', sqlalchemy.UnicodeText),
sqlalchemy.Column('status', sqlalc... | python | def _init_jobs_table():
"""Initialise the "jobs" table in the db."""
_jobs_table = sqlalchemy.Table(
'jobs', _METADATA,
sqlalchemy.Column('job_id', sqlalchemy.UnicodeText, primary_key=True),
sqlalchemy.Column('job_type', sqlalchemy.UnicodeText),
sqlalchemy.Column('status', sqlalc... | [
"def",
"_init_jobs_table",
"(",
")",
":",
"_jobs_table",
"=",
"sqlalchemy",
".",
"Table",
"(",
"'jobs'",
",",
"_METADATA",
",",
"sqlalchemy",
".",
"Column",
"(",
"'job_id'",
",",
"sqlalchemy",
".",
"UnicodeText",
",",
"primary_key",
"=",
"True",
")",
",",
... | Initialise the "jobs" table in the db. | [
"Initialise",
"the",
"jobs",
"table",
"in",
"the",
"db",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L446-L465 |
44,429 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _init_metadata_table | def _init_metadata_table():
"""Initialise the "metadata" table in the db."""
_metadata_table = sqlalchemy.Table(
'metadata', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False, primary_key=True),
sqlalc... | python | def _init_metadata_table():
"""Initialise the "metadata" table in the db."""
_metadata_table = sqlalchemy.Table(
'metadata', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False, primary_key=True),
sqlalc... | [
"def",
"_init_metadata_table",
"(",
")",
":",
"_metadata_table",
"=",
"sqlalchemy",
".",
"Table",
"(",
"'metadata'",
",",
"_METADATA",
",",
"sqlalchemy",
".",
"Column",
"(",
"'job_id'",
",",
"sqlalchemy",
".",
"ForeignKey",
"(",
"\"jobs.job_id\"",
",",
"ondelete... | Initialise the "metadata" table in the db. | [
"Initialise",
"the",
"metadata",
"table",
"in",
"the",
"db",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L468-L479 |
44,430 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _init_logs_table | def _init_logs_table():
"""Initialise the "logs" table in the db."""
_logs_table = sqlalchemy.Table(
'logs', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False),
sqlalchemy.Column('timestamp', sqlalchem... | python | def _init_logs_table():
"""Initialise the "logs" table in the db."""
_logs_table = sqlalchemy.Table(
'logs', _METADATA,
sqlalchemy.Column(
'job_id', sqlalchemy.ForeignKey("jobs.job_id", ondelete="CASCADE"),
nullable=False),
sqlalchemy.Column('timestamp', sqlalchem... | [
"def",
"_init_logs_table",
"(",
")",
":",
"_logs_table",
"=",
"sqlalchemy",
".",
"Table",
"(",
"'logs'",
",",
"_METADATA",
",",
"sqlalchemy",
".",
"Column",
"(",
"'job_id'",
",",
"sqlalchemy",
".",
"ForeignKey",
"(",
"\"jobs.job_id\"",
",",
"ondelete",
"=",
... | Initialise the "logs" table in the db. | [
"Initialise",
"the",
"logs",
"table",
"in",
"the",
"db",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L482-L496 |
44,431 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _get_metadata | def _get_metadata(job_id):
"""Return any metadata for the given job_id from the metadata table."""
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
METADATA_TABLE.select().where(
METADATA_TABLE... | python | def _get_metadata(job_id):
"""Return any metadata for the given job_id from the metadata table."""
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
METADATA_TABLE.select().where(
METADATA_TABLE... | [
"def",
"_get_metadata",
"(",
"job_id",
")",
":",
"# Avoid SQLAlchemy \"Unicode type received non-unicode bind param value\"",
"# warnings.",
"job_id",
"=",
"unicode",
"(",
"job_id",
")",
"results",
"=",
"ENGINE",
".",
"execute",
"(",
"METADATA_TABLE",
".",
"select",
"("... | Return any metadata for the given job_id from the metadata table. | [
"Return",
"any",
"metadata",
"for",
"the",
"given",
"job_id",
"from",
"the",
"metadata",
"table",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L499-L514 |
44,432 | ckan/ckan-service-provider | ckanserviceprovider/db.py | _get_logs | def _get_logs(job_id):
"""Return any logs for the given job_id from the logs table."""
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall()
... | python | def _get_logs(job_id):
"""Return any logs for the given job_id from the logs table."""
# Avoid SQLAlchemy "Unicode type received non-unicode bind param value"
# warnings.
job_id = unicode(job_id)
results = ENGINE.execute(
LOGS_TABLE.select().where(LOGS_TABLE.c.job_id == job_id)).fetchall()
... | [
"def",
"_get_logs",
"(",
"job_id",
")",
":",
"# Avoid SQLAlchemy \"Unicode type received non-unicode bind param value\"",
"# warnings.",
"job_id",
"=",
"unicode",
"(",
"job_id",
")",
"results",
"=",
"ENGINE",
".",
"execute",
"(",
"LOGS_TABLE",
".",
"select",
"(",
")",... | Return any logs for the given job_id from the logs table. | [
"Return",
"any",
"logs",
"for",
"the",
"given",
"job_id",
"from",
"the",
"logs",
"table",
"."
] | 83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa | https://github.com/ckan/ckan-service-provider/blob/83a42b027dba8a0b3ca7e5f689f990b7bc2cd7fa/ckanserviceprovider/db.py#L517-L531 |
44,433 | bookieio/breadability | breadability/scoring.py | check_node_attributes | def check_node_attributes(pattern, node, *attributes):
"""
Searches match in attributes against given pattern and if
finds the match against any of them returns True.
"""
for attribute_name in attributes:
attribute = node.get(attribute_name)
if attribute is not None and pattern.searc... | python | def check_node_attributes(pattern, node, *attributes):
"""
Searches match in attributes against given pattern and if
finds the match against any of them returns True.
"""
for attribute_name in attributes:
attribute = node.get(attribute_name)
if attribute is not None and pattern.searc... | [
"def",
"check_node_attributes",
"(",
"pattern",
",",
"node",
",",
"*",
"attributes",
")",
":",
"for",
"attribute_name",
"in",
"attributes",
":",
"attribute",
"=",
"node",
".",
"get",
"(",
"attribute_name",
")",
"if",
"attribute",
"is",
"not",
"None",
"and",
... | Searches match in attributes against given pattern and if
finds the match against any of them returns True. | [
"Searches",
"match",
"in",
"attributes",
"against",
"given",
"pattern",
"and",
"if",
"finds",
"the",
"match",
"against",
"any",
"of",
"them",
"returns",
"True",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/scoring.py#L43-L53 |
44,434 | bookieio/breadability | breadability/scoring.py | generate_hash_id | def generate_hash_id(node):
"""
Generates a hash_id for the node in question.
:param node: lxml etree node
"""
try:
content = tostring(node)
except Exception:
logger.exception("Generating of hash failed")
content = to_bytes(repr(node))
hash_id = md5(content).hexdige... | python | def generate_hash_id(node):
"""
Generates a hash_id for the node in question.
:param node: lxml etree node
"""
try:
content = tostring(node)
except Exception:
logger.exception("Generating of hash failed")
content = to_bytes(repr(node))
hash_id = md5(content).hexdige... | [
"def",
"generate_hash_id",
"(",
"node",
")",
":",
"try",
":",
"content",
"=",
"tostring",
"(",
"node",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"\"Generating of hash failed\"",
")",
"content",
"=",
"to_bytes",
"(",
"repr",
"(",
"node... | Generates a hash_id for the node in question.
:param node: lxml etree node | [
"Generates",
"a",
"hash_id",
"for",
"the",
"node",
"in",
"question",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/scoring.py#L56-L69 |
44,435 | bookieio/breadability | breadability/scoring.py | get_link_density | def get_link_density(node, node_text=None):
"""
Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text... | python | def get_link_density(node, node_text=None):
"""
Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text... | [
"def",
"get_link_density",
"(",
"node",
",",
"node_text",
"=",
"None",
")",
":",
"if",
"node_text",
"is",
"None",
":",
"node_text",
"=",
"node",
".",
"text_content",
"(",
")",
"node_text",
"=",
"normalize_whitespace",
"(",
"node_text",
".",
"strip",
"(",
"... | Computes the ratio for text in given node and text in links
contained in the node. It is computed from number of
characters in the texts.
:parameter Element node:
HTML element in which links density is computed.
:parameter string node_text:
Text content of given node if it was obtained ... | [
"Computes",
"the",
"ratio",
"for",
"text",
"in",
"given",
"node",
"and",
"text",
"in",
"links",
"contained",
"in",
"the",
"node",
".",
"It",
"is",
"computed",
"from",
"number",
"of",
"characters",
"in",
"the",
"texts",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/scoring.py#L72-L100 |
44,436 | bookieio/breadability | breadability/scoring.py | is_unlikely_node | def is_unlikely_node(node):
"""
Short helper for checking unlikely status.
If the class or id are in the unlikely list, and there's not also a
class/id in the likely list then it might need to be removed.
"""
unlikely = check_node_attributes(CLS_UNLIKELY, node, "class", "id")
maybe = check_... | python | def is_unlikely_node(node):
"""
Short helper for checking unlikely status.
If the class or id are in the unlikely list, and there's not also a
class/id in the likely list then it might need to be removed.
"""
unlikely = check_node_attributes(CLS_UNLIKELY, node, "class", "id")
maybe = check_... | [
"def",
"is_unlikely_node",
"(",
"node",
")",
":",
"unlikely",
"=",
"check_node_attributes",
"(",
"CLS_UNLIKELY",
",",
"node",
",",
"\"class\"",
",",
"\"id\"",
")",
"maybe",
"=",
"check_node_attributes",
"(",
"CLS_MAYBE",
",",
"node",
",",
"\"class\"",
",",
"\"... | Short helper for checking unlikely status.
If the class or id are in the unlikely list, and there's not also a
class/id in the likely list then it might need to be removed. | [
"Short",
"helper",
"for",
"checking",
"unlikely",
"status",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/scoring.py#L128-L138 |
44,437 | bookieio/breadability | breadability/scoring.py | score_candidates | def score_candidates(nodes):
"""Given a list of potential nodes, find some initial scores to start"""
MIN_HIT_LENTH = 25
candidates = {}
for node in nodes:
logger.debug("* Scoring candidate %s %r", node.tag, node.attrib)
# if the node has no parent it knows of then it ends up creating ... | python | def score_candidates(nodes):
"""Given a list of potential nodes, find some initial scores to start"""
MIN_HIT_LENTH = 25
candidates = {}
for node in nodes:
logger.debug("* Scoring candidate %s %r", node.tag, node.attrib)
# if the node has no parent it knows of then it ends up creating ... | [
"def",
"score_candidates",
"(",
"nodes",
")",
":",
"MIN_HIT_LENTH",
"=",
"25",
"candidates",
"=",
"{",
"}",
"for",
"node",
"in",
"nodes",
":",
"logger",
".",
"debug",
"(",
"\"* Scoring candidate %s %r\"",
",",
"node",
".",
"tag",
",",
"node",
".",
"attrib"... | Given a list of potential nodes, find some initial scores to start | [
"Given",
"a",
"list",
"of",
"potential",
"nodes",
"find",
"some",
"initial",
"scores",
"to",
"start"
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/scoring.py#L141-L222 |
44,438 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.getTime | def getTime(self):
"""
Actually, this function creates a time stamp vector
based on the number of samples and sample rate.
"""
T = 1/float(self.samp[self.nrates-1])
endtime = self.endsamp[self.nrates-1] * T
t = numpy.linspace(0,endtime,self.endsamp[self.nrates-1... | python | def getTime(self):
"""
Actually, this function creates a time stamp vector
based on the number of samples and sample rate.
"""
T = 1/float(self.samp[self.nrates-1])
endtime = self.endsamp[self.nrates-1] * T
t = numpy.linspace(0,endtime,self.endsamp[self.nrates-1... | [
"def",
"getTime",
"(",
"self",
")",
":",
"T",
"=",
"1",
"/",
"float",
"(",
"self",
".",
"samp",
"[",
"self",
".",
"nrates",
"-",
"1",
"]",
")",
"endtime",
"=",
"self",
".",
"endsamp",
"[",
"self",
".",
"nrates",
"-",
"1",
"]",
"*",
"T",
"t",
... | Actually, this function creates a time stamp vector
based on the number of samples and sample rate. | [
"Actually",
"this",
"function",
"creates",
"a",
"time",
"stamp",
"vector",
"based",
"on",
"the",
"number",
"of",
"samples",
"and",
"sample",
"rate",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L288-L298 |
44,439 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.getAnalogID | def getAnalogID(self,num):
"""
Returns the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.An.index(num) # Get the position of the channel number.
return self.Ach_id[listidx] | python | def getAnalogID(self,num):
"""
Returns the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.An.index(num) # Get the position of the channel number.
return self.Ach_id[listidx] | [
"def",
"getAnalogID",
"(",
"self",
",",
"num",
")",
":",
"listidx",
"=",
"self",
".",
"An",
".",
"index",
"(",
"num",
")",
"# Get the position of the channel number.",
"return",
"self",
".",
"Ach_id",
"[",
"listidx",
"]"
] | Returns the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header. | [
"Returns",
"the",
"COMTRADE",
"ID",
"of",
"a",
"given",
"channel",
"number",
".",
"The",
"number",
"to",
"be",
"given",
"is",
"the",
"same",
"of",
"the",
"COMTRADE",
"header",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L300-L306 |
44,440 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.getDigitalID | def getDigitalID(self,num):
"""
Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.Dn.index(num) # Get the position of the channel number.
return self.Dch_id[listidx] | python | def getDigitalID(self,num):
"""
Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header.
"""
listidx = self.Dn.index(num) # Get the position of the channel number.
return self.Dch_id[listidx] | [
"def",
"getDigitalID",
"(",
"self",
",",
"num",
")",
":",
"listidx",
"=",
"self",
".",
"Dn",
".",
"index",
"(",
"num",
")",
"# Get the position of the channel number.",
"return",
"self",
".",
"Dch_id",
"[",
"listidx",
"]"
] | Reads the COMTRADE ID of a given channel number.
The number to be given is the same of the COMTRADE header. | [
"Reads",
"the",
"COMTRADE",
"ID",
"of",
"a",
"given",
"channel",
"number",
".",
"The",
"number",
"to",
"be",
"given",
"is",
"the",
"same",
"of",
"the",
"COMTRADE",
"header",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L308-L314 |
44,441 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.getAnalogType | def getAnalogType(self,num):
"""
Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel.
"""
listidx = self.An.index(num)
unit = self.uu[listidx]
... | python | def getAnalogType(self,num):
"""
Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel.
"""
listidx = self.An.index(num)
unit = self.uu[listidx]
... | [
"def",
"getAnalogType",
"(",
"self",
",",
"num",
")",
":",
"listidx",
"=",
"self",
".",
"An",
".",
"index",
"(",
"num",
")",
"unit",
"=",
"self",
".",
"uu",
"[",
"listidx",
"]",
"if",
"unit",
"==",
"'kV'",
"or",
"unit",
"==",
"'V'",
":",
"return"... | Returns the type of the channel 'num' based
on its unit stored in the Comtrade header file.
Returns 'V' for a voltage channel and 'I' for a current channel. | [
"Returns",
"the",
"type",
"of",
"the",
"channel",
"num",
"based",
"on",
"its",
"unit",
"stored",
"in",
"the",
"Comtrade",
"header",
"file",
".",
"Returns",
"V",
"for",
"a",
"voltage",
"channel",
"and",
"I",
"for",
"a",
"current",
"channel",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L316-L332 |
44,442 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.ReadDataFile | def ReadDataFile(self):
"""
Reads the contents of the Comtrade .dat file and store them in a
private variable.
For accessing a specific channel data, see methods getAnalogData and
getDigitalData.
"""
if os.path.isfile(self.filename[0:-4] + '.dat'):
... | python | def ReadDataFile(self):
"""
Reads the contents of the Comtrade .dat file and store them in a
private variable.
For accessing a specific channel data, see methods getAnalogData and
getDigitalData.
"""
if os.path.isfile(self.filename[0:-4] + '.dat'):
... | [
"def",
"ReadDataFile",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"filename",
"[",
"0",
":",
"-",
"4",
"]",
"+",
"'.dat'",
")",
":",
"filename",
"=",
"self",
".",
"filename",
"[",
"0",
":",
"-",
"4",
"]",
... | Reads the contents of the Comtrade .dat file and store them in a
private variable.
For accessing a specific channel data, see methods getAnalogData and
getDigitalData. | [
"Reads",
"the",
"contents",
"of",
"the",
"Comtrade",
".",
"dat",
"file",
"and",
"store",
"them",
"in",
"a",
"private",
"variable",
".",
"For",
"accessing",
"a",
"specific",
"channel",
"data",
"see",
"methods",
"getAnalogData",
"and",
"getDigitalData",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L343-L367 |
44,443 | miguelmoreto/pycomtrade | src/pyComtrade.py | ComtradeRecord.getAnalogChannelData | def getAnalogChannelData(self,ChNumber):
"""
Returns an array of numbers containing the data values of the channel
number "ChNumber".
ChNumber is the number of the channal as in .cfg file.
"""
if not self.DatFileContent:
print "No data file content. ... | python | def getAnalogChannelData(self,ChNumber):
"""
Returns an array of numbers containing the data values of the channel
number "ChNumber".
ChNumber is the number of the channal as in .cfg file.
"""
if not self.DatFileContent:
print "No data file content. ... | [
"def",
"getAnalogChannelData",
"(",
"self",
",",
"ChNumber",
")",
":",
"if",
"not",
"self",
".",
"DatFileContent",
":",
"print",
"\"No data file content. Use the method ReadDataFile first\"",
"return",
"0",
"if",
"(",
"ChNumber",
">",
"self",
".",
"A",
")",
":",
... | Returns an array of numbers containing the data values of the channel
number "ChNumber".
ChNumber is the number of the channal as in .cfg file. | [
"Returns",
"an",
"array",
"of",
"numbers",
"containing",
"the",
"data",
"values",
"of",
"the",
"channel",
"number",
"ChNumber",
".",
"ChNumber",
"is",
"the",
"number",
"of",
"the",
"channal",
"as",
"in",
".",
"cfg",
"file",
"."
] | 1785ebbc96c01a60e58fb11f0aa4848be855aa0d | https://github.com/miguelmoreto/pycomtrade/blob/1785ebbc96c01a60e58fb11f0aa4848be855aa0d/src/pyComtrade.py#L369-L405 |
44,444 | holtjma/msbwt | MUS/CommandLineInterface.py | initLogger | def initLogger():
'''
This code taken from Matt's Suspenders for initializing a logger
'''
global logger
logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(l... | python | def initLogger():
'''
This code taken from Matt's Suspenders for initializing a logger
'''
global logger
logger = logging.getLogger('root')
logger.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter("[%(asctime)s] %(l... | [
"def",
"initLogger",
"(",
")",
":",
"global",
"logger",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'root'",
")",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"DEBUG",
")",
"ch",
"=",
"logging",
".",
"StreamHandler",
"(",
"sys",
".",
"stdout",
... | This code taken from Matt's Suspenders for initializing a logger | [
"This",
"code",
"taken",
"from",
"Matt",
"s",
"Suspenders",
"for",
"initializing",
"a",
"logger"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/CommandLineInterface.py#L22-L33 |
44,445 | holtjma/msbwt | MUS/MSBWTGen.py | writeSeqsToFiles | def writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength):
'''
This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list o... | python | def writeSeqsToFiles(seqArray, seqFNPrefix, offsetFN, uniformLength):
'''
This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list o... | [
"def",
"writeSeqsToFiles",
"(",
"seqArray",
",",
"seqFNPrefix",
",",
"offsetFN",
",",
"uniformLength",
")",
":",
"if",
"uniformLength",
":",
"#first, store the uniform size in our offsets file",
"offsets",
"=",
"np",
".",
"lib",
".",
"format",
".",
"open_memmap",
"(... | This function takes a seqArray and saves the values to a memmap file that can be accessed for multi-processing.
Additionally, it saves some offset indices in a numpy file for quicker string access.
@param seqArray - the list of '$'-terminated strings to be saved
@param fnPrefix - the prefix for the temporar... | [
"This",
"function",
"takes",
"a",
"seqArray",
"and",
"saves",
"the",
"values",
"to",
"a",
"memmap",
"file",
"that",
"can",
"be",
"accessed",
"for",
"multi",
"-",
"processing",
".",
"Additionally",
"it",
"saves",
"some",
"offset",
"indices",
"in",
"a",
"num... | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MSBWTGen.py#L618-L681 |
44,446 | holtjma/msbwt | MUS/MSBWTGen.py | decompressBWT | def decompressBWT(inputDir, outputDir, numProcs, logger):
'''
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
... | python | def decompressBWT(inputDir, outputDir, numProcs, logger):
'''
This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
... | [
"def",
"decompressBWT",
"(",
"inputDir",
",",
"outputDir",
",",
"numProcs",
",",
"logger",
")",
":",
"#load it, force it to be a compressed bwt also",
"msbwt",
"=",
"MultiStringBWT",
".",
"CompressedMSBWT",
"(",
")",
"msbwt",
".",
"loadMsbwt",
"(",
"inputDir",
",",
... | This is called for taking a BWT and decompressing it back out to it's original form. While unusual to do,
it's included in this package for completion purposes.
@param inputDir - the directory of the compressed BWT we plan on decompressing
@param outputFN - the directory for the output decompressed BWT, it... | [
"This",
"is",
"called",
"for",
"taking",
"a",
"BWT",
"and",
"decompressing",
"it",
"back",
"out",
"to",
"it",
"s",
"original",
"form",
".",
"While",
"unusual",
"to",
"do",
"it",
"s",
"included",
"in",
"this",
"package",
"for",
"completion",
"purposes",
"... | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MSBWTGen.py#L1169-L1203 |
44,447 | holtjma/msbwt | MUS/MSBWTGen.py | decompressBWTPoolProcess | def decompressBWTPoolProcess(tup):
'''
Individual process for decompression
'''
(inputDir, outputDir, startIndex, endIndex) = tup
if startIndex == endIndex:
return True
#load the thing we'll be extracting from
msbwt = MultiStringBWT.CompressedMSBWT()
msbwt.loadMsbwt(inp... | python | def decompressBWTPoolProcess(tup):
'''
Individual process for decompression
'''
(inputDir, outputDir, startIndex, endIndex) = tup
if startIndex == endIndex:
return True
#load the thing we'll be extracting from
msbwt = MultiStringBWT.CompressedMSBWT()
msbwt.loadMsbwt(inp... | [
"def",
"decompressBWTPoolProcess",
"(",
"tup",
")",
":",
"(",
"inputDir",
",",
"outputDir",
",",
"startIndex",
",",
"endIndex",
")",
"=",
"tup",
"if",
"startIndex",
"==",
"endIndex",
":",
"return",
"True",
"#load the thing we'll be extracting from",
"msbwt",
"=",
... | Individual process for decompression | [
"Individual",
"process",
"for",
"decompression"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MSBWTGen.py#L1207-L1224 |
44,448 | holtjma/msbwt | MUS/MSBWTGen.py | clearAuxiliaryData | def clearAuxiliaryData(dirName):
'''
This function removes auxiliary files associated with a given filename
'''
if dirName != None:
if os.path.exists(dirName+'/auxiliary.npy'):
os.remove(dirName+'/auxiliary.npy')
if os.path.exists(dirName+'/totalCounts.p'):
... | python | def clearAuxiliaryData(dirName):
'''
This function removes auxiliary files associated with a given filename
'''
if dirName != None:
if os.path.exists(dirName+'/auxiliary.npy'):
os.remove(dirName+'/auxiliary.npy')
if os.path.exists(dirName+'/totalCounts.p'):
... | [
"def",
"clearAuxiliaryData",
"(",
"dirName",
")",
":",
"if",
"dirName",
"!=",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/auxiliary.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/auxiliary.npy'",
")",
"if",... | This function removes auxiliary files associated with a given filename | [
"This",
"function",
"removes",
"auxiliary",
"files",
"associated",
"with",
"a",
"given",
"filename"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MSBWTGen.py#L1226-L1250 |
44,449 | bookieio/breadability | breadability/readable.py | build_base_document | def build_base_document(dom, return_fragment=True):
"""
Builds a base document with the body as root.
:param dom: Parsed lxml tree (Document Object Model).
:param bool return_fragment: If True only <div> fragment is returned.
Otherwise full HTML document is returned.
"""
body_element = ... | python | def build_base_document(dom, return_fragment=True):
"""
Builds a base document with the body as root.
:param dom: Parsed lxml tree (Document Object Model).
:param bool return_fragment: If True only <div> fragment is returned.
Otherwise full HTML document is returned.
"""
body_element = ... | [
"def",
"build_base_document",
"(",
"dom",
",",
"return_fragment",
"=",
"True",
")",
":",
"body_element",
"=",
"dom",
".",
"find",
"(",
"\".//body\"",
")",
"if",
"body_element",
"is",
"None",
":",
"fragment",
"=",
"fragment_fromstring",
"(",
"'<div id=\"readabili... | Builds a base document with the body as root.
:param dom: Parsed lxml tree (Document Object Model).
:param bool return_fragment: If True only <div> fragment is returned.
Otherwise full HTML document is returned. | [
"Builds",
"a",
"base",
"document",
"with",
"the",
"body",
"as",
"root",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L67-L85 |
44,450 | bookieio/breadability | breadability/readable.py | check_siblings | def check_siblings(candidate_node, candidate_list):
"""
Looks through siblings for content that might also be related.
Things like preambles, content split by ads that we removed, etc.
"""
candidate_css = candidate_node.node.get("class")
potential_target = candidate_node.content_score * 0.2
... | python | def check_siblings(candidate_node, candidate_list):
"""
Looks through siblings for content that might also be related.
Things like preambles, content split by ads that we removed, etc.
"""
candidate_css = candidate_node.node.get("class")
potential_target = candidate_node.content_score * 0.2
... | [
"def",
"check_siblings",
"(",
"candidate_node",
",",
"candidate_list",
")",
":",
"candidate_css",
"=",
"candidate_node",
".",
"node",
".",
"get",
"(",
"\"class\"",
")",
"potential_target",
"=",
"candidate_node",
".",
"content_score",
"*",
"0.2",
"sibling_target_scor... | Looks through siblings for content that might also be related.
Things like preambles, content split by ads that we removed, etc. | [
"Looks",
"through",
"siblings",
"for",
"content",
"that",
"might",
"also",
"be",
"related",
".",
"Things",
"like",
"preambles",
"content",
"split",
"by",
"ads",
"that",
"we",
"removed",
"etc",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L113-L166 |
44,451 | bookieio/breadability | breadability/readable.py | clean_document | def clean_document(node):
"""Cleans up the final document we return as the readable article."""
if node is None or len(node) == 0:
return None
logger.debug("\n\n-------------- CLEANING DOCUMENT -----------------")
to_drop = []
for n in node.iter():
# clean out any in-line style pro... | python | def clean_document(node):
"""Cleans up the final document we return as the readable article."""
if node is None or len(node) == 0:
return None
logger.debug("\n\n-------------- CLEANING DOCUMENT -----------------")
to_drop = []
for n in node.iter():
# clean out any in-line style pro... | [
"def",
"clean_document",
"(",
"node",
")",
":",
"if",
"node",
"is",
"None",
"or",
"len",
"(",
"node",
")",
"==",
"0",
":",
"return",
"None",
"logger",
".",
"debug",
"(",
"\"\\n\\n-------------- CLEANING DOCUMENT -----------------\"",
")",
"to_drop",
"=",
"[",
... | Cleans up the final document we return as the readable article. | [
"Cleans",
"up",
"the",
"final",
"document",
"we",
"return",
"as",
"the",
"readable",
"article",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L169-L210 |
44,452 | bookieio/breadability | breadability/readable.py | clean_conditionally | def clean_conditionally(node):
"""Remove the clean_el if it looks like bad content based on rules."""
if node.tag not in ('form', 'table', 'ul', 'div', 'p'):
return # this is not the tag we are looking for
weight = get_class_weight(node)
# content_score = LOOK up the content score for this nod... | python | def clean_conditionally(node):
"""Remove the clean_el if it looks like bad content based on rules."""
if node.tag not in ('form', 'table', 'ul', 'div', 'p'):
return # this is not the tag we are looking for
weight = get_class_weight(node)
# content_score = LOOK up the content score for this nod... | [
"def",
"clean_conditionally",
"(",
"node",
")",
":",
"if",
"node",
".",
"tag",
"not",
"in",
"(",
"'form'",
",",
"'table'",
",",
"'ul'",
",",
"'div'",
",",
"'p'",
")",
":",
"return",
"# this is not the tag we are looking for",
"weight",
"=",
"get_class_weight",... | Remove the clean_el if it looks like bad content based on rules. | [
"Remove",
"the",
"clean_el",
"if",
"it",
"looks",
"like",
"bad",
"content",
"based",
"on",
"rules",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L227-L290 |
44,453 | bookieio/breadability | breadability/readable.py | find_candidates | def find_candidates(document):
"""
Finds cadidate nodes for the readable version of the article.
Here's we're going to remove unlikely nodes, find scores on the rest,
clean up and return the final best match.
"""
nodes_to_score = set()
should_remove = set()
for node in document.iter():... | python | def find_candidates(document):
"""
Finds cadidate nodes for the readable version of the article.
Here's we're going to remove unlikely nodes, find scores on the rest,
clean up and return the final best match.
"""
nodes_to_score = set()
should_remove = set()
for node in document.iter():... | [
"def",
"find_candidates",
"(",
"document",
")",
":",
"nodes_to_score",
"=",
"set",
"(",
")",
"should_remove",
"=",
"set",
"(",
")",
"for",
"node",
"in",
"document",
".",
"iter",
"(",
")",
":",
"if",
"is_unlikely_node",
"(",
"node",
")",
":",
"logger",
... | Finds cadidate nodes for the readable version of the article.
Here's we're going to remove unlikely nodes, find scores on the rest,
clean up and return the final best match. | [
"Finds",
"cadidate",
"nodes",
"for",
"the",
"readable",
"version",
"of",
"the",
"article",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L305-L327 |
44,454 | bookieio/breadability | breadability/readable.py | is_bad_link | def is_bad_link(node):
"""
Helper to determine if the node is link that is useless.
We've hit articles with many multiple links that should be cleaned out
because they're just there to pollute the space. See tests for examples.
"""
if node.tag != "a":
return False
name = node.get("... | python | def is_bad_link(node):
"""
Helper to determine if the node is link that is useless.
We've hit articles with many multiple links that should be cleaned out
because they're just there to pollute the space. See tests for examples.
"""
if node.tag != "a":
return False
name = node.get("... | [
"def",
"is_bad_link",
"(",
"node",
")",
":",
"if",
"node",
".",
"tag",
"!=",
"\"a\"",
":",
"return",
"False",
"name",
"=",
"node",
".",
"get",
"(",
"\"name\"",
")",
"href",
"=",
"node",
".",
"get",
"(",
"\"href\"",
")",
"if",
"name",
"and",
"not",
... | Helper to determine if the node is link that is useless.
We've hit articles with many multiple links that should be cleaned out
because they're just there to pollute the space. See tests for examples. | [
"Helper",
"to",
"determine",
"if",
"the",
"node",
"is",
"link",
"that",
"is",
"useless",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L330-L350 |
44,455 | bookieio/breadability | breadability/readable.py | Article.candidates | def candidates(self):
"""Generates list of candidates from the DOM."""
dom = self.dom
if dom is None or len(dom) == 0:
return None
candidates, unlikely_candidates = find_candidates(dom)
drop_nodes_with_parents(unlikely_candidates)
return candidates | python | def candidates(self):
"""Generates list of candidates from the DOM."""
dom = self.dom
if dom is None or len(dom) == 0:
return None
candidates, unlikely_candidates = find_candidates(dom)
drop_nodes_with_parents(unlikely_candidates)
return candidates | [
"def",
"candidates",
"(",
"self",
")",
":",
"dom",
"=",
"self",
".",
"dom",
"if",
"dom",
"is",
"None",
"or",
"len",
"(",
"dom",
")",
"==",
"0",
":",
"return",
"None",
"candidates",
",",
"unlikely_candidates",
"=",
"find_candidates",
"(",
"dom",
")",
... | Generates list of candidates from the DOM. | [
"Generates",
"list",
"of",
"candidates",
"from",
"the",
"DOM",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L386-L395 |
44,456 | bookieio/breadability | breadability/readable.py | Article._readable | def _readable(self):
"""The readable parsed article"""
if not self.candidates:
logger.info("No candidates found in document.")
return self._handle_no_candidates()
# right now we return the highest scoring candidate content
best_candidates = sorted(
(c... | python | def _readable(self):
"""The readable parsed article"""
if not self.candidates:
logger.info("No candidates found in document.")
return self._handle_no_candidates()
# right now we return the highest scoring candidate content
best_candidates = sorted(
(c... | [
"def",
"_readable",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"candidates",
":",
"logger",
".",
"info",
"(",
"\"No candidates found in document.\"",
")",
"return",
"self",
".",
"_handle_no_candidates",
"(",
")",
"# right now we return the highest scoring candid... | The readable parsed article | [
"The",
"readable",
"parsed",
"article"
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L410-L437 |
44,457 | bookieio/breadability | breadability/readable.py | Article._handle_no_candidates | def _handle_no_candidates(self):
"""
If we fail to find a good candidate we need to find something else.
"""
# since we've not found a good candidate we're should help this
if self.dom is not None and len(self.dom):
dom = prep_article(self.dom)
dom = build... | python | def _handle_no_candidates(self):
"""
If we fail to find a good candidate we need to find something else.
"""
# since we've not found a good candidate we're should help this
if self.dom is not None and len(self.dom):
dom = prep_article(self.dom)
dom = build... | [
"def",
"_handle_no_candidates",
"(",
"self",
")",
":",
"# since we've not found a good candidate we're should help this",
"if",
"self",
".",
"dom",
"is",
"not",
"None",
"and",
"len",
"(",
"self",
".",
"dom",
")",
":",
"dom",
"=",
"prep_article",
"(",
"self",
"."... | If we fail to find a good candidate we need to find something else. | [
"If",
"we",
"fail",
"to",
"find",
"a",
"good",
"candidate",
"we",
"need",
"to",
"find",
"something",
"else",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/readable.py#L446-L458 |
44,458 | holtjma/msbwt | MUS/util.py | fastaIterator | def fastaIterator(fastaFN):
'''
Iterator that yields tuples containing a sequence label and the sequence itself
@param fastaFN - the FASTA filename to open and parse
@return - an iterator yielding tuples of the form (label, sequence) from the FASTA file
'''
if fastaFN[len(fastaFN)-3:] == '.gz':
... | python | def fastaIterator(fastaFN):
'''
Iterator that yields tuples containing a sequence label and the sequence itself
@param fastaFN - the FASTA filename to open and parse
@return - an iterator yielding tuples of the form (label, sequence) from the FASTA file
'''
if fastaFN[len(fastaFN)-3:] == '.gz':
... | [
"def",
"fastaIterator",
"(",
"fastaFN",
")",
":",
"if",
"fastaFN",
"[",
"len",
"(",
"fastaFN",
")",
"-",
"3",
":",
"]",
"==",
"'.gz'",
":",
"fp",
"=",
"gzip",
".",
"open",
"(",
"fastaFN",
",",
"'r'",
")",
"else",
":",
"fp",
"=",
"open",
"(",
"f... | Iterator that yields tuples containing a sequence label and the sequence itself
@param fastaFN - the FASTA filename to open and parse
@return - an iterator yielding tuples of the form (label, sequence) from the FASTA file | [
"Iterator",
"that",
"yields",
"tuples",
"containing",
"a",
"sequence",
"label",
"and",
"the",
"sequence",
"itself"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/util.py#L110-L137 |
44,459 | holtjma/msbwt | MUS/MultiStringBWT.py | loadBWT | def loadBWT(bwtDir, logger=None):
'''
Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression
and assign the appropriate class preferring the decompressed version if both exist.
@return - a MultiStringBWT, CompressedBWT, or none if neith... | python | def loadBWT(bwtDir, logger=None):
'''
Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression
and assign the appropriate class preferring the decompressed version if both exist.
@return - a MultiStringBWT, CompressedBWT, or none if neith... | [
"def",
"loadBWT",
"(",
"bwtDir",
",",
"logger",
"=",
"None",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"bwtDir",
"+",
"'/msbwt.npy'",
")",
":",
"msbwt",
"=",
"MultiStringBWT",
"(",
")",
"msbwt",
".",
"loadMsbwt",
"(",
"bwtDir",
",",
"log... | Generic load function, this is recommended for anyone wishing to use this code as it will automatically detect compression
and assign the appropriate class preferring the decompressed version if both exist.
@return - a MultiStringBWT, CompressedBWT, or none if neither can be instantiated | [
"Generic",
"load",
"function",
"this",
"is",
"recommended",
"for",
"anyone",
"wishing",
"to",
"use",
"this",
"code",
"as",
"it",
"will",
"automatically",
"detect",
"compression",
"and",
"assign",
"the",
"appropriate",
"class",
"preferring",
"the",
"decompressed",
... | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L730-L746 |
44,460 | holtjma/msbwt | MUS/MultiStringBWT.py | createMSBWTFromSeqs | def createMSBWTFromSeqs(seqArray, mergedDir, numProcs, areUniform, logger):
'''
This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
@param seqArray - a list of '$'-terminated sequences to be in the MSBWT
@param mergedFN - the final destination filename fo... | python | def createMSBWTFromSeqs(seqArray, mergedDir, numProcs, areUniform, logger):
'''
This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
@param seqArray - a list of '$'-terminated sequences to be in the MSBWT
@param mergedFN - the final destination filename fo... | [
"def",
"createMSBWTFromSeqs",
"(",
"seqArray",
",",
"mergedDir",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")",
":",
"#wipe the auxiliary data stored here",
"MSBWTGen",
".",
"clearAuxiliaryData",
"(",
"mergedDir",
")",
"#TODO: do we want a special case for N=1? the... | This function takes a series of sequences and creates the BWT using the technique from Cox and Bauer
@param seqArray - a list of '$'-terminated sequences to be in the MSBWT
@param mergedFN - the final destination filename for the BWT
@param numProcs - the number of processes it's allowed to use | [
"This",
"function",
"takes",
"a",
"series",
"of",
"sequences",
"and",
"creates",
"the",
"BWT",
"using",
"the",
"technique",
"from",
"Cox",
"and",
"Bauer"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L748-L776 |
44,461 | holtjma/msbwt | MUS/MultiStringBWT.py | createMSBWTFromFastq | def createMSBWTFromFastq(fastqFNs, outputDir, numProcs, areUniform, logger):
'''
This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading
all string prior to computation
@param fastqFNs - a list of fastq filenames to extract sequences from
@par... | python | def createMSBWTFromFastq(fastqFNs, outputDir, numProcs, areUniform, logger):
'''
This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading
all string prior to computation
@param fastqFNs - a list of fastq filenames to extract sequences from
@par... | [
"def",
"createMSBWTFromFastq",
"(",
"fastqFNs",
",",
"outputDir",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")",
":",
"#generate the files we will reference and clear out the in memory array before making the BWT",
"logger",
".",
"info",
"(",
"'Saving sorted sequences.... | This function takes fasta filenames and creates the BWT using the technique from Cox and Bauer by simply loading
all string prior to computation
@param fastqFNs - a list of fastq filenames to extract sequences from
@param outputDir - the directory for all of the bwt related data
@param numProcs - the nu... | [
"This",
"function",
"takes",
"fasta",
"filenames",
"and",
"creates",
"the",
"BWT",
"using",
"the",
"technique",
"from",
"Cox",
"and",
"Bauer",
"by",
"simply",
"loading",
"all",
"string",
"prior",
"to",
"computation"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L778-L796 |
44,462 | holtjma/msbwt | MUS/MultiStringBWT.py | createMSBWTFromBam | def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger):
'''
This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory fo... | python | def createMSBWTFromBam(bamFNs, outputDir, numProcs, areUniform, logger):
'''
This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory fo... | [
"def",
"createMSBWTFromBam",
"(",
"bamFNs",
",",
"outputDir",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")",
":",
"#generate the files we will reference and clear out the in memory array before making the BWT",
"logger",
".",
"info",
"(",
"'Saving sorted sequences...'"... | This function takes a fasta filename and creates the BWT using the technique from Cox and Bauer
@param bamFNs - a list of BAM filenames to extract sequences from, READS MUST BE SORTED BY NAME
@param outputDir - the directory for all of the bwt related data
@param numProcs - the number of processes it's allo... | [
"This",
"function",
"takes",
"a",
"fasta",
"filename",
"and",
"creates",
"the",
"BWT",
"using",
"the",
"technique",
"from",
"Cox",
"and",
"Bauer"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L798-L815 |
44,463 | holtjma/msbwt | MUS/MultiStringBWT.py | mergeNewSeqs | def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger):
'''
This function takes a series of sequences and creates a big BWT by merging the smaller ones
Mostly a test function, no real purpose to the tool as of now
@param seqArray - a list of '$'-terminated strings to be placed into the arr... | python | def mergeNewSeqs(seqArray, mergedDir, numProcs, areUniform, logger):
'''
This function takes a series of sequences and creates a big BWT by merging the smaller ones
Mostly a test function, no real purpose to the tool as of now
@param seqArray - a list of '$'-terminated strings to be placed into the arr... | [
"def",
"mergeNewSeqs",
"(",
"seqArray",
",",
"mergedDir",
",",
"numProcs",
",",
"areUniform",
",",
"logger",
")",
":",
"#first wipe away any traces of old information for the case of overwriting a BWT at mergedFN",
"MSBWTGen",
".",
"clearAuxiliaryData",
"(",
"mergedDir",
")",... | This function takes a series of sequences and creates a big BWT by merging the smaller ones
Mostly a test function, no real purpose to the tool as of now
@param seqArray - a list of '$'-terminated strings to be placed into the array
@param mergedFN - the final destination filename for the merged BWT
@p... | [
"This",
"function",
"takes",
"a",
"series",
"of",
"sequences",
"and",
"creates",
"a",
"big",
"BWT",
"by",
"merging",
"the",
"smaller",
"ones",
"Mostly",
"a",
"test",
"function",
"no",
"real",
"purpose",
"to",
"the",
"tool",
"as",
"of",
"now"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L1088-L1126 |
44,464 | holtjma/msbwt | MUS/MultiStringBWT.py | compareKmerProfiles | def compareKmerProfiles(profileFN1, profileFN2):
'''
This function takes two kmer profiles and compare them for similarity.
@param profileFN1 - the first kmer-profile to compare to
@param profileFN2 - the second kmer-profile to compare to
@return - a tuple of the form (1-norm, 2-norm, sum of differe... | python | def compareKmerProfiles(profileFN1, profileFN2):
'''
This function takes two kmer profiles and compare them for similarity.
@param profileFN1 - the first kmer-profile to compare to
@param profileFN2 - the second kmer-profile to compare to
@return - a tuple of the form (1-norm, 2-norm, sum of differe... | [
"def",
"compareKmerProfiles",
"(",
"profileFN1",
",",
"profileFN2",
")",
":",
"fp1",
"=",
"open",
"(",
"profileFN1",
",",
"'r'",
")",
"fp2",
"=",
"open",
"(",
"profileFN2",
",",
"'r'",
")",
"oneNorm",
"=",
"0",
"twoNorm",
"=",
"0",
"sumDeltas",
"=",
"0... | This function takes two kmer profiles and compare them for similarity.
@param profileFN1 - the first kmer-profile to compare to
@param profileFN2 - the second kmer-profile to compare to
@return - a tuple of the form (1-norm, 2-norm, sum of differences, normalized Dot product) | [
"This",
"function",
"takes",
"two",
"kmer",
"profiles",
"and",
"compare",
"them",
"for",
"similarity",
"."
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L1128-L1175 |
44,465 | holtjma/msbwt | MUS/MultiStringBWT.py | parseProfileLine | def parseProfileLine(fp):
'''
Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int)
'''
nextLine = fp.readline()
if nextLine == None or nextLine == '':
return (None, None)
else:
pieces = nex... | python | def parseProfileLine(fp):
'''
Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int)
'''
nextLine = fp.readline()
if nextLine == None or nextLine == '':
return (None, None)
else:
pieces = nex... | [
"def",
"parseProfileLine",
"(",
"fp",
")",
":",
"nextLine",
"=",
"fp",
".",
"readline",
"(",
")",
"if",
"nextLine",
"==",
"None",
"or",
"nextLine",
"==",
"''",
":",
"return",
"(",
"None",
",",
"None",
")",
"else",
":",
"pieces",
"=",
"nextLine",
".",... | Helper function for profile parsing
@param fp - the file pointer to get the next line from
@return - (kmer, kmerCount) as (string, int) | [
"Helper",
"function",
"for",
"profile",
"parsing"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L1177-L1188 |
44,466 | holtjma/msbwt | MUS/MultiStringBWT.py | reverseComplement | def reverseComplement(seq):
'''
Helper function for generating reverse-complements
'''
revComp = ''
complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'}
for c in reversed(seq):
revComp += complement[c]
return revComp | python | def reverseComplement(seq):
'''
Helper function for generating reverse-complements
'''
revComp = ''
complement = {'A':'T', 'C':'G', 'G':'C', 'T':'A', 'N':'N', '$':'$'}
for c in reversed(seq):
revComp += complement[c]
return revComp | [
"def",
"reverseComplement",
"(",
"seq",
")",
":",
"revComp",
"=",
"''",
"complement",
"=",
"{",
"'A'",
":",
"'T'",
",",
"'C'",
":",
"'G'",
",",
"'G'",
":",
"'C'",
",",
"'T'",
":",
"'A'",
",",
"'N'",
":",
"'N'",
",",
"'$'",
":",
"'$'",
"}",
"for... | Helper function for generating reverse-complements | [
"Helper",
"function",
"for",
"generating",
"reverse",
"-",
"complements"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L1408-L1416 |
44,467 | holtjma/msbwt | MUS/MultiStringBWT.py | BasicBWT.countOccurrencesOfSeq | def countOccurrencesOfSeq(self, seq, givenRange=None):
'''
This function counts the number of occurrences of the given sequence
@param seq - the sequence to search for
@param givenRange - the range to start from (if a partial search has already been run), default=whole range
@ret... | python | def countOccurrencesOfSeq(self, seq, givenRange=None):
'''
This function counts the number of occurrences of the given sequence
@param seq - the sequence to search for
@param givenRange - the range to start from (if a partial search has already been run), default=whole range
@ret... | [
"def",
"countOccurrencesOfSeq",
"(",
"self",
",",
"seq",
",",
"givenRange",
"=",
"None",
")",
":",
"#init the current range",
"if",
"givenRange",
"==",
"None",
":",
"if",
"not",
"self",
".",
"searchCache",
".",
"has_key",
"(",
"seq",
"[",
"-",
"self",
".",... | This function counts the number of occurrences of the given sequence
@param seq - the sequence to search for
@param givenRange - the range to start from (if a partial search has already been run), default=whole range
@return - an integer count of the number of times seq occurred in this BWT | [
"This",
"function",
"counts",
"the",
"number",
"of",
"occurrences",
"of",
"the",
"given",
"sequence"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L79-L112 |
44,468 | holtjma/msbwt | MUS/MultiStringBWT.py | BasicBWT.recoverString | def recoverString(self, strIndex, withIndex=False):
'''
This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index
'''
retNums = []
indi... | python | def recoverString(self, strIndex, withIndex=False):
'''
This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index
'''
retNums = []
indi... | [
"def",
"recoverString",
"(",
"self",
",",
"strIndex",
",",
"withIndex",
"=",
"False",
")",
":",
"retNums",
"=",
"[",
"]",
"indices",
"=",
"[",
"]",
"#figure out the first hop backwards",
"currIndex",
"=",
"strIndex",
"prevChar",
"=",
"self",
".",
"getCharAtInd... | This will return the string that starts at the given index
@param strIndex - the index of the string we want to recover
@return - string that we found starting at the specified '$' index | [
"This",
"will",
"return",
"the",
"string",
"that",
"starts",
"at",
"the",
"given",
"index"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L169-L209 |
44,469 | holtjma/msbwt | MUS/MultiStringBWT.py | MultiStringBWT.getOccurrenceOfCharAtIndex | def getOccurrenceOfCharAtIndex(self, sym, index):
'''
This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of o... | python | def getOccurrenceOfCharAtIndex(self, sym, index):
'''
This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of o... | [
"def",
"getOccurrenceOfCharAtIndex",
"(",
"self",
",",
"sym",
",",
"index",
")",
":",
"#sampling method",
"#get the bin we occupy",
"binID",
"=",
"index",
">>",
"self",
".",
"bitPower",
"#these two methods seem to have the same approximate run time",
"if",
"(",
"binID",
... | This functions gets the FM-index value of a character at the specified position
@param sym - the character to find the occurrence level
@param index - the index we want to find the occurrence level at
@return - the number of occurrences of char before the specified index | [
"This",
"functions",
"gets",
"the",
"FM",
"-",
"index",
"value",
"of",
"a",
"character",
"at",
"the",
"specified",
"position"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L319-L335 |
44,470 | holtjma/msbwt | MUS/MultiStringBWT.py | CompressedMSBWT.loadMsbwt | def loadMsbwt(self, dirName, logger):
'''
This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail
'''
#open the file ... | python | def loadMsbwt(self, dirName, logger):
'''
This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail
'''
#open the file ... | [
"def",
"loadMsbwt",
"(",
"self",
",",
"dirName",
",",
"logger",
")",
":",
"#open the file with our BWT in it",
"self",
".",
"dirName",
"=",
"dirName",
"self",
".",
"bwt",
"=",
"np",
".",
"load",
"(",
"self",
".",
"dirName",
"+",
"'/comp_msbwt.npy'",
",",
"... | This functions loads a BWT file and constructs total counts, indexes start positions, and constructs an FM index in memory
@param dirName - the directory to load, inside should be '<DIR>/comp_msbwt.npy' or it will fail | [
"This",
"functions",
"loads",
"a",
"BWT",
"file",
"and",
"constructs",
"total",
"counts",
"indexes",
"start",
"positions",
"and",
"constructs",
"an",
"FM",
"index",
"in",
"memory"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L396-L408 |
44,471 | holtjma/msbwt | MUS/MultiStringBWT.py | CompressedMSBWT.getCharAtIndex | def getCharAtIndex(self, index):
'''
Used for searching, this function masks the complexity behind retrieving a specific character at a specific index
in our compressed BWT.
@param index - the index to retrieve the character from
@param return - return the character in our BWT th... | python | def getCharAtIndex(self, index):
'''
Used for searching, this function masks the complexity behind retrieving a specific character at a specific index
in our compressed BWT.
@param index - the index to retrieve the character from
@param return - return the character in our BWT th... | [
"def",
"getCharAtIndex",
"(",
"self",
",",
"index",
")",
":",
"#get the bin we should start from",
"binID",
"=",
"index",
">>",
"self",
".",
"bitPower",
"bwtIndex",
"=",
"self",
".",
"refFM",
"[",
"binID",
"]",
"#these are the values that indicate how far in we really... | Used for searching, this function masks the complexity behind retrieving a specific character at a specific index
in our compressed BWT.
@param index - the index to retrieve the character from
@param return - return the character in our BWT that's at a particular index (integer format) | [
"Used",
"for",
"searching",
"this",
"function",
"masks",
"the",
"complexity",
"behind",
"retrieving",
"a",
"specific",
"character",
"at",
"a",
"specific",
"index",
"in",
"our",
"compressed",
"BWT",
"."
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L555-L593 |
44,472 | holtjma/msbwt | MUS/MultiStringBWT.py | CompressedMSBWT.getBWTRange | def getBWTRange(self, start, end):
'''
This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
... | python | def getBWTRange(self, start, end):
'''
This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
... | [
"def",
"getBWTRange",
"(",
"self",
",",
"start",
",",
"end",
")",
":",
"#set aside an array block to fill",
"startBlockIndex",
"=",
"start",
">>",
"self",
".",
"bitPower",
"endBlockIndex",
"=",
"int",
"(",
"math",
".",
"floor",
"(",
"float",
"(",
"end",
")",... | This function masks the complexity of retrieving a chunk of the BWT from the compressed format
@param start - the beginning of the range to retrieve
@param end - the end of the range in normal python notation (bwt[end] is not part of the return)
@return - a range of integers representing the cha... | [
"This",
"function",
"masks",
"the",
"complexity",
"of",
"retrieving",
"a",
"chunk",
"of",
"the",
"BWT",
"from",
"the",
"compressed",
"format"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L595-L608 |
44,473 | holtjma/msbwt | MUS/MultiStringBWT.py | CompressedMSBWT.decompressBlocks | def decompressBlocks(self, startBlock, endBlock):
'''
This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in
decompression
@param startBlock - the index of the start block we will decode
@param endBlock - the index of the fi... | python | def decompressBlocks(self, startBlock, endBlock):
'''
This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in
decompression
@param startBlock - the index of the start block we will decode
@param endBlock - the index of the fi... | [
"def",
"decompressBlocks",
"(",
"self",
",",
"startBlock",
",",
"endBlock",
")",
":",
"expectedIndex",
"=",
"startBlock",
"*",
"self",
".",
"binSize",
"trueIndex",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"partialFM",
"[",
"startBlock",
"]",
")",
"-",
"s... | This is mostly a helper function to get BWT range, but I wanted it to be a separate thing for use possibly in
decompression
@param startBlock - the index of the start block we will decode
@param endBlock - the index of the final block we will decode, if they are the same, we decode one block
... | [
"This",
"is",
"mostly",
"a",
"helper",
"function",
"to",
"get",
"BWT",
"range",
"but",
"I",
"wanted",
"it",
"to",
"be",
"a",
"separate",
"thing",
"for",
"use",
"possibly",
"in",
"decompression"
] | 7503346ec072ddb89520db86fef85569a9ba093a | https://github.com/holtjma/msbwt/blob/7503346ec072ddb89520db86fef85569a9ba093a/MUS/MultiStringBWT.py#L610-L666 |
44,474 | bookieio/breadability | breadability/document.py | decode_html | def decode_html(html):
"""
Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library.
"""
if isinstance(html, unicode):
return html
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_enco... | python | def decode_html(html):
"""
Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library.
"""
if isinstance(html, unicode):
return html
match = CHARSET_META_TAG_PATTERN.search(html)
if match:
declared_enco... | [
"def",
"decode_html",
"(",
"html",
")",
":",
"if",
"isinstance",
"(",
"html",
",",
"unicode",
")",
":",
"return",
"html",
"match",
"=",
"CHARSET_META_TAG_PATTERN",
".",
"search",
"(",
"html",
")",
"if",
"match",
":",
"declared_encoding",
"=",
"match",
".",... | Converts bytes stream containing an HTML page into Unicode.
Tries to guess character encoding from meta tag of by "chardet" library. | [
"Converts",
"bytes",
"stream",
"containing",
"an",
"HTML",
"page",
"into",
"Unicode",
".",
"Tries",
"to",
"guess",
"character",
"encoding",
"from",
"meta",
"tag",
"of",
"by",
"chardet",
"library",
"."
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/document.py#L28-L61 |
44,475 | bookieio/breadability | breadability/document.py | build_document | def build_document(html_content, base_href=None):
"""Requires that the `html_content` not be None"""
assert html_content is not None
if isinstance(html_content, unicode):
html_content = html_content.encode("utf8", "xmlcharrefreplace")
try:
document = document_fromstring(html_content, p... | python | def build_document(html_content, base_href=None):
"""Requires that the `html_content` not be None"""
assert html_content is not None
if isinstance(html_content, unicode):
html_content = html_content.encode("utf8", "xmlcharrefreplace")
try:
document = document_fromstring(html_content, p... | [
"def",
"build_document",
"(",
"html_content",
",",
"base_href",
"=",
"None",
")",
":",
"assert",
"html_content",
"is",
"not",
"None",
"if",
"isinstance",
"(",
"html_content",
",",
"unicode",
")",
":",
"html_content",
"=",
"html_content",
".",
"encode",
"(",
... | Requires that the `html_content` not be None | [
"Requires",
"that",
"the",
"html_content",
"not",
"be",
"None"
] | 95a364c43b00baf6664bea1997a7310827fb1ee9 | https://github.com/bookieio/breadability/blob/95a364c43b00baf6664bea1997a7310827fb1ee9/breadability/document.py#L90-L107 |
44,476 | ngzhian/pycrunchbase | src/pycrunchbase/resource/node.py | Node._parse_properties | def _parse_properties(self):
"""Nodes have properties, which are facts like the
name, description, url etc.
Loop through each of them and set it as attributes on this company so
that we can make calls like
company.name
person.description
"""
props_... | python | def _parse_properties(self):
"""Nodes have properties, which are facts like the
name, description, url etc.
Loop through each of them and set it as attributes on this company so
that we can make calls like
company.name
person.description
"""
props_... | [
"def",
"_parse_properties",
"(",
"self",
")",
":",
"props_dict",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'properties'",
",",
"{",
"}",
")",
"for",
"prop_name",
"in",
"self",
".",
"KNOWN_PROPERTIES",
":",
"if",
"prop_name",
"in",
"props_dict",
":",
"s... | Nodes have properties, which are facts like the
name, description, url etc.
Loop through each of them and set it as attributes on this company so
that we can make calls like
company.name
person.description | [
"Nodes",
"have",
"properties",
"which",
"are",
"facts",
"like",
"the",
"name",
"description",
"url",
"etc",
".",
"Loop",
"through",
"each",
"of",
"them",
"and",
"set",
"it",
"as",
"attributes",
"on",
"this",
"company",
"so",
"that",
"we",
"can",
"make",
... | 8635ee343ff0d02db01e15967e00894ea2a37b7d | https://github.com/ngzhian/pycrunchbase/blob/8635ee343ff0d02db01e15967e00894ea2a37b7d/src/pycrunchbase/resource/node.py#L23-L36 |
44,477 | ngzhian/pycrunchbase | src/pycrunchbase/resource/node.py | Node._parse_relationship | def _parse_relationship(self):
"""Nodes have Relationships, and similarly to properties,
we set it as an attribute on the Organization so we can make calls like
company.current_team
person.degrees
"""
rs_dict = self.data.get('relationships', {})
for rs_nam... | python | def _parse_relationship(self):
"""Nodes have Relationships, and similarly to properties,
we set it as an attribute on the Organization so we can make calls like
company.current_team
person.degrees
"""
rs_dict = self.data.get('relationships', {})
for rs_nam... | [
"def",
"_parse_relationship",
"(",
"self",
")",
":",
"rs_dict",
"=",
"self",
".",
"data",
".",
"get",
"(",
"'relationships'",
",",
"{",
"}",
")",
"for",
"rs_name",
"in",
"self",
".",
"KNOWN_RELATIONSHIPS",
":",
"if",
"rs_name",
"in",
"rs_dict",
":",
"set... | Nodes have Relationships, and similarly to properties,
we set it as an attribute on the Organization so we can make calls like
company.current_team
person.degrees | [
"Nodes",
"have",
"Relationships",
"and",
"similarly",
"to",
"properties",
"we",
"set",
"it",
"as",
"an",
"attribute",
"on",
"the",
"Organization",
"so",
"we",
"can",
"make",
"calls",
"like",
"company",
".",
"current_team",
"person",
".",
"degrees"
] | 8635ee343ff0d02db01e15967e00894ea2a37b7d | https://github.com/ngzhian/pycrunchbase/blob/8635ee343ff0d02db01e15967e00894ea2a37b7d/src/pycrunchbase/resource/node.py#L38-L51 |
44,478 | AmesCornish/buttersink | buttersink/progress.py | DisplayProgress.open | def open(self):
""" Reset time and counts. """
self.startTime = datetime.datetime.now()
self.offset = 0
return self | python | def open(self):
""" Reset time and counts. """
self.startTime = datetime.datetime.now()
self.offset = 0
return self | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"startTime",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"offset",
"=",
"0",
"return",
"self"
] | Reset time and counts. | [
"Reset",
"time",
"and",
"counts",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/progress.py#L28-L32 |
44,479 | AmesCornish/buttersink | buttersink/progress.py | DisplayProgress.update | def update(self, sent):
""" Update self and parent with intermediate progress. """
self.offset = sent
now = datetime.datetime.now()
elapsed = (now - self.startTime).total_seconds()
if elapsed > 0:
mbps = (sent * 8 / (10 ** 6)) / elapsed
else:
mbp... | python | def update(self, sent):
""" Update self and parent with intermediate progress. """
self.offset = sent
now = datetime.datetime.now()
elapsed = (now - self.startTime).total_seconds()
if elapsed > 0:
mbps = (sent * 8 / (10 ** 6)) / elapsed
else:
mbp... | [
"def",
"update",
"(",
"self",
",",
"sent",
")",
":",
"self",
".",
"offset",
"=",
"sent",
"now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"elapsed",
"=",
"(",
"now",
"-",
"self",
".",
"startTime",
")",
".",
"total_seconds",
"(",
")",
... | Update self and parent with intermediate progress. | [
"Update",
"self",
"and",
"parent",
"with",
"intermediate",
"progress",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/progress.py#L39-L51 |
44,480 | AmesCornish/buttersink | buttersink/progress.py | DisplayProgress._display | def _display(self, sent, now, chunk, mbps):
""" Display intermediate progress. """
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent... | python | def _display(self, sent, now, chunk, mbps):
""" Display intermediate progress. """
if self.parent is not None:
self.parent._display(self.parent.offset + sent, now, chunk, mbps)
return
elapsed = now - self.startTime
if sent > 0 and self.total is not None and sent... | [
"def",
"_display",
"(",
"self",
",",
"sent",
",",
"now",
",",
"chunk",
",",
"mbps",
")",
":",
"if",
"self",
".",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"parent",
".",
"_display",
"(",
"self",
".",
"parent",
".",
"offset",
"+",
"sent",
"... | Display intermediate progress. | [
"Display",
"intermediate",
"progress",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/progress.py#L53-L80 |
44,481 | AmesCornish/buttersink | buttersink/progress.py | DisplayProgress.close | def close(self):
""" Stop overwriting display, or update parent. """
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
self.output.write("\n")
self.output.flush() | python | def close(self):
""" Stop overwriting display, or update parent. """
if self.parent:
self.parent.update(self.parent.offset + self.offset)
return
self.output.write("\n")
self.output.flush() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
":",
"self",
".",
"parent",
".",
"update",
"(",
"self",
".",
"parent",
".",
"offset",
"+",
"self",
".",
"offset",
")",
"return",
"self",
".",
"output",
".",
"write",
"(",
"\"\\n\""... | Stop overwriting display, or update parent. | [
"Stop",
"overwriting",
"display",
"or",
"update",
"parent",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/progress.py#L82-L88 |
44,482 | AmesCornish/buttersink | buttersink/Store.py | _printUUID | def _printUUID(uuid, detail='word'):
""" Return friendly abbreviated string for uuid. """
if not isinstance(detail, int):
detail = detailNum[detail]
if detail > detailNum['word']:
return uuid
if uuid is None:
return None
return "%s...%s" % (uuid[:4], uuid[-4:]) | python | def _printUUID(uuid, detail='word'):
""" Return friendly abbreviated string for uuid. """
if not isinstance(detail, int):
detail = detailNum[detail]
if detail > detailNum['word']:
return uuid
if uuid is None:
return None
return "%s...%s" % (uuid[:4], uuid[-4:]) | [
"def",
"_printUUID",
"(",
"uuid",
",",
"detail",
"=",
"'word'",
")",
":",
"if",
"not",
"isinstance",
"(",
"detail",
",",
"int",
")",
":",
"detail",
"=",
"detailNum",
"[",
"detail",
"]",
"if",
"detail",
">",
"detailNum",
"[",
"'word'",
"]",
":",
"retu... | Return friendly abbreviated string for uuid. | [
"Return",
"friendly",
"abbreviated",
"string",
"for",
"uuid",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L527-L538 |
44,483 | AmesCornish/buttersink | buttersink/Store.py | skipDryRun | def skipDryRun(logger, dryRun, level=logging.DEBUG):
""" Return logging function.
When logging function called, will return True if action should be skipped.
Log will indicate if skipped because of dry run.
"""
# This is an undocumented "feature" of logging module:
# logging.log() requires a nu... | python | def skipDryRun(logger, dryRun, level=logging.DEBUG):
""" Return logging function.
When logging function called, will return True if action should be skipped.
Log will indicate if skipped because of dry run.
"""
# This is an undocumented "feature" of logging module:
# logging.log() requires a nu... | [
"def",
"skipDryRun",
"(",
"logger",
",",
"dryRun",
",",
"level",
"=",
"logging",
".",
"DEBUG",
")",
":",
"# This is an undocumented \"feature\" of logging module:",
"# logging.log() requires a numeric level",
"# logging.getLevelName() maps names to numbers",
"if",
"not",
"isins... | Return logging function.
When logging function called, will return True if action should be skipped.
Log will indicate if skipped because of dry run. | [
"Return",
"logging",
"function",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L541-L555 |
44,484 | AmesCornish/buttersink | buttersink/Store.py | Store.listVolumes | def listVolumes(self):
""" Return list of all volumes in this Store's selected directory. """
for (vol, paths) in self.paths.items():
for path in paths:
if path.startswith('/'):
continue
if path == '.':
continue
... | python | def listVolumes(self):
""" Return list of all volumes in this Store's selected directory. """
for (vol, paths) in self.paths.items():
for path in paths:
if path.startswith('/'):
continue
if path == '.':
continue
... | [
"def",
"listVolumes",
"(",
"self",
")",
":",
"for",
"(",
"vol",
",",
"paths",
")",
"in",
"self",
".",
"paths",
".",
"items",
"(",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"path",
".",
"startswith",
"(",
"'/'",
")",
":",
"continue",
"if"... | Return list of all volumes in this Store's selected directory. | [
"Return",
"list",
"of",
"all",
"volumes",
"in",
"this",
"Store",
"s",
"selected",
"directory",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L90-L101 |
44,485 | AmesCornish/buttersink | buttersink/Store.py | Store.getSendPath | def getSendPath(self, volume):
""" Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store.
"""
try:
return self._fullPath(next(iter(self.getPaths(volume))))
except StopIteration:
return None | python | def getSendPath(self, volume):
""" Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store.
"""
try:
return self._fullPath(next(iter(self.getPaths(volume))))
except StopIteration:
return None | [
"def",
"getSendPath",
"(",
"self",
",",
"volume",
")",
":",
"try",
":",
"return",
"self",
".",
"_fullPath",
"(",
"next",
"(",
"iter",
"(",
"self",
".",
"getPaths",
"(",
"volume",
")",
")",
")",
")",
"except",
"StopIteration",
":",
"return",
"None"
] | Get a path appropriate for sending the volume from this Store.
The path may be relative or absolute in this Store. | [
"Get",
"a",
"path",
"appropriate",
"for",
"sending",
"the",
"volume",
"from",
"this",
"Store",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L107-L116 |
44,486 | AmesCornish/buttersink | buttersink/Store.py | Store.selectReceivePath | def selectReceivePath(self, paths):
""" From a set of source paths, recommend a destination path.
The paths are relative or absolute, in a source Store.
The result will be absolute, suitable for this destination Store.
"""
logger.debug("%s", paths)
if not paths:
... | python | def selectReceivePath(self, paths):
""" From a set of source paths, recommend a destination path.
The paths are relative or absolute, in a source Store.
The result will be absolute, suitable for this destination Store.
"""
logger.debug("%s", paths)
if not paths:
... | [
"def",
"selectReceivePath",
"(",
"self",
",",
"paths",
")",
":",
"logger",
".",
"debug",
"(",
"\"%s\"",
",",
"paths",
")",
"if",
"not",
"paths",
":",
"path",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"userPath",
")",
"+",
"'/Anon'",
... | From a set of source paths, recommend a destination path.
The paths are relative or absolute, in a source Store.
The result will be absolute, suitable for this destination Store. | [
"From",
"a",
"set",
"of",
"source",
"paths",
"recommend",
"a",
"destination",
"path",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L118-L137 |
44,487 | AmesCornish/buttersink | buttersink/Store.py | Store._relativePath | def _relativePath(self, fullPath):
""" Return fullPath relative to Store directory.
Return fullPath if fullPath is not inside directory.
Return None if fullPath is outside our scope.
"""
if fullPath is None:
return None
assert fullPath.startswith("/"), full... | python | def _relativePath(self, fullPath):
""" Return fullPath relative to Store directory.
Return fullPath if fullPath is not inside directory.
Return None if fullPath is outside our scope.
"""
if fullPath is None:
return None
assert fullPath.startswith("/"), full... | [
"def",
"_relativePath",
"(",
"self",
",",
"fullPath",
")",
":",
"if",
"fullPath",
"is",
"None",
":",
"return",
"None",
"assert",
"fullPath",
".",
"startswith",
"(",
"\"/\"",
")",
",",
"fullPath",
"path",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"fu... | Return fullPath relative to Store directory.
Return fullPath if fullPath is not inside directory.
Return None if fullPath is outside our scope. | [
"Return",
"fullPath",
"relative",
"to",
"Store",
"directory",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L148-L167 |
44,488 | AmesCornish/buttersink | buttersink/Store.py | Diff.setSize | def setSize(self, size, sizeIsEstimated):
""" Update size. """
self._size = size
self._sizeIsEstimated = sizeIsEstimated
if self.fromVol is not None and size is not None and not sizeIsEstimated:
Diff.theKnownSizes[self.toUUID][self.fromUUID] = size | python | def setSize(self, size, sizeIsEstimated):
""" Update size. """
self._size = size
self._sizeIsEstimated = sizeIsEstimated
if self.fromVol is not None and size is not None and not sizeIsEstimated:
Diff.theKnownSizes[self.toUUID][self.fromUUID] = size | [
"def",
"setSize",
"(",
"self",
",",
"size",
",",
"sizeIsEstimated",
")",
":",
"self",
".",
"_size",
"=",
"size",
"self",
".",
"_sizeIsEstimated",
"=",
"sizeIsEstimated",
"if",
"self",
".",
"fromVol",
"is",
"not",
"None",
"and",
"size",
"is",
"not",
"None... | Update size. | [
"Update",
"size",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L333-L339 |
44,489 | AmesCornish/buttersink | buttersink/Store.py | Diff.sendTo | def sendTo(self, dest, chunkSize):
""" Send this difference to the dest Store. """
vol = self.toVol
paths = self.sink.getPaths(vol)
if self.sink == dest:
logger.info("Keep: %s", self)
self.sink.keep(self)
else:
# Log, but don't skip yet, so we... | python | def sendTo(self, dest, chunkSize):
""" Send this difference to the dest Store. """
vol = self.toVol
paths = self.sink.getPaths(vol)
if self.sink == dest:
logger.info("Keep: %s", self)
self.sink.keep(self)
else:
# Log, but don't skip yet, so we... | [
"def",
"sendTo",
"(",
"self",
",",
"dest",
",",
"chunkSize",
")",
":",
"vol",
"=",
"self",
".",
"toVol",
"paths",
"=",
"self",
".",
"sink",
".",
"getPaths",
"(",
"vol",
")",
"if",
"self",
".",
"sink",
"==",
"dest",
":",
"logger",
".",
"info",
"("... | Send this difference to the dest Store. | [
"Send",
"this",
"difference",
"to",
"the",
"dest",
"Store",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L341-L372 |
44,490 | AmesCornish/buttersink | buttersink/Store.py | Volume.writeInfoLine | def writeInfoLine(self, stream, fromUUID, size):
""" Write one line of diff information. """
if size is None or fromUUID is None:
return
if not isinstance(size, int):
logger.warning("Bad size: %s", size)
return
stream.write(str("%s\t%s\t%d\n" % (
... | python | def writeInfoLine(self, stream, fromUUID, size):
""" Write one line of diff information. """
if size is None or fromUUID is None:
return
if not isinstance(size, int):
logger.warning("Bad size: %s", size)
return
stream.write(str("%s\t%s\t%d\n" % (
... | [
"def",
"writeInfoLine",
"(",
"self",
",",
"stream",
",",
"fromUUID",
",",
"size",
")",
":",
"if",
"size",
"is",
"None",
"or",
"fromUUID",
"is",
"None",
":",
"return",
"if",
"not",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"logger",
".",
"warni... | Write one line of diff information. | [
"Write",
"one",
"line",
"of",
"diff",
"information",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L425-L436 |
44,491 | AmesCornish/buttersink | buttersink/Store.py | Volume.writeInfo | def writeInfo(self, stream):
""" Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size) | python | def writeInfo(self, stream):
""" Write information about diffs into a file stream for use later. """
for (fromUUID, size) in Diff.theKnownSizes[self.uuid].iteritems():
self.writeInfoLine(stream, fromUUID, size) | [
"def",
"writeInfo",
"(",
"self",
",",
"stream",
")",
":",
"for",
"(",
"fromUUID",
",",
"size",
")",
"in",
"Diff",
".",
"theKnownSizes",
"[",
"self",
".",
"uuid",
"]",
".",
"iteritems",
"(",
")",
":",
"self",
".",
"writeInfoLine",
"(",
"stream",
",",
... | Write information about diffs into a file stream for use later. | [
"Write",
"information",
"about",
"diffs",
"into",
"a",
"file",
"stream",
"for",
"use",
"later",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L438-L441 |
44,492 | AmesCornish/buttersink | buttersink/Store.py | Volume.hasInfo | def hasInfo(self):
""" Will have information to write. """
count = len([None
for (fromUUID, size)
in Diff.theKnownSizes[self.uuid].iteritems()
if size is not None and fromUUID is not None
])
return count > 0 | python | def hasInfo(self):
""" Will have information to write. """
count = len([None
for (fromUUID, size)
in Diff.theKnownSizes[self.uuid].iteritems()
if size is not None and fromUUID is not None
])
return count > 0 | [
"def",
"hasInfo",
"(",
"self",
")",
":",
"count",
"=",
"len",
"(",
"[",
"None",
"for",
"(",
"fromUUID",
",",
"size",
")",
"in",
"Diff",
".",
"theKnownSizes",
"[",
"self",
".",
"uuid",
"]",
".",
"iteritems",
"(",
")",
"if",
"size",
"is",
"not",
"N... | Will have information to write. | [
"Will",
"have",
"information",
"to",
"write",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L443-L450 |
44,493 | AmesCornish/buttersink | buttersink/Store.py | Volume.readInfo | def readInfo(stream):
""" Read previously-written information about diffs. """
try:
for line in stream:
(toUUID, fromUUID, size) = line.split()
try:
size = int(size)
except Exception:
logger.warning("Bad ... | python | def readInfo(stream):
""" Read previously-written information about diffs. """
try:
for line in stream:
(toUUID, fromUUID, size) = line.split()
try:
size = int(size)
except Exception:
logger.warning("Bad ... | [
"def",
"readInfo",
"(",
"stream",
")",
":",
"try",
":",
"for",
"line",
"in",
"stream",
":",
"(",
"toUUID",
",",
"fromUUID",
",",
"size",
")",
"=",
"line",
".",
"split",
"(",
")",
"try",
":",
"size",
"=",
"int",
"(",
"size",
")",
"except",
"Except... | Read previously-written information about diffs. | [
"Read",
"previously",
"-",
"written",
"information",
"about",
"diffs",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L453-L466 |
44,494 | AmesCornish/buttersink | buttersink/Store.py | Volume.make | def make(cls, vol):
""" Convert uuid to Volume, if necessary. """
if isinstance(vol, cls):
return vol
elif vol is None:
return None
else:
return cls(vol, None) | python | def make(cls, vol):
""" Convert uuid to Volume, if necessary. """
if isinstance(vol, cls):
return vol
elif vol is None:
return None
else:
return cls(vol, None) | [
"def",
"make",
"(",
"cls",
",",
"vol",
")",
":",
"if",
"isinstance",
"(",
"vol",
",",
"cls",
")",
":",
"return",
"vol",
"elif",
"vol",
"is",
"None",
":",
"return",
"None",
"else",
":",
"return",
"cls",
"(",
"vol",
",",
"None",
")"
] | Convert uuid to Volume, if necessary. | [
"Convert",
"uuid",
"to",
"Volume",
"if",
"necessary",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Store.py#L506-L513 |
44,495 | AmesCornish/buttersink | buttersink/S3Store.py | S3Store.hasEdge | def hasEdge(self, diff):
""" Test whether edge is in this sink. """
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]] | python | def hasEdge(self, diff):
""" Test whether edge is in this sink. """
return diff.toVol in [d.toVol for d in self.diffs[diff.fromVol]] | [
"def",
"hasEdge",
"(",
"self",
",",
"diff",
")",
":",
"return",
"diff",
".",
"toVol",
"in",
"[",
"d",
".",
"toVol",
"for",
"d",
"in",
"self",
".",
"diffs",
"[",
"diff",
".",
"fromVol",
"]",
"]"
] | Test whether edge is in this sink. | [
"Test",
"whether",
"edge",
"is",
"in",
"this",
"sink",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/S3Store.py#L176-L178 |
44,496 | AmesCornish/buttersink | buttersink/S3Store.py | S3Store._parseKeyName | def _parseKeyName(self, name):
""" Returns dict with fullpath, to, from. """
if name.endswith(Store.theInfoExtension):
return {'type': 'info'}
match = self.keyPattern.match(name)
if not match:
return None
match = match.groupdict()
match.update(ty... | python | def _parseKeyName(self, name):
""" Returns dict with fullpath, to, from. """
if name.endswith(Store.theInfoExtension):
return {'type': 'info'}
match = self.keyPattern.match(name)
if not match:
return None
match = match.groupdict()
match.update(ty... | [
"def",
"_parseKeyName",
"(",
"self",
",",
"name",
")",
":",
"if",
"name",
".",
"endswith",
"(",
"Store",
".",
"theInfoExtension",
")",
":",
"return",
"{",
"'type'",
":",
"'info'",
"}",
"match",
"=",
"self",
".",
"keyPattern",
".",
"match",
"(",
"name",... | Returns dict with fullpath, to, from. | [
"Returns",
"dict",
"with",
"fullpath",
"to",
"from",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/S3Store.py#L210-L222 |
44,497 | AmesCornish/buttersink | buttersink/util.py | humanize | def humanize(number):
""" Return a human-readable string for number. """
# units = ('bytes', 'KB', 'MB', 'GB', 'TB')
# base = 1000
units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB')
base = 1024
if number is None:
return None
pow = int(math.log(number, base)) if number > 0 else 0
pow =... | python | def humanize(number):
""" Return a human-readable string for number. """
# units = ('bytes', 'KB', 'MB', 'GB', 'TB')
# base = 1000
units = ('bytes', 'KiB', 'MiB', 'GiB', 'TiB')
base = 1024
if number is None:
return None
pow = int(math.log(number, base)) if number > 0 else 0
pow =... | [
"def",
"humanize",
"(",
"number",
")",
":",
"# units = ('bytes', 'KB', 'MB', 'GB', 'TB')",
"# base = 1000",
"units",
"=",
"(",
"'bytes'",
",",
"'KiB'",
",",
"'MiB'",
",",
"'GiB'",
",",
"'TiB'",
")",
"base",
"=",
"1024",
"if",
"number",
"is",
"None",
":",
"re... | Return a human-readable string for number. | [
"Return",
"a",
"human",
"-",
"readable",
"string",
"for",
"number",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/util.py#L24-L35 |
44,498 | AmesCornish/buttersink | buttersink/Butter.py | Butter.receive | def receive(self, path, diff, showProgress=True):
""" Return a context manager for stream that will store a diff. """
directory = os.path.dirname(path)
cmd = ["btrfs", "receive", "-e", directory]
if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd):
return None
... | python | def receive(self, path, diff, showProgress=True):
""" Return a context manager for stream that will store a diff. """
directory = os.path.dirname(path)
cmd = ["btrfs", "receive", "-e", directory]
if Store.skipDryRun(logger, self.dryrun)("Command: %s", cmd):
return None
... | [
"def",
"receive",
"(",
"self",
",",
"path",
",",
"diff",
",",
"showProgress",
"=",
"True",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
"cmd",
"=",
"[",
"\"btrfs\"",
",",
"\"receive\"",
",",
"\"-e\"",
",",
"directo... | Return a context manager for stream that will store a diff. | [
"Return",
"a",
"context",
"manager",
"for",
"stream",
"that",
"will",
"store",
"a",
"diff",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/Butter.py#L81-L101 |
44,499 | AmesCornish/buttersink | buttersink/BestDiffs.py | BestDiffs.iterDiffs | def iterDiffs(self):
""" Return all diffs used in optimal network. """
nodes = self.nodes.values()
nodes.sort(key=lambda node: self._height(node))
for node in nodes:
yield node.diff | python | def iterDiffs(self):
""" Return all diffs used in optimal network. """
nodes = self.nodes.values()
nodes.sort(key=lambda node: self._height(node))
for node in nodes:
yield node.diff | [
"def",
"iterDiffs",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"nodes",
".",
"values",
"(",
")",
"nodes",
".",
"sort",
"(",
"key",
"=",
"lambda",
"node",
":",
"self",
".",
"_height",
"(",
"node",
")",
")",
"for",
"node",
"in",
"nodes",
":"... | Return all diffs used in optimal network. | [
"Return",
"all",
"diffs",
"used",
"in",
"optimal",
"network",
"."
] | 5cc37e30d9f8071fcf3497dca8b8a91b910321ea | https://github.com/AmesCornish/buttersink/blob/5cc37e30d9f8071fcf3497dca8b8a91b910321ea/buttersink/BestDiffs.py#L301-L306 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.