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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
13,200 | ihucos/plash | opt/plash/lib/py/plash/macros/common.py | write_file | def write_file(fname, *lines):
'write lines to a file'
yield 'touch {}'.format(fname)
for line in lines:
yield "echo {} >> {}".format(line, fname) | python | def write_file(fname, *lines):
'write lines to a file'
yield 'touch {}'.format(fname)
for line in lines:
yield "echo {} >> {}".format(line, fname) | [
"def",
"write_file",
"(",
"fname",
",",
"*",
"lines",
")",
":",
"yield",
"'touch {}'",
".",
"format",
"(",
"fname",
")",
"for",
"line",
"in",
"lines",
":",
"yield",
"\"echo {} >> {}\"",
".",
"format",
"(",
"line",
",",
"fname",
")"
] | write lines to a file | [
"write",
"lines",
"to",
"a",
"file"
] | 2ab2bc956e309d5aa6414c80983bfbf29b0ce572 | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L62-L66 |
13,201 | ihucos/plash | opt/plash/lib/py/plash/macros/common.py | eval_file | def eval_file(file):
'evaluate file content as expressions'
fname = os.path.realpath(os.path.expanduser(file))
with open(fname) as f:
inscript = f.read()
sh = run_write_read(['plash', 'eval'], inscript.encode()).decode()
# we remove an possibly existing newline
# because else this mac... | python | def eval_file(file):
'evaluate file content as expressions'
fname = os.path.realpath(os.path.expanduser(file))
with open(fname) as f:
inscript = f.read()
sh = run_write_read(['plash', 'eval'], inscript.encode()).decode()
# we remove an possibly existing newline
# because else this mac... | [
"def",
"eval_file",
"(",
"file",
")",
":",
"fname",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"file",
")",
")",
"with",
"open",
"(",
"fname",
")",
"as",
"f",
":",
"inscript",
"=",
"f",
".",
"read",
... | evaluate file content as expressions | [
"evaluate",
"file",
"content",
"as",
"expressions"
] | 2ab2bc956e309d5aa6414c80983bfbf29b0ce572 | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L78-L92 |
13,202 | ihucos/plash | opt/plash/lib/py/plash/macros/common.py | eval_string | def eval_string(stri):
'evaluate expressions passed as string'
tokens = shlex.split(stri)
return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode() | python | def eval_string(stri):
'evaluate expressions passed as string'
tokens = shlex.split(stri)
return run_write_read(['plash', 'eval'], '\n'.join(tokens).encode()).decode() | [
"def",
"eval_string",
"(",
"stri",
")",
":",
"tokens",
"=",
"shlex",
".",
"split",
"(",
"stri",
")",
"return",
"run_write_read",
"(",
"[",
"'plash'",
",",
"'eval'",
"]",
",",
"'\\n'",
".",
"join",
"(",
"tokens",
")",
".",
"encode",
"(",
")",
")",
"... | evaluate expressions passed as string | [
"evaluate",
"expressions",
"passed",
"as",
"string"
] | 2ab2bc956e309d5aa6414c80983bfbf29b0ce572 | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L96-L100 |
13,203 | ihucos/plash | opt/plash/lib/py/plash/macros/common.py | eval_stdin | def eval_stdin():
'evaluate expressions read from stdin'
cmd = ['plash', 'eval']
p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout)
exit = p.wait()
if exit:
raise subprocess.CalledProcessError(exit, cmd) | python | def eval_stdin():
'evaluate expressions read from stdin'
cmd = ['plash', 'eval']
p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout)
exit = p.wait()
if exit:
raise subprocess.CalledProcessError(exit, cmd) | [
"def",
"eval_stdin",
"(",
")",
":",
"cmd",
"=",
"[",
"'plash'",
",",
"'eval'",
"]",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"sys",
".",
"stdin",
",",
"stdout",
"=",
"sys",
".",
"stdout",
")",
"exit",
"=",
"p",
".",
... | evaluate expressions read from stdin | [
"evaluate",
"expressions",
"read",
"from",
"stdin"
] | 2ab2bc956e309d5aa6414c80983bfbf29b0ce572 | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/common.py#L104-L110 |
13,204 | ihucos/plash | opt/plash/lib/py/plash/macros/froms.py | from_map | def from_map(map_key):
'use resolved map as image'
image_id = subprocess.check_output(['plash', 'map',
map_key]).decode().strip('\n')
if not image_id:
raise MapDoesNotExist('map {} not found'.format(repr(map_key)))
return hint('image', image_id) | python | def from_map(map_key):
'use resolved map as image'
image_id = subprocess.check_output(['plash', 'map',
map_key]).decode().strip('\n')
if not image_id:
raise MapDoesNotExist('map {} not found'.format(repr(map_key)))
return hint('image', image_id) | [
"def",
"from_map",
"(",
"map_key",
")",
":",
"image_id",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'plash'",
",",
"'map'",
",",
"map_key",
"]",
")",
".",
"decode",
"(",
")",
".",
"strip",
"(",
"'\\n'",
")",
"if",
"not",
"image_id",
":",
"rai... | use resolved map as image | [
"use",
"resolved",
"map",
"as",
"image"
] | 2ab2bc956e309d5aa6414c80983bfbf29b0ce572 | https://github.com/ihucos/plash/blob/2ab2bc956e309d5aa6414c80983bfbf29b0ce572/opt/plash/lib/py/plash/macros/froms.py#L61-L67 |
13,205 | dbrgn/drf-dynamic-fields | drf_dynamic_fields/__init__.py | DynamicFieldsMixin.fields | def fields(self):
"""
Filters the fields according to the `fields` query parameter.
A blank `fields` parameter (?fields) will remove all fields. Not
passing `fields` will pass all fields individual fields are comma
separated (?fields=id,name,url,email).
"""
fiel... | python | def fields(self):
"""
Filters the fields according to the `fields` query parameter.
A blank `fields` parameter (?fields) will remove all fields. Not
passing `fields` will pass all fields individual fields are comma
separated (?fields=id,name,url,email).
"""
fiel... | [
"def",
"fields",
"(",
"self",
")",
":",
"fields",
"=",
"super",
"(",
"DynamicFieldsMixin",
",",
"self",
")",
".",
"fields",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_context'",
")",
":",
"# We are being called before a request cycle",
"return",
"fields",
"#... | Filters the fields according to the `fields` query parameter.
A blank `fields` parameter (?fields) will remove all fields. Not
passing `fields` will pass all fields individual fields are comma
separated (?fields=id,name,url,email). | [
"Filters",
"the",
"fields",
"according",
"to",
"the",
"fields",
"query",
"parameter",
"."
] | d24da8bc321462ea6231821d6c3d210b76d4785b | https://github.com/dbrgn/drf-dynamic-fields/blob/d24da8bc321462ea6231821d6c3d210b76d4785b/drf_dynamic_fields/__init__.py#L16-L84 |
13,206 | aio-libs/aiohttp_admin | aiohttp_admin/admin.py | setup_admin_on_rest_handlers | def setup_admin_on_rest_handlers(admin, admin_handler):
"""
Initialize routes.
"""
add_route = admin.router.add_route
add_static = admin.router.add_static
static_folder = str(PROJ_ROOT / 'static')
a = admin_handler
add_route('GET', '', a.index_page, name='admin.index')
add_route('PO... | python | def setup_admin_on_rest_handlers(admin, admin_handler):
"""
Initialize routes.
"""
add_route = admin.router.add_route
add_static = admin.router.add_static
static_folder = str(PROJ_ROOT / 'static')
a = admin_handler
add_route('GET', '', a.index_page, name='admin.index')
add_route('PO... | [
"def",
"setup_admin_on_rest_handlers",
"(",
"admin",
",",
"admin_handler",
")",
":",
"add_route",
"=",
"admin",
".",
"router",
".",
"add_route",
"add_static",
"=",
"admin",
".",
"router",
".",
"add_static",
"static_folder",
"=",
"str",
"(",
"PROJ_ROOT",
"/",
"... | Initialize routes. | [
"Initialize",
"routes",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L148-L160 |
13,207 | aio-libs/aiohttp_admin | aiohttp_admin/admin.py | AdminOnRestHandler.index_page | async def index_page(self, request):
"""
Return index page with initial state for admin
"""
context = {"initial_state": self.schema.to_json()}
return render_template(
self.template,
request,
context,
app_key=TEMPLATE_APP_KEY,
... | python | async def index_page(self, request):
"""
Return index page with initial state for admin
"""
context = {"initial_state": self.schema.to_json()}
return render_template(
self.template,
request,
context,
app_key=TEMPLATE_APP_KEY,
... | [
"async",
"def",
"index_page",
"(",
"self",
",",
"request",
")",
":",
"context",
"=",
"{",
"\"initial_state\"",
":",
"self",
".",
"schema",
".",
"to_json",
"(",
")",
"}",
"return",
"render_template",
"(",
"self",
".",
"template",
",",
"request",
",",
"con... | Return index page with initial state for admin | [
"Return",
"index",
"page",
"with",
"initial",
"state",
"for",
"admin"
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L105-L116 |
13,208 | aio-libs/aiohttp_admin | aiohttp_admin/admin.py | AdminOnRestHandler.logout | async def logout(self, request):
"""
Simple handler for logout
"""
if "Authorization" not in request.headers:
msg = "Auth header is not present, can not destroy token"
raise JsonValidaitonError(msg)
response = json_response()
await forget(request,... | python | async def logout(self, request):
"""
Simple handler for logout
"""
if "Authorization" not in request.headers:
msg = "Auth header is not present, can not destroy token"
raise JsonValidaitonError(msg)
response = json_response()
await forget(request,... | [
"async",
"def",
"logout",
"(",
"self",
",",
"request",
")",
":",
"if",
"\"Authorization\"",
"not",
"in",
"request",
".",
"headers",
":",
"msg",
"=",
"\"Auth header is not present, can not destroy token\"",
"raise",
"JsonValidaitonError",
"(",
"msg",
")",
"response",... | Simple handler for logout | [
"Simple",
"handler",
"for",
"logout"
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/admin.py#L134-L145 |
13,209 | aio-libs/aiohttp_admin | aiohttp_admin/utils.py | validate_query_structure | def validate_query_structure(query):
"""Validate query arguments in list request.
:param query: mapping with pagination and filtering information
"""
query_dict = dict(query)
filters = query_dict.pop('_filters', None)
if filters:
try:
f = json.loads(filters)
except V... | python | def validate_query_structure(query):
"""Validate query arguments in list request.
:param query: mapping with pagination and filtering information
"""
query_dict = dict(query)
filters = query_dict.pop('_filters', None)
if filters:
try:
f = json.loads(filters)
except V... | [
"def",
"validate_query_structure",
"(",
"query",
")",
":",
"query_dict",
"=",
"dict",
"(",
"query",
")",
"filters",
"=",
"query_dict",
".",
"pop",
"(",
"'_filters'",
",",
"None",
")",
"if",
"filters",
":",
"try",
":",
"f",
"=",
"json",
".",
"loads",
"(... | Validate query arguments in list request.
:param query: mapping with pagination and filtering information | [
"Validate",
"query",
"arguments",
"in",
"list",
"request",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/utils.py#L82-L103 |
13,210 | aio-libs/aiohttp_admin | aiohttp_admin/contrib/admin.py | Schema.to_json | def to_json(self):
"""
Prepare data for the initial state of the admin-on-rest
"""
endpoints = []
for endpoint in self.endpoints:
list_fields = endpoint.fields
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
... | python | def to_json(self):
"""
Prepare data for the initial state of the admin-on-rest
"""
endpoints = []
for endpoint in self.endpoints:
list_fields = endpoint.fields
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
... | [
"def",
"to_json",
"(",
"self",
")",
":",
"endpoints",
"=",
"[",
"]",
"for",
"endpoint",
"in",
"self",
".",
"endpoints",
":",
"list_fields",
"=",
"endpoint",
".",
"fields",
"resource_type",
"=",
"endpoint",
".",
"Meta",
".",
"resource_type",
"table",
"=",
... | Prepare data for the initial state of the admin-on-rest | [
"Prepare",
"data",
"for",
"the",
"initial",
"state",
"of",
"the",
"admin",
"-",
"on",
"-",
"rest"
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L30-L52 |
13,211 | aio-libs/aiohttp_admin | aiohttp_admin/contrib/admin.py | Schema.resources | def resources(self):
"""
Return list of all registered resources.
"""
resources = []
for endpoint in self.endpoints:
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
url = endpoint.name
resources.append((res... | python | def resources(self):
"""
Return list of all registered resources.
"""
resources = []
for endpoint in self.endpoints:
resource_type = endpoint.Meta.resource_type
table = endpoint.Meta.table
url = endpoint.name
resources.append((res... | [
"def",
"resources",
"(",
"self",
")",
":",
"resources",
"=",
"[",
"]",
"for",
"endpoint",
"in",
"self",
".",
"endpoints",
":",
"resource_type",
"=",
"endpoint",
".",
"Meta",
".",
"resource_type",
"table",
"=",
"endpoint",
".",
"Meta",
".",
"table",
"url"... | Return list of all registered resources. | [
"Return",
"list",
"of",
"all",
"registered",
"resources",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/admin.py#L55-L68 |
13,212 | aio-libs/aiohttp_admin | aiohttp_admin/backends/sa.py | PGResource.get_type_of_fields | def get_type_of_fields(fields, table):
"""
Return data types of `fields` that are in `table`. If a given
parameter is empty return primary key.
:param fields: list - list of fields that need to be returned
:param table: sa.Table - the current table
:return: list - list o... | python | def get_type_of_fields(fields, table):
"""
Return data types of `fields` that are in `table`. If a given
parameter is empty return primary key.
:param fields: list - list of fields that need to be returned
:param table: sa.Table - the current table
:return: list - list o... | [
"def",
"get_type_of_fields",
"(",
"fields",
",",
"table",
")",
":",
"if",
"not",
"fields",
":",
"fields",
"=",
"table",
".",
"primary_key",
"actual_fields",
"=",
"[",
"field",
"for",
"field",
"in",
"table",
".",
"c",
".",
"items",
"(",
")",
"if",
"fiel... | Return data types of `fields` that are in `table`. If a given
parameter is empty return primary key.
:param fields: list - list of fields that need to be returned
:param table: sa.Table - the current table
:return: list - list of the tuples `(field_name, fields_type)` | [
"Return",
"data",
"types",
"of",
"fields",
"that",
"are",
"in",
"table",
".",
"If",
"a",
"given",
"parameter",
"is",
"empty",
"return",
"primary",
"key",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L58-L80 |
13,213 | aio-libs/aiohttp_admin | aiohttp_admin/backends/sa.py | PGResource.get_type_for_inputs | def get_type_for_inputs(table):
"""
Return information about table's fields in dictionary type.
:param table: sa.Table - the current table
:return: list - list of the dictionaries
"""
return [
dict(
type=INPUT_TYPES.get(
ty... | python | def get_type_for_inputs(table):
"""
Return information about table's fields in dictionary type.
:param table: sa.Table - the current table
:return: list - list of the dictionaries
"""
return [
dict(
type=INPUT_TYPES.get(
ty... | [
"def",
"get_type_for_inputs",
"(",
"table",
")",
":",
"return",
"[",
"dict",
"(",
"type",
"=",
"INPUT_TYPES",
".",
"get",
"(",
"type",
"(",
"field_type",
".",
"type",
")",
",",
"rc",
".",
"TEXT_INPUT",
".",
"value",
")",
",",
"name",
"=",
"name",
","... | Return information about table's fields in dictionary type.
:param table: sa.Table - the current table
:return: list - list of the dictionaries | [
"Return",
"information",
"about",
"table",
"s",
"fields",
"in",
"dictionary",
"type",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/backends/sa.py#L83-L99 |
13,214 | aio-libs/aiohttp_admin | aiohttp_admin/__init__.py | _setup | def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None):
"""Initialize the admin-on-rest admin"""
admin = web.Application(loop=app.loop)
app[app_key] = admin
loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ])
aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)
if t... | python | def _setup(app, *, schema, title=None, app_key=APP_KEY, db=None):
"""Initialize the admin-on-rest admin"""
admin = web.Application(loop=app.loop)
app[app_key] = admin
loader = jinja2.FileSystemLoader([TEMPLATES_ROOT, ])
aiohttp_jinja2.setup(admin, loader=loader, app_key=TEMPLATE_APP_KEY)
if t... | [
"def",
"_setup",
"(",
"app",
",",
"*",
",",
"schema",
",",
"title",
"=",
"None",
",",
"app_key",
"=",
"APP_KEY",
",",
"db",
"=",
"None",
")",
":",
"admin",
"=",
"web",
".",
"Application",
"(",
"loop",
"=",
"app",
".",
"loop",
")",
"app",
"[",
"... | Initialize the admin-on-rest admin | [
"Initialize",
"the",
"admin",
"-",
"on",
"-",
"rest",
"admin"
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/__init__.py#L44-L70 |
13,215 | aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.to_dict | def to_dict(self):
"""
Return dict with the all base information about the instance.
"""
data = {
"name": self.name,
"canEdit": self.can_edit,
"canCreate": self.can_create,
"canDelete": self.can_delete,
"perPage": self.per_page,... | python | def to_dict(self):
"""
Return dict with the all base information about the instance.
"""
data = {
"name": self.name,
"canEdit": self.can_edit,
"canCreate": self.can_create,
"canDelete": self.can_delete,
"perPage": self.per_page,... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"data",
"=",
"{",
"\"name\"",
":",
"self",
".",
"name",
",",
"\"canEdit\"",
":",
"self",
".",
"can_edit",
",",
"\"canCreate\"",
":",
"self",
".",
"can_create",
",",
"\"canDelete\"",
":",
"self",
".",
"can_delete",... | Return dict with the all base information about the instance. | [
"Return",
"dict",
"with",
"the",
"all",
"base",
"information",
"about",
"the",
"instance",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L30-L45 |
13,216 | aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.generate_data_for_edit_page | def generate_data_for_edit_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict
"""
if not self.can_edit:
return {}
if self.edit_form:
ret... | python | def generate_data_for_edit_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict
"""
if not self.can_edit:
return {}
if self.edit_form:
ret... | [
"def",
"generate_data_for_edit_page",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"can_edit",
":",
"return",
"{",
"}",
"if",
"self",
".",
"edit_form",
":",
"return",
"self",
".",
"edit_form",
".",
"to_dict",
"(",
")",
"return",
"self",
".",
"generat... | Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict | [
"Generate",
"a",
"custom",
"representation",
"of",
"table",
"s",
"fields",
"in",
"dictionary",
"type",
"if",
"exist",
"edit",
"form",
"else",
"use",
"default",
"representation",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L55-L69 |
13,217 | aio-libs/aiohttp_admin | aiohttp_admin/contrib/models.py | ModelAdmin.generate_data_for_create_page | def generate_data_for_create_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist create form else use default representation.
:return: dict
"""
if not self.can_create:
return {}
if self.create_form:
... | python | def generate_data_for_create_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist create form else use default representation.
:return: dict
"""
if not self.can_create:
return {}
if self.create_form:
... | [
"def",
"generate_data_for_create_page",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"can_create",
":",
"return",
"{",
"}",
"if",
"self",
".",
"create_form",
":",
"return",
"self",
".",
"create_form",
".",
"to_dict",
"(",
")",
"return",
"self",
".",
... | Generate a custom representation of table's fields in dictionary type
if exist create form else use default representation.
:return: dict | [
"Generate",
"a",
"custom",
"representation",
"of",
"table",
"s",
"fields",
"in",
"dictionary",
"type",
"if",
"exist",
"create",
"form",
"else",
"use",
"default",
"representation",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/aiohttp_admin/contrib/models.py#L83-L96 |
13,218 | aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.register | async def register(self, request):
"""Registers the user."""
session = await get_session(request)
user_id = session.get('user_id')
if user_id:
return redirect(request, 'timeline')
error = None
form = None
if request.method == 'POST':
form ... | python | async def register(self, request):
"""Registers the user."""
session = await get_session(request)
user_id = session.get('user_id')
if user_id:
return redirect(request, 'timeline')
error = None
form = None
if request.method == 'POST':
form ... | [
"async",
"def",
"register",
"(",
"self",
",",
"request",
")",
":",
"session",
"=",
"await",
"get_session",
"(",
"request",
")",
"user_id",
"=",
"session",
".",
"get",
"(",
"'user_id'",
")",
"if",
"user_id",
":",
"return",
"redirect",
"(",
"request",
",",... | Registers the user. | [
"Registers",
"the",
"user",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L116-L145 |
13,219 | aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.follow_user | async def follow_user(self, request):
"""Adds the current user as follower of the given user."""
username = request.match_info['username']
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
who... | python | async def follow_user(self, request):
"""Adds the current user as follower of the given user."""
username = request.match_info['username']
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
who... | [
"async",
"def",
"follow_user",
"(",
"self",
",",
"request",
")",
":",
"username",
"=",
"request",
".",
"match_info",
"[",
"'username'",
"]",
"session",
"=",
"await",
"get_session",
"(",
"request",
")",
"user_id",
"=",
"session",
".",
"get",
"(",
"'user_id'... | Adds the current user as follower of the given user. | [
"Adds",
"the",
"current",
"user",
"as",
"follower",
"of",
"the",
"given",
"user",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L147-L165 |
13,220 | aio-libs/aiohttp_admin | demos/motortwit/motortwit/views.py | SiteHandler.add_message | async def add_message(self, request):
"""Registers a new message for the user."""
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
form = await request.post()
if form.get('text'):
... | python | async def add_message(self, request):
"""Registers a new message for the user."""
session = await get_session(request)
user_id = session.get('user_id')
if not user_id:
raise web.HTTPNotAuthorized()
form = await request.post()
if form.get('text'):
... | [
"async",
"def",
"add_message",
"(",
"self",
",",
"request",
")",
":",
"session",
"=",
"await",
"get_session",
"(",
"request",
")",
"user_id",
"=",
"session",
".",
"get",
"(",
"'user_id'",
")",
"if",
"not",
"user_id",
":",
"raise",
"web",
".",
"HTTPNotAut... | Registers a new message for the user. | [
"Registers",
"a",
"new",
"message",
"for",
"the",
"user",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/views.py#L184-L203 |
13,221 | aio-libs/aiohttp_admin | demos/motortwit/motortwit/utils.py | robo_avatar_url | def robo_avatar_url(user_data, size=80):
"""Return the gravatar image for the given email address."""
hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest()
url = "https://robohash.org/{hash}.png?size={size}x{size}".format(
hash=hash, size=size)
return url | python | def robo_avatar_url(user_data, size=80):
"""Return the gravatar image for the given email address."""
hash = md5(str(user_data).strip().lower().encode('utf-8')).hexdigest()
url = "https://robohash.org/{hash}.png?size={size}x{size}".format(
hash=hash, size=size)
return url | [
"def",
"robo_avatar_url",
"(",
"user_data",
",",
"size",
"=",
"80",
")",
":",
"hash",
"=",
"md5",
"(",
"str",
"(",
"user_data",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
".",
"encode",
"(",
"'utf-8'",
")",
")",
".",
"hexdigest",
"(",
"... | Return the gravatar image for the given email address. | [
"Return",
"the",
"gravatar",
"image",
"for",
"the",
"given",
"email",
"address",
"."
] | 82e5032ef14ae8cc3c594fdd45d6c977aab1baad | https://github.com/aio-libs/aiohttp_admin/blob/82e5032ef14ae8cc3c594fdd45d6c977aab1baad/demos/motortwit/motortwit/utils.py#L27-L32 |
13,222 | ponty/PyVirtualDisplay | pyvirtualdisplay/smartdisplay.py | SmartDisplay.waitgrab | def waitgrab(self, timeout=60, autocrop=True, cb_imgcheck=None):
'''start process and create screenshot.
Repeat screenshot until it is not empty and
cb_imgcheck callback function returns True
for current screenshot.
:param autocrop: True -> crop screenshot
:param timeout... | python | def waitgrab(self, timeout=60, autocrop=True, cb_imgcheck=None):
'''start process and create screenshot.
Repeat screenshot until it is not empty and
cb_imgcheck callback function returns True
for current screenshot.
:param autocrop: True -> crop screenshot
:param timeout... | [
"def",
"waitgrab",
"(",
"self",
",",
"timeout",
"=",
"60",
",",
"autocrop",
"=",
"True",
",",
"cb_imgcheck",
"=",
"None",
")",
":",
"t",
"=",
"0",
"sleep_time",
"=",
"0.3",
"# for fast windows",
"repeat_time",
"=",
"1",
"while",
"1",
":",
"log",
".",
... | start process and create screenshot.
Repeat screenshot until it is not empty and
cb_imgcheck callback function returns True
for current screenshot.
:param autocrop: True -> crop screenshot
:param timeout: int
:param cb_imgcheck: None or callback for testing img,
... | [
"start",
"process",
"and",
"create",
"screenshot",
".",
"Repeat",
"screenshot",
"until",
"it",
"is",
"not",
"empty",
"and",
"cb_imgcheck",
"callback",
"function",
"returns",
"True",
"for",
"current",
"screenshot",
"."
] | 903841f5ef13bf162be6fdd22daa5c349af45d67 | https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/smartdisplay.py#L54-L90 |
13,223 | ponty/PyVirtualDisplay | pyvirtualdisplay/abstractdisplay.py | AbstractDisplay._setup_xauth | def _setup_xauth(self):
'''
Set up the Xauthority file and the XAUTHORITY environment variable.
'''
handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.',
suffix='.Xauthority')
self._xauth_filename = filename
os.close(h... | python | def _setup_xauth(self):
'''
Set up the Xauthority file and the XAUTHORITY environment variable.
'''
handle, filename = tempfile.mkstemp(prefix='PyVirtualDisplay.',
suffix='.Xauthority')
self._xauth_filename = filename
os.close(h... | [
"def",
"_setup_xauth",
"(",
"self",
")",
":",
"handle",
",",
"filename",
"=",
"tempfile",
".",
"mkstemp",
"(",
"prefix",
"=",
"'PyVirtualDisplay.'",
",",
"suffix",
"=",
"'.Xauthority'",
")",
"self",
".",
"_xauth_filename",
"=",
"filename",
"os",
".",
"close"... | Set up the Xauthority file and the XAUTHORITY environment variable. | [
"Set",
"up",
"the",
"Xauthority",
"file",
"and",
"the",
"XAUTHORITY",
"environment",
"variable",
"."
] | 903841f5ef13bf162be6fdd22daa5c349af45d67 | https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/abstractdisplay.py#L154-L169 |
13,224 | ponty/PyVirtualDisplay | pyvirtualdisplay/abstractdisplay.py | AbstractDisplay._clear_xauth | def _clear_xauth(self):
'''
Clear the Xauthority file and restore the environment variables.
'''
os.remove(self._xauth_filename)
for varname in ['AUTHFILE', 'XAUTHORITY']:
if self._old_xauth[varname] is None:
del os.environ[varname]
else:
... | python | def _clear_xauth(self):
'''
Clear the Xauthority file and restore the environment variables.
'''
os.remove(self._xauth_filename)
for varname in ['AUTHFILE', 'XAUTHORITY']:
if self._old_xauth[varname] is None:
del os.environ[varname]
else:
... | [
"def",
"_clear_xauth",
"(",
"self",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_xauth_filename",
")",
"for",
"varname",
"in",
"[",
"'AUTHFILE'",
",",
"'XAUTHORITY'",
"]",
":",
"if",
"self",
".",
"_old_xauth",
"[",
"varname",
"]",
"is",
"None",
"... | Clear the Xauthority file and restore the environment variables. | [
"Clear",
"the",
"Xauthority",
"file",
"and",
"restore",
"the",
"environment",
"variables",
"."
] | 903841f5ef13bf162be6fdd22daa5c349af45d67 | https://github.com/ponty/PyVirtualDisplay/blob/903841f5ef13bf162be6fdd22daa5c349af45d67/pyvirtualdisplay/abstractdisplay.py#L171-L181 |
13,225 | jasonrollins/shareplum | shareplum/shareplum.py | Office365.GetCookies | def GetCookies(self):
"""
Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls
"""
sectoken = self.GetSecurityToken(self.Username, self.Password)
url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0'
... | python | def GetCookies(self):
"""
Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls
"""
sectoken = self.GetSecurityToken(self.Username, self.Password)
url = self.share_point_site+ '/_forms/default.aspx?wa=wsignin1.0'
... | [
"def",
"GetCookies",
"(",
"self",
")",
":",
"sectoken",
"=",
"self",
".",
"GetSecurityToken",
"(",
"self",
".",
"Username",
",",
"self",
".",
"Password",
")",
"url",
"=",
"self",
".",
"share_point_site",
"+",
"'/_forms/default.aspx?wa=wsignin1.0'",
"response",
... | Grabs the cookies form your Office Sharepoint site
and uses it as Authentication for the rest of the calls | [
"Grabs",
"the",
"cookies",
"form",
"your",
"Office",
"Sharepoint",
"site",
"and",
"uses",
"it",
"as",
"Authentication",
"for",
"the",
"rest",
"of",
"the",
"calls"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L70-L78 |
13,226 | jasonrollins/shareplum | shareplum/shareplum.py | Site.DeleteList | def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._ur... | python | def DeleteList(self, listName):
"""Delete a List with given name"""
# Build Request
soap_request = soap('DeleteList')
soap_request.add_parameter('listName', listName)
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._ur... | [
"def",
"DeleteList",
"(",
"self",
",",
"listName",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'DeleteList'",
")",
"soap_request",
".",
"add_parameter",
"(",
"'listName'",
",",
"listName",
")",
"self",
".",
"last_request",
"=",
"str",
"(",
... | Delete a List with given name | [
"Delete",
"a",
"List",
"with",
"given",
"name"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L207-L226 |
13,227 | jasonrollins/shareplum | shareplum/shareplum.py | Site.GetListCollection | def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
... | python | def GetListCollection(self):
"""Returns List information for current Site"""
# Build Request
soap_request = soap('GetListCollection')
self.last_request = str(soap_request)
# Send Request
response = self._session.post(url=self._url('SiteData'),
... | [
"def",
"GetListCollection",
"(",
"self",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'GetListCollection'",
")",
"self",
".",
"last_request",
"=",
"str",
"(",
"soap_request",
")",
"# Send Request",
"response",
"=",
"self",
".",
"_session",
"."... | Returns List information for current Site | [
"Returns",
"List",
"information",
"for",
"current",
"Site"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L228-L257 |
13,228 | jasonrollins/shareplum | shareplum/shareplum.py | _List._convert_to_internal | def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
... | python | def _convert_to_internal(self, data):
"""From 'Column Title' to 'Column_x0020_Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._disp_cols:
raise Exception(key + ' not a column in current List.')
... | [
"def",
"_convert_to_internal",
"(",
"self",
",",
"data",
")",
":",
"for",
"_dict",
"in",
"data",
":",
"keys",
"=",
"list",
"(",
"_dict",
".",
"keys",
"(",
")",
")",
"[",
":",
"]",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"self",... | From 'Column Title' to 'Column_x0020_Title | [
"From",
"Column",
"Title",
"to",
"Column_x0020_Title"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L358-L365 |
13,229 | jasonrollins/shareplum | shareplum/shareplum.py | _List._convert_to_display | def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
... | python | def _convert_to_display(self, data):
"""From 'Column_x0020_Title' to 'Column Title'"""
for _dict in data:
keys = list(_dict.keys())[:]
for key in keys:
if key not in self._sp_cols:
raise Exception(key + ' not a column in current List.')
... | [
"def",
"_convert_to_display",
"(",
"self",
",",
"data",
")",
":",
"for",
"_dict",
"in",
"data",
":",
"keys",
"=",
"list",
"(",
"_dict",
".",
"keys",
"(",
")",
")",
"[",
":",
"]",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
"not",
"in",
"self",
... | From 'Column_x0020_Title' to 'Column Title | [
"From",
"Column_x0020_Title",
"to",
"Column",
"Title"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L367-L374 |
13,230 | jasonrollins/shareplum | shareplum/shareplum.py | _List.GetView | def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
... | python | def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
... | [
"def",
"GetView",
"(",
"self",
",",
"viewname",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'GetView'",
")",
"soap_request",
".",
"add_parameter",
"(",
"'listName'",
",",
"self",
".",
"listName",
")",
"if",
"viewname",
"==",
"None",
":",
... | Get Info on View Name | [
"Get",
"Info",
"on",
"View",
"Name"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L562-L600 |
13,231 | jasonrollins/shareplum | shareplum/shareplum.py | _List.UpdateListItems | def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, ... | python | def UpdateListItems(self, data, kind):
"""Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, ... | [
"def",
"UpdateListItems",
"(",
"self",
",",
"data",
",",
"kind",
")",
":",
"if",
"type",
"(",
"data",
")",
"!=",
"list",
":",
"raise",
"Exception",
"(",
"'data must be a list of dictionaries'",
")",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'Update... | Update List Items
kind = 'New', 'Update', or 'Delete'
New:
Provide data like so:
data = [{'Title': 'New Title', 'Col1': 'New Value'}]
Update:
Provide data like so:
data = [{'ID': 23, 'Title': 'Updated Title'},
... | [
"Update",
"List",
"Items",
"kind",
"=",
"New",
"Update",
"or",
"Delete"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L658-L704 |
13,232 | jasonrollins/shareplum | shareplum/shareplum.py | _List.GetAttachmentCollection | def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str... | python | def GetAttachmentCollection(self, _id):
"""Get Attachments for given List Item ID"""
# Build Request
soap_request = soap('GetAttachmentCollection')
soap_request.add_parameter('listName', self.listName)
soap_request.add_parameter('listItemID', _id)
self.last_request = str... | [
"def",
"GetAttachmentCollection",
"(",
"self",
",",
"_id",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'GetAttachmentCollection'",
")",
"soap_request",
".",
"add_parameter",
"(",
"'listName'",
",",
"self",
".",
"listName",
")",
"soap_request",
... | Get Attachments for given List Item ID | [
"Get",
"Attachments",
"for",
"given",
"List",
"Item",
"ID"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/shareplum.py#L706-L731 |
13,233 | jasonrollins/shareplum | shareplum/ListDict.py | changes | def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | python | def changes(new_cmp_dict, old_cmp_dict, id_column, columns):
"""Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict
"""
update_ldict = []
same_keys = set(new_cmp_dict).intersection(set(old_cmp_dict))
for same_ke... | [
"def",
"changes",
"(",
"new_cmp_dict",
",",
"old_cmp_dict",
",",
"id_column",
",",
"columns",
")",
":",
"update_ldict",
"=",
"[",
"]",
"same_keys",
"=",
"set",
"(",
"new_cmp_dict",
")",
".",
"intersection",
"(",
"set",
"(",
"old_cmp_dict",
")",
")",
"for",... | Return a list dict of the changes of the
rows that exist in both dictionaries
User must provide an ID column for old_cmp_dict | [
"Return",
"a",
"list",
"dict",
"of",
"the",
"changes",
"of",
"the",
"rows",
"that",
"exist",
"in",
"both",
"dictionaries",
"User",
"must",
"provide",
"an",
"ID",
"column",
"for",
"old_cmp_dict"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L4-L33 |
13,234 | jasonrollins/shareplum | shareplum/ListDict.py | unique | def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique... | python | def unique(new_cmp_dict, old_cmp_dict):
"""Return a list dict of
the unique keys in new_cmp_dict
"""
newkeys = set(new_cmp_dict)
oldkeys = set(old_cmp_dict)
unique = newkeys - oldkeys
unique_ldict = []
for key in unique:
unique_ldict.append(new_cmp_dict[key])
return unique... | [
"def",
"unique",
"(",
"new_cmp_dict",
",",
"old_cmp_dict",
")",
":",
"newkeys",
"=",
"set",
"(",
"new_cmp_dict",
")",
"oldkeys",
"=",
"set",
"(",
"old_cmp_dict",
")",
"unique",
"=",
"newkeys",
"-",
"oldkeys",
"unique_ldict",
"=",
"[",
"]",
"for",
"key",
... | Return a list dict of
the unique keys in new_cmp_dict | [
"Return",
"a",
"list",
"dict",
"of",
"the",
"unique",
"keys",
"in",
"new_cmp_dict"
] | 404f320808912619920e2d787f2c4387225a14e0 | https://github.com/jasonrollins/shareplum/blob/404f320808912619920e2d787f2c4387225a14e0/shareplum/ListDict.py#L35-L45 |
13,235 | improbable-research/keanu | keanu-python/keanu/plots/traceplot.py | traceplot | def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None,
x0: int = 0) -> Any:
"""
Plot samples values.
:param trace: result of MCMC run
:param labels: labels of vertices to be plotted. if None, all vertices are plotted.
:param ax: Matplotli... | python | def traceplot(trace: sample_types, labels: List[Union[str, Tuple[str, str]]] = None, ax: Any = None,
x0: int = 0) -> Any:
"""
Plot samples values.
:param trace: result of MCMC run
:param labels: labels of vertices to be plotted. if None, all vertices are plotted.
:param ax: Matplotli... | [
"def",
"traceplot",
"(",
"trace",
":",
"sample_types",
",",
"labels",
":",
"List",
"[",
"Union",
"[",
"str",
",",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"]",
"=",
"None",
",",
"ax",
":",
"Any",
"=",
"None",
",",
"x0",
":",
"int",
"=",
"0",
... | Plot samples values.
:param trace: result of MCMC run
:param labels: labels of vertices to be plotted. if None, all vertices are plotted.
:param ax: Matplotlib axes
:param x0: index of first data point, used for sample stream plots | [
"Plot",
"samples",
"values",
"."
] | 73189a8f569078e156168e795f82c7366c59574b | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/keanu-python/keanu/plots/traceplot.py#L12-L37 |
13,236 | improbable-research/keanu | docs/bin/snippet_writer.py | read_file_snippets | def read_file_snippets(file, snippet_store):
"""Parse a file and add all snippets to the snippet_store dictionary"""
start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)")
end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)")
open_snippets = {}
with open(file, encoding="utf-8") as w:
... | python | def read_file_snippets(file, snippet_store):
"""Parse a file and add all snippets to the snippet_store dictionary"""
start_reg = re.compile("(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)")
end_reg = re.compile("(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)")
open_snippets = {}
with open(file, encoding="utf-8") as w:
... | [
"def",
"read_file_snippets",
"(",
"file",
",",
"snippet_store",
")",
":",
"start_reg",
"=",
"re",
".",
"compile",
"(",
"\"(.*%%SNIPPET_START%% )([a-zA-Z0-9]+)\"",
")",
"end_reg",
"=",
"re",
".",
"compile",
"(",
"\"(.*%%SNIPPET_END%% )([a-zA-Z0-9]+)\"",
")",
"open_snip... | Parse a file and add all snippets to the snippet_store dictionary | [
"Parse",
"a",
"file",
"and",
"add",
"all",
"snippets",
"to",
"the",
"snippet_store",
"dictionary"
] | 73189a8f569078e156168e795f82c7366c59574b | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/docs/bin/snippet_writer.py#L31-L73 |
13,237 | improbable-research/keanu | docs/bin/snippet_writer.py | strip_block_whitespace | def strip_block_whitespace(string_list):
"""Treats a list of strings as a code block and strips
whitespace so that the min whitespace line sits at char 0 of line."""
min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n'])
return [x[min_ws:] if x != '\n' else x for x in string_li... | python | def strip_block_whitespace(string_list):
"""Treats a list of strings as a code block and strips
whitespace so that the min whitespace line sits at char 0 of line."""
min_ws = min([(len(x) - len(x.lstrip())) for x in string_list if x != '\n'])
return [x[min_ws:] if x != '\n' else x for x in string_li... | [
"def",
"strip_block_whitespace",
"(",
"string_list",
")",
":",
"min_ws",
"=",
"min",
"(",
"[",
"(",
"len",
"(",
"x",
")",
"-",
"len",
"(",
"x",
".",
"lstrip",
"(",
")",
")",
")",
"for",
"x",
"in",
"string_list",
"if",
"x",
"!=",
"'\\n'",
"]",
")"... | Treats a list of strings as a code block and strips
whitespace so that the min whitespace line sits at char 0 of line. | [
"Treats",
"a",
"list",
"of",
"strings",
"as",
"a",
"code",
"block",
"and",
"strips",
"whitespace",
"so",
"that",
"the",
"min",
"whitespace",
"line",
"sits",
"at",
"char",
"0",
"of",
"line",
"."
] | 73189a8f569078e156168e795f82c7366c59574b | https://github.com/improbable-research/keanu/blob/73189a8f569078e156168e795f82c7366c59574b/docs/bin/snippet_writer.py#L126-L130 |
13,238 | aio-libs/aiohttp-sse | aiohttp_sse/__init__.py | EventSourceResponse.prepare | async def prepare(self, request):
"""Prepare for streaming and send HTTP headers.
:param request: regular aiohttp.web.Request.
"""
if request.method != 'GET':
raise HTTPMethodNotAllowed(request.method, ['GET'])
if not self.prepared:
writer = await super(... | python | async def prepare(self, request):
"""Prepare for streaming and send HTTP headers.
:param request: regular aiohttp.web.Request.
"""
if request.method != 'GET':
raise HTTPMethodNotAllowed(request.method, ['GET'])
if not self.prepared:
writer = await super(... | [
"async",
"def",
"prepare",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"method",
"!=",
"'GET'",
":",
"raise",
"HTTPMethodNotAllowed",
"(",
"request",
".",
"method",
",",
"[",
"'GET'",
"]",
")",
"if",
"not",
"self",
".",
"prepared",
":"... | Prepare for streaming and send HTTP headers.
:param request: regular aiohttp.web.Request. | [
"Prepare",
"for",
"streaming",
"and",
"send",
"HTTP",
"headers",
"."
] | 5148d087f9df75ecea61f574d3c768506680e5dc | https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L52-L74 |
13,239 | aio-libs/aiohttp-sse | aiohttp_sse/__init__.py | EventSourceResponse.send | async def send(self, data, id=None, event=None, retry=None):
"""Send data using EventSource protocol
:param str data: The data field for the message.
:param str id: The event ID to set the EventSource object's last
event ID value to.
:param str event: The event's type. If th... | python | async def send(self, data, id=None, event=None, retry=None):
"""Send data using EventSource protocol
:param str data: The data field for the message.
:param str id: The event ID to set the EventSource object's last
event ID value to.
:param str event: The event's type. If th... | [
"async",
"def",
"send",
"(",
"self",
",",
"data",
",",
"id",
"=",
"None",
",",
"event",
"=",
"None",
",",
"retry",
"=",
"None",
")",
":",
"buffer",
"=",
"io",
".",
"StringIO",
"(",
")",
"if",
"id",
"is",
"not",
"None",
":",
"buffer",
".",
"writ... | Send data using EventSource protocol
:param str data: The data field for the message.
:param str id: The event ID to set the EventSource object's last
event ID value to.
:param str event: The event's type. If this is specified, an event will
be dispatched on the browser ... | [
"Send",
"data",
"using",
"EventSource",
"protocol"
] | 5148d087f9df75ecea61f574d3c768506680e5dc | https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L76-L111 |
13,240 | aio-libs/aiohttp-sse | aiohttp_sse/__init__.py | EventSourceResponse.wait | async def wait(self):
"""EventSourceResponse object is used for streaming data to the client,
this method returns future, so we can wain until connection will
be closed or other task explicitly call ``stop_streaming`` method.
"""
if self._ping_task is None:
raise Runt... | python | async def wait(self):
"""EventSourceResponse object is used for streaming data to the client,
this method returns future, so we can wain until connection will
be closed or other task explicitly call ``stop_streaming`` method.
"""
if self._ping_task is None:
raise Runt... | [
"async",
"def",
"wait",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ping_task",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Response is not started'",
")",
"with",
"contextlib",
".",
"suppress",
"(",
"asyncio",
".",
"CancelledError",
")",
":",
"await"... | EventSourceResponse object is used for streaming data to the client,
this method returns future, so we can wain until connection will
be closed or other task explicitly call ``stop_streaming`` method. | [
"EventSourceResponse",
"object",
"is",
"used",
"for",
"streaming",
"data",
"to",
"the",
"client",
"this",
"method",
"returns",
"future",
"so",
"we",
"can",
"wain",
"until",
"connection",
"will",
"be",
"closed",
"or",
"other",
"task",
"explicitly",
"call",
"sto... | 5148d087f9df75ecea61f574d3c768506680e5dc | https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L113-L121 |
13,241 | aio-libs/aiohttp-sse | aiohttp_sse/__init__.py | EventSourceResponse.ping_interval | def ping_interval(self, value):
"""Setter for ping_interval property.
:param int value: interval in sec between two ping values.
"""
if not isinstance(value, int):
raise TypeError("ping interval must be int")
if value < 0:
raise ValueError("ping interval... | python | def ping_interval(self, value):
"""Setter for ping_interval property.
:param int value: interval in sec between two ping values.
"""
if not isinstance(value, int):
raise TypeError("ping interval must be int")
if value < 0:
raise ValueError("ping interval... | [
"def",
"ping_interval",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"raise",
"TypeError",
"(",
"\"ping interval must be int\"",
")",
"if",
"value",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"ping i... | Setter for ping_interval property.
:param int value: interval in sec between two ping values. | [
"Setter",
"for",
"ping_interval",
"property",
"."
] | 5148d087f9df75ecea61f574d3c768506680e5dc | https://github.com/aio-libs/aiohttp-sse/blob/5148d087f9df75ecea61f574d3c768506680e5dc/aiohttp_sse/__init__.py#L140-L151 |
13,242 | google/budou | budou/parser.py | get_parser | def get_parser(segmenter, **options):
"""Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified.
"""
if segmenter == 'nlapi':
ret... | python | def get_parser(segmenter, **options):
"""Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified.
"""
if segmenter == 'nlapi':
ret... | [
"def",
"get_parser",
"(",
"segmenter",
",",
"*",
"*",
"options",
")",
":",
"if",
"segmenter",
"==",
"'nlapi'",
":",
"return",
"NLAPIParser",
"(",
"*",
"*",
"options",
")",
"elif",
"segmenter",
"==",
"'mecab'",
":",
"return",
"MecabParser",
"(",
")",
"eli... | Gets a parser.
Args:
segmenter (str): Segmenter to use.
options (:obj:`dict`, optional): Optional settings.
Returns:
Parser (:obj:`budou.parser.Parser`)
Raises:
ValueError: If unsupported segmenter is specified. | [
"Gets",
"a",
"parser",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/parser.py#L129-L149 |
13,243 | google/budou | budou/parser.py | preprocess | def preprocess(source):
"""Removes unnecessary break lines and white spaces.
Args:
source (str): Input sentence.
Returns:
Preprocessed sentence. (str)
"""
doc = html5lib.parseFragment(source)
source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8')
source = source.replace(u'\n'... | python | def preprocess(source):
"""Removes unnecessary break lines and white spaces.
Args:
source (str): Input sentence.
Returns:
Preprocessed sentence. (str)
"""
doc = html5lib.parseFragment(source)
source = ET.tostring(doc, encoding='utf-8', method='text').decode('utf-8')
source = source.replace(u'\n'... | [
"def",
"preprocess",
"(",
"source",
")",
":",
"doc",
"=",
"html5lib",
".",
"parseFragment",
"(",
"source",
")",
"source",
"=",
"ET",
".",
"tostring",
"(",
"doc",
",",
"encoding",
"=",
"'utf-8'",
",",
"method",
"=",
"'text'",
")",
".",
"decode",
"(",
... | Removes unnecessary break lines and white spaces.
Args:
source (str): Input sentence.
Returns:
Preprocessed sentence. (str) | [
"Removes",
"unnecessary",
"break",
"lines",
"and",
"white",
"spaces",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/parser.py#L169-L182 |
13,244 | google/budou | budou/budou.py | main | def main():
"""Budou main method for the command line tool.
"""
args = docopt(__doc__)
if args['--version']:
print(__version__)
sys.exit()
result = parse(
args['<source>'],
segmenter=args['--segmenter'],
language=args['--language'],
classname=args['--classname'])
print(resul... | python | def main():
"""Budou main method for the command line tool.
"""
args = docopt(__doc__)
if args['--version']:
print(__version__)
sys.exit()
result = parse(
args['<source>'],
segmenter=args['--segmenter'],
language=args['--language'],
classname=args['--classname'])
print(resul... | [
"def",
"main",
"(",
")",
":",
"args",
"=",
"docopt",
"(",
"__doc__",
")",
"if",
"args",
"[",
"'--version'",
"]",
":",
"print",
"(",
"__version__",
")",
"sys",
".",
"exit",
"(",
")",
"result",
"=",
"parse",
"(",
"args",
"[",
"'<source>'",
"]",
",",
... | Budou main method for the command line tool. | [
"Budou",
"main",
"method",
"for",
"the",
"command",
"line",
"tool",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/budou.py#L48-L62 |
13,245 | google/budou | budou/budou.py | parse | def parse(source, segmenter='nlapi', language=None, max_length=None,
classname=None, attributes=None, **kwargs):
"""Parses input source.
Args:
source (str): Input source to process.
segmenter (:obj:`str`, optional): Segmenter to use [default: nlapi].
language (:obj:`str`, optional): Language ... | python | def parse(source, segmenter='nlapi', language=None, max_length=None,
classname=None, attributes=None, **kwargs):
"""Parses input source.
Args:
source (str): Input source to process.
segmenter (:obj:`str`, optional): Segmenter to use [default: nlapi].
language (:obj:`str`, optional): Language ... | [
"def",
"parse",
"(",
"source",
",",
"segmenter",
"=",
"'nlapi'",
",",
"language",
"=",
"None",
",",
"max_length",
"=",
"None",
",",
"classname",
"=",
"None",
",",
"attributes",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"parser",
"=",
"get_parser"... | Parses input source.
Args:
source (str): Input source to process.
segmenter (:obj:`str`, optional): Segmenter to use [default: nlapi].
language (:obj:`str`, optional): Language code.
max_length (:obj:`int`, optional): Maximum length of a chunk.
classname (:obj:`str`, optional): Class name of outp... | [
"Parses",
"input",
"source",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/budou.py#L64-L84 |
13,246 | google/budou | budou/budou.py | authenticate | def authenticate(json_path=None):
"""Gets a Natural Language API parser by authenticating the API.
**This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a
parser instead.
Args:
json_path (:obj:`str`, optional): The file path to the service account's
credentials.
Returns:
... | python | def authenticate(json_path=None):
"""Gets a Natural Language API parser by authenticating the API.
**This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a
parser instead.
Args:
json_path (:obj:`str`, optional): The file path to the service account's
credentials.
Returns:
... | [
"def",
"authenticate",
"(",
"json_path",
"=",
"None",
")",
":",
"msg",
"=",
"(",
"'budou.authentication() is deprecated. '",
"'Please use budou.get_parser() to obtain a parser instead.'",
")",
"warnings",
".",
"warn",
"(",
"msg",
",",
"DeprecationWarning",
")",
"parser",
... | Gets a Natural Language API parser by authenticating the API.
**This method is deprecated.** Please use :obj:`budou.get_parser` to obtain a
parser instead.
Args:
json_path (:obj:`str`, optional): The file path to the service account's
credentials.
Returns:
Parser. (:obj:`budou.parser.NLAPIPar... | [
"Gets",
"a",
"Natural",
"Language",
"API",
"parser",
"by",
"authenticating",
"the",
"API",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/budou.py#L86-L104 |
13,247 | google/budou | budou/nlapisegmenter.py | _memorize | def _memorize(func):
"""Decorator to cache the given function's output.
"""
def _wrapper(self, *args, **kwargs):
"""Wrapper to cache the function's output.
"""
if self.use_cache:
cache = load_cache(self.cache_filename)
original_key = ':'.join([
self.__class__.__name__,
... | python | def _memorize(func):
"""Decorator to cache the given function's output.
"""
def _wrapper(self, *args, **kwargs):
"""Wrapper to cache the function's output.
"""
if self.use_cache:
cache = load_cache(self.cache_filename)
original_key = ':'.join([
self.__class__.__name__,
... | [
"def",
"_memorize",
"(",
"func",
")",
":",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrapper to cache the function's output.\n \"\"\"",
"if",
"self",
".",
"use_cache",
":",
"cache",
"=",
"load_cache",
"(",
... | Decorator to cache the given function's output. | [
"Decorator",
"to",
"cache",
"the",
"given",
"function",
"s",
"output",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L62-L84 |
13,248 | google/budou | budou/nlapisegmenter.py | NLAPISegmenter._get_source_chunks | def _get_source_chunks(self, input_text, language=None):
"""Returns a chunk list retrieved from Syntax Analysis results.
Args:
input_text (str): Text to annotate.
language (:obj:`str`, optional): Language of the text.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`)
"""
chun... | python | def _get_source_chunks(self, input_text, language=None):
"""Returns a chunk list retrieved from Syntax Analysis results.
Args:
input_text (str): Text to annotate.
language (:obj:`str`, optional): Language of the text.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`)
"""
chun... | [
"def",
"_get_source_chunks",
"(",
"self",
",",
"input_text",
",",
"language",
"=",
"None",
")",
":",
"chunks",
"=",
"ChunkList",
"(",
")",
"seek",
"=",
"0",
"result",
"=",
"self",
".",
"_get_annotations",
"(",
"input_text",
",",
"language",
"=",
"language"... | Returns a chunk list retrieved from Syntax Analysis results.
Args:
input_text (str): Text to annotate.
language (:obj:`str`, optional): Language of the text.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`) | [
"Returns",
"a",
"chunk",
"list",
"retrieved",
"from",
"Syntax",
"Analysis",
"results",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L170-L201 |
13,249 | google/budou | budou/nlapisegmenter.py | NLAPISegmenter._group_chunks_by_entities | def _group_chunks_by_entities(self, chunks, entities):
"""Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.
entities (:obj:`list` of :obj:`dict`): List of entities.
Returns:
A chunk list. (:obj:`b... | python | def _group_chunks_by_entities(self, chunks, entities):
"""Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.
entities (:obj:`list` of :obj:`dict`): List of entities.
Returns:
A chunk list. (:obj:`b... | [
"def",
"_group_chunks_by_entities",
"(",
"self",
",",
"chunks",
",",
"entities",
")",
":",
"for",
"entity",
"in",
"entities",
":",
"chunks_to_concat",
"=",
"chunks",
".",
"get_overlaps",
"(",
"entity",
"[",
"'beginOffset'",
"]",
",",
"len",
"(",
"entity",
"[... | Groups chunks by entities retrieved from NL API Entity Analysis.
Args:
chunks (:obj:`budou.chunk.ChunkList`): List of chunks to be processed.
entities (:obj:`list` of :obj:`dict`): List of entities.
Returns:
A chunk list. (:obj:`budou.chunk.ChunkList`) | [
"Groups",
"chunks",
"by",
"entities",
"retrieved",
"from",
"NL",
"API",
"Entity",
"Analysis",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L203-L221 |
13,250 | google/budou | budou/nlapisegmenter.py | NLAPISegmenter._get_annotations | def _get_annotations(self, text, language=''):
"""Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code... | python | def _get_annotations(self, text, language=''):
"""Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code... | [
"def",
"_get_annotations",
"(",
"self",
",",
"text",
",",
"language",
"=",
"''",
")",
":",
"body",
"=",
"{",
"'document'",
":",
"{",
"'type'",
":",
"'PLAIN_TEXT'",
",",
"'content'",
":",
"text",
",",
"}",
",",
"'features'",
":",
"{",
"'extract_syntax'",
... | Returns the list of annotations retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
Results in a dictionary. :code:`tokens` contains the list of annotations
and :code:`language` contains the inferred language from the in... | [
"Returns",
"the",
"list",
"of",
"annotations",
"retrieved",
"from",
"the",
"given",
"text",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L224-L253 |
13,251 | google/budou | budou/nlapisegmenter.py | NLAPISegmenter._get_entities | def _get_entities(self, text, language=''):
"""Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
List of entities.
"""
body = {
'document': {
'type': 'PLAIN_TEXT',... | python | def _get_entities(self, text, language=''):
"""Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
List of entities.
"""
body = {
'document': {
'type': 'PLAIN_TEXT',... | [
"def",
"_get_entities",
"(",
"self",
",",
"text",
",",
"language",
"=",
"''",
")",
":",
"body",
"=",
"{",
"'document'",
":",
"{",
"'type'",
":",
"'PLAIN_TEXT'",
",",
"'content'",
":",
"text",
",",
"}",
",",
"'encodingType'",
":",
"'UTF32'",
",",
"}",
... | Returns the list of entities retrieved from the given text.
Args:
text (str): Input text.
language (:obj:`str`, optional): Language code.
Returns:
List of entities. | [
"Returns",
"the",
"list",
"of",
"entities",
"retrieved",
"from",
"the",
"given",
"text",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/nlapisegmenter.py#L256-L288 |
13,252 | google/budou | budou/cachefactory.py | PickleCache.get | def get(self, key):
"""Gets a value by a key.
Args:
key (str): Key to retrieve the value.
Returns: Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'rb') as file_object:
cache_pickle = pickle.load(file_object)
val = cache_pickle.get(key, None)
... | python | def get(self, key):
"""Gets a value by a key.
Args:
key (str): Key to retrieve the value.
Returns: Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'rb') as file_object:
cache_pickle = pickle.load(file_object)
val = cache_pickle.get(key, None)
... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_create_file_if_none_exists",
"(",
")",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"file_object",
":",
"cache_pickle",
"=",
"pickle",
".",
"load",
"(",
"file_object... | Gets a value by a key.
Args:
key (str): Key to retrieve the value.
Returns: Retrieved value. | [
"Gets",
"a",
"value",
"by",
"a",
"key",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/cachefactory.py#L93-L105 |
13,253 | google/budou | budou/cachefactory.py | PickleCache.set | def set(self, key, val):
"""Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache... | python | def set(self, key, val):
"""Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'r+b') as file_object:
cache_pickle = pickle.load(file_object)
cache... | [
"def",
"set",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"self",
".",
"_create_file_if_none_exists",
"(",
")",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'r+b'",
")",
"as",
"file_object",
":",
"cache_pickle",
"=",
"pickle",
".",
"load",
"(... | Sets a value in a key.
Args:
key (str): Key for the value.
val: Value to set.
Returns:
Retrieved value. | [
"Sets",
"a",
"value",
"in",
"a",
"key",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/cachefactory.py#L107-L122 |
13,254 | google/budou | budou/chunk.py | Chunk.serialize | def serialize(self):
"""Returns serialized chunk data in dictionary."""
return {
'word': self.word,
'pos': self.pos,
'label': self.label,
'dependency': self.dependency,
'has_cjk': self.has_cjk(),
} | python | def serialize(self):
"""Returns serialized chunk data in dictionary."""
return {
'word': self.word,
'pos': self.pos,
'label': self.label,
'dependency': self.dependency,
'has_cjk': self.has_cjk(),
} | [
"def",
"serialize",
"(",
"self",
")",
":",
"return",
"{",
"'word'",
":",
"self",
".",
"word",
",",
"'pos'",
":",
"self",
".",
"pos",
",",
"'label'",
":",
"self",
".",
"label",
",",
"'dependency'",
":",
"self",
".",
"dependency",
",",
"'has_cjk'",
":"... | Returns serialized chunk data in dictionary. | [
"Returns",
"serialized",
"chunk",
"data",
"in",
"dictionary",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L79-L87 |
13,255 | google/budou | budou/chunk.py | Chunk.has_cjk | def has_cjk(self):
"""Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character.
"""
cjk_codepoint_ranges = [
(43... | python | def has_cjk(self):
"""Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character.
"""
cjk_codepoint_ranges = [
(43... | [
"def",
"has_cjk",
"(",
"self",
")",
":",
"cjk_codepoint_ranges",
"=",
"[",
"(",
"4352",
",",
"4607",
")",
",",
"(",
"11904",
",",
"42191",
")",
",",
"(",
"43072",
",",
"43135",
")",
",",
"(",
"44032",
",",
"55215",
")",
",",
"(",
"63744",
",",
... | Checks if the word of the chunk contains CJK characters.
This is using unicode codepoint ranges from
https://github.com/nltk/nltk/blob/develop/nltk/tokenize/util.py#L149
Returns:
bool: True if the chunk has any CJK character. | [
"Checks",
"if",
"the",
"word",
"of",
"the",
"chunk",
"contains",
"CJK",
"characters",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L119-L135 |
13,256 | google/budou | budou/chunk.py | ChunkList.get_overlaps | def get_overlaps(self, offset, length):
"""Returns chunks overlapped with the given range.
Args:
offset (int): Begin offset of the range.
length (int): Length of the range.
Returns:
Overlapped chunks. (:obj:`budou.chunk.ChunkList`)
"""
# In case entity's offset points to a space ... | python | def get_overlaps(self, offset, length):
"""Returns chunks overlapped with the given range.
Args:
offset (int): Begin offset of the range.
length (int): Length of the range.
Returns:
Overlapped chunks. (:obj:`budou.chunk.ChunkList`)
"""
# In case entity's offset points to a space ... | [
"def",
"get_overlaps",
"(",
"self",
",",
"offset",
",",
"length",
")",
":",
"# In case entity's offset points to a space just before the entity.",
"if",
"''",
".",
"join",
"(",
"[",
"chunk",
".",
"word",
"for",
"chunk",
"in",
"self",
"]",
")",
"[",
"offset",
"... | Returns chunks overlapped with the given range.
Args:
offset (int): Begin offset of the range.
length (int): Length of the range.
Returns:
Overlapped chunks. (:obj:`budou.chunk.ChunkList`) | [
"Returns",
"chunks",
"overlapped",
"with",
"the",
"given",
"range",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L189-L208 |
13,257 | google/budou | budou/chunk.py | ChunkList.swap | def swap(self, old_chunks, new_chunk):
"""Swaps old consecutive chunks with new chunk.
Args:
old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to
be removed.
new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted.
"""
indexes = [self.index(chunk) for chun... | python | def swap(self, old_chunks, new_chunk):
"""Swaps old consecutive chunks with new chunk.
Args:
old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to
be removed.
new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted.
"""
indexes = [self.index(chunk) for chun... | [
"def",
"swap",
"(",
"self",
",",
"old_chunks",
",",
"new_chunk",
")",
":",
"indexes",
"=",
"[",
"self",
".",
"index",
"(",
"chunk",
")",
"for",
"chunk",
"in",
"old_chunks",
"]",
"del",
"self",
"[",
"indexes",
"[",
"0",
"]",
":",
"indexes",
"[",
"-"... | Swaps old consecutive chunks with new chunk.
Args:
old_chunks (:obj:`budou.chunk.ChunkList`): List of consecutive Chunks to
be removed.
new_chunk (:obj:`budou.chunk.Chunk`): A Chunk to be inserted. | [
"Swaps",
"old",
"consecutive",
"chunks",
"with",
"new",
"chunk",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L210-L220 |
13,258 | google/budou | budou/chunk.py | ChunkList.resolve_dependencies | def resolve_dependencies(self):
"""Resolves chunk dependency by concatenating them.
"""
self._concatenate_inner(True)
self._concatenate_inner(False)
self._insert_breaklines() | python | def resolve_dependencies(self):
"""Resolves chunk dependency by concatenating them.
"""
self._concatenate_inner(True)
self._concatenate_inner(False)
self._insert_breaklines() | [
"def",
"resolve_dependencies",
"(",
"self",
")",
":",
"self",
".",
"_concatenate_inner",
"(",
"True",
")",
"self",
".",
"_concatenate_inner",
"(",
"False",
")",
"self",
".",
"_insert_breaklines",
"(",
")"
] | Resolves chunk dependency by concatenating them. | [
"Resolves",
"chunk",
"dependency",
"by",
"concatenating",
"them",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L222-L227 |
13,259 | google/budou | budou/chunk.py | ChunkList._concatenate_inner | def _concatenate_inner(self, direction):
"""Concatenates chunks based on each chunk's dependency.
Args:
direction (bool): Direction of concatenation process. True for forward.
"""
tmp_bucket = []
source_chunks = self if direction else self[::-1]
target_chunks = ChunkList()
for chunk i... | python | def _concatenate_inner(self, direction):
"""Concatenates chunks based on each chunk's dependency.
Args:
direction (bool): Direction of concatenation process. True for forward.
"""
tmp_bucket = []
source_chunks = self if direction else self[::-1]
target_chunks = ChunkList()
for chunk i... | [
"def",
"_concatenate_inner",
"(",
"self",
",",
"direction",
")",
":",
"tmp_bucket",
"=",
"[",
"]",
"source_chunks",
"=",
"self",
"if",
"direction",
"else",
"self",
"[",
":",
":",
"-",
"1",
"]",
"target_chunks",
"=",
"ChunkList",
"(",
")",
"for",
"chunk",... | Concatenates chunks based on each chunk's dependency.
Args:
direction (bool): Direction of concatenation process. True for forward. | [
"Concatenates",
"chunks",
"based",
"on",
"each",
"chunk",
"s",
"dependency",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L229-L259 |
13,260 | google/budou | budou/chunk.py | ChunkList._insert_breaklines | def _insert_breaklines(self):
"""Inserts a breakline instead of a trailing space if the chunk is in CJK.
"""
target_chunks = ChunkList()
for chunk in self:
if chunk.word[-1] == ' ' and chunk.has_cjk():
chunk.word = chunk.word[:-1]
target_chunks.append(chunk)
target_chunks.a... | python | def _insert_breaklines(self):
"""Inserts a breakline instead of a trailing space if the chunk is in CJK.
"""
target_chunks = ChunkList()
for chunk in self:
if chunk.word[-1] == ' ' and chunk.has_cjk():
chunk.word = chunk.word[:-1]
target_chunks.append(chunk)
target_chunks.a... | [
"def",
"_insert_breaklines",
"(",
"self",
")",
":",
"target_chunks",
"=",
"ChunkList",
"(",
")",
"for",
"chunk",
"in",
"self",
":",
"if",
"chunk",
".",
"word",
"[",
"-",
"1",
"]",
"==",
"' '",
"and",
"chunk",
".",
"has_cjk",
"(",
")",
":",
"chunk",
... | Inserts a breakline instead of a trailing space if the chunk is in CJK. | [
"Inserts",
"a",
"breakline",
"instead",
"of",
"a",
"trailing",
"space",
"if",
"the",
"chunk",
"is",
"in",
"CJK",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L261-L272 |
13,261 | google/budou | budou/chunk.py | ChunkList.html_serialize | def html_serialize(self, attributes, max_length=None):
"""Returns concatenated HTML code with SPAN tag.
Args:
attributes (dict): A map of name-value pairs for attributes of output
SPAN tags.
max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.
Returns:
The ... | python | def html_serialize(self, attributes, max_length=None):
"""Returns concatenated HTML code with SPAN tag.
Args:
attributes (dict): A map of name-value pairs for attributes of output
SPAN tags.
max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.
Returns:
The ... | [
"def",
"html_serialize",
"(",
"self",
",",
"attributes",
",",
"max_length",
"=",
"None",
")",
":",
"doc",
"=",
"ET",
".",
"Element",
"(",
"'span'",
")",
"for",
"chunk",
"in",
"self",
":",
"if",
"(",
"chunk",
".",
"has_cjk",
"(",
")",
"and",
"not",
... | Returns concatenated HTML code with SPAN tag.
Args:
attributes (dict): A map of name-value pairs for attributes of output
SPAN tags.
max_length (:obj:`int`, optional): Maximum length of span enclosed chunk.
Returns:
The organized HTML code. (str) | [
"Returns",
"concatenated",
"HTML",
"code",
"with",
"SPAN",
"tag",
"."
] | 101224e6523186851f38ee57a6b2e7bdbd826de2 | https://github.com/google/budou/blob/101224e6523186851f38ee57a6b2e7bdbd826de2/budou/chunk.py#L274-L311 |
13,262 | c-w/gutenberg | gutenberg/acquire/text.py | _etextno_to_uri_subdirectory | def _etextno_to_uri_subdirectory(etextno):
"""Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are... | python | def _etextno_to_uri_subdirectory(etextno):
"""Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are... | [
"def",
"_etextno_to_uri_subdirectory",
"(",
"etextno",
")",
":",
"str_etextno",
"=",
"str",
"(",
"etextno",
")",
".",
"zfill",
"(",
"2",
")",
"all_but_last_digit",
"=",
"list",
"(",
"str_etextno",
"[",
":",
"-",
"1",
"]",
")",
"subdir_part",
"=",
"\"/\"",
... | Returns the subdirectory that an etextno will be found in a gutenberg
mirror. Generally, one finds the subdirectory by separating out each digit
of the etext number, and uses it for a directory. The exception here is for
etext numbers less than 10, which are prepended with a 0 for the directory
traversa... | [
"Returns",
"the",
"subdirectory",
"that",
"an",
"etextno",
"will",
"be",
"found",
"in",
"a",
"gutenberg",
"mirror",
".",
"Generally",
"one",
"finds",
"the",
"subdirectory",
"by",
"separating",
"out",
"each",
"digit",
"of",
"the",
"etext",
"number",
"and",
"u... | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/text.py#L30-L48 |
13,263 | c-w/gutenberg | gutenberg/acquire/text.py | _format_download_uri_for_extension | def _format_download_uri_for_extension(etextno, extension, mirror=None):
"""Returns the download location on the Project Gutenberg servers for a
given text and extension. The list of available extensions for a given
text can be found via the formaturi metadata extractor.
"""
mirror = mirror or _GUT... | python | def _format_download_uri_for_extension(etextno, extension, mirror=None):
"""Returns the download location on the Project Gutenberg servers for a
given text and extension. The list of available extensions for a given
text can be found via the formaturi metadata extractor.
"""
mirror = mirror or _GUT... | [
"def",
"_format_download_uri_for_extension",
"(",
"etextno",
",",
"extension",
",",
"mirror",
"=",
"None",
")",
":",
"mirror",
"=",
"mirror",
"or",
"_GUTENBERG_MIRROR",
"root",
"=",
"mirror",
".",
"strip",
"(",
")",
".",
"rstrip",
"(",
"'/'",
")",
"path",
... | Returns the download location on the Project Gutenberg servers for a
given text and extension. The list of available extensions for a given
text can be found via the formaturi metadata extractor. | [
"Returns",
"the",
"download",
"location",
"on",
"the",
"Project",
"Gutenberg",
"servers",
"for",
"a",
"given",
"text",
"and",
"extension",
".",
"The",
"list",
"of",
"available",
"extensions",
"for",
"a",
"given",
"text",
"can",
"be",
"found",
"via",
"the",
... | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/text.py#L64-L80 |
13,264 | c-w/gutenberg | gutenberg/acquire/text.py | _format_download_uri | def _format_download_uri(etextno, mirror=None, prefer_ascii=False):
"""Returns the download location on the Project Gutenberg servers for a
given text.
Use prefer_ascii to control whether you want to fetch plaintext us-ascii
file first (default old behavior) or if you prefer UTF-8 then 8-bits then
... | python | def _format_download_uri(etextno, mirror=None, prefer_ascii=False):
"""Returns the download location on the Project Gutenberg servers for a
given text.
Use prefer_ascii to control whether you want to fetch plaintext us-ascii
file first (default old behavior) or if you prefer UTF-8 then 8-bits then
... | [
"def",
"_format_download_uri",
"(",
"etextno",
",",
"mirror",
"=",
"None",
",",
"prefer_ascii",
"=",
"False",
")",
":",
"mirror",
"=",
"mirror",
"or",
"_GUTENBERG_MIRROR",
"if",
"not",
"_does_mirror_exist",
"(",
"mirror",
")",
":",
"raise",
"UnknownDownloadUriEx... | Returns the download location on the Project Gutenberg servers for a
given text.
Use prefer_ascii to control whether you want to fetch plaintext us-ascii
file first (default old behavior) or if you prefer UTF-8 then 8-bits then
plaintext.
Raises:
UnknownDownloadUri: If no download location... | [
"Returns",
"the",
"download",
"location",
"on",
"the",
"Project",
"Gutenberg",
"servers",
"for",
"a",
"given",
"text",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/text.py#L83-L119 |
13,265 | c-w/gutenberg | gutenberg/acquire/text.py | load_etext | def load_etext(etextno, refresh_cache=False, mirror=None, prefer_ascii=False):
"""Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally.
"""
etextno = validate_etextno(etextno)... | python | def load_etext(etextno, refresh_cache=False, mirror=None, prefer_ascii=False):
"""Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally.
"""
etextno = validate_etextno(etextno)... | [
"def",
"load_etext",
"(",
"etextno",
",",
"refresh_cache",
"=",
"False",
",",
"mirror",
"=",
"None",
",",
"prefer_ascii",
"=",
"False",
")",
":",
"etextno",
"=",
"validate_etextno",
"(",
"etextno",
")",
"cached",
"=",
"os",
".",
"path",
".",
"join",
"(",... | Returns a unicode representation of the full body of a Project Gutenberg
text. After making an initial remote call to Project Gutenberg's servers,
the text is persisted locally. | [
"Returns",
"a",
"unicode",
"representation",
"of",
"the",
"full",
"body",
"of",
"a",
"Project",
"Gutenberg",
"text",
".",
"After",
"making",
"an",
"initial",
"remote",
"call",
"to",
"Project",
"Gutenberg",
"s",
"servers",
"the",
"text",
"is",
"persisted",
"l... | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/text.py#L122-L153 |
13,266 | c-w/gutenberg | gutenberg/_util/logging.py | disable_logging | def disable_logging(logger=None):
"""Context manager to temporarily suppress all logging for a given logger
or the root logger if no particular logger is specified.
"""
logger = logger or logging.getLogger()
disabled = logger.disabled
logger.disabled = True
yield
logger.disabled = disab... | python | def disable_logging(logger=None):
"""Context manager to temporarily suppress all logging for a given logger
or the root logger if no particular logger is specified.
"""
logger = logger or logging.getLogger()
disabled = logger.disabled
logger.disabled = True
yield
logger.disabled = disab... | [
"def",
"disable_logging",
"(",
"logger",
"=",
"None",
")",
":",
"logger",
"=",
"logger",
"or",
"logging",
".",
"getLogger",
"(",
")",
"disabled",
"=",
"logger",
".",
"disabled",
"logger",
".",
"disabled",
"=",
"True",
"yield",
"logger",
".",
"disabled",
... | Context manager to temporarily suppress all logging for a given logger
or the root logger if no particular logger is specified. | [
"Context",
"manager",
"to",
"temporarily",
"suppress",
"all",
"logging",
"for",
"a",
"given",
"logger",
"or",
"the",
"root",
"logger",
"if",
"no",
"particular",
"logger",
"is",
"specified",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/logging.py#L11-L20 |
13,267 | c-w/gutenberg | gutenberg/_util/os.py | makedirs | def makedirs(*args, **kwargs):
"""Wrapper around os.makedirs that doesn't raise an exception if the
directory already exists.
"""
try:
os.makedirs(*args, **kwargs)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise | python | def makedirs(*args, **kwargs):
"""Wrapper around os.makedirs that doesn't raise an exception if the
directory already exists.
"""
try:
os.makedirs(*args, **kwargs)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise | [
"def",
"makedirs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"OSError",
"as",
"ex",
":",
"if",
"ex",
".",
"errno",
"!=",
"errno",
".",
"EEXI... | Wrapper around os.makedirs that doesn't raise an exception if the
directory already exists. | [
"Wrapper",
"around",
"os",
".",
"makedirs",
"that",
"doesn",
"t",
"raise",
"an",
"exception",
"if",
"the",
"directory",
"already",
"exists",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/os.py#L12-L21 |
13,268 | c-w/gutenberg | gutenberg/_util/os.py | remove | def remove(path):
"""Wrapper that switches between os.remove and shutil.rmtree depending on
whether the provided path is a file or directory.
"""
if not os.path.exists(path):
return
if os.path.isdir(path):
return shutil.rmtree(path)
if os.path.isfile(path):
return os.r... | python | def remove(path):
"""Wrapper that switches between os.remove and shutil.rmtree depending on
whether the provided path is a file or directory.
"""
if not os.path.exists(path):
return
if os.path.isdir(path):
return shutil.rmtree(path)
if os.path.isfile(path):
return os.r... | [
"def",
"remove",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"if",
"os... | Wrapper that switches between os.remove and shutil.rmtree depending on
whether the provided path is a file or directory. | [
"Wrapper",
"that",
"switches",
"between",
"os",
".",
"remove",
"and",
"shutil",
".",
"rmtree",
"depending",
"on",
"whether",
"the",
"provided",
"path",
"is",
"a",
"file",
"or",
"directory",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/os.py#L24-L36 |
13,269 | c-w/gutenberg | gutenberg/_util/os.py | determine_encoding | def determine_encoding(path, default=None):
"""Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str... | python | def determine_encoding(path, default=None):
"""Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str... | [
"def",
"determine_encoding",
"(",
"path",
",",
"default",
"=",
"None",
")",
":",
"byte_order_marks",
"=",
"(",
"(",
"'utf-8-sig'",
",",
"(",
"codecs",
".",
"BOM_UTF8",
",",
")",
")",
",",
"(",
"'utf-16'",
",",
"(",
"codecs",
".",
"BOM_UTF16_LE",
",",
"... | Determines the encoding of a file based on byte order marks.
Arguments:
path (str): The path to the file.
default (str, optional): The encoding to return if the byte-order-mark
lookup does not return an answer.
Returns:
str: The encoding of the file. | [
"Determines",
"the",
"encoding",
"of",
"a",
"file",
"based",
"on",
"byte",
"order",
"marks",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/os.py#L39-L67 |
13,270 | c-w/gutenberg | gutenberg/_util/os.py | reopen_encoded | def reopen_encoded(fileobj, mode='r', fallback_encoding=None):
"""Makes sure that a file was opened with some valid encoding.
Arguments:
fileobj (file): The file-object.
mode (str, optional): The mode in which to re-open the file.
fallback_encoding (str, optional): The encoding in which... | python | def reopen_encoded(fileobj, mode='r', fallback_encoding=None):
"""Makes sure that a file was opened with some valid encoding.
Arguments:
fileobj (file): The file-object.
mode (str, optional): The mode in which to re-open the file.
fallback_encoding (str, optional): The encoding in which... | [
"def",
"reopen_encoded",
"(",
"fileobj",
",",
"mode",
"=",
"'r'",
",",
"fallback_encoding",
"=",
"None",
")",
":",
"encoding",
"=",
"determine_encoding",
"(",
"fileobj",
".",
"name",
",",
"fallback_encoding",
")",
"fileobj",
".",
"close",
"(",
")",
"return",... | Makes sure that a file was opened with some valid encoding.
Arguments:
fileobj (file): The file-object.
mode (str, optional): The mode in which to re-open the file.
fallback_encoding (str, optional): The encoding in which to re-open
the file if it does not specify an encoding it... | [
"Makes",
"sure",
"that",
"a",
"file",
"was",
"opened",
"with",
"some",
"valid",
"encoding",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/os.py#L70-L85 |
13,271 | c-w/gutenberg | gutenberg/query/api.py | get_metadata | def get_metadata(feature_name, etextno):
"""Looks up the value of a meta-data feature for a given text.
Arguments:
feature_name (str): The name of the meta-data to look up.
etextno (int): The identifier of the Gutenberg text for which to look
up the meta-data.
Returns:
... | python | def get_metadata(feature_name, etextno):
"""Looks up the value of a meta-data feature for a given text.
Arguments:
feature_name (str): The name of the meta-data to look up.
etextno (int): The identifier of the Gutenberg text for which to look
up the meta-data.
Returns:
... | [
"def",
"get_metadata",
"(",
"feature_name",
",",
"etextno",
")",
":",
"metadata_values",
"=",
"MetadataExtractor",
".",
"get",
"(",
"feature_name",
")",
".",
"get_metadata",
"(",
"etextno",
")",
"return",
"frozenset",
"(",
"metadata_values",
")"
] | Looks up the value of a meta-data feature for a given text.
Arguments:
feature_name (str): The name of the meta-data to look up.
etextno (int): The identifier of the Gutenberg text for which to look
up the meta-data.
Returns:
frozenset: The values of the meta-data for the t... | [
"Looks",
"up",
"the",
"value",
"of",
"a",
"meta",
"-",
"data",
"feature",
"for",
"a",
"given",
"text",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/query/api.py#L20-L38 |
13,272 | c-w/gutenberg | gutenberg/query/api.py | get_etexts | def get_etexts(feature_name, value):
"""Looks up all the texts that have meta-data matching some criterion.
Arguments:
feature_name (str): The meta-data on which to select the texts.
value (str): The value of the meta-data on which to filter the texts.
Returns:
frozenset: The set o... | python | def get_etexts(feature_name, value):
"""Looks up all the texts that have meta-data matching some criterion.
Arguments:
feature_name (str): The meta-data on which to select the texts.
value (str): The value of the meta-data on which to filter the texts.
Returns:
frozenset: The set o... | [
"def",
"get_etexts",
"(",
"feature_name",
",",
"value",
")",
":",
"matching_etexts",
"=",
"MetadataExtractor",
".",
"get",
"(",
"feature_name",
")",
".",
"get_etexts",
"(",
"value",
")",
"return",
"frozenset",
"(",
"matching_etexts",
")"
] | Looks up all the texts that have meta-data matching some criterion.
Arguments:
feature_name (str): The meta-data on which to select the texts.
value (str): The value of the meta-data on which to filter the texts.
Returns:
frozenset: The set of all the Project Gutenberg text identifiers... | [
"Looks",
"up",
"all",
"the",
"texts",
"that",
"have",
"meta",
"-",
"data",
"matching",
"some",
"criterion",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/query/api.py#L41-L58 |
13,273 | c-w/gutenberg | gutenberg/query/api.py | MetadataExtractor._uri_to_etext | def _uri_to_etext(cls, uri_ref):
"""Converts the representation used to identify a text in the
meta-data RDF graph to a human-friendly integer text identifier.
"""
try:
return validate_etextno(int(os.path.basename(uri_ref.toPython())))
except InvalidEtextIdException:... | python | def _uri_to_etext(cls, uri_ref):
"""Converts the representation used to identify a text in the
meta-data RDF graph to a human-friendly integer text identifier.
"""
try:
return validate_etextno(int(os.path.basename(uri_ref.toPython())))
except InvalidEtextIdException:... | [
"def",
"_uri_to_etext",
"(",
"cls",
",",
"uri_ref",
")",
":",
"try",
":",
"return",
"validate_etextno",
"(",
"int",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"uri_ref",
".",
"toPython",
"(",
")",
")",
")",
")",
"except",
"InvalidEtextIdException",
":... | Converts the representation used to identify a text in the
meta-data RDF graph to a human-friendly integer text identifier. | [
"Converts",
"the",
"representation",
"used",
"to",
"identify",
"a",
"text",
"in",
"the",
"meta",
"-",
"data",
"RDF",
"graph",
"to",
"a",
"human",
"-",
"friendly",
"integer",
"text",
"identifier",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/query/api.py#L127-L135 |
13,274 | c-w/gutenberg | gutenberg/query/api.py | MetadataExtractor._implementations | def _implementations(cls):
"""Returns all the concrete subclasses of MetadataExtractor.
"""
if cls.__implementations:
return cls.__implementations
cls.__implementations = {}
for implementation in all_subclasses(MetadataExtractor):
try:
fe... | python | def _implementations(cls):
"""Returns all the concrete subclasses of MetadataExtractor.
"""
if cls.__implementations:
return cls.__implementations
cls.__implementations = {}
for implementation in all_subclasses(MetadataExtractor):
try:
fe... | [
"def",
"_implementations",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__implementations",
":",
"return",
"cls",
".",
"__implementations",
"cls",
".",
"__implementations",
"=",
"{",
"}",
"for",
"implementation",
"in",
"all_subclasses",
"(",
"MetadataExtractor",
")"... | Returns all the concrete subclasses of MetadataExtractor. | [
"Returns",
"all",
"the",
"concrete",
"subclasses",
"of",
"MetadataExtractor",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/query/api.py#L138-L152 |
13,275 | c-w/gutenberg | gutenberg/query/api.py | MetadataExtractor.get | def get(feature_name):
"""Returns the MetadataExtractor that can extract information about the
provided feature name.
Raises:
UnsupportedFeature: If no extractor exists for the feature name.
"""
implementations = MetadataExtractor._implementations()
try:
... | python | def get(feature_name):
"""Returns the MetadataExtractor that can extract information about the
provided feature name.
Raises:
UnsupportedFeature: If no extractor exists for the feature name.
"""
implementations = MetadataExtractor._implementations()
try:
... | [
"def",
"get",
"(",
"feature_name",
")",
":",
"implementations",
"=",
"MetadataExtractor",
".",
"_implementations",
"(",
")",
"try",
":",
"return",
"implementations",
"[",
"feature_name",
"]",
"except",
"KeyError",
":",
"raise",
"UnsupportedFeatureException",
"(",
... | Returns the MetadataExtractor that can extract information about the
provided feature name.
Raises:
UnsupportedFeature: If no extractor exists for the feature name. | [
"Returns",
"the",
"MetadataExtractor",
"that",
"can",
"extract",
"information",
"about",
"the",
"provided",
"feature",
"name",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/query/api.py#L155-L171 |
13,276 | c-w/gutenberg | gutenberg/acquire/metadata.py | set_metadata_cache | def set_metadata_cache(cache):
"""Sets the metadata cache object to use.
"""
global _METADATA_CACHE
if _METADATA_CACHE and _METADATA_CACHE.is_open:
_METADATA_CACHE.close()
_METADATA_CACHE = cache | python | def set_metadata_cache(cache):
"""Sets the metadata cache object to use.
"""
global _METADATA_CACHE
if _METADATA_CACHE and _METADATA_CACHE.is_open:
_METADATA_CACHE.close()
_METADATA_CACHE = cache | [
"def",
"set_metadata_cache",
"(",
"cache",
")",
":",
"global",
"_METADATA_CACHE",
"if",
"_METADATA_CACHE",
"and",
"_METADATA_CACHE",
".",
"is_open",
":",
"_METADATA_CACHE",
".",
"close",
"(",
")",
"_METADATA_CACHE",
"=",
"cache"
] | Sets the metadata cache object to use. | [
"Sets",
"the",
"metadata",
"cache",
"object",
"to",
"use",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L323-L332 |
13,277 | c-w/gutenberg | gutenberg/acquire/metadata.py | _create_metadata_cache | def _create_metadata_cache(cache_location):
"""Creates a new metadata cache instance appropriate for this platform.
"""
cache_url = os.getenv('GUTENBERG_FUSEKI_URL')
if cache_url:
return FusekiMetadataCache(cache_location, cache_url)
try:
return SleepycatMetadataCache(cache_locatio... | python | def _create_metadata_cache(cache_location):
"""Creates a new metadata cache instance appropriate for this platform.
"""
cache_url = os.getenv('GUTENBERG_FUSEKI_URL')
if cache_url:
return FusekiMetadataCache(cache_location, cache_url)
try:
return SleepycatMetadataCache(cache_locatio... | [
"def",
"_create_metadata_cache",
"(",
"cache_location",
")",
":",
"cache_url",
"=",
"os",
".",
"getenv",
"(",
"'GUTENBERG_FUSEKI_URL'",
")",
"if",
"cache_url",
":",
"return",
"FusekiMetadataCache",
"(",
"cache_location",
",",
"cache_url",
")",
"try",
":",
"return"... | Creates a new metadata cache instance appropriate for this platform. | [
"Creates",
"a",
"new",
"metadata",
"cache",
"instance",
"appropriate",
"for",
"this",
"platform",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L347-L362 |
13,278 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache.open | def open(self):
"""Opens an existing cache.
"""
try:
self.graph.open(self.cache_uri, create=False)
self._add_namespaces(self.graph)
self.is_open = True
except Exception:
raise InvalidCacheException('The cache is invalid or not created') | python | def open(self):
"""Opens an existing cache.
"""
try:
self.graph.open(self.cache_uri, create=False)
self._add_namespaces(self.graph)
self.is_open = True
except Exception:
raise InvalidCacheException('The cache is invalid or not created') | [
"def",
"open",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"graph",
".",
"open",
"(",
"self",
".",
"cache_uri",
",",
"create",
"=",
"False",
")",
"self",
".",
"_add_namespaces",
"(",
"self",
".",
"graph",
")",
"self",
".",
"is_open",
"=",
"True... | Opens an existing cache. | [
"Opens",
"an",
"existing",
"cache",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L61-L70 |
13,279 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache.populate | def populate(self):
"""Populates a new cache.
"""
if self.exists:
raise CacheAlreadyExistsException('location: %s' % self.cache_uri)
self._populate_setup()
with closing(self.graph):
with self._download_metadata_archive() as metadata_archive:
... | python | def populate(self):
"""Populates a new cache.
"""
if self.exists:
raise CacheAlreadyExistsException('location: %s' % self.cache_uri)
self._populate_setup()
with closing(self.graph):
with self._download_metadata_archive() as metadata_archive:
... | [
"def",
"populate",
"(",
"self",
")",
":",
"if",
"self",
".",
"exists",
":",
"raise",
"CacheAlreadyExistsException",
"(",
"'location: %s'",
"%",
"self",
".",
"cache_uri",
")",
"self",
".",
"_populate_setup",
"(",
")",
"with",
"closing",
"(",
"self",
".",
"g... | Populates a new cache. | [
"Populates",
"a",
"new",
"cache",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L86-L98 |
13,280 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache.refresh | def refresh(self):
"""Refresh the cache by deleting the old one and creating a new one.
"""
if self.exists:
self.delete()
self.populate()
self.open() | python | def refresh(self):
"""Refresh the cache by deleting the old one and creating a new one.
"""
if self.exists:
self.delete()
self.populate()
self.open() | [
"def",
"refresh",
"(",
"self",
")",
":",
"if",
"self",
".",
"exists",
":",
"self",
".",
"delete",
"(",
")",
"self",
".",
"populate",
"(",
")",
"self",
".",
"open",
"(",
")"
] | Refresh the cache by deleting the old one and creating a new one. | [
"Refresh",
"the",
"cache",
"by",
"deleting",
"the",
"old",
"one",
"and",
"creating",
"a",
"new",
"one",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L112-L119 |
13,281 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache._download_metadata_archive | def _download_metadata_archive(self):
"""Makes a remote call to the Project Gutenberg servers and downloads
the entire Project Gutenberg meta-data catalog. The catalog describes
the texts on Project Gutenberg in RDF. The function returns a
file-pointer to the catalog.
"""
... | python | def _download_metadata_archive(self):
"""Makes a remote call to the Project Gutenberg servers and downloads
the entire Project Gutenberg meta-data catalog. The catalog describes
the texts on Project Gutenberg in RDF. The function returns a
file-pointer to the catalog.
"""
... | [
"def",
"_download_metadata_archive",
"(",
"self",
")",
":",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"as",
"metadata_archive",
":",
"shutil",
".",
"copyfileobj",
"(",
"urlopen",
"(",
"self",
".",
"catalog_source",
")",
"... | Makes a remote call to the Project Gutenberg servers and downloads
the entire Project Gutenberg meta-data catalog. The catalog describes
the texts on Project Gutenberg in RDF. The function returns a
file-pointer to the catalog. | [
"Makes",
"a",
"remote",
"call",
"to",
"the",
"Project",
"Gutenberg",
"servers",
"and",
"downloads",
"the",
"entire",
"Project",
"Gutenberg",
"meta",
"-",
"data",
"catalog",
".",
"The",
"catalog",
"describes",
"the",
"texts",
"on",
"Project",
"Gutenberg",
"in",... | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L138-L148 |
13,282 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache._metadata_is_invalid | def _metadata_is_invalid(cls, fact):
"""Determines if the fact is not well formed.
"""
return any(isinstance(token, URIRef) and ' ' in token
for token in fact) | python | def _metadata_is_invalid(cls, fact):
"""Determines if the fact is not well formed.
"""
return any(isinstance(token, URIRef) and ' ' in token
for token in fact) | [
"def",
"_metadata_is_invalid",
"(",
"cls",
",",
"fact",
")",
":",
"return",
"any",
"(",
"isinstance",
"(",
"token",
",",
"URIRef",
")",
"and",
"' '",
"in",
"token",
"for",
"token",
"in",
"fact",
")"
] | Determines if the fact is not well formed. | [
"Determines",
"if",
"the",
"fact",
"is",
"not",
"well",
"formed",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L151-L156 |
13,283 | c-w/gutenberg | gutenberg/acquire/metadata.py | MetadataCache._iter_metadata_triples | def _iter_metadata_triples(cls, metadata_archive_path):
"""Yields all meta-data of Project Gutenberg texts contained in the
catalog dump.
"""
pg_rdf_regex = re.compile(r'pg\d+.rdf$')
with closing(tarfile.open(metadata_archive_path)) as metadata_archive:
for item in m... | python | def _iter_metadata_triples(cls, metadata_archive_path):
"""Yields all meta-data of Project Gutenberg texts contained in the
catalog dump.
"""
pg_rdf_regex = re.compile(r'pg\d+.rdf$')
with closing(tarfile.open(metadata_archive_path)) as metadata_archive:
for item in m... | [
"def",
"_iter_metadata_triples",
"(",
"cls",
",",
"metadata_archive_path",
")",
":",
"pg_rdf_regex",
"=",
"re",
".",
"compile",
"(",
"r'pg\\d+.rdf$'",
")",
"with",
"closing",
"(",
"tarfile",
".",
"open",
"(",
"metadata_archive_path",
")",
")",
"as",
"metadata_ar... | Yields all meta-data of Project Gutenberg texts contained in the
catalog dump. | [
"Yields",
"all",
"meta",
"-",
"data",
"of",
"Project",
"Gutenberg",
"texts",
"contained",
"in",
"the",
"catalog",
"dump",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L159-L175 |
13,284 | c-w/gutenberg | gutenberg/acquire/metadata.py | FusekiMetadataCache._populate_setup | def _populate_setup(self):
"""Just create a local marker file since the actual database should
already be created on the Fuseki server.
"""
makedirs(os.path.dirname(self._cache_marker))
with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj:
fobj.write(s... | python | def _populate_setup(self):
"""Just create a local marker file since the actual database should
already be created on the Fuseki server.
"""
makedirs(os.path.dirname(self._cache_marker))
with codecs.open(self._cache_marker, 'w', encoding='utf-8') as fobj:
fobj.write(s... | [
"def",
"_populate_setup",
"(",
"self",
")",
":",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"self",
".",
"_cache_marker",
")",
")",
"with",
"codecs",
".",
"open",
"(",
"self",
".",
"_cache_marker",
",",
"'w'",
",",
"encoding",
"=",
"'utf-... | Just create a local marker file since the actual database should
already be created on the Fuseki server. | [
"Just",
"create",
"a",
"local",
"marker",
"file",
"since",
"the",
"actual",
"database",
"should",
"already",
"be",
"created",
"on",
"the",
"Fuseki",
"server",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L219-L227 |
13,285 | c-w/gutenberg | gutenberg/acquire/metadata.py | FusekiMetadataCache.delete | def delete(self):
"""Deletes the local marker file and also any data in the Fuseki
server.
"""
MetadataCache.delete(self)
try:
self.graph.query('DELETE WHERE { ?s ?p ?o . }')
except ResultException:
# this is often just a false positive since Jena... | python | def delete(self):
"""Deletes the local marker file and also any data in the Fuseki
server.
"""
MetadataCache.delete(self)
try:
self.graph.query('DELETE WHERE { ?s ?p ?o . }')
except ResultException:
# this is often just a false positive since Jena... | [
"def",
"delete",
"(",
"self",
")",
":",
"MetadataCache",
".",
"delete",
"(",
"self",
")",
"try",
":",
"self",
".",
"graph",
".",
"query",
"(",
"'DELETE WHERE { ?s ?p ?o . }'",
")",
"except",
"ResultException",
":",
"# this is often just a false positive since Jena F... | Deletes the local marker file and also any data in the Fuseki
server. | [
"Deletes",
"the",
"local",
"marker",
"file",
"and",
"also",
"any",
"data",
"in",
"the",
"Fuseki",
"server",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L229-L241 |
13,286 | c-w/gutenberg | gutenberg/acquire/metadata.py | FusekiMetadataCache._metadata_is_invalid | def _metadata_is_invalid(cls, fact):
"""Filters out blank nodes since the SPARQLUpdateStore does not
support them.
"""
return (MetadataCache._metadata_is_invalid(fact)
or any(isinstance(token, BNode) for token in fact)) | python | def _metadata_is_invalid(cls, fact):
"""Filters out blank nodes since the SPARQLUpdateStore does not
support them.
"""
return (MetadataCache._metadata_is_invalid(fact)
or any(isinstance(token, BNode) for token in fact)) | [
"def",
"_metadata_is_invalid",
"(",
"cls",
",",
"fact",
")",
":",
"return",
"(",
"MetadataCache",
".",
"_metadata_is_invalid",
"(",
"fact",
")",
"or",
"any",
"(",
"isinstance",
"(",
"token",
",",
"BNode",
")",
"for",
"token",
"in",
"fact",
")",
")"
] | Filters out blank nodes since the SPARQLUpdateStore does not
support them. | [
"Filters",
"out",
"blank",
"nodes",
"since",
"the",
"SPARQLUpdateStore",
"does",
"not",
"support",
"them",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/acquire/metadata.py#L269-L275 |
13,287 | c-w/gutenberg | gutenberg/_util/objects.py | all_subclasses | def all_subclasses(cls):
"""Recursively returns all the subclasses of the provided class.
"""
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | python | def all_subclasses(cls):
"""Recursively returns all the subclasses of the provided class.
"""
subclasses = cls.__subclasses__()
descendants = (descendant for subclass in subclasses
for descendant in all_subclasses(subclass))
return set(subclasses) | set(descendants) | [
"def",
"all_subclasses",
"(",
"cls",
")",
":",
"subclasses",
"=",
"cls",
".",
"__subclasses__",
"(",
")",
"descendants",
"=",
"(",
"descendant",
"for",
"subclass",
"in",
"subclasses",
"for",
"descendant",
"in",
"all_subclasses",
"(",
"subclass",
")",
")",
"r... | Recursively returns all the subclasses of the provided class. | [
"Recursively",
"returns",
"all",
"the",
"subclasses",
"of",
"the",
"provided",
"class",
"."
] | d1ef3da6fba6c3636d452479ed6bcb17c7d4d246 | https://github.com/c-w/gutenberg/blob/d1ef3da6fba6c3636d452479ed6bcb17c7d4d246/gutenberg/_util/objects.py#L4-L11 |
13,288 | ralphbean/ansi2html | ansi2html/converter.py | Ansi2HTMLConverter._collapse_cursor | def _collapse_cursor(self, parts):
""" Act on any CursorMoveUp commands by deleting preceding tokens """
final_parts = []
for part in parts:
# Throw out empty string tokens ("")
if not part:
continue
# Go back, deleting every token in the la... | python | def _collapse_cursor(self, parts):
""" Act on any CursorMoveUp commands by deleting preceding tokens """
final_parts = []
for part in parts:
# Throw out empty string tokens ("")
if not part:
continue
# Go back, deleting every token in the la... | [
"def",
"_collapse_cursor",
"(",
"self",
",",
"parts",
")",
":",
"final_parts",
"=",
"[",
"]",
"for",
"part",
"in",
"parts",
":",
"# Throw out empty string tokens (\"\")",
"if",
"not",
"part",
":",
"continue",
"# Go back, deleting every token in the last 'line'",
"if",... | Act on any CursorMoveUp commands by deleting preceding tokens | [
"Act",
"on",
"any",
"CursorMoveUp",
"commands",
"by",
"deleting",
"preceding",
"tokens"
] | ac3b230f29d3ab180d29efd98c14ffef29707e2b | https://github.com/ralphbean/ansi2html/blob/ac3b230f29d3ab180d29efd98c14ffef29707e2b/ansi2html/converter.py#L413-L436 |
13,289 | ralphbean/ansi2html | ansi2html/converter.py | Ansi2HTMLConverter.prepare | def prepare(self, ansi='', ensure_trailing_newline=False):
""" Load the contents of 'ansi' into this object """
body, styles = self.apply_regex(ansi)
if ensure_trailing_newline and _needs_extra_newline(body):
body += '\n'
self._attrs = {
'dark_bg': self.dark_bg... | python | def prepare(self, ansi='', ensure_trailing_newline=False):
""" Load the contents of 'ansi' into this object """
body, styles = self.apply_regex(ansi)
if ensure_trailing_newline and _needs_extra_newline(body):
body += '\n'
self._attrs = {
'dark_bg': self.dark_bg... | [
"def",
"prepare",
"(",
"self",
",",
"ansi",
"=",
"''",
",",
"ensure_trailing_newline",
"=",
"False",
")",
":",
"body",
",",
"styles",
"=",
"self",
".",
"apply_regex",
"(",
"ansi",
")",
"if",
"ensure_trailing_newline",
"and",
"_needs_extra_newline",
"(",
"bod... | Load the contents of 'ansi' into this object | [
"Load",
"the",
"contents",
"of",
"ansi",
"into",
"this",
"object"
] | ac3b230f29d3ab180d29efd98c14ffef29707e2b | https://github.com/ralphbean/ansi2html/blob/ac3b230f29d3ab180d29efd98c14ffef29707e2b/ansi2html/converter.py#L438-L454 |
13,290 | PyO3/setuptools-rust | setuptools_rust/build_ext.py | build_ext.run | def run(self):
"""Run build_rust sub command """
if self.has_rust_extensions():
log.info("running build_rust")
build_rust = self.get_finalized_command("build_rust")
build_rust.inplace = self.inplace
build_rust.run()
_build_ext.run(self) | python | def run(self):
"""Run build_rust sub command """
if self.has_rust_extensions():
log.info("running build_rust")
build_rust = self.get_finalized_command("build_rust")
build_rust.inplace = self.inplace
build_rust.run()
_build_ext.run(self) | [
"def",
"run",
"(",
"self",
")",
":",
"if",
"self",
".",
"has_rust_extensions",
"(",
")",
":",
"log",
".",
"info",
"(",
"\"running build_rust\"",
")",
"build_rust",
"=",
"self",
".",
"get_finalized_command",
"(",
"\"build_rust\"",
")",
"build_rust",
".",
"inp... | Run build_rust sub command | [
"Run",
"build_rust",
"sub",
"command"
] | cd3ecec5749927a5c69b8ea516fc918ae95d18ce | https://github.com/PyO3/setuptools-rust/blob/cd3ecec5749927a5c69b8ea516fc918ae95d18ce/setuptools_rust/build_ext.py#L20-L28 |
13,291 | PyO3/setuptools-rust | setuptools_rust/extension.py | RustExtension.get_lib_name | def get_lib_name(self):
""" Parse Cargo.toml to get the name of the shared library. """
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
... | python | def get_lib_name(self):
""" Parse Cargo.toml to get the name of the shared library. """
# We import in here to make sure the the setup_requires are already installed
import toml
cfg = toml.load(self.path)
name = cfg.get("lib", {}).get("name")
if name is None:
... | [
"def",
"get_lib_name",
"(",
"self",
")",
":",
"# We import in here to make sure the the setup_requires are already installed",
"import",
"toml",
"cfg",
"=",
"toml",
".",
"load",
"(",
"self",
".",
"path",
")",
"name",
"=",
"cfg",
".",
"get",
"(",
"\"lib\"",
",",
... | Parse Cargo.toml to get the name of the shared library. | [
"Parse",
"Cargo",
".",
"toml",
"to",
"get",
"the",
"name",
"of",
"the",
"shared",
"library",
"."
] | cd3ecec5749927a5c69b8ea516fc918ae95d18ce | https://github.com/PyO3/setuptools-rust/blob/cd3ecec5749927a5c69b8ea516fc918ae95d18ce/setuptools_rust/extension.py#L106-L122 |
13,292 | PyO3/setuptools-rust | setuptools_rust/tomlgen.py | find_rust_extensions | def find_rust_extensions(*directories, **kwargs):
"""Attempt to find Rust extensions in given directories.
This function will recurse through the directories in the given
directories, to find a name whose name is ``libfile``. When such
a file is found, an extension is created, expecting the cargo
m... | python | def find_rust_extensions(*directories, **kwargs):
"""Attempt to find Rust extensions in given directories.
This function will recurse through the directories in the given
directories, to find a name whose name is ``libfile``. When such
a file is found, an extension is created, expecting the cargo
m... | [
"def",
"find_rust_extensions",
"(",
"*",
"directories",
",",
"*",
"*",
"kwargs",
")",
":",
"# Get the file used to mark a Rust extension",
"libfile",
"=",
"kwargs",
".",
"get",
"(",
"\"libfile\"",
",",
"\"lib.rs\"",
")",
"# Get the directories to explore",
"directories"... | Attempt to find Rust extensions in given directories.
This function will recurse through the directories in the given
directories, to find a name whose name is ``libfile``. When such
a file is found, an extension is created, expecting the cargo
manifest file (``Cargo.toml``) to be next to that file. Th... | [
"Attempt",
"to",
"find",
"Rust",
"extensions",
"in",
"given",
"directories",
"."
] | cd3ecec5749927a5c69b8ea516fc918ae95d18ce | https://github.com/PyO3/setuptools-rust/blob/cd3ecec5749927a5c69b8ea516fc918ae95d18ce/setuptools_rust/tomlgen.py#L207-L274 |
13,293 | gamechanger/mongothon | mongothon/events.py | EventHandlerRegistrar.register | def register(self, event, fn):
"""
Registers the given function as a handler to be applied
in response to the the given event.
"""
# TODO: Can we check the method signature?
self._handler_dict.setdefault(event, [])
if fn not in self._handler_dict[event]:
... | python | def register(self, event, fn):
"""
Registers the given function as a handler to be applied
in response to the the given event.
"""
# TODO: Can we check the method signature?
self._handler_dict.setdefault(event, [])
if fn not in self._handler_dict[event]:
... | [
"def",
"register",
"(",
"self",
",",
"event",
",",
"fn",
")",
":",
"# TODO: Can we check the method signature?",
"self",
".",
"_handler_dict",
".",
"setdefault",
"(",
"event",
",",
"[",
"]",
")",
"if",
"fn",
"not",
"in",
"self",
".",
"_handler_dict",
"[",
... | Registers the given function as a handler to be applied
in response to the the given event. | [
"Registers",
"the",
"given",
"function",
"as",
"a",
"handler",
"to",
"be",
"applied",
"in",
"response",
"to",
"the",
"the",
"given",
"event",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/events.py#L15-L24 |
13,294 | gamechanger/mongothon | mongothon/events.py | EventHandlerRegistrar.apply | def apply(self, event, document, *args, **kwargs):
"""
Applies all middleware functions registered against the given
event in order to the given document.
"""
for fn in self._handler_dict.get(event, []):
fn(document, *args, **kwargs) | python | def apply(self, event, document, *args, **kwargs):
"""
Applies all middleware functions registered against the given
event in order to the given document.
"""
for fn in self._handler_dict.get(event, []):
fn(document, *args, **kwargs) | [
"def",
"apply",
"(",
"self",
",",
"event",
",",
"document",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"fn",
"in",
"self",
".",
"_handler_dict",
".",
"get",
"(",
"event",
",",
"[",
"]",
")",
":",
"fn",
"(",
"document",
",",
"*"... | Applies all middleware functions registered against the given
event in order to the given document. | [
"Applies",
"all",
"middleware",
"functions",
"registered",
"against",
"the",
"given",
"event",
"in",
"order",
"to",
"the",
"given",
"document",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/events.py#L26-L32 |
13,295 | gamechanger/mongothon | mongothon/events.py | EventHandlerRegistrar.deregister | def deregister(self, event, fn):
"""
Deregister the handler function from the given event.
"""
if event in self._handler_dict and fn in self._handler_dict[event]:
self._handler_dict[event].remove(fn) | python | def deregister(self, event, fn):
"""
Deregister the handler function from the given event.
"""
if event in self._handler_dict and fn in self._handler_dict[event]:
self._handler_dict[event].remove(fn) | [
"def",
"deregister",
"(",
"self",
",",
"event",
",",
"fn",
")",
":",
"if",
"event",
"in",
"self",
".",
"_handler_dict",
"and",
"fn",
"in",
"self",
".",
"_handler_dict",
"[",
"event",
"]",
":",
"self",
".",
"_handler_dict",
"[",
"event",
"]",
".",
"re... | Deregister the handler function from the given event. | [
"Deregister",
"the",
"handler",
"function",
"from",
"the",
"given",
"event",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/events.py#L34-L39 |
13,296 | gamechanger/mongothon | mongothon/queries.py | ScopeBuilder.unpack_scope | def unpack_scope(cls, scope):
"""Unpacks the response from a scope function. The function should return
either a query, a query and a projection, or a query a projection and
an query options hash."""
query = {}
projection = {}
options = {}
if isinstance(scope, tu... | python | def unpack_scope(cls, scope):
"""Unpacks the response from a scope function. The function should return
either a query, a query and a projection, or a query a projection and
an query options hash."""
query = {}
projection = {}
options = {}
if isinstance(scope, tu... | [
"def",
"unpack_scope",
"(",
"cls",
",",
"scope",
")",
":",
"query",
"=",
"{",
"}",
"projection",
"=",
"{",
"}",
"options",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"scope",
",",
"tuple",
")",
":",
"if",
"len",
"(",
"scope",
")",
">",
"3",
":",
"... | Unpacks the response from a scope function. The function should return
either a query, a query and a projection, or a query a projection and
an query options hash. | [
"Unpacks",
"the",
"response",
"from",
"a",
"scope",
"function",
".",
"The",
"function",
"should",
"return",
"either",
"a",
"query",
"a",
"query",
"and",
"a",
"projection",
"or",
"a",
"query",
"a",
"projection",
"and",
"an",
"query",
"options",
"hash",
"."
... | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/queries.py#L24-L46 |
13,297 | gamechanger/mongothon | mongothon/queries.py | ScopeBuilder.register_fn | def register_fn(cls, f):
"""Registers a scope function on this builder."""
def inner(self, *args, **kwargs):
try:
query, projection, options = cls.unpack_scope(f(*args, **kwargs))
new_query = deepcopy(self.query)
new_projection = deepcopy(self.... | python | def register_fn(cls, f):
"""Registers a scope function on this builder."""
def inner(self, *args, **kwargs):
try:
query, projection, options = cls.unpack_scope(f(*args, **kwargs))
new_query = deepcopy(self.query)
new_projection = deepcopy(self.... | [
"def",
"register_fn",
"(",
"cls",
",",
"f",
")",
":",
"def",
"inner",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"query",
",",
"projection",
",",
"options",
"=",
"cls",
".",
"unpack_scope",
"(",
"f",
"(",
"*",
... | Registers a scope function on this builder. | [
"Registers",
"a",
"scope",
"function",
"on",
"this",
"builder",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/queries.py#L50-L66 |
13,298 | gamechanger/mongothon | mongothon/queries.py | ScopeBuilder.cursor | def cursor(self):
"""
Returns a cursor for the currently assembled query, creating it if
it doesn't already exist.
"""
if not self._active_cursor:
self._active_cursor = self.model.find(self.query,
self.projection or No... | python | def cursor(self):
"""
Returns a cursor for the currently assembled query, creating it if
it doesn't already exist.
"""
if not self._active_cursor:
self._active_cursor = self.model.find(self.query,
self.projection or No... | [
"def",
"cursor",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_active_cursor",
":",
"self",
".",
"_active_cursor",
"=",
"self",
".",
"model",
".",
"find",
"(",
"self",
".",
"query",
",",
"self",
".",
"projection",
"or",
"None",
",",
"*",
"*",
... | Returns a cursor for the currently assembled query, creating it if
it doesn't already exist. | [
"Returns",
"a",
"cursor",
"for",
"the",
"currently",
"assembled",
"query",
"creating",
"it",
"if",
"it",
"doesn",
"t",
"already",
"exist",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/queries.py#L80-L89 |
13,299 | gamechanger/mongothon | mongothon/model.py | Model._ensure_object_id | def _ensure_object_id(cls, id):
"""Checks whether the given id is an ObjectId instance, and if not wraps it."""
if isinstance(id, ObjectId):
return id
if isinstance(id, basestring) and OBJECTIDEXPR.match(id):
return ObjectId(id)
return id | python | def _ensure_object_id(cls, id):
"""Checks whether the given id is an ObjectId instance, and if not wraps it."""
if isinstance(id, ObjectId):
return id
if isinstance(id, basestring) and OBJECTIDEXPR.match(id):
return ObjectId(id)
return id | [
"def",
"_ensure_object_id",
"(",
"cls",
",",
"id",
")",
":",
"if",
"isinstance",
"(",
"id",
",",
"ObjectId",
")",
":",
"return",
"id",
"if",
"isinstance",
"(",
"id",
",",
"basestring",
")",
"and",
"OBJECTIDEXPR",
".",
"match",
"(",
"id",
")",
":",
"r... | Checks whether the given id is an ObjectId instance, and if not wraps it. | [
"Checks",
"whether",
"the",
"given",
"id",
"is",
"an",
"ObjectId",
"instance",
"and",
"if",
"not",
"wraps",
"it",
"."
] | 5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b | https://github.com/gamechanger/mongothon/blob/5305bdae8e38d09bfe7881f1edc99ac0a2e6b96b/mongothon/model.py#L69-L77 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.