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 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
alephdata/memorious | memorious/operations/fetch.py | session | def session(context, data):
"""Set some HTTP parameters for all subsequent requests.
This includes ``user`` and ``password`` for HTTP basic authentication,
and ``user_agent`` as a header.
"""
context.http.reset()
user = context.get('user')
password = context.get('password')
if user is... | python | def session(context, data):
"""Set some HTTP parameters for all subsequent requests.
This includes ``user`` and ``password`` for HTTP basic authentication,
and ``user_agent`` as a header.
"""
context.http.reset()
user = context.get('user')
password = context.get('password')
if user is... | [
"def",
"session",
"(",
"context",
",",
"data",
")",
":",
"context",
".",
"http",
".",
"reset",
"(",
")",
"user",
"=",
"context",
".",
"get",
"(",
"'user'",
")",
"password",
"=",
"context",
".",
"get",
"(",
"'password'",
")",
"if",
"user",
"is",
"no... | Set some HTTP parameters for all subsequent requests.
This includes ``user`` and ``password`` for HTTP basic authentication,
and ``user_agent`` as a header. | [
"Set",
"some",
"HTTP",
"parameters",
"for",
"all",
"subsequent",
"requests",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/fetch.py#L74-L103 | train |
alephdata/memorious | memorious/model/event.py | Event.save | def save(cls, crawler, stage, level, run_id, error=None, message=None):
"""Create an event, possibly based on an exception."""
event = {
'stage': stage.name,
'level': level,
'timestamp': pack_now(),
'error': error,
'message': message
}
... | python | def save(cls, crawler, stage, level, run_id, error=None, message=None):
"""Create an event, possibly based on an exception."""
event = {
'stage': stage.name,
'level': level,
'timestamp': pack_now(),
'error': error,
'message': message
}
... | [
"def",
"save",
"(",
"cls",
",",
"crawler",
",",
"stage",
",",
"level",
",",
"run_id",
",",
"error",
"=",
"None",
",",
"message",
"=",
"None",
")",
":",
"event",
"=",
"{",
"'stage'",
":",
"stage",
".",
"name",
",",
"'level'",
":",
"level",
",",
"'... | Create an event, possibly based on an exception. | [
"Create",
"an",
"event",
"possibly",
"based",
"on",
"an",
"exception",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/model/event.py#L19-L35 | train |
alephdata/memorious | memorious/model/event.py | Event.get_stage_events | def get_stage_events(cls, crawler, stage_name, start, end, level=None):
"""events from a particular stage"""
key = make_key(crawler, "events", stage_name, level)
return cls.event_list(key, start, end) | python | def get_stage_events(cls, crawler, stage_name, start, end, level=None):
"""events from a particular stage"""
key = make_key(crawler, "events", stage_name, level)
return cls.event_list(key, start, end) | [
"def",
"get_stage_events",
"(",
"cls",
",",
"crawler",
",",
"stage_name",
",",
"start",
",",
"end",
",",
"level",
"=",
"None",
")",
":",
"key",
"=",
"make_key",
"(",
"crawler",
",",
"\"events\"",
",",
"stage_name",
",",
"level",
")",
"return",
"cls",
"... | events from a particular stage | [
"events",
"from",
"a",
"particular",
"stage"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/model/event.py#L93-L96 | train |
alephdata/memorious | memorious/model/event.py | Event.get_run_events | def get_run_events(cls, crawler, run_id, start, end, level=None):
"""Events from a particular run"""
key = make_key(crawler, "events", run_id, level)
return cls.event_list(key, start, end) | python | def get_run_events(cls, crawler, run_id, start, end, level=None):
"""Events from a particular run"""
key = make_key(crawler, "events", run_id, level)
return cls.event_list(key, start, end) | [
"def",
"get_run_events",
"(",
"cls",
",",
"crawler",
",",
"run_id",
",",
"start",
",",
"end",
",",
"level",
"=",
"None",
")",
":",
"key",
"=",
"make_key",
"(",
"crawler",
",",
"\"events\"",
",",
"run_id",
",",
"level",
")",
"return",
"cls",
".",
"eve... | Events from a particular run | [
"Events",
"from",
"a",
"particular",
"run"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/model/event.py#L99-L102 | train |
alephdata/memorious | memorious/helpers/__init__.py | soviet_checksum | def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digit) * index
summed = (total / 11 * 11)
return total - summed
check = sum_digits(code, 1)
... | python | def soviet_checksum(code):
"""Courtesy of Sir Vlad Lavrov."""
def sum_digits(code, offset=1):
total = 0
for digit, index in zip(code[:7], count(offset)):
total += int(digit) * index
summed = (total / 11 * 11)
return total - summed
check = sum_digits(code, 1)
... | [
"def",
"soviet_checksum",
"(",
"code",
")",
":",
"def",
"sum_digits",
"(",
"code",
",",
"offset",
"=",
"1",
")",
":",
"total",
"=",
"0",
"for",
"digit",
",",
"index",
"in",
"zip",
"(",
"code",
"[",
":",
"7",
"]",
",",
"count",
"(",
"offset",
")",... | Courtesy of Sir Vlad Lavrov. | [
"Courtesy",
"of",
"Sir",
"Vlad",
"Lavrov",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/__init__.py#L16-L30 | train |
alephdata/memorious | memorious/helpers/__init__.py | search_results_total | def search_results_total(html, xpath, check, delimiter):
""" Get the total number of results from the DOM of a search index. """
for container in html.findall(xpath):
if check in container.findtext('.'):
text = container.findtext('.').split(delimiter)
total = int(text[-1].strip()... | python | def search_results_total(html, xpath, check, delimiter):
""" Get the total number of results from the DOM of a search index. """
for container in html.findall(xpath):
if check in container.findtext('.'):
text = container.findtext('.').split(delimiter)
total = int(text[-1].strip()... | [
"def",
"search_results_total",
"(",
"html",
",",
"xpath",
",",
"check",
",",
"delimiter",
")",
":",
"for",
"container",
"in",
"html",
".",
"findall",
"(",
"xpath",
")",
":",
"if",
"check",
"in",
"container",
".",
"findtext",
"(",
"'.'",
")",
":",
"text... | Get the total number of results from the DOM of a search index. | [
"Get",
"the",
"total",
"number",
"of",
"results",
"from",
"the",
"DOM",
"of",
"a",
"search",
"index",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/__init__.py#L33-L39 | train |
alephdata/memorious | memorious/helpers/__init__.py | search_results_last_url | def search_results_last_url(html, xpath, label):
""" Get the URL of the 'last' button in a search results listing. """
for container in html.findall(xpath):
if container.text_content().strip() == label:
return container.find('.//a').get('href') | python | def search_results_last_url(html, xpath, label):
""" Get the URL of the 'last' button in a search results listing. """
for container in html.findall(xpath):
if container.text_content().strip() == label:
return container.find('.//a').get('href') | [
"def",
"search_results_last_url",
"(",
"html",
",",
"xpath",
",",
"label",
")",
":",
"for",
"container",
"in",
"html",
".",
"findall",
"(",
"xpath",
")",
":",
"if",
"container",
".",
"text_content",
"(",
")",
".",
"strip",
"(",
")",
"==",
"label",
":",... | Get the URL of the 'last' button in a search results listing. | [
"Get",
"the",
"URL",
"of",
"the",
"last",
"button",
"in",
"a",
"search",
"results",
"listing",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/helpers/__init__.py#L42-L46 | train |
alephdata/memorious | memorious/model/crawl.py | Crawl.op_count | def op_count(cls, crawler, stage=None):
"""Total operations performed for this crawler"""
if stage:
total_ops = conn.get(make_key(crawler, stage))
else:
total_ops = conn.get(make_key(crawler, "total_ops"))
return unpack_int(total_ops) | python | def op_count(cls, crawler, stage=None):
"""Total operations performed for this crawler"""
if stage:
total_ops = conn.get(make_key(crawler, stage))
else:
total_ops = conn.get(make_key(crawler, "total_ops"))
return unpack_int(total_ops) | [
"def",
"op_count",
"(",
"cls",
",",
"crawler",
",",
"stage",
"=",
"None",
")",
":",
"if",
"stage",
":",
"total_ops",
"=",
"conn",
".",
"get",
"(",
"make_key",
"(",
"crawler",
",",
"stage",
")",
")",
"else",
":",
"total_ops",
"=",
"conn",
".",
"get"... | Total operations performed for this crawler | [
"Total",
"operations",
"performed",
"for",
"this",
"crawler"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/model/crawl.py#L21-L27 | train |
alephdata/memorious | memorious/ui/views.py | index | def index():
"""Generate a list of all crawlers, alphabetically, with op counts."""
crawlers = []
for crawler in manager:
data = Event.get_counts(crawler)
data['last_active'] = crawler.last_run
data['total_ops'] = crawler.op_count
data['running'] = crawler.is_running
... | python | def index():
"""Generate a list of all crawlers, alphabetically, with op counts."""
crawlers = []
for crawler in manager:
data = Event.get_counts(crawler)
data['last_active'] = crawler.last_run
data['total_ops'] = crawler.op_count
data['running'] = crawler.is_running
... | [
"def",
"index",
"(",
")",
":",
"crawlers",
"=",
"[",
"]",
"for",
"crawler",
"in",
"manager",
":",
"data",
"=",
"Event",
".",
"get_counts",
"(",
"crawler",
")",
"data",
"[",
"'last_active'",
"]",
"=",
"crawler",
".",
"last_run",
"data",
"[",
"'total_ops... | Generate a list of all crawlers, alphabetically, with op counts. | [
"Generate",
"a",
"list",
"of",
"all",
"crawlers",
"alphabetically",
"with",
"op",
"counts",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/ui/views.py#L67-L77 | train |
alephdata/memorious | memorious/operations/clean.py | clean_html | def clean_html(context, data):
"""Clean an HTML DOM and store the changed version."""
doc = _get_html_document(context, data)
if doc is None:
context.emit(data=data)
return
remove_paths = context.params.get('remove_paths')
for path in ensure_list(remove_paths):
for el in doc... | python | def clean_html(context, data):
"""Clean an HTML DOM and store the changed version."""
doc = _get_html_document(context, data)
if doc is None:
context.emit(data=data)
return
remove_paths = context.params.get('remove_paths')
for path in ensure_list(remove_paths):
for el in doc... | [
"def",
"clean_html",
"(",
"context",
",",
"data",
")",
":",
"doc",
"=",
"_get_html_document",
"(",
"context",
",",
"data",
")",
"if",
"doc",
"is",
"None",
":",
"context",
".",
"emit",
"(",
"data",
"=",
"data",
")",
"return",
"remove_paths",
"=",
"conte... | Clean an HTML DOM and store the changed version. | [
"Clean",
"an",
"HTML",
"DOM",
"and",
"store",
"the",
"changed",
"version",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/clean.py#L11-L26 | train |
alephdata/memorious | memorious/task_runner.py | TaskRunner.execute | def execute(cls, stage, state, data, next_allowed_exec_time=None):
"""Execute the operation, rate limiting allowing."""
try:
context = Context.from_state(state, stage)
now = datetime.utcnow()
if next_allowed_exec_time and now < next_allowed_exec_time:
... | python | def execute(cls, stage, state, data, next_allowed_exec_time=None):
"""Execute the operation, rate limiting allowing."""
try:
context = Context.from_state(state, stage)
now = datetime.utcnow()
if next_allowed_exec_time and now < next_allowed_exec_time:
... | [
"def",
"execute",
"(",
"cls",
",",
"stage",
",",
"state",
",",
"data",
",",
"next_allowed_exec_time",
"=",
"None",
")",
":",
"try",
":",
"context",
"=",
"Context",
".",
"from_state",
"(",
"state",
",",
"stage",
")",
"now",
"=",
"datetime",
".",
"utcnow... | Execute the operation, rate limiting allowing. | [
"Execute",
"the",
"operation",
"rate",
"limiting",
"allowing",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/task_runner.py#L19-L49 | train |
alephdata/memorious | memorious/operations/db.py | _recursive_upsert | def _recursive_upsert(context, params, data):
"""Insert or update nested dicts recursively into db tables"""
children = params.get("children", {})
nested_calls = []
for child_params in children:
key = child_params.get("key")
child_data_list = ensure_list(data.pop(key))
if isinsta... | python | def _recursive_upsert(context, params, data):
"""Insert or update nested dicts recursively into db tables"""
children = params.get("children", {})
nested_calls = []
for child_params in children:
key = child_params.get("key")
child_data_list = ensure_list(data.pop(key))
if isinsta... | [
"def",
"_recursive_upsert",
"(",
"context",
",",
"params",
",",
"data",
")",
":",
"children",
"=",
"params",
".",
"get",
"(",
"\"children\"",
",",
"{",
"}",
")",
"nested_calls",
"=",
"[",
"]",
"for",
"child_params",
"in",
"children",
":",
"key",
"=",
"... | Insert or update nested dicts recursively into db tables | [
"Insert",
"or",
"update",
"nested",
"dicts",
"recursively",
"into",
"db",
"tables"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/db.py#L21-L48 | train |
alephdata/memorious | memorious/operations/db.py | db | def db(context, data):
"""Insert or update `data` as a row into specified db table"""
table = context.params.get("table", context.crawler.name)
params = context.params
params["table"] = table
_recursive_upsert(context, params, data) | python | def db(context, data):
"""Insert or update `data` as a row into specified db table"""
table = context.params.get("table", context.crawler.name)
params = context.params
params["table"] = table
_recursive_upsert(context, params, data) | [
"def",
"db",
"(",
"context",
",",
"data",
")",
":",
"table",
"=",
"context",
".",
"params",
".",
"get",
"(",
"\"table\"",
",",
"context",
".",
"crawler",
".",
"name",
")",
"params",
"=",
"context",
".",
"params",
"params",
"[",
"\"table\"",
"]",
"=",... | Insert or update `data` as a row into specified db table | [
"Insert",
"or",
"update",
"data",
"as",
"a",
"row",
"into",
"specified",
"db",
"table"
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/db.py#L51-L56 | train |
alephdata/memorious | memorious/cli.py | cli | def cli(debug, cache, incremental):
"""Crawler framework for documents and structured scrapers."""
settings.HTTP_CACHE = cache
settings.INCREMENTAL = incremental
settings.DEBUG = debug
if settings.DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=log... | python | def cli(debug, cache, incremental):
"""Crawler framework for documents and structured scrapers."""
settings.HTTP_CACHE = cache
settings.INCREMENTAL = incremental
settings.DEBUG = debug
if settings.DEBUG:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=log... | [
"def",
"cli",
"(",
"debug",
",",
"cache",
",",
"incremental",
")",
":",
"settings",
".",
"HTTP_CACHE",
"=",
"cache",
"settings",
".",
"INCREMENTAL",
"=",
"incremental",
"settings",
".",
"DEBUG",
"=",
"debug",
"if",
"settings",
".",
"DEBUG",
":",
"logging",... | Crawler framework for documents and structured scrapers. | [
"Crawler",
"framework",
"for",
"documents",
"and",
"structured",
"scrapers",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/cli.py#L21-L30 | train |
alephdata/memorious | memorious/cli.py | run | def run(crawler):
"""Run a specified crawler."""
crawler = get_crawler(crawler)
crawler.run()
if is_sync_mode():
TaskRunner.run_sync() | python | def run(crawler):
"""Run a specified crawler."""
crawler = get_crawler(crawler)
crawler.run()
if is_sync_mode():
TaskRunner.run_sync() | [
"def",
"run",
"(",
"crawler",
")",
":",
"crawler",
"=",
"get_crawler",
"(",
"crawler",
")",
"crawler",
".",
"run",
"(",
")",
"if",
"is_sync_mode",
"(",
")",
":",
"TaskRunner",
".",
"run_sync",
"(",
")"
] | Run a specified crawler. | [
"Run",
"a",
"specified",
"crawler",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/cli.py#L43-L48 | train |
alephdata/memorious | memorious/cli.py | index | def index():
"""List the available crawlers."""
crawler_list = []
for crawler in manager:
is_due = 'yes' if crawler.check_due() else 'no'
if crawler.disabled:
is_due = 'off'
crawler_list.append([crawler.name,
crawler.description,
... | python | def index():
"""List the available crawlers."""
crawler_list = []
for crawler in manager:
is_due = 'yes' if crawler.check_due() else 'no'
if crawler.disabled:
is_due = 'off'
crawler_list.append([crawler.name,
crawler.description,
... | [
"def",
"index",
"(",
")",
":",
"crawler_list",
"=",
"[",
"]",
"for",
"crawler",
"in",
"manager",
":",
"is_due",
"=",
"'yes'",
"if",
"crawler",
".",
"check_due",
"(",
")",
"else",
"'no'",
"if",
"crawler",
".",
"disabled",
":",
"is_due",
"=",
"'off'",
... | List the available crawlers. | [
"List",
"the",
"available",
"crawlers",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/cli.py#L74-L87 | train |
alephdata/memorious | memorious/cli.py | scheduled | def scheduled(wait=False):
"""Run crawlers that are due."""
manager.run_scheduled()
while wait:
# Loop and try to run scheduled crawlers at short intervals
manager.run_scheduled()
time.sleep(settings.SCHEDULER_INTERVAL) | python | def scheduled(wait=False):
"""Run crawlers that are due."""
manager.run_scheduled()
while wait:
# Loop and try to run scheduled crawlers at short intervals
manager.run_scheduled()
time.sleep(settings.SCHEDULER_INTERVAL) | [
"def",
"scheduled",
"(",
"wait",
"=",
"False",
")",
":",
"manager",
".",
"run_scheduled",
"(",
")",
"while",
"wait",
":",
"manager",
".",
"run_scheduled",
"(",
")",
"time",
".",
"sleep",
"(",
"settings",
".",
"SCHEDULER_INTERVAL",
")"
] | Run crawlers that are due. | [
"Run",
"crawlers",
"that",
"are",
"due",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/cli.py#L92-L98 | train |
alephdata/memorious | memorious/operations/store.py | _get_directory_path | def _get_directory_path(context):
"""Get the storage path fro the output."""
path = os.path.join(settings.BASE_PATH, 'store')
path = context.params.get('path', path)
path = os.path.join(path, context.crawler.name)
path = os.path.abspath(os.path.expandvars(path))
try:
os.makedirs(path)
... | python | def _get_directory_path(context):
"""Get the storage path fro the output."""
path = os.path.join(settings.BASE_PATH, 'store')
path = context.params.get('path', path)
path = os.path.join(path, context.crawler.name)
path = os.path.abspath(os.path.expandvars(path))
try:
os.makedirs(path)
... | [
"def",
"_get_directory_path",
"(",
"context",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"settings",
".",
"BASE_PATH",
",",
"'store'",
")",
"path",
"=",
"context",
".",
"params",
".",
"get",
"(",
"'path'",
",",
"path",
")",
"path",
"... | Get the storage path fro the output. | [
"Get",
"the",
"storage",
"path",
"fro",
"the",
"output",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/store.py#L9-L19 | train |
alephdata/memorious | memorious/operations/store.py | directory | def directory(context, data):
"""Store the collected files to a given directory."""
with context.http.rehash(data) as result:
if not result.ok:
return
content_hash = data.get('content_hash')
if content_hash is None:
context.emit_warning("No content hash in data."... | python | def directory(context, data):
"""Store the collected files to a given directory."""
with context.http.rehash(data) as result:
if not result.ok:
return
content_hash = data.get('content_hash')
if content_hash is None:
context.emit_warning("No content hash in data."... | [
"def",
"directory",
"(",
"context",
",",
"data",
")",
":",
"with",
"context",
".",
"http",
".",
"rehash",
"(",
"data",
")",
"as",
"result",
":",
"if",
"not",
"result",
".",
"ok",
":",
"return",
"content_hash",
"=",
"data",
".",
"get",
"(",
"'content_... | Store the collected files to a given directory. | [
"Store",
"the",
"collected",
"files",
"to",
"a",
"given",
"directory",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/store.py#L22-L46 | train |
alephdata/memorious | memorious/operations/initializers.py | seed | def seed(context, data):
"""Initialize a crawler with a set of seed URLs.
The URLs are given as a list or single value to the ``urls`` parameter.
If this is called as a second stage in a crawler, the URL will be formatted
against the supplied ``data`` values, e.g.:
https://crawl.site/entries/... | python | def seed(context, data):
"""Initialize a crawler with a set of seed URLs.
The URLs are given as a list or single value to the ``urls`` parameter.
If this is called as a second stage in a crawler, the URL will be formatted
against the supplied ``data`` values, e.g.:
https://crawl.site/entries/... | [
"def",
"seed",
"(",
"context",
",",
"data",
")",
":",
"for",
"key",
"in",
"(",
"'url'",
",",
"'urls'",
")",
":",
"for",
"url",
"in",
"ensure_list",
"(",
"context",
".",
"params",
".",
"get",
"(",
"key",
")",
")",
":",
"url",
"=",
"url",
"%",
"d... | Initialize a crawler with a set of seed URLs.
The URLs are given as a list or single value to the ``urls`` parameter.
If this is called as a second stage in a crawler, the URL will be formatted
against the supplied ``data`` values, e.g.:
https://crawl.site/entries/%(number)s.html | [
"Initialize",
"a",
"crawler",
"with",
"a",
"set",
"of",
"seed",
"URLs",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/initializers.py#L5-L18 | train |
alephdata/memorious | memorious/operations/initializers.py | enumerate | def enumerate(context, data):
"""Iterate through a set of items and emit each one of them."""
items = ensure_list(context.params.get('items'))
for item in items:
data['item'] = item
context.emit(data=data) | python | def enumerate(context, data):
"""Iterate through a set of items and emit each one of them."""
items = ensure_list(context.params.get('items'))
for item in items:
data['item'] = item
context.emit(data=data) | [
"def",
"enumerate",
"(",
"context",
",",
"data",
")",
":",
"items",
"=",
"ensure_list",
"(",
"context",
".",
"params",
".",
"get",
"(",
"'items'",
")",
")",
"for",
"item",
"in",
"items",
":",
"data",
"[",
"'item'",
"]",
"=",
"item",
"context",
".",
... | Iterate through a set of items and emit each one of them. | [
"Iterate",
"through",
"a",
"set",
"of",
"items",
"and",
"emit",
"each",
"one",
"of",
"them",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/initializers.py#L21-L26 | train |
alephdata/memorious | memorious/operations/initializers.py | sequence | def sequence(context, data):
"""Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given range.
* Recursively, generatin... | python | def sequence(context, data):
"""Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given range.
* Recursively, generatin... | [
"def",
"sequence",
"(",
"context",
",",
"data",
")",
":",
"number",
"=",
"data",
".",
"get",
"(",
"'number'",
",",
"context",
".",
"params",
".",
"get",
"(",
"'start'",
",",
"1",
")",
")",
"stop",
"=",
"context",
".",
"params",
".",
"get",
"(",
"... | Generate a sequence of numbers.
It is the memorious equivalent of the xrange function, accepting the
``start``, ``stop`` and ``step`` parameters.
This can run in two ways:
* As a single function generating all numbers in the given range.
* Recursively, generating numbers one by one with an optiona... | [
"Generate",
"a",
"sequence",
"of",
"numbers",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/operations/initializers.py#L29-L67 | train |
alephdata/memorious | memorious/logic/http.py | ContextHttpResponse.fetch | def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
... | python | def fetch(self):
"""Lazily trigger download of the data when requested."""
if self._file_path is not None:
return self._file_path
temp_path = self.context.work_path
if self._content_hash is not None:
self._file_path = storage.load_file(self._content_hash,
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"if",
"self",
".",
"_file_path",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_file_path",
"temp_path",
"=",
"self",
".",
"context",
".",
"work_path",
"if",
"self",
".",
"_content_hash",
"is",
"not",
"None",
... | Lazily trigger download of the data when requested. | [
"Lazily",
"trigger",
"download",
"of",
"the",
"data",
"when",
"requested",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/logic/http.py#L162-L185 | train |
alephdata/memorious | memorious/util.py | make_key | def make_key(*criteria):
"""Make a string key out of many criteria."""
criteria = [stringify(c) for c in criteria]
criteria = [c for c in criteria if c is not None]
if len(criteria):
return ':'.join(criteria) | python | def make_key(*criteria):
"""Make a string key out of many criteria."""
criteria = [stringify(c) for c in criteria]
criteria = [c for c in criteria if c is not None]
if len(criteria):
return ':'.join(criteria) | [
"def",
"make_key",
"(",
"*",
"criteria",
")",
":",
"criteria",
"=",
"[",
"stringify",
"(",
"c",
")",
"for",
"c",
"in",
"criteria",
"]",
"criteria",
"=",
"[",
"c",
"for",
"c",
"in",
"criteria",
"if",
"c",
"is",
"not",
"None",
"]",
"if",
"len",
"("... | Make a string key out of many criteria. | [
"Make",
"a",
"string",
"key",
"out",
"of",
"many",
"criteria",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/util.py#L6-L11 | train |
alephdata/memorious | memorious/util.py | random_filename | def random_filename(path=None):
"""Make a UUID-based file name which is extremely unlikely
to exist already."""
filename = uuid4().hex
if path is not None:
filename = os.path.join(path, filename)
return filename | python | def random_filename(path=None):
"""Make a UUID-based file name which is extremely unlikely
to exist already."""
filename = uuid4().hex
if path is not None:
filename = os.path.join(path, filename)
return filename | [
"def",
"random_filename",
"(",
"path",
"=",
"None",
")",
":",
"filename",
"=",
"uuid4",
"(",
")",
".",
"hex",
"if",
"path",
"is",
"not",
"None",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
"return",
"fil... | Make a UUID-based file name which is extremely unlikely
to exist already. | [
"Make",
"a",
"UUID",
"-",
"based",
"file",
"name",
"which",
"is",
"extremely",
"unlikely",
"to",
"exist",
"already",
"."
] | b4033c5064447ed5f696f9c2bbbc6c12062d2fa4 | https://github.com/alephdata/memorious/blob/b4033c5064447ed5f696f9c2bbbc6c12062d2fa4/memorious/util.py#L14-L20 | train |
jasonlaska/spherecluster | spherecluster/util.py | sample_vMF | def sample_vMF(mu, kappa, num_samples):
"""Generate num_samples N-dimensional samples from von Mises Fisher
distribution around center mu \in R^N with concentration kappa.
"""
dim = len(mu)
result = np.zeros((num_samples, dim))
for nn in range(num_samples):
# sample offset from center (o... | python | def sample_vMF(mu, kappa, num_samples):
"""Generate num_samples N-dimensional samples from von Mises Fisher
distribution around center mu \in R^N with concentration kappa.
"""
dim = len(mu)
result = np.zeros((num_samples, dim))
for nn in range(num_samples):
# sample offset from center (o... | [
"def",
"sample_vMF",
"(",
"mu",
",",
"kappa",
",",
"num_samples",
")",
":",
"dim",
"=",
"len",
"(",
"mu",
")",
"result",
"=",
"np",
".",
"zeros",
"(",
"(",
"num_samples",
",",
"dim",
")",
")",
"for",
"nn",
"in",
"range",
"(",
"num_samples",
")",
... | Generate num_samples N-dimensional samples from von Mises Fisher
distribution around center mu \in R^N with concentration kappa. | [
"Generate",
"num_samples",
"N",
"-",
"dimensional",
"samples",
"from",
"von",
"Mises",
"Fisher",
"distribution",
"around",
"center",
"mu",
"\\",
"in",
"R^N",
"with",
"concentration",
"kappa",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/util.py#L16-L32 | train |
jasonlaska/spherecluster | spherecluster/util.py | _sample_weight | def _sample_weight(kappa, dim):
"""Rejection sampling scheme for sampling distance from center on
surface of the sphere.
"""
dim = dim - 1 # since S^{n-1}
b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1. - b) / (1. + b)
c = kappa * x + dim * np.log(1 - x ** 2)
while ... | python | def _sample_weight(kappa, dim):
"""Rejection sampling scheme for sampling distance from center on
surface of the sphere.
"""
dim = dim - 1 # since S^{n-1}
b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1. - b) / (1. + b)
c = kappa * x + dim * np.log(1 - x ** 2)
while ... | [
"def",
"_sample_weight",
"(",
"kappa",
",",
"dim",
")",
":",
"dim",
"=",
"dim",
"-",
"1",
"b",
"=",
"dim",
"/",
"(",
"np",
".",
"sqrt",
"(",
"4.",
"*",
"kappa",
"**",
"2",
"+",
"dim",
"**",
"2",
")",
"+",
"2",
"*",
"kappa",
")",
"x",
"=",
... | Rejection sampling scheme for sampling distance from center on
surface of the sphere. | [
"Rejection",
"sampling",
"scheme",
"for",
"sampling",
"distance",
"from",
"center",
"on",
"surface",
"of",
"the",
"sphere",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/util.py#L35-L49 | train |
jasonlaska/spherecluster | spherecluster/util.py | _sample_orthonormal_to | def _sample_orthonormal_to(mu):
"""Sample point on sphere orthogonal to mu."""
v = np.random.randn(mu.shape[0])
proj_mu_v = mu * np.dot(mu, v) / np.linalg.norm(mu)
orthto = v - proj_mu_v
return orthto / np.linalg.norm(orthto) | python | def _sample_orthonormal_to(mu):
"""Sample point on sphere orthogonal to mu."""
v = np.random.randn(mu.shape[0])
proj_mu_v = mu * np.dot(mu, v) / np.linalg.norm(mu)
orthto = v - proj_mu_v
return orthto / np.linalg.norm(orthto) | [
"def",
"_sample_orthonormal_to",
"(",
"mu",
")",
":",
"v",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"mu",
".",
"shape",
"[",
"0",
"]",
")",
"proj_mu_v",
"=",
"mu",
"*",
"np",
".",
"dot",
"(",
"mu",
",",
"v",
")",
"/",
"np",
".",
"linalg",
... | Sample point on sphere orthogonal to mu. | [
"Sample",
"point",
"on",
"sphere",
"orthogonal",
"to",
"mu",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/util.py#L52-L57 | train |
jasonlaska/spherecluster | spherecluster/spherical_kmeans.py | _spherical_kmeans_single_lloyd | def _spherical_kmeans_single_lloyd(
X,
n_clusters,
sample_weight=None,
max_iter=300,
init="k-means++",
verbose=False,
x_squared_norms=None,
random_state=None,
tol=1e-4,
precompute_distances=True,
):
"""
Modified from sklearn.cluster.k_means_.k_means_single_lloyd.
"""
... | python | def _spherical_kmeans_single_lloyd(
X,
n_clusters,
sample_weight=None,
max_iter=300,
init="k-means++",
verbose=False,
x_squared_norms=None,
random_state=None,
tol=1e-4,
precompute_distances=True,
):
"""
Modified from sklearn.cluster.k_means_.k_means_single_lloyd.
"""
... | [
"def",
"_spherical_kmeans_single_lloyd",
"(",
"X",
",",
"n_clusters",
",",
"sample_weight",
"=",
"None",
",",
"max_iter",
"=",
"300",
",",
"init",
"=",
"\"k-means++\"",
",",
"verbose",
"=",
"False",
",",
"x_squared_norms",
"=",
"None",
",",
"random_state",
"="... | Modified from sklearn.cluster.k_means_.k_means_single_lloyd. | [
"Modified",
"from",
"sklearn",
".",
"cluster",
".",
"k_means_",
".",
"k_means_single_lloyd",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/spherical_kmeans.py#L22-L113 | train |
jasonlaska/spherecluster | spherecluster/spherical_kmeans.py | spherical_k_means | def spherical_k_means(
X,
n_clusters,
sample_weight=None,
init="k-means++",
n_init=10,
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
n_jobs=1,
algorithm="auto",
return_n_iter=False,
):
"""Modified from sklearn.cluster.k_means_.k_means.
... | python | def spherical_k_means(
X,
n_clusters,
sample_weight=None,
init="k-means++",
n_init=10,
max_iter=300,
verbose=False,
tol=1e-4,
random_state=None,
copy_x=True,
n_jobs=1,
algorithm="auto",
return_n_iter=False,
):
"""Modified from sklearn.cluster.k_means_.k_means.
... | [
"def",
"spherical_k_means",
"(",
"X",
",",
"n_clusters",
",",
"sample_weight",
"=",
"None",
",",
"init",
"=",
"\"k-means++\"",
",",
"n_init",
"=",
"10",
",",
"max_iter",
"=",
"300",
",",
"verbose",
"=",
"False",
",",
"tol",
"=",
"1e-4",
",",
"random_stat... | Modified from sklearn.cluster.k_means_.k_means. | [
"Modified",
"from",
"sklearn",
".",
"cluster",
".",
"k_means_",
".",
"k_means",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/spherical_kmeans.py#L116-L228 | train |
jasonlaska/spherecluster | spherecluster/spherical_kmeans.py | SphericalKMeans.fit | def fit(self, X, y=None, sample_weight=None):
"""Compute k-means clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
y : Ignored
not used, present here for API consistency by convention.
sample_weight : array-li... | python | def fit(self, X, y=None, sample_weight=None):
"""Compute k-means clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
y : Ignored
not used, present here for API consistency by convention.
sample_weight : array-li... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
",",
"sample_weight",
"=",
"None",
")",
":",
"if",
"self",
".",
"normalize",
":",
"X",
"=",
"normalize",
"(",
"X",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".",
"random_s... | Compute k-means clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
y : Ignored
not used, present here for API consistency by convention.
sample_weight : array-like, shape (n_samples,), optional
The weights ... | [
"Compute",
"k",
"-",
"means",
"clustering",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/spherical_kmeans.py#L329-L366 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _inertia_from_labels | def _inertia_from_labels(X, centers, labels):
"""Compute inertia with cosine distance using known labels.
"""
n_examples, n_features = X.shape
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
inertia[ee] = 1 - X[ee, :].dot(centers[int(labels[ee]), :].T)
return np.sum(inert... | python | def _inertia_from_labels(X, centers, labels):
"""Compute inertia with cosine distance using known labels.
"""
n_examples, n_features = X.shape
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
inertia[ee] = 1 - X[ee, :].dot(centers[int(labels[ee]), :].T)
return np.sum(inert... | [
"def",
"_inertia_from_labels",
"(",
"X",
",",
"centers",
",",
"labels",
")",
":",
"n_examples",
",",
"n_features",
"=",
"X",
".",
"shape",
"inertia",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_examples",
",",
")",
")",
"for",
"ee",
"in",
"range",
"(",
"n_... | Compute inertia with cosine distance using known labels. | [
"Compute",
"inertia",
"with",
"cosine",
"distance",
"using",
"known",
"labels",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L25-L33 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _labels_inertia | def _labels_inertia(X, centers):
"""Compute labels and inertia with cosine distance.
"""
n_examples, n_features = X.shape
n_clusters, n_features = centers.shape
labels = np.zeros((n_examples,))
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
dists = np.zeros((n_clust... | python | def _labels_inertia(X, centers):
"""Compute labels and inertia with cosine distance.
"""
n_examples, n_features = X.shape
n_clusters, n_features = centers.shape
labels = np.zeros((n_examples,))
inertia = np.zeros((n_examples,))
for ee in range(n_examples):
dists = np.zeros((n_clust... | [
"def",
"_labels_inertia",
"(",
"X",
",",
"centers",
")",
":",
"n_examples",
",",
"n_features",
"=",
"X",
".",
"shape",
"n_clusters",
",",
"n_features",
"=",
"centers",
".",
"shape",
"labels",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_examples",
",",
")",
"... | Compute labels and inertia with cosine distance. | [
"Compute",
"labels",
"and",
"inertia",
"with",
"cosine",
"distance",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L36-L53 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _S | def _S(kappa, alpha, beta):
"""Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
Note: Handles scalar kappa, alpha, and beta only.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html... | python | def _S(kappa, alpha, beta):
"""Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
Note: Handles scalar kappa, alpha, and beta only.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html... | [
"def",
"_S",
"(",
"kappa",
",",
"alpha",
",",
"beta",
")",
":",
"kappa",
"=",
"1.",
"*",
"np",
".",
"abs",
"(",
"kappa",
")",
"alpha",
"=",
"1.",
"*",
"alpha",
"beta",
"=",
"1.",
"*",
"np",
".",
"abs",
"(",
"beta",
")",
"a_plus_b",
"=",
"alph... | Compute the antiderivative of the Amos-type bound G on the modified
Bessel function ratio.
Note: Handles scalar kappa, alpha, and beta only.
See "S <-" in movMF.R and utility function implementation notes from
https://cran.r-project.org/web/packages/movMF/index.html | [
"Compute",
"the",
"antiderivative",
"of",
"the",
"Amos",
"-",
"type",
"bound",
"G",
"on",
"the",
"modified",
"Bessel",
"function",
"ratio",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L105-L124 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _init_unit_centers | def _init_unit_centers(X, n_clusters, random_state, init):
"""Initializes unit norm centers.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids... | python | def _init_unit_centers(X, n_clusters, random_state, init):
"""Initializes unit norm centers.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids... | [
"def",
"_init_unit_centers",
"(",
"X",
",",
"n_clusters",
",",
"random_state",
",",
"init",
")",
":",
"n_examples",
",",
"n_features",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"if",
"isinstance",
"(",
"init",
",",
"np",
".",
"ndarray",
")",
":",
"n_init... | Initializes unit norm centers.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
n_clusters : int, optional, default: 8
The number of clusters to form as well as the number of
centroids to generate.
random_state : integer or numpy.RandomState, op... | [
"Initializes",
"unit",
"norm",
"centers",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L171-L252 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _expectation | def _expectation(X, centers, weights, concentrations, posterior_type="soft"):
"""Compute the log-likelihood of each datapoint being in each cluster.
Parameters
----------
centers (mu) : array, [n_centers x n_features]
weights (alpha) : array, [n_centers, ] (alpha)
concentrations (kappa) : array... | python | def _expectation(X, centers, weights, concentrations, posterior_type="soft"):
"""Compute the log-likelihood of each datapoint being in each cluster.
Parameters
----------
centers (mu) : array, [n_centers x n_features]
weights (alpha) : array, [n_centers, ] (alpha)
concentrations (kappa) : array... | [
"def",
"_expectation",
"(",
"X",
",",
"centers",
",",
"weights",
",",
"concentrations",
",",
"posterior_type",
"=",
"\"soft\"",
")",
":",
"n_examples",
",",
"n_features",
"=",
"np",
".",
"shape",
"(",
"X",
")",
"n_clusters",
",",
"_",
"=",
"centers",
"."... | Compute the log-likelihood of each datapoint being in each cluster.
Parameters
----------
centers (mu) : array, [n_centers x n_features]
weights (alpha) : array, [n_centers, ] (alpha)
concentrations (kappa) : array, [n_centers, ]
Returns
----------
posterior : array, [n_centers, n_exam... | [
"Compute",
"the",
"log",
"-",
"likelihood",
"of",
"each",
"datapoint",
"being",
"in",
"each",
"cluster",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L255-L293 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _maximization | def _maximization(X, posterior, force_weights=None):
"""Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is pa... | python | def _maximization(X, posterior, force_weights=None):
"""Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is pa... | [
"def",
"_maximization",
"(",
"X",
",",
"posterior",
",",
"force_weights",
"=",
"None",
")",
":",
"n_examples",
",",
"n_features",
"=",
"X",
".",
"shape",
"n_clusters",
",",
"n_examples",
"=",
"posterior",
".",
"shape",
"concentrations",
"=",
"np",
".",
"ze... | Estimate new centers, weights, and concentrations from
Parameters
----------
posterior : array, [n_centers, n_examples]
The posterior matrix from the expectation step.
force_weights : None or array, [n_centers, ]
If None is passed, will estimate weights.
If an array is passed, ... | [
"Estimate",
"new",
"centers",
"weights",
"and",
"concentrations",
"from"
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L296-L354 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | _movMF | def _movMF(
X,
n_clusters,
posterior_type="soft",
force_weights=None,
max_iter=300,
verbose=False,
init="random-class",
random_state=None,
tol=1e-6,
):
"""Mixture of von Mises Fisher clustering.
Implements the algorithms (i) and (ii) from
"Clustering on the Unit Hyper... | python | def _movMF(
X,
n_clusters,
posterior_type="soft",
force_weights=None,
max_iter=300,
verbose=False,
init="random-class",
random_state=None,
tol=1e-6,
):
"""Mixture of von Mises Fisher clustering.
Implements the algorithms (i) and (ii) from
"Clustering on the Unit Hyper... | [
"def",
"_movMF",
"(",
"X",
",",
"n_clusters",
",",
"posterior_type",
"=",
"\"soft\"",
",",
"force_weights",
"=",
"None",
",",
"max_iter",
"=",
"300",
",",
"verbose",
"=",
"False",
",",
"init",
"=",
"\"random-class\"",
",",
"random_state",
"=",
"None",
",",... | Mixture of von Mises Fisher clustering.
Implements the algorithms (i) and (ii) from
"Clustering on the Unit Hypersphere using von Mises-Fisher Distributions"
by Banerjee, Dhillon, Ghosh, and Sra.
TODO: Currently only supports Banerjee et al 2005 approximation of kappa,
however, there ar... | [
"Mixture",
"of",
"von",
"Mises",
"Fisher",
"clustering",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L357-L497 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | movMF | def movMF(
X,
n_clusters,
posterior_type="soft",
force_weights=None,
n_init=10,
n_jobs=1,
max_iter=300,
verbose=False,
init="random-class",
random_state=None,
tol=1e-6,
copy_x=True,
):
"""Wrapper for parallelization of _movMF and running n_init times.
"""
if n... | python | def movMF(
X,
n_clusters,
posterior_type="soft",
force_weights=None,
n_init=10,
n_jobs=1,
max_iter=300,
verbose=False,
init="random-class",
random_state=None,
tol=1e-6,
copy_x=True,
):
"""Wrapper for parallelization of _movMF and running n_init times.
"""
if n... | [
"def",
"movMF",
"(",
"X",
",",
"n_clusters",
",",
"posterior_type",
"=",
"\"soft\"",
",",
"force_weights",
"=",
"None",
",",
"n_init",
"=",
"10",
",",
"n_jobs",
"=",
"1",
",",
"max_iter",
"=",
"300",
",",
"verbose",
"=",
"False",
",",
"init",
"=",
"\... | Wrapper for parallelization of _movMF and running n_init times. | [
"Wrapper",
"for",
"parallelization",
"of",
"_movMF",
"and",
"running",
"n_init",
"times",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L500-L614 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | VonMisesFisherMixture._check_fit_data | def _check_fit_data(self, X):
"""Verify that the number of samples given is larger than k"""
X = check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32])
n_samples, n_features = X.shape
if X.shape[0] < self.n_clusters:
raise ValueError(
"n_samples=%... | python | def _check_fit_data(self, X):
"""Verify that the number of samples given is larger than k"""
X = check_array(X, accept_sparse="csr", dtype=[np.float64, np.float32])
n_samples, n_features = X.shape
if X.shape[0] < self.n_clusters:
raise ValueError(
"n_samples=%... | [
"def",
"_check_fit_data",
"(",
"self",
",",
"X",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
",",
"accept_sparse",
"=",
"\"csr\"",
",",
"dtype",
"=",
"[",
"np",
".",
"float64",
",",
"np",
".",
"float32",
"]",
")",
"n_samples",
",",
"n_features",
"="... | Verify that the number of samples given is larger than k | [
"Verify",
"that",
"the",
"number",
"of",
"samples",
"given",
"is",
"larger",
"than",
"k"
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L772-L791 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | VonMisesFisherMixture.fit | def fit(self, X, y=None):
"""Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
"""
if self.normalize:
X = normalize(X)
self._check_force_weights()
random_state... | python | def fit(self, X, y=None):
"""Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
"""
if self.normalize:
X = normalize(X)
self._check_force_weights()
random_state... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"normalize",
":",
"X",
"=",
"normalize",
"(",
"X",
")",
"self",
".",
"_check_force_weights",
"(",
")",
"random_state",
"=",
"check_random_state",
"(",
"self",
".... | Compute mixture of von Mises Fisher clustering.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features) | [
"Compute",
"mixture",
"of",
"von",
"Mises",
"Fisher",
"clustering",
"."
] | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L814-L850 | train |
jasonlaska/spherecluster | spherecluster/von_mises_fisher_mixture.py | VonMisesFisherMixture.transform | def transform(self, X, y=None):
"""Transform X to a cluster-distance space.
In the new space, each dimension is the cosine distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
----------
... | python | def transform(self, X, y=None):
"""Transform X to a cluster-distance space.
In the new space, each dimension is the cosine distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
----------
... | [
"def",
"transform",
"(",
"self",
",",
"X",
",",
"y",
"=",
"None",
")",
":",
"if",
"self",
".",
"normalize",
":",
"X",
"=",
"normalize",
"(",
"X",
")",
"check_is_fitted",
"(",
"self",
",",
"\"cluster_centers_\"",
")",
"X",
"=",
"self",
".",
"_check_te... | Transform X to a cluster-distance space.
In the new space, each dimension is the cosine distance to the cluster
centers. Note that even if X is sparse, the array returned by
`transform` will typically be dense.
Parameters
----------
X : {array-like, sparse matrix}, shap... | [
"Transform",
"X",
"to",
"a",
"cluster",
"-",
"distance",
"space",
".",
"In",
"the",
"new",
"space",
"each",
"dimension",
"is",
"the",
"cosine",
"distance",
"to",
"the",
"cluster",
"centers",
".",
"Note",
"that",
"even",
"if",
"X",
"is",
"sparse",
"the",
... | 701b0b1909088a56e353b363b2672580d4fe9d93 | https://github.com/jasonlaska/spherecluster/blob/701b0b1909088a56e353b363b2672580d4fe9d93/spherecluster/von_mises_fisher_mixture.py#L869-L890 | train |
skggm/skggm | inverse_covariance/metrics.py | log_likelihood | def log_likelihood(covariance, precision):
"""Computes the log-likelihood between the covariance and precision
estimate.
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
Maximum Likelihood Estimator of covariance
precision : 2D ndarray (n_features, n_features)
... | python | def log_likelihood(covariance, precision):
"""Computes the log-likelihood between the covariance and precision
estimate.
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
Maximum Likelihood Estimator of covariance
precision : 2D ndarray (n_features, n_features)
... | [
"def",
"log_likelihood",
"(",
"covariance",
",",
"precision",
")",
":",
"assert",
"covariance",
".",
"shape",
"==",
"precision",
".",
"shape",
"dim",
",",
"_",
"=",
"precision",
".",
"shape",
"log_likelihood_",
"=",
"(",
"-",
"np",
".",
"sum",
"(",
"cova... | Computes the log-likelihood between the covariance and precision
estimate.
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
Maximum Likelihood Estimator of covariance
precision : 2D ndarray (n_features, n_features)
The precision matrix of the covariance model ... | [
"Computes",
"the",
"log",
"-",
"likelihood",
"between",
"the",
"covariance",
"and",
"precision",
"estimate",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/metrics.py#L6-L30 | train |
skggm/skggm | inverse_covariance/metrics.py | kl_loss | def kl_loss(covariance, precision):
"""Computes the KL divergence between precision estimate and
reference covariance.
The loss is computed as:
Trace(Theta_1 * Sigma_0) - log(Theta_0 * Sigma_1) - dim(Sigma)
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
... | python | def kl_loss(covariance, precision):
"""Computes the KL divergence between precision estimate and
reference covariance.
The loss is computed as:
Trace(Theta_1 * Sigma_0) - log(Theta_0 * Sigma_1) - dim(Sigma)
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
... | [
"def",
"kl_loss",
"(",
"covariance",
",",
"precision",
")",
":",
"assert",
"covariance",
".",
"shape",
"==",
"precision",
".",
"shape",
"dim",
",",
"_",
"=",
"precision",
".",
"shape",
"logdet_p_dot_c",
"=",
"fast_logdet",
"(",
"np",
".",
"dot",
"(",
"pr... | Computes the KL divergence between precision estimate and
reference covariance.
The loss is computed as:
Trace(Theta_1 * Sigma_0) - log(Theta_0 * Sigma_1) - dim(Sigma)
Parameters
----------
covariance : 2D ndarray (n_features, n_features)
Maximum Likelihood Estimator of covariance... | [
"Computes",
"the",
"KL",
"divergence",
"between",
"precision",
"estimate",
"and",
"reference",
"covariance",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/metrics.py#L33-L56 | train |
skggm/skggm | inverse_covariance/metrics.py | ebic | def ebic(covariance, precision, n_samples, n_features, gamma=0):
"""
Extended Bayesian Information Criteria for model selection.
When using path mode, use this as an alternative to cross-validation for
finding lambda.
See:
"Extended Bayesian Information Criteria for Gaussian Graphical Mode... | python | def ebic(covariance, precision, n_samples, n_features, gamma=0):
"""
Extended Bayesian Information Criteria for model selection.
When using path mode, use this as an alternative to cross-validation for
finding lambda.
See:
"Extended Bayesian Information Criteria for Gaussian Graphical Mode... | [
"def",
"ebic",
"(",
"covariance",
",",
"precision",
",",
"n_samples",
",",
"n_features",
",",
"gamma",
"=",
"0",
")",
":",
"l_theta",
"=",
"-",
"np",
".",
"sum",
"(",
"covariance",
"*",
"precision",
")",
"+",
"fast_logdet",
"(",
"precision",
")",
"l_th... | Extended Bayesian Information Criteria for model selection.
When using path mode, use this as an alternative to cross-validation for
finding lambda.
See:
"Extended Bayesian Information Criteria for Gaussian Graphical Models"
R. Foygel and M. Drton, NIPS 2010
Parameters
----------
... | [
"Extended",
"Bayesian",
"Information",
"Criteria",
"for",
"model",
"selection",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/metrics.py#L79-L130 | train |
skggm/skggm | inverse_covariance/profiling/graphs.py | lattice | def lattice(prng, n_features, alpha, random_sign=False, low=0.3, high=0.7):
"""Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the para... | python | def lattice(prng, n_features, alpha, random_sign=False, low=0.3, high=0.7):
"""Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the para... | [
"def",
"lattice",
"(",
"prng",
",",
"n_features",
",",
"alpha",
",",
"random_sign",
"=",
"False",
",",
"low",
"=",
"0.3",
",",
"high",
"=",
"0.7",
")",
":",
"degree",
"=",
"int",
"(",
"1",
"+",
"np",
".",
"round",
"(",
"alpha",
"*",
"n_features",
... | Returns the adjacency matrix for a lattice network.
The resulting network is a Toeplitz matrix with random values summing
between -1 and 1 and zeros along the diagonal.
The range of the values can be controlled via the parameters low and high.
If random_sign is false, all entries will be negative, oth... | [
"Returns",
"the",
"adjacency",
"matrix",
"for",
"a",
"lattice",
"network",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/graphs.py#L5-L61 | train |
skggm/skggm | inverse_covariance/profiling/graphs.py | _to_diagonally_dominant | def _to_diagonally_dominant(mat):
"""Make matrix unweighted diagonally dominant using the Laplacian."""
mat += np.diag(np.sum(mat != 0, axis=1) + 0.01)
return mat | python | def _to_diagonally_dominant(mat):
"""Make matrix unweighted diagonally dominant using the Laplacian."""
mat += np.diag(np.sum(mat != 0, axis=1) + 0.01)
return mat | [
"def",
"_to_diagonally_dominant",
"(",
"mat",
")",
":",
"mat",
"+=",
"np",
".",
"diag",
"(",
"np",
".",
"sum",
"(",
"mat",
"!=",
"0",
",",
"axis",
"=",
"1",
")",
"+",
"0.01",
")",
"return",
"mat"
] | Make matrix unweighted diagonally dominant using the Laplacian. | [
"Make",
"matrix",
"unweighted",
"diagonally",
"dominant",
"using",
"the",
"Laplacian",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/graphs.py#L103-L106 | train |
skggm/skggm | inverse_covariance/profiling/graphs.py | _to_diagonally_dominant_weighted | def _to_diagonally_dominant_weighted(mat):
"""Make matrix weighted diagonally dominant using the Laplacian."""
mat += np.diag(np.sum(np.abs(mat), axis=1) + 0.01)
return mat | python | def _to_diagonally_dominant_weighted(mat):
"""Make matrix weighted diagonally dominant using the Laplacian."""
mat += np.diag(np.sum(np.abs(mat), axis=1) + 0.01)
return mat | [
"def",
"_to_diagonally_dominant_weighted",
"(",
"mat",
")",
":",
"mat",
"+=",
"np",
".",
"diag",
"(",
"np",
".",
"sum",
"(",
"np",
".",
"abs",
"(",
"mat",
")",
",",
"axis",
"=",
"1",
")",
"+",
"0.01",
")",
"return",
"mat"
] | Make matrix weighted diagonally dominant using the Laplacian. | [
"Make",
"matrix",
"weighted",
"diagonally",
"dominant",
"using",
"the",
"Laplacian",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/graphs.py#L109-L112 | train |
skggm/skggm | inverse_covariance/profiling/graphs.py | _rescale_to_unit_diagonals | def _rescale_to_unit_diagonals(mat):
"""Rescale matrix to have unit diagonals.
Note: Call only after diagonal dominance is ensured.
"""
d = np.sqrt(np.diag(mat))
mat /= d
mat /= d[:, np.newaxis]
return mat | python | def _rescale_to_unit_diagonals(mat):
"""Rescale matrix to have unit diagonals.
Note: Call only after diagonal dominance is ensured.
"""
d = np.sqrt(np.diag(mat))
mat /= d
mat /= d[:, np.newaxis]
return mat | [
"def",
"_rescale_to_unit_diagonals",
"(",
"mat",
")",
":",
"d",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"diag",
"(",
"mat",
")",
")",
"mat",
"/=",
"d",
"mat",
"/=",
"d",
"[",
":",
",",
"np",
".",
"newaxis",
"]",
"return",
"mat"
] | Rescale matrix to have unit diagonals.
Note: Call only after diagonal dominance is ensured. | [
"Rescale",
"matrix",
"to",
"have",
"unit",
"diagonals",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/graphs.py#L115-L123 | train |
skggm/skggm | inverse_covariance/profiling/graphs.py | Graph.create | def create(self, n_features, alpha):
"""Build a new graph with block structure.
Parameters
-----------
n_features : int
alpha : float (0,1)
The complexity / sparsity factor for each graph type.
Returns
-----------
(n_features, n_features) ma... | python | def create(self, n_features, alpha):
"""Build a new graph with block structure.
Parameters
-----------
n_features : int
alpha : float (0,1)
The complexity / sparsity factor for each graph type.
Returns
-----------
(n_features, n_features) ma... | [
"def",
"create",
"(",
"self",
",",
"n_features",
",",
"alpha",
")",
":",
"n_block_features",
"=",
"int",
"(",
"np",
".",
"floor",
"(",
"1.",
"*",
"n_features",
"/",
"self",
".",
"n_blocks",
")",
")",
"if",
"n_block_features",
"*",
"self",
".",
"n_block... | Build a new graph with block structure.
Parameters
-----------
n_features : int
alpha : float (0,1)
The complexity / sparsity factor for each graph type.
Returns
-----------
(n_features, n_features) matrices: covariance, precision, adjacency | [
"Build",
"a",
"new",
"graph",
"with",
"block",
"structure",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/graphs.py#L176-L207 | train |
skggm/skggm | inverse_covariance/profiling/monte_carlo_profile.py | _sample_mvn | def _sample_mvn(n_samples, cov, prng):
"""Draw a multivariate normal sample from the graph defined by cov.
Parameters
-----------
n_samples : int
cov : matrix of shape (n_features, n_features)
Covariance matrix of the graph.
prng : np.random.RandomState instance.
"""
n_feature... | python | def _sample_mvn(n_samples, cov, prng):
"""Draw a multivariate normal sample from the graph defined by cov.
Parameters
-----------
n_samples : int
cov : matrix of shape (n_features, n_features)
Covariance matrix of the graph.
prng : np.random.RandomState instance.
"""
n_feature... | [
"def",
"_sample_mvn",
"(",
"n_samples",
",",
"cov",
",",
"prng",
")",
":",
"n_features",
",",
"_",
"=",
"cov",
".",
"shape",
"return",
"prng",
".",
"multivariate_normal",
"(",
"np",
".",
"zeros",
"(",
"n_features",
")",
",",
"cov",
",",
"size",
"=",
... | Draw a multivariate normal sample from the graph defined by cov.
Parameters
-----------
n_samples : int
cov : matrix of shape (n_features, n_features)
Covariance matrix of the graph.
prng : np.random.RandomState instance. | [
"Draw",
"a",
"multivariate",
"normal",
"sample",
"from",
"the",
"graph",
"defined",
"by",
"cov",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/monte_carlo_profile.py#L13-L26 | train |
skggm/skggm | inverse_covariance/model_average.py | _fully_random_weights | def _fully_random_weights(n_features, lam_scale, prng):
"""Generate a symmetric random matrix with zeros along the diagonal."""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_features ** 2 - n_features) / 2)
weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(
... | python | def _fully_random_weights(n_features, lam_scale, prng):
"""Generate a symmetric random matrix with zeros along the diagonal."""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_features ** 2 - n_features) / 2)
weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn(
... | [
"def",
"_fully_random_weights",
"(",
"n_features",
",",
"lam_scale",
",",
"prng",
")",
":",
"weights",
"=",
"np",
".",
"zeros",
"(",
"(",
"n_features",
",",
"n_features",
")",
")",
"n_off_diag",
"=",
"int",
"(",
"(",
"n_features",
"**",
"2",
"-",
"n_feat... | Generate a symmetric random matrix with zeros along the diagonal. | [
"Generate",
"a",
"symmetric",
"random",
"matrix",
"with",
"zeros",
"along",
"the",
"diagonal",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/model_average.py#L17-L26 | train |
skggm/skggm | inverse_covariance/model_average.py | _fix_weights | def _fix_weights(weight_fun, *args):
"""Ensure random weight matrix is valid.
TODO: The diagonally dominant tuning currently doesn't make sense.
Our weight matrix has zeros along the diagonal, so multiplying by
a diagonal matrix results in a zero-matrix.
"""
weights = weight_fun(... | python | def _fix_weights(weight_fun, *args):
"""Ensure random weight matrix is valid.
TODO: The diagonally dominant tuning currently doesn't make sense.
Our weight matrix has zeros along the diagonal, so multiplying by
a diagonal matrix results in a zero-matrix.
"""
weights = weight_fun(... | [
"def",
"_fix_weights",
"(",
"weight_fun",
",",
"*",
"args",
")",
":",
"weights",
"=",
"weight_fun",
"(",
"*",
"args",
")",
"return",
"weights",
"if",
"_check_psd",
"(",
"weights",
")",
":",
"return",
"weights",
"off_diag_sums",
"=",
"np",
".",
"sum",
"("... | Ensure random weight matrix is valid.
TODO: The diagonally dominant tuning currently doesn't make sense.
Our weight matrix has zeros along the diagonal, so multiplying by
a diagonal matrix results in a zero-matrix. | [
"Ensure",
"random",
"weight",
"matrix",
"is",
"valid",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/model_average.py#L46-L66 | train |
skggm/skggm | inverse_covariance/model_average.py | _fit | def _fit(
indexed_params,
penalization,
lam,
lam_perturb,
lam_scale_,
estimator,
penalty_name,
subsample,
bootstrap,
prng,
X=None,
):
"""Wrapper function outside of instance for fitting a single model average
trial.
If X is None, then we assume we are using a bro... | python | def _fit(
indexed_params,
penalization,
lam,
lam_perturb,
lam_scale_,
estimator,
penalty_name,
subsample,
bootstrap,
prng,
X=None,
):
"""Wrapper function outside of instance for fitting a single model average
trial.
If X is None, then we assume we are using a bro... | [
"def",
"_fit",
"(",
"indexed_params",
",",
"penalization",
",",
"lam",
",",
"lam_perturb",
",",
"lam_scale_",
",",
"estimator",
",",
"penalty_name",
",",
"subsample",
",",
"bootstrap",
",",
"prng",
",",
"X",
"=",
"None",
",",
")",
":",
"index",
"=",
"ind... | Wrapper function outside of instance for fitting a single model average
trial.
If X is None, then we assume we are using a broadcast spark object. Else,
we expect X to get passed into this function. | [
"Wrapper",
"function",
"outside",
"of",
"instance",
"for",
"fitting",
"a",
"single",
"model",
"average",
"trial",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/model_average.py#L74-L145 | train |
skggm/skggm | inverse_covariance/model_average.py | _spark_map | def _spark_map(fun, indexed_param_grid, sc, seed, X_bc):
"""We cannot pass a RandomState instance to each spark worker since it will
behave identically across partitions. Instead, we explictly handle the
partitions with a newly seeded instance.
The seed for each partition will be the "seed" (MonteCarl... | python | def _spark_map(fun, indexed_param_grid, sc, seed, X_bc):
"""We cannot pass a RandomState instance to each spark worker since it will
behave identically across partitions. Instead, we explictly handle the
partitions with a newly seeded instance.
The seed for each partition will be the "seed" (MonteCarl... | [
"def",
"_spark_map",
"(",
"fun",
",",
"indexed_param_grid",
",",
"sc",
",",
"seed",
",",
"X_bc",
")",
":",
"def",
"_wrap_random_state",
"(",
"split_index",
",",
"partition",
")",
":",
"prng",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
"+"... | We cannot pass a RandomState instance to each spark worker since it will
behave identically across partitions. Instead, we explictly handle the
partitions with a newly seeded instance.
The seed for each partition will be the "seed" (MonteCarloProfile.seed) +
"split_index" which is the partition index.... | [
"We",
"cannot",
"pass",
"a",
"RandomState",
"instance",
"to",
"each",
"spark",
"worker",
"since",
"it",
"will",
"behave",
"identically",
"across",
"partitions",
".",
"Instead",
"we",
"explictly",
"handle",
"the",
"partitions",
"with",
"a",
"newly",
"seeded",
"... | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/model_average.py#L156-L177 | train |
skggm/skggm | examples/estimator_suite_spark.py | quic_graph_lasso_ebic_manual | def quic_graph_lasso_ebic_manual(X, gamma=0):
"""Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model
selection.
The EBIC criteria is built into InverseCovarianceEstimator base class
so we demonstrate those utilities here.
"""
print("QuicGraphicalLasso (manual EBIC) wi... | python | def quic_graph_lasso_ebic_manual(X, gamma=0):
"""Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model
selection.
The EBIC criteria is built into InverseCovarianceEstimator base class
so we demonstrate those utilities here.
"""
print("QuicGraphicalLasso (manual EBIC) wi... | [
"def",
"quic_graph_lasso_ebic_manual",
"(",
"X",
",",
"gamma",
"=",
"0",
")",
":",
"print",
"(",
"\"QuicGraphicalLasso (manual EBIC) with:\"",
")",
"print",
"(",
"\" mode: path\"",
")",
"print",
"(",
"\" gamma: {}\"",
".",
"format",
"(",
"gamma",
")",
")",
"... | Run QuicGraphicalLasso with mode='path' and gamma; use EBIC criteria for model
selection.
The EBIC criteria is built into InverseCovarianceEstimator base class
so we demonstrate those utilities here. | [
"Run",
"QuicGraphicalLasso",
"with",
"mode",
"=",
"path",
"and",
"gamma",
";",
"use",
"EBIC",
"criteria",
"for",
"model",
"selection",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite_spark.py#L110-L135 | train |
skggm/skggm | examples/estimator_suite_spark.py | quic_graph_lasso_ebic | def quic_graph_lasso_ebic(X, gamma=0):
"""Run QuicGraphicalLassoEBIC with gamma.
QuicGraphicalLassoEBIC is a convenience class. Results should be identical to
those obtained via quic_graph_lasso_ebic_manual.
"""
print("QuicGraphicalLassoEBIC with:")
print(" mode: path")
print(" gamma: ... | python | def quic_graph_lasso_ebic(X, gamma=0):
"""Run QuicGraphicalLassoEBIC with gamma.
QuicGraphicalLassoEBIC is a convenience class. Results should be identical to
those obtained via quic_graph_lasso_ebic_manual.
"""
print("QuicGraphicalLassoEBIC with:")
print(" mode: path")
print(" gamma: ... | [
"def",
"quic_graph_lasso_ebic",
"(",
"X",
",",
"gamma",
"=",
"0",
")",
":",
"print",
"(",
"\"QuicGraphicalLassoEBIC with:\"",
")",
"print",
"(",
"\" mode: path\"",
")",
"print",
"(",
"\" gamma: {}\"",
".",
"format",
"(",
"gamma",
")",
")",
"model",
"=",
... | Run QuicGraphicalLassoEBIC with gamma.
QuicGraphicalLassoEBIC is a convenience class. Results should be identical to
those obtained via quic_graph_lasso_ebic_manual. | [
"Run",
"QuicGraphicalLassoEBIC",
"with",
"gamma",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite_spark.py#L138-L152 | train |
skggm/skggm | examples/estimator_suite_spark.py | empirical | def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov) | python | def empirical(X):
"""Compute empirical covariance as baseline estimator.
"""
print("Empirical")
cov = np.dot(X.T, X) / n_samples
return cov, np.linalg.inv(cov) | [
"def",
"empirical",
"(",
"X",
")",
":",
"print",
"(",
"\"Empirical\"",
")",
"cov",
"=",
"np",
".",
"dot",
"(",
"X",
".",
"T",
",",
"X",
")",
"/",
"n_samples",
"return",
"cov",
",",
"np",
".",
"linalg",
".",
"inv",
"(",
"cov",
")"
] | Compute empirical covariance as baseline estimator. | [
"Compute",
"empirical",
"covariance",
"as",
"baseline",
"estimator",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite_spark.py#L232-L237 | train |
skggm/skggm | examples/estimator_suite_spark.py | sk_ledoit_wolf | def sk_ledoit_wolf(X):
"""Estimate inverse covariance via scikit-learn ledoit_wolf function.
"""
print("Ledoit-Wolf (sklearn)")
lw_cov_, _ = ledoit_wolf(X)
lw_prec_ = np.linalg.inv(lw_cov_)
return lw_cov_, lw_prec_ | python | def sk_ledoit_wolf(X):
"""Estimate inverse covariance via scikit-learn ledoit_wolf function.
"""
print("Ledoit-Wolf (sklearn)")
lw_cov_, _ = ledoit_wolf(X)
lw_prec_ = np.linalg.inv(lw_cov_)
return lw_cov_, lw_prec_ | [
"def",
"sk_ledoit_wolf",
"(",
"X",
")",
":",
"print",
"(",
"\"Ledoit-Wolf (sklearn)\"",
")",
"lw_cov_",
",",
"_",
"=",
"ledoit_wolf",
"(",
"X",
")",
"lw_prec_",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"lw_cov_",
")",
"return",
"lw_cov_",
",",
"lw_prec... | Estimate inverse covariance via scikit-learn ledoit_wolf function. | [
"Estimate",
"inverse",
"covariance",
"via",
"scikit",
"-",
"learn",
"ledoit_wolf",
"function",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite_spark.py#L240-L246 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | _nonzero_intersection | def _nonzero_intersection(m, m_hat):
"""Count the number of nonzeros in and between m and m_hat.
Returns
----------
m_nnz : number of nonzeros in m (w/o diagonal)
m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)
intersection_nnz : number of nonzeros in intersection of m/m_hat
... | python | def _nonzero_intersection(m, m_hat):
"""Count the number of nonzeros in and between m and m_hat.
Returns
----------
m_nnz : number of nonzeros in m (w/o diagonal)
m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)
intersection_nnz : number of nonzeros in intersection of m/m_hat
... | [
"def",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
":",
"n_features",
",",
"_",
"=",
"m",
".",
"shape",
"m_no_diag",
"=",
"m",
".",
"copy",
"(",
")",
"m_no_diag",
"[",
"np",
".",
"diag_indices",
"(",
"n_features",
")",
"]",
"=",
"0",
"m_hat... | Count the number of nonzeros in and between m and m_hat.
Returns
----------
m_nnz : number of nonzeros in m (w/o diagonal)
m_hat_nnz : number of nonzeros in m_hat (w/o diagonal)
intersection_nnz : number of nonzeros in intersection of m/m_hat
(w/o diagonal) | [
"Count",
"the",
"number",
"of",
"nonzeros",
"in",
"and",
"between",
"m",
"and",
"m_hat",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L4-L30 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | support_false_positive_count | def support_false_positive_count(m, m_hat):
"""Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_hat_nnz - intersection_nnz) / 2.0) | python | def support_false_positive_count(m, m_hat):
"""Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_hat_nnz - intersection_nnz) / 2.0) | [
"def",
"support_false_positive_count",
"(",
"m",
",",
"m_hat",
")",
":",
"m_nnz",
",",
"m_hat_nnz",
",",
"intersection_nnz",
"=",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
"return",
"int",
"(",
"(",
"m_hat_nnz",
"-",
"intersection_nnz",
")",
"/",
... | Count the number of false positive support elements in
m_hat in one triangle, not including the diagonal. | [
"Count",
"the",
"number",
"of",
"false",
"positive",
"support",
"elements",
"in",
"m_hat",
"in",
"one",
"triangle",
"not",
"including",
"the",
"diagonal",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L33-L38 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | support_false_negative_count | def support_false_negative_count(m, m_hat):
"""Count the number of false negative support elements in
m_hat in one triangle, not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz - intersection_nnz) / 2.0) | python | def support_false_negative_count(m, m_hat):
"""Count the number of false negative support elements in
m_hat in one triangle, not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz - intersection_nnz) / 2.0) | [
"def",
"support_false_negative_count",
"(",
"m",
",",
"m_hat",
")",
":",
"m_nnz",
",",
"m_hat_nnz",
",",
"intersection_nnz",
"=",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
"return",
"int",
"(",
"(",
"m_nnz",
"-",
"intersection_nnz",
")",
"/",
"2.... | Count the number of false negative support elements in
m_hat in one triangle, not including the diagonal. | [
"Count",
"the",
"number",
"of",
"false",
"negative",
"support",
"elements",
"in",
"m_hat",
"in",
"one",
"triangle",
"not",
"including",
"the",
"diagonal",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L41-L46 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | support_difference_count | def support_difference_count(m, m_hat):
"""Count the number of different elements in the support in one triangle,
not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) / 2.0) | python | def support_difference_count(m, m_hat):
"""Count the number of different elements in the support in one triangle,
not including the diagonal.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) / 2.0) | [
"def",
"support_difference_count",
"(",
"m",
",",
"m_hat",
")",
":",
"m_nnz",
",",
"m_hat_nnz",
",",
"intersection_nnz",
"=",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
"return",
"int",
"(",
"(",
"m_nnz",
"+",
"m_hat_nnz",
"-",
"(",
"2",
"*",
... | Count the number of different elements in the support in one triangle,
not including the diagonal. | [
"Count",
"the",
"number",
"of",
"different",
"elements",
"in",
"the",
"support",
"in",
"one",
"triangle",
"not",
"including",
"the",
"diagonal",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L49-L54 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | has_exact_support | def has_exact_support(m, m_hat):
"""Returns 1 if support_difference_count is zero, 0 else.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) == 0) | python | def has_exact_support(m, m_hat):
"""Returns 1 if support_difference_count is zero, 0 else.
"""
m_nnz, m_hat_nnz, intersection_nnz = _nonzero_intersection(m, m_hat)
return int((m_nnz + m_hat_nnz - (2 * intersection_nnz)) == 0) | [
"def",
"has_exact_support",
"(",
"m",
",",
"m_hat",
")",
":",
"m_nnz",
",",
"m_hat_nnz",
",",
"intersection_nnz",
"=",
"_nonzero_intersection",
"(",
"m",
",",
"m_hat",
")",
"return",
"int",
"(",
"(",
"m_nnz",
"+",
"m_hat_nnz",
"-",
"(",
"2",
"*",
"inters... | Returns 1 if support_difference_count is zero, 0 else. | [
"Returns",
"1",
"if",
"support_difference_count",
"is",
"zero",
"0",
"else",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L57-L61 | train |
skggm/skggm | inverse_covariance/profiling/metrics.py | has_approx_support | def has_approx_support(m, m_hat, prob=0.01):
"""Returns 1 if model selection error is less than or equal to prob rate,
0 else.
NOTE: why does np.nonzero/np.flatnonzero create so much problems?
"""
m_nz = np.flatnonzero(np.triu(m, 1))
m_hat_nz = np.flatnonzero(np.triu(m_hat, 1))
upper_diago... | python | def has_approx_support(m, m_hat, prob=0.01):
"""Returns 1 if model selection error is less than or equal to prob rate,
0 else.
NOTE: why does np.nonzero/np.flatnonzero create so much problems?
"""
m_nz = np.flatnonzero(np.triu(m, 1))
m_hat_nz = np.flatnonzero(np.triu(m_hat, 1))
upper_diago... | [
"def",
"has_approx_support",
"(",
"m",
",",
"m_hat",
",",
"prob",
"=",
"0.01",
")",
":",
"m_nz",
"=",
"np",
".",
"flatnonzero",
"(",
"np",
".",
"triu",
"(",
"m",
",",
"1",
")",
")",
"m_hat_nz",
"=",
"np",
".",
"flatnonzero",
"(",
"np",
".",
"triu... | Returns 1 if model selection error is less than or equal to prob rate,
0 else.
NOTE: why does np.nonzero/np.flatnonzero create so much problems? | [
"Returns",
"1",
"if",
"model",
"selection",
"error",
"is",
"less",
"than",
"or",
"equal",
"to",
"prob",
"rate",
"0",
"else",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/profiling/metrics.py#L64-L88 | train |
skggm/skggm | inverse_covariance/inverse_covariance.py | _validate_path | def _validate_path(path):
"""Sorts path values from largest to smallest.
Will warn if path parameter was not already sorted.
"""
if path is None:
return None
new_path = np.array(sorted(set(path), reverse=True))
if new_path[0] != path[0]:
print("Warning: Path must be sorted larg... | python | def _validate_path(path):
"""Sorts path values from largest to smallest.
Will warn if path parameter was not already sorted.
"""
if path is None:
return None
new_path = np.array(sorted(set(path), reverse=True))
if new_path[0] != path[0]:
print("Warning: Path must be sorted larg... | [
"def",
"_validate_path",
"(",
"path",
")",
":",
"if",
"path",
"is",
"None",
":",
"return",
"None",
"new_path",
"=",
"np",
".",
"array",
"(",
"sorted",
"(",
"set",
"(",
"path",
")",
",",
"reverse",
"=",
"True",
")",
")",
"if",
"new_path",
"[",
"0",
... | Sorts path values from largest to smallest.
Will warn if path parameter was not already sorted. | [
"Sorts",
"path",
"values",
"from",
"largest",
"to",
"smallest",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/inverse_covariance.py#L77-L89 | train |
skggm/skggm | inverse_covariance/inverse_covariance.py | InverseCovarianceEstimator.ebic | def ebic(self, gamma=0):
"""Compute EBIC scores for each model. If model is not "path" then
returns a scalar score value.
May require self.path_
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS 2010
P... | python | def ebic(self, gamma=0):
"""Compute EBIC scores for each model. If model is not "path" then
returns a scalar score value.
May require self.path_
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS 2010
P... | [
"def",
"ebic",
"(",
"self",
",",
"gamma",
"=",
"0",
")",
":",
"if",
"not",
"self",
".",
"is_fitted_",
":",
"return",
"if",
"not",
"isinstance",
"(",
"self",
".",
"precision_",
",",
"list",
")",
":",
"return",
"metrics",
".",
"ebic",
"(",
"self",
".... | Compute EBIC scores for each model. If model is not "path" then
returns a scalar score value.
May require self.path_
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS 2010
Parameters
----------
... | [
"Compute",
"EBIC",
"scores",
"for",
"each",
"model",
".",
"If",
"model",
"is",
"not",
"path",
"then",
"returns",
"a",
"scalar",
"score",
"value",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/inverse_covariance.py#L268-L313 | train |
skggm/skggm | inverse_covariance/inverse_covariance.py | InverseCovarianceEstimator.ebic_select | def ebic_select(self, gamma=0):
"""Uses Extended Bayesian Information Criteria for model selection.
Can only be used in path mode (doesn't really make sense otherwise).
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS... | python | def ebic_select(self, gamma=0):
"""Uses Extended Bayesian Information Criteria for model selection.
Can only be used in path mode (doesn't really make sense otherwise).
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS... | [
"def",
"ebic_select",
"(",
"self",
",",
"gamma",
"=",
"0",
")",
":",
"if",
"not",
"isinstance",
"(",
"self",
".",
"precision_",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"EBIC requires multiple models to select from.\"",
")",
"return",
"if",
"not",
... | Uses Extended Bayesian Information Criteria for model selection.
Can only be used in path mode (doesn't really make sense otherwise).
See:
Extended Bayesian Information Criteria for Gaussian Graphical Models
R. Foygel and M. Drton
NIPS 2010
Parameters
---------... | [
"Uses",
"Extended",
"Bayesian",
"Information",
"Criteria",
"for",
"model",
"selection",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/inverse_covariance.py#L315-L345 | train |
skggm/skggm | examples/estimator_suite.py | quic_graph_lasso | def quic_graph_lasso(X, num_folds, metric):
"""Run QuicGraphicalLasso with mode='default' and use standard scikit
GridSearchCV to find the best lambda.
Primarily demonstrates compatibility with existing scikit tooling.
"""
print("QuicGraphicalLasso + GridSearchCV with:")
print(" metric: {}".f... | python | def quic_graph_lasso(X, num_folds, metric):
"""Run QuicGraphicalLasso with mode='default' and use standard scikit
GridSearchCV to find the best lambda.
Primarily demonstrates compatibility with existing scikit tooling.
"""
print("QuicGraphicalLasso + GridSearchCV with:")
print(" metric: {}".f... | [
"def",
"quic_graph_lasso",
"(",
"X",
",",
"num_folds",
",",
"metric",
")",
":",
"print",
"(",
"\"QuicGraphicalLasso + GridSearchCV with:\"",
")",
"print",
"(",
"\" metric: {}\"",
".",
"format",
"(",
"metric",
")",
")",
"search_grid",
"=",
"{",
"\"lam\"",
":",
... | Run QuicGraphicalLasso with mode='default' and use standard scikit
GridSearchCV to find the best lambda.
Primarily demonstrates compatibility with existing scikit tooling. | [
"Run",
"QuicGraphicalLasso",
"with",
"mode",
"=",
"default",
"and",
"use",
"standard",
"scikit",
"GridSearchCV",
"to",
"find",
"the",
"best",
"lambda",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite.py#L97-L117 | train |
skggm/skggm | examples/estimator_suite.py | quic_graph_lasso_cv | def quic_graph_lasso_cv(X, metric):
"""Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of
lambdas tested should be much lower with similar final lam_ selected.
"""
print("QuicGraphicalLassoCV with:")
print(" metric: {}"... | python | def quic_graph_lasso_cv(X, metric):
"""Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of
lambdas tested should be much lower with similar final lam_ selected.
"""
print("QuicGraphicalLassoCV with:")
print(" metric: {}"... | [
"def",
"quic_graph_lasso_cv",
"(",
"X",
",",
"metric",
")",
":",
"print",
"(",
"\"QuicGraphicalLassoCV with:\"",
")",
"print",
"(",
"\" metric: {}\"",
".",
"format",
"(",
"metric",
")",
")",
"model",
"=",
"QuicGraphicalLassoCV",
"(",
"cv",
"=",
"2",
",",
"... | Run QuicGraphicalLassoCV on data with metric of choice.
Compare results with GridSearchCV + quic_graph_lasso. The number of
lambdas tested should be much lower with similar final lam_ selected. | [
"Run",
"QuicGraphicalLassoCV",
"on",
"data",
"with",
"metric",
"of",
"choice",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite.py#L120-L139 | train |
skggm/skggm | examples/estimator_suite.py | graph_lasso | def graph_lasso(X, num_folds):
"""Estimate inverse covariance via scikit-learn GraphLassoCV class.
"""
print("GraphLasso (sklearn)")
model = GraphLassoCV(cv=num_folds)
model.fit(X)
print(" lam_: {}".format(model.alpha_))
return model.covariance_, model.precision_, model.alpha_ | python | def graph_lasso(X, num_folds):
"""Estimate inverse covariance via scikit-learn GraphLassoCV class.
"""
print("GraphLasso (sklearn)")
model = GraphLassoCV(cv=num_folds)
model.fit(X)
print(" lam_: {}".format(model.alpha_))
return model.covariance_, model.precision_, model.alpha_ | [
"def",
"graph_lasso",
"(",
"X",
",",
"num_folds",
")",
":",
"print",
"(",
"\"GraphLasso (sklearn)\"",
")",
"model",
"=",
"GraphLassoCV",
"(",
"cv",
"=",
"num_folds",
")",
"model",
".",
"fit",
"(",
"X",
")",
"print",
"(",
"\" lam_: {}\"",
".",
"format",
... | Estimate inverse covariance via scikit-learn GraphLassoCV class. | [
"Estimate",
"inverse",
"covariance",
"via",
"scikit",
"-",
"learn",
"GraphLassoCV",
"class",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/examples/estimator_suite.py#L295-L302 | train |
skggm/skggm | inverse_covariance/quic_graph_lasso.py | _quic_path | def _quic_path(
X,
path,
X_test=None,
lam=0.5,
tol=1e-6,
max_iter=1000,
Theta0=None,
Sigma0=None,
method="quic",
verbose=0,
score_metric="log_likelihood",
init_method="corrcoef",
):
"""Wrapper to compute path for example X.
"""
S, lam_scale_ = _init_coefs(X, m... | python | def _quic_path(
X,
path,
X_test=None,
lam=0.5,
tol=1e-6,
max_iter=1000,
Theta0=None,
Sigma0=None,
method="quic",
verbose=0,
score_metric="log_likelihood",
init_method="corrcoef",
):
"""Wrapper to compute path for example X.
"""
S, lam_scale_ = _init_coefs(X, m... | [
"def",
"_quic_path",
"(",
"X",
",",
"path",
",",
"X_test",
"=",
"None",
",",
"lam",
"=",
"0.5",
",",
"tol",
"=",
"1e-6",
",",
"max_iter",
"=",
"1000",
",",
"Theta0",
"=",
"None",
",",
"Sigma0",
"=",
"None",
",",
"method",
"=",
"\"quic\"",
",",
"v... | Wrapper to compute path for example X. | [
"Wrapper",
"to",
"compute",
"path",
"for",
"example",
"X",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/quic_graph_lasso.py#L383-L435 | train |
skggm/skggm | inverse_covariance/quic_graph_lasso.py | QuicGraphicalLasso.lam_at_index | def lam_at_index(self, lidx):
"""Compute the scaled lambda used at index lidx.
"""
if self.path_ is None:
return self.lam * self.lam_scale_
return self.lam * self.lam_scale_ * self.path_[lidx] | python | def lam_at_index(self, lidx):
"""Compute the scaled lambda used at index lidx.
"""
if self.path_ is None:
return self.lam * self.lam_scale_
return self.lam * self.lam_scale_ * self.path_[lidx] | [
"def",
"lam_at_index",
"(",
"self",
",",
"lidx",
")",
":",
"if",
"self",
".",
"path_",
"is",
"None",
":",
"return",
"self",
".",
"lam",
"*",
"self",
".",
"lam_scale_",
"return",
"self",
".",
"lam",
"*",
"self",
".",
"lam_scale_",
"*",
"self",
".",
... | Compute the scaled lambda used at index lidx. | [
"Compute",
"the",
"scaled",
"lambda",
"used",
"at",
"index",
"lidx",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/quic_graph_lasso.py#L361-L367 | train |
skggm/skggm | inverse_covariance/rank_correlation.py | _compute_ranks | def _compute_ranks(X, winsorize=False, truncation=None, verbose=True):
"""
Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X :... | python | def _compute_ranks(X, winsorize=False, truncation=None, verbose=True):
"""
Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X :... | [
"def",
"_compute_ranks",
"(",
"X",
",",
"winsorize",
"=",
"False",
",",
"truncation",
"=",
"None",
",",
"verbose",
"=",
"True",
")",
":",
"n_samples",
",",
"n_features",
"=",
"X",
".",
"shape",
"Xrank",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"X"... | Transform each column into ranked data. Tied ranks are averaged.
Ranks can optionally be winsorized as described in Liu 2009 otherwise
this returns Tsukahara's scaled rank based Z-estimator.
Parameters
----------
X : array-like, shape = (n_samples, n_features)
The data matrix where each col... | [
"Transform",
"each",
"column",
"into",
"ranked",
"data",
".",
"Tied",
"ranks",
"are",
"averaged",
".",
"Ranks",
"can",
"optionally",
"be",
"winsorized",
"as",
"described",
"in",
"Liu",
"2009",
"otherwise",
"this",
"returns",
"Tsukahara",
"s",
"scaled",
"rank",... | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/rank_correlation.py#L9-L66 | train |
skggm/skggm | inverse_covariance/rank_correlation.py | spearman_correlation | def spearman_correlation(X, rowvar=False):
"""
Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we ... | python | def spearman_correlation(X, rowvar=False):
"""
Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we ... | [
"def",
"spearman_correlation",
"(",
"X",
",",
"rowvar",
"=",
"False",
")",
":",
"Xrank",
"=",
"_compute_ranks",
"(",
"X",
")",
"rank_correlation",
"=",
"np",
".",
"corrcoef",
"(",
"Xrank",
",",
"rowvar",
"=",
"rowvar",
")",
"return",
"2",
"*",
"np",
".... | Computes the spearman correlation estimate.
This is effectively a bias corrected pearson correlation
between rank transformed columns of X.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we compute the empirical
correlation
Returns
... | [
"Computes",
"the",
"spearman",
"correlation",
"estimate",
".",
"This",
"is",
"effectively",
"a",
"bias",
"corrected",
"pearson",
"correlation",
"between",
"rank",
"transformed",
"columns",
"of",
"X",
"."
] | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/rank_correlation.py#L69-L101 | train |
skggm/skggm | inverse_covariance/rank_correlation.py | kendalltau_correlation | def kendalltau_correlation(X, rowvar=False, weighted=False):
"""
Computes kendall's tau correlation estimate.
The option to use scipy.stats.weightedtau is not recommended
as the implementation does not appear to handle ties correctly.
Parameters
----------
X: array-like, shape = [n_samples,... | python | def kendalltau_correlation(X, rowvar=False, weighted=False):
"""
Computes kendall's tau correlation estimate.
The option to use scipy.stats.weightedtau is not recommended
as the implementation does not appear to handle ties correctly.
Parameters
----------
X: array-like, shape = [n_samples,... | [
"def",
"kendalltau_correlation",
"(",
"X",
",",
"rowvar",
"=",
"False",
",",
"weighted",
"=",
"False",
")",
":",
"if",
"rowvar",
":",
"X",
"=",
"X",
".",
"T",
"_",
",",
"n_features",
"=",
"X",
".",
"shape",
"rank_correlation",
"=",
"np",
".",
"eye",
... | Computes kendall's tau correlation estimate.
The option to use scipy.stats.weightedtau is not recommended
as the implementation does not appear to handle ties correctly.
Parameters
----------
X: array-like, shape = [n_samples, n_features]
Data matrix using which we compute the empirical
... | [
"Computes",
"kendall",
"s",
"tau",
"correlation",
"estimate",
".",
"The",
"option",
"to",
"use",
"scipy",
".",
"stats",
".",
"weightedtau",
"is",
"not",
"recommended",
"as",
"the",
"implementation",
"does",
"not",
"appear",
"to",
"handle",
"ties",
"correctly",... | a0ed406586c4364ea3297a658f415e13b5cbdaf8 | https://github.com/skggm/skggm/blob/a0ed406586c4364ea3297a658f415e13b5cbdaf8/inverse_covariance/rank_correlation.py#L104-L148 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Endpoint.version | def version(self):
"""
This attribute retrieve the API version.
>>> Works().version
'1.0.0'
"""
request_params = dict(self.request_params)
request_url = str(self.request_url)
result = self.do_http_request(
'get',
reque... | python | def version(self):
"""
This attribute retrieve the API version.
>>> Works().version
'1.0.0'
"""
request_params = dict(self.request_params)
request_url = str(self.request_url)
result = self.do_http_request(
'get',
reque... | [
"def",
"version",
"(",
"self",
")",
":",
"request_params",
"=",
"dict",
"(",
"self",
".",
"request_params",
")",
"request_url",
"=",
"str",
"(",
"self",
".",
"request_url",
")",
"result",
"=",
"self",
".",
"do_http_request",
"(",
"'get'",
",",
"request_url... | This attribute retrieve the API version.
>>> Works().version
'1.0.0' | [
"This",
"attribute",
"retrieve",
"the",
"API",
"version",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L157-L174 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Endpoint.count | def count(self):
"""
This method retrieve the total of records resulting from a given query.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika... | python | def count(self):
"""
This method retrieve the total of records resulting from a given query.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika... | [
"def",
"count",
"(",
"self",
")",
":",
"request_params",
"=",
"dict",
"(",
"self",
".",
"request_params",
")",
"request_url",
"=",
"str",
"(",
"self",
".",
"request_url",
")",
"request_params",
"[",
"'rows'",
"]",
"=",
"0",
"result",
"=",
"self",
".",
... | This method retrieve the total of records resulting from a given query.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika').count()
3597
... | [
"This",
"method",
"retrieve",
"the",
"total",
"of",
"records",
"resulting",
"from",
"a",
"given",
"query",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L186-L215 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Endpoint.url | def url(self):
"""
This attribute retrieve the url that will be used as a HTTP request to
the Crossref API.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
... | python | def url(self):
"""
This attribute retrieve the url that will be used as a HTTP request to
the Crossref API.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
... | [
"def",
"url",
"(",
"self",
")",
":",
"request_params",
"=",
"self",
".",
"_escaped_pagging",
"(",
")",
"sorted_request_params",
"=",
"sorted",
"(",
"[",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"request_params",
".",
"items",
"(",
")",
"]... | This attribute retrieve the url that will be used as a HTTP request to
the Crossref API.
This attribute can be used compounded with query, filter,
sort, order and facet methods.
Examples:
>>> from crossref.restful import Works
>>> Works().query('zika').url
... | [
"This",
"attribute",
"retrieve",
"the",
"url",
"that",
"will",
"be",
"used",
"as",
"a",
"HTTP",
"request",
"to",
"the",
"Crossref",
"API",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L218-L243 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Works.doi | def doi(self, doi, only_message=True):
"""
This method retrieve the DOI metadata related to a given DOI
number.
args: Crossref DOI id (String)
return: JSON
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works... | python | def doi(self, doi, only_message=True):
"""
This method retrieve the DOI metadata related to a given DOI
number.
args: Crossref DOI id (String)
return: JSON
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works... | [
"def",
"doi",
"(",
"self",
",",
"doi",
",",
"only_message",
"=",
"True",
")",
":",
"request_url",
"=",
"build_url_endpoint",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"ENDPOINT",
",",
"doi",
"]",
")",
")",
"request_params",
"=",
"{",
"}",
"resu... | This method retrieve the DOI metadata related to a given DOI
number.
args: Crossref DOI id (String)
return: JSON
Example:
>>> from crossref.restful import Works
>>> works = Works()
>>> works.doi('10.1590/S0004-28032013005000001')
{'is-re... | [
"This",
"method",
"retrieve",
"the",
"DOI",
"metadata",
"related",
"to",
"a",
"given",
"DOI",
"number",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L901-L959 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Works.doi_exists | def doi_exists(self, doi):
"""
This method retrieve a boolean according to the existence of a crossref
DOI number. It returns False if the API results a 404 status code.
args: Crossref DOI id (String)
return: Boolean
Example 1:
>>> from crossref.restful imp... | python | def doi_exists(self, doi):
"""
This method retrieve a boolean according to the existence of a crossref
DOI number. It returns False if the API results a 404 status code.
args: Crossref DOI id (String)
return: Boolean
Example 1:
>>> from crossref.restful imp... | [
"def",
"doi_exists",
"(",
"self",
",",
"doi",
")",
":",
"request_url",
"=",
"build_url_endpoint",
"(",
"'/'",
".",
"join",
"(",
"[",
"self",
".",
"ENDPOINT",
",",
"doi",
"]",
")",
")",
"request_params",
"=",
"{",
"}",
"result",
"=",
"self",
".",
"do_... | This method retrieve a boolean according to the existence of a crossref
DOI number. It returns False if the API results a 404 status code.
args: Crossref DOI id (String)
return: Boolean
Example 1:
>>> from crossref.restful import Works
>>> works = Works()
... | [
"This",
"method",
"retrieve",
"a",
"boolean",
"according",
"to",
"the",
"existence",
"of",
"a",
"crossref",
"DOI",
"number",
".",
"It",
"returns",
"False",
"if",
"the",
"API",
"results",
"a",
"404",
"status",
"code",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L995-L1032 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Funders.works | def works(self, funder_id):
"""
This method retrieve a iterable of Works of the given funder.
args: Crossref allowed document Types (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(funder_id))
return Works(context=context) | python | def works(self, funder_id):
"""
This method retrieve a iterable of Works of the given funder.
args: Crossref allowed document Types (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(funder_id))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"funder_id",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"funder_id",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given funder.
args: Crossref allowed document Types (String)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"funder",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1199-L1208 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Members.works | def works(self, member_id):
"""
This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(member_id))
return Works(context=context) | python | def works(self, member_id):
"""
This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(member_id))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"member_id",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"member_id",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given member.
args: Member ID (Integer)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"member",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1418-L1427 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Types.all | def all(self):
"""
This method retrieve an iterator with all the available types.
return: iterator of crossref document types
Example:
>>> from crossref.restful import Types
>>> types = Types()
>>> [i for i in types.all()]
[{'label': 'Boo... | python | def all(self):
"""
This method retrieve an iterator with all the available types.
return: iterator of crossref document types
Example:
>>> from crossref.restful import Types
>>> types = Types()
>>> [i for i in types.all()]
[{'label': 'Boo... | [
"def",
"all",
"(",
"self",
")",
":",
"request_url",
"=",
"build_url_endpoint",
"(",
"self",
".",
"ENDPOINT",
",",
"self",
".",
"context",
")",
"request_params",
"=",
"dict",
"(",
"self",
".",
"request_params",
")",
"result",
"=",
"self",
".",
"do_http_requ... | This method retrieve an iterator with all the available types.
return: iterator of crossref document types
Example:
>>> from crossref.restful import Types
>>> types = Types()
>>> [i for i in types.all()]
[{'label': 'Book Section', 'id': 'book-section'},
... | [
"This",
"method",
"retrieve",
"an",
"iterator",
"with",
"all",
"the",
"available",
"types",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1466-L1501 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Types.works | def works(self, type_id):
"""
This method retrieve a iterable of Works of the given type.
args: Crossref allowed document Types (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(type_id))
return Works(context=context) | python | def works(self, type_id):
"""
This method retrieve a iterable of Works of the given type.
args: Crossref allowed document Types (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(type_id))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"type_id",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"type_id",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given type.
args: Crossref allowed document Types (String)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"type",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1542-L1551 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Prefixes.works | def works(self, prefix_id):
"""
This method retrieve a iterable of Works of the given prefix.
args: Crossref Prefix (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(prefix_id))
return Works(context=context) | python | def works(self, prefix_id):
"""
This method retrieve a iterable of Works of the given prefix.
args: Crossref Prefix (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(prefix_id))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"prefix_id",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"prefix_id",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given prefix.
args: Crossref Prefix (String)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"prefix",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1594-L1603 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Journals.works | def works(self, issn):
"""
This method retrieve a iterable of Works of the given journal.
args: Journal ISSN (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(issn))
return Works(context=context) | python | def works(self, issn):
"""
This method retrieve a iterable of Works of the given journal.
args: Journal ISSN (String)
return: Works()
"""
context = '%s/%s' % (self.ENDPOINT, str(issn))
return Works(context=context) | [
"def",
"works",
"(",
"self",
",",
"issn",
")",
":",
"context",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"ENDPOINT",
",",
"str",
"(",
"issn",
")",
")",
"return",
"Works",
"(",
"context",
"=",
"context",
")"
] | This method retrieve a iterable of Works of the given journal.
args: Journal ISSN (String)
return: Works() | [
"This",
"method",
"retrieve",
"a",
"iterable",
"of",
"Works",
"of",
"the",
"given",
"journal",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1718-L1728 | train |
fabiobatalha/crossrefapi | crossref/restful.py | Depositor.register_doi | def register_doi(self, submission_id, request_xml):
"""
This method registry a new DOI number in Crossref or update some DOI
metadata.
submission_id: Will be used as the submission file name. The file name
could be used in future requests to retrieve the submission status.
... | python | def register_doi(self, submission_id, request_xml):
"""
This method registry a new DOI number in Crossref or update some DOI
metadata.
submission_id: Will be used as the submission file name. The file name
could be used in future requests to retrieve the submission status.
... | [
"def",
"register_doi",
"(",
"self",
",",
"submission_id",
",",
"request_xml",
")",
":",
"endpoint",
"=",
"self",
".",
"get_endpoint",
"(",
"'deposit'",
")",
"files",
"=",
"{",
"'mdFile'",
":",
"(",
"'%s.xml'",
"%",
"submission_id",
",",
"request_xml",
")",
... | This method registry a new DOI number in Crossref or update some DOI
metadata.
submission_id: Will be used as the submission file name. The file name
could be used in future requests to retrieve the submission status.
request_xml: The XML with the document metadata. It must be under
... | [
"This",
"method",
"registry",
"a",
"new",
"DOI",
"number",
"in",
"Crossref",
"or",
"update",
"some",
"DOI",
"metadata",
"."
] | 53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7 | https://github.com/fabiobatalha/crossrefapi/blob/53f84ee0d8a8fc6ad9b2493f51c5151e66d2faf7/crossref/restful.py#L1746-L1779 | train |
buildinspace/peru | peru/plugin.py | _find_plugin_dir | def _find_plugin_dir(module_type):
'''Find the directory containing the plugin definition for the given type.
Do this by searching all the paths where plugins can live for a dir that
matches the type name.'''
for install_dir in _get_plugin_install_dirs():
candidate = os.path.join(install_dir, m... | python | def _find_plugin_dir(module_type):
'''Find the directory containing the plugin definition for the given type.
Do this by searching all the paths where plugins can live for a dir that
matches the type name.'''
for install_dir in _get_plugin_install_dirs():
candidate = os.path.join(install_dir, m... | [
"def",
"_find_plugin_dir",
"(",
"module_type",
")",
":",
"for",
"install_dir",
"in",
"_get_plugin_install_dirs",
"(",
")",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"install_dir",
",",
"module_type",
")",
"if",
"os",
".",
"path",
".",
"is... | Find the directory containing the plugin definition for the given type.
Do this by searching all the paths where plugins can live for a dir that
matches the type name. | [
"Find",
"the",
"directory",
"containing",
"the",
"plugin",
"definition",
"for",
"the",
"given",
"type",
".",
"Do",
"this",
"by",
"searching",
"all",
"the",
"paths",
"where",
"plugins",
"can",
"live",
"for",
"a",
"dir",
"that",
"matches",
"the",
"type",
"na... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/plugin.py#L264-L276 | train |
buildinspace/peru | peru/main.py | merged_args_dicts | def merged_args_dicts(global_args, subcommand_args):
'''We deal with docopt args from the toplevel peru parse and the subcommand
parse. We don't want False values for a flag in the subcommand to override
True values if that flag was given at the top level. This function
specifically handles that case.''... | python | def merged_args_dicts(global_args, subcommand_args):
'''We deal with docopt args from the toplevel peru parse and the subcommand
parse. We don't want False values for a flag in the subcommand to override
True values if that flag was given at the top level. This function
specifically handles that case.''... | [
"def",
"merged_args_dicts",
"(",
"global_args",
",",
"subcommand_args",
")",
":",
"merged",
"=",
"global_args",
".",
"copy",
"(",
")",
"for",
"key",
",",
"val",
"in",
"subcommand_args",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"merged",
":"... | We deal with docopt args from the toplevel peru parse and the subcommand
parse. We don't want False values for a flag in the subcommand to override
True values if that flag was given at the top level. This function
specifically handles that case. | [
"We",
"deal",
"with",
"docopt",
"args",
"from",
"the",
"toplevel",
"peru",
"parse",
"and",
"the",
"subcommand",
"parse",
".",
"We",
"don",
"t",
"want",
"False",
"values",
"for",
"a",
"flag",
"in",
"the",
"subcommand",
"to",
"override",
"True",
"values",
... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/main.py#L299-L312 | train |
buildinspace/peru | peru/main.py | force_utf8_in_ascii_mode_hack | def force_utf8_in_ascii_mode_hack():
'''In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emit... | python | def force_utf8_in_ascii_mode_hack():
'''In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emit... | [
"def",
"force_utf8_in_ascii_mode_hack",
"(",
")",
":",
"if",
"sys",
".",
"stdout",
".",
"encoding",
"==",
"'ANSI_X3.4-1968'",
":",
"sys",
".",
"stdout",
"=",
"open",
"(",
"sys",
".",
"stdout",
".",
"fileno",
"(",
")",
",",
"mode",
"=",
"'w'",
",",
"enc... | In systems without a UTF8 locale configured, Python will default to
ASCII mode for stdout and stderr. This causes our fancy display to fail
with encoding errors. In particular, you run into this if you try to run
peru inside of Docker. This is a hack to force emitting UTF8 in that case.
Hopefully it doe... | [
"In",
"systems",
"without",
"a",
"UTF8",
"locale",
"configured",
"Python",
"will",
"default",
"to",
"ASCII",
"mode",
"for",
"stdout",
"and",
"stderr",
".",
"This",
"causes",
"our",
"fancy",
"display",
"to",
"fail",
"with",
"encoding",
"errors",
".",
"In",
... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/main.py#L334-L344 | train |
buildinspace/peru | peru/scope.py | Scope.parse_target | async def parse_target(self, runtime, target_str):
'''A target is a pipeline of a module into zero or more rules, and each
module and rule can itself be scoped with zero or more module names.'''
pipeline_parts = target_str.split(RULE_SEPARATOR)
module = await self.resolve_module(runtime,... | python | async def parse_target(self, runtime, target_str):
'''A target is a pipeline of a module into zero or more rules, and each
module and rule can itself be scoped with zero or more module names.'''
pipeline_parts = target_str.split(RULE_SEPARATOR)
module = await self.resolve_module(runtime,... | [
"async",
"def",
"parse_target",
"(",
"self",
",",
"runtime",
",",
"target_str",
")",
":",
"pipeline_parts",
"=",
"target_str",
".",
"split",
"(",
"RULE_SEPARATOR",
")",
"module",
"=",
"await",
"self",
".",
"resolve_module",
"(",
"runtime",
",",
"pipeline_parts... | A target is a pipeline of a module into zero or more rules, and each
module and rule can itself be scoped with zero or more module names. | [
"A",
"target",
"is",
"a",
"pipeline",
"of",
"a",
"module",
"into",
"zero",
"or",
"more",
"rules",
"and",
"each",
"module",
"and",
"rule",
"can",
"itself",
"be",
"scoped",
"with",
"zero",
"or",
"more",
"module",
"names",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/scope.py#L17-L27 | train |
buildinspace/peru | peru/edit_yaml.py | _maybe_quote | def _maybe_quote(val):
'''All of our values should be strings. Usually those can be passed in as
bare words, but if they're parseable as an int or float we need to quote
them.'''
assert isinstance(val, str), 'We should never set non-string values.'
needs_quoting = False
try:
int(val)
... | python | def _maybe_quote(val):
'''All of our values should be strings. Usually those can be passed in as
bare words, but if they're parseable as an int or float we need to quote
them.'''
assert isinstance(val, str), 'We should never set non-string values.'
needs_quoting = False
try:
int(val)
... | [
"def",
"_maybe_quote",
"(",
"val",
")",
":",
"assert",
"isinstance",
"(",
"val",
",",
"str",
")",
",",
"'We should never set non-string values.'",
"needs_quoting",
"=",
"False",
"try",
":",
"int",
"(",
"val",
")",
"needs_quoting",
"=",
"True",
"except",
"Excep... | All of our values should be strings. Usually those can be passed in as
bare words, but if they're parseable as an int or float we need to quote
them. | [
"All",
"of",
"our",
"values",
"should",
"be",
"strings",
".",
"Usually",
"those",
"can",
"be",
"passed",
"in",
"as",
"bare",
"words",
"but",
"if",
"they",
"re",
"parseable",
"as",
"an",
"int",
"or",
"float",
"we",
"need",
"to",
"quote",
"them",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/edit_yaml.py#L26-L45 | train |
buildinspace/peru | peru/async_helpers.py | gather_coalescing_exceptions | async def gather_coalescing_exceptions(coros, display, *, verbose):
'''The tricky thing about running multiple coroutines in parallel is what
we're supposed to do when one of them raises an exception. The approach
we're using here is to catch exceptions and keep waiting for other tasks to
finish. At the... | python | async def gather_coalescing_exceptions(coros, display, *, verbose):
'''The tricky thing about running multiple coroutines in parallel is what
we're supposed to do when one of them raises an exception. The approach
we're using here is to catch exceptions and keep waiting for other tasks to
finish. At the... | [
"async",
"def",
"gather_coalescing_exceptions",
"(",
"coros",
",",
"display",
",",
"*",
",",
"verbose",
")",
":",
"exceptions",
"=",
"[",
"]",
"reprs",
"=",
"[",
"]",
"async",
"def",
"catching_wrapper",
"(",
"coro",
")",
":",
"try",
":",
"return",
"(",
... | The tricky thing about running multiple coroutines in parallel is what
we're supposed to do when one of them raises an exception. The approach
we're using here is to catch exceptions and keep waiting for other tasks to
finish. At the end, we reraise a GatheredExceptions error, if any
exceptions were cau... | [
"The",
"tricky",
"thing",
"about",
"running",
"multiple",
"coroutines",
"in",
"parallel",
"is",
"what",
"we",
"re",
"supposed",
"to",
"do",
"when",
"one",
"of",
"them",
"raises",
"an",
"exception",
".",
"The",
"approach",
"we",
"re",
"using",
"here",
"is",... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_helpers.py#L53-L94 | train |
buildinspace/peru | peru/async_helpers.py | create_subprocess_with_handle | async def create_subprocess_with_handle(command,
display_handle,
*,
shell=False,
cwd,
**kwargs):
'''Writes subproces... | python | async def create_subprocess_with_handle(command,
display_handle,
*,
shell=False,
cwd,
**kwargs):
'''Writes subproces... | [
"async",
"def",
"create_subprocess_with_handle",
"(",
"command",
",",
"display_handle",
",",
"*",
",",
"shell",
"=",
"False",
",",
"cwd",
",",
"**",
"kwargs",
")",
":",
"encoding",
"=",
"sys",
".",
"stdout",
".",
"encoding",
"or",
"'utf8'",
"decoder_factory"... | Writes subprocess output to a display handle as it comes in, and also
returns a copy of it as a string. Throws if the subprocess returns an
error. Note that cwd is a required keyword-only argument, on theory that
peru should never start child processes "wherever I happen to be running
right now." | [
"Writes",
"subprocess",
"output",
"to",
"a",
"display",
"handle",
"as",
"it",
"comes",
"in",
"and",
"also",
"returns",
"a",
"copy",
"of",
"it",
"as",
"a",
"string",
".",
"Throws",
"if",
"the",
"subprocess",
"returns",
"an",
"error",
".",
"Note",
"that",
... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_helpers.py#L97-L164 | train |
buildinspace/peru | peru/async_helpers.py | raises_gathered | def raises_gathered(error_type):
'''For use in tests. Many tests expect a single error to be thrown, and
want it to be of a specific type. This is a helper method for when that
type is inside a gathered exception.'''
container = RaisesGatheredContainer()
try:
yield container
except Gathe... | python | def raises_gathered(error_type):
'''For use in tests. Many tests expect a single error to be thrown, and
want it to be of a specific type. This is a helper method for when that
type is inside a gathered exception.'''
container = RaisesGatheredContainer()
try:
yield container
except Gathe... | [
"def",
"raises_gathered",
"(",
"error_type",
")",
":",
"container",
"=",
"RaisesGatheredContainer",
"(",
")",
"try",
":",
"yield",
"container",
"except",
"GatheredExceptions",
"as",
"e",
":",
"if",
"len",
"(",
"e",
".",
"exceptions",
")",
"!=",
"1",
":",
"... | For use in tests. Many tests expect a single error to be thrown, and
want it to be of a specific type. This is a helper method for when that
type is inside a gathered exception. | [
"For",
"use",
"in",
"tests",
".",
"Many",
"tests",
"expect",
"a",
"single",
"error",
"to",
"be",
"thrown",
"and",
"want",
"it",
"to",
"be",
"of",
"a",
"specific",
"type",
".",
"This",
"is",
"a",
"helper",
"method",
"for",
"when",
"that",
"type",
"is"... | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_helpers.py#L201-L217 | train |
buildinspace/peru | peru/resources/plugins/curl/curl_plugin.py | get_request_filename | def get_request_filename(request):
'''Figure out the filename for an HTTP download.'''
# Check to see if a filename is specified in the HTTP headers.
if 'Content-Disposition' in request.info():
disposition = request.info()['Content-Disposition']
pieces = re.split(r'\s*;\s*', disposition)
... | python | def get_request_filename(request):
'''Figure out the filename for an HTTP download.'''
# Check to see if a filename is specified in the HTTP headers.
if 'Content-Disposition' in request.info():
disposition = request.info()['Content-Disposition']
pieces = re.split(r'\s*;\s*', disposition)
... | [
"def",
"get_request_filename",
"(",
"request",
")",
":",
"if",
"'Content-Disposition'",
"in",
"request",
".",
"info",
"(",
")",
":",
"disposition",
"=",
"request",
".",
"info",
"(",
")",
"[",
"'Content-Disposition'",
"]",
"pieces",
"=",
"re",
".",
"split",
... | Figure out the filename for an HTTP download. | [
"Figure",
"out",
"the",
"filename",
"for",
"an",
"HTTP",
"download",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/resources/plugins/curl/curl_plugin.py#L16-L34 | train |
buildinspace/peru | peru/parser.py | _extract_optional_list_field | def _extract_optional_list_field(blob, name):
'''Handle optional fields that can be either a string or a list of
strings.'''
value = _optional_list(typesafe_pop(blob, name, []))
if value is None:
raise ParserError(
'"{}" field must be a string or a list.'.format(name))
return val... | python | def _extract_optional_list_field(blob, name):
'''Handle optional fields that can be either a string or a list of
strings.'''
value = _optional_list(typesafe_pop(blob, name, []))
if value is None:
raise ParserError(
'"{}" field must be a string or a list.'.format(name))
return val... | [
"def",
"_extract_optional_list_field",
"(",
"blob",
",",
"name",
")",
":",
"value",
"=",
"_optional_list",
"(",
"typesafe_pop",
"(",
"blob",
",",
"name",
",",
"[",
"]",
")",
")",
"if",
"value",
"is",
"None",
":",
"raise",
"ParserError",
"(",
"'\"{}\" field... | Handle optional fields that can be either a string or a list of
strings. | [
"Handle",
"optional",
"fields",
"that",
"can",
"be",
"either",
"a",
"string",
"or",
"a",
"list",
"of",
"strings",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/parser.py#L135-L142 | train |
buildinspace/peru | peru/async_exit_stack.py | AsyncExitStack.pop_all | def pop_all(self):
"""Preserve the context stack by transferring it to a new instance."""
new_stack = type(self)()
new_stack._exit_callbacks = self._exit_callbacks
self._exit_callbacks = deque()
return new_stack | python | def pop_all(self):
"""Preserve the context stack by transferring it to a new instance."""
new_stack = type(self)()
new_stack._exit_callbacks = self._exit_callbacks
self._exit_callbacks = deque()
return new_stack | [
"def",
"pop_all",
"(",
"self",
")",
":",
"new_stack",
"=",
"type",
"(",
"self",
")",
"(",
")",
"new_stack",
".",
"_exit_callbacks",
"=",
"self",
".",
"_exit_callbacks",
"self",
".",
"_exit_callbacks",
"=",
"deque",
"(",
")",
"return",
"new_stack"
] | Preserve the context stack by transferring it to a new instance. | [
"Preserve",
"the",
"context",
"stack",
"by",
"transferring",
"it",
"to",
"a",
"new",
"instance",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_exit_stack.py#L55-L60 | train |
buildinspace/peru | peru/async_exit_stack.py | AsyncExitStack.callback | def callback(self, callback, *args, **kwds):
"""Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
_exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
# We changed the signature, so using @wraps is not appropriate, but
# setting _... | python | def callback(self, callback, *args, **kwds):
"""Registers an arbitrary callback and arguments.
Cannot suppress exceptions.
"""
_exit_wrapper = self._create_cb_wrapper(callback, *args, **kwds)
# We changed the signature, so using @wraps is not appropriate, but
# setting _... | [
"def",
"callback",
"(",
"self",
",",
"callback",
",",
"*",
"args",
",",
"**",
"kwds",
")",
":",
"_exit_wrapper",
"=",
"self",
".",
"_create_cb_wrapper",
"(",
"callback",
",",
"*",
"args",
",",
"**",
"kwds",
")",
"_exit_wrapper",
".",
"__wrapped__",
"=",
... | Registers an arbitrary callback and arguments.
Cannot suppress exceptions. | [
"Registers",
"an",
"arbitrary",
"callback",
"and",
"arguments",
".",
"Cannot",
"suppress",
"exceptions",
"."
] | 76e4012c6c34e85fb53a4c6d85f4ac3633d93f77 | https://github.com/buildinspace/peru/blob/76e4012c6c34e85fb53a4c6d85f4ac3633d93f77/peru/async_exit_stack.py#L94-L104 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.