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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | install_from_zip | def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
"""Install plugin from zipfile."""
logger.debug("%s is a file, attempting to load zip", pkgpath)
pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
try:
with zipfile.ZipFile(pkgpath) as pkgzip:
pk... | python | def install_from_zip(pkgpath, install_path, register_func, delete_after_install=False):
"""Install plugin from zipfile."""
logger.debug("%s is a file, attempting to load zip", pkgpath)
pkgtempdir = tempfile.mkdtemp(prefix="honeycomb_")
try:
with zipfile.ZipFile(pkgpath) as pkgzip:
pk... | [
"def",
"install_from_zip",
"(",
"pkgpath",
",",
"install_path",
",",
"register_func",
",",
"delete_after_install",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"%s is a file, attempting to load zip\"",
",",
"pkgpath",
")",
"pkgtempdir",
"=",
"tempfile",
".... | Install plugin from zipfile. | [
"Install",
"plugin",
"from",
"zipfile",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L187-L201 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | install_from_repo | def install_from_repo(pkgname, plugin_type, install_path, register_func):
"""Install plugin from online repo."""
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
logger.debug("trying to install %s from online repo", pkgname)
pkgurl = "{}/{}s/{}.zip".format(defs.G... | python | def install_from_repo(pkgname, plugin_type, install_path, register_func):
"""Install plugin from online repo."""
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
logger.debug("trying to install %s from online repo", pkgname)
pkgurl = "{}/{}s/{}.zip".format(defs.G... | [
"def",
"install_from_repo",
"(",
"pkgname",
",",
"plugin_type",
",",
"install_path",
",",
"register_func",
")",
":",
"rsession",
"=",
"requests",
".",
"Session",
"(",
")",
"rsession",
".",
"mount",
"(",
"\"https://\"",
",",
"HTTPAdapter",
"(",
"max_retries",
"... | Install plugin from online repo. | [
"Install",
"plugin",
"from",
"online",
"repo",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L204-L233 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | uninstall_plugin | def uninstall_plugin(pkgpath, force):
"""Uninstall a plugin.
:param pkgpath: Path to package to uninstall (delete)
:param force: Force uninstall without asking
"""
pkgname = os.path.basename(pkgpath)
if os.path.exists(pkgpath):
if not force:
click.confirm("[?] Are you sure y... | python | def uninstall_plugin(pkgpath, force):
"""Uninstall a plugin.
:param pkgpath: Path to package to uninstall (delete)
:param force: Force uninstall without asking
"""
pkgname = os.path.basename(pkgpath)
if os.path.exists(pkgpath):
if not force:
click.confirm("[?] Are you sure y... | [
"def",
"uninstall_plugin",
"(",
"pkgpath",
",",
"force",
")",
":",
"pkgname",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"pkgpath",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"pkgpath",
")",
":",
"if",
"not",
"force",
":",
"click",
".",
"... | Uninstall a plugin.
:param pkgpath: Path to package to uninstall (delete)
:param force: Force uninstall without asking | [
"Uninstall",
"a",
"plugin",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L246-L264 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | list_remote_plugins | def list_remote_plugins(installed_plugins, plugin_type):
"""List remote plugins from online repo."""
click.secho("\n[*] Additional plugins from online repository:")
try:
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
r = rsession.get("{0}/{1}s/{... | python | def list_remote_plugins(installed_plugins, plugin_type):
"""List remote plugins from online repo."""
click.secho("\n[*] Additional plugins from online repository:")
try:
rsession = requests.Session()
rsession.mount("https://", HTTPAdapter(max_retries=3))
r = rsession.get("{0}/{1}s/{... | [
"def",
"list_remote_plugins",
"(",
"installed_plugins",
",",
"plugin_type",
")",
":",
"click",
".",
"secho",
"(",
"\"\\n[*] Additional plugins from online repository:\"",
")",
"try",
":",
"rsession",
"=",
"requests",
".",
"Session",
"(",
")",
"rsession",
".",
"mount... | List remote plugins from online repo. | [
"List",
"remote",
"plugins",
"from",
"online",
"repo",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L267-L281 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | list_local_plugins | def list_local_plugins(plugin_type, plugins_path, plugin_details):
"""List local plugins with details."""
installed_plugins = list()
for plugin in next(os.walk(plugins_path))[1]:
s = plugin_details(plugin)
installed_plugins.append(plugin)
click.secho(s)
if not installed_plugins:... | python | def list_local_plugins(plugin_type, plugins_path, plugin_details):
"""List local plugins with details."""
installed_plugins = list()
for plugin in next(os.walk(plugins_path))[1]:
s = plugin_details(plugin)
installed_plugins.append(plugin)
click.secho(s)
if not installed_plugins:... | [
"def",
"list_local_plugins",
"(",
"plugin_type",
",",
"plugins_path",
",",
"plugin_details",
")",
":",
"installed_plugins",
"=",
"list",
"(",
")",
"for",
"plugin",
"in",
"next",
"(",
"os",
".",
"walk",
"(",
"plugins_path",
")",
")",
"[",
"1",
"]",
":",
"... | List local plugins with details. | [
"List",
"local",
"plugins",
"with",
"details",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L284-L296 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | parse_plugin_args | def parse_plugin_args(command_args, config_args):
"""Parse command line arguments based on the plugin's parameters config.
:param command_args: Command line arguments as provided by the user in `key=value` format.
:param config_args: Plugin parameters parsed from config.json.
:returns: Validated dicti... | python | def parse_plugin_args(command_args, config_args):
"""Parse command line arguments based on the plugin's parameters config.
:param command_args: Command line arguments as provided by the user in `key=value` format.
:param config_args: Plugin parameters parsed from config.json.
:returns: Validated dicti... | [
"def",
"parse_plugin_args",
"(",
"command_args",
",",
"config_args",
")",
":",
"parsed_args",
"=",
"dict",
"(",
")",
"for",
"arg",
"in",
"command_args",
":",
"kv",
"=",
"arg",
".",
"split",
"(",
"\"=\"",
")",
"if",
"len",
"(",
"kv",
")",
"!=",
"2",
"... | Parse command line arguments based on the plugin's parameters config.
:param command_args: Command line arguments as provided by the user in `key=value` format.
:param config_args: Plugin parameters parsed from config.json.
:returns: Validated dictionary of parameters that will be passed to plugin class | [
"Parse",
"command",
"line",
"arguments",
"based",
"on",
"the",
"plugin",
"s",
"parameters",
"config",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L299-L327 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | get_select_items | def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldError... | python | def get_select_items(items):
"""Return list of possible select items."""
option_items = list()
for item in items:
if isinstance(item, dict) and defs.VALUE in item and defs.LABEL in item:
option_items.append(item[defs.VALUE])
else:
raise exceptions.ParametersFieldError... | [
"def",
"get_select_items",
"(",
"items",
")",
":",
"option_items",
"=",
"list",
"(",
")",
"for",
"item",
"in",
"items",
":",
"if",
"isinstance",
"(",
"item",
",",
"dict",
")",
"and",
"defs",
".",
"VALUE",
"in",
"item",
"and",
"defs",
".",
"LABEL",
"i... | Return list of possible select items. | [
"Return",
"list",
"of",
"possible",
"select",
"items",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L330-L339 | train |
Cymmetria/honeycomb | honeycomb/utils/plugin_utils.py | print_plugin_args | def print_plugin_args(plugin_path):
"""Print plugin parameters table."""
args = config_utils.get_config_parameters(plugin_path)
args_format = "{:20} {:10} {:^15} {:^10} {:25}"
title = args_format.format(defs.NAME.upper(), defs.TYPE.upper(), defs.DEFAULT.upper(),
defs.REQUI... | python | def print_plugin_args(plugin_path):
"""Print plugin parameters table."""
args = config_utils.get_config_parameters(plugin_path)
args_format = "{:20} {:10} {:^15} {:^10} {:25}"
title = args_format.format(defs.NAME.upper(), defs.TYPE.upper(), defs.DEFAULT.upper(),
defs.REQUI... | [
"def",
"print_plugin_args",
"(",
"plugin_path",
")",
":",
"args",
"=",
"config_utils",
".",
"get_config_parameters",
"(",
"plugin_path",
")",
"args_format",
"=",
"\"{:20} {:10} {:^15} {:^10} {:25}\"",
"title",
"=",
"args_format",
".",
"format",
"(",
"defs",
".",
"NA... | Print plugin parameters table. | [
"Print",
"plugin",
"parameters",
"table",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/plugin_utils.py#L354-L367 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | configure_integration | def configure_integration(path):
"""Configure and enable an integration."""
integration = register_integration(path)
integration_args = {}
try:
with open(os.path.join(path, ARGS_JSON)) as f:
integration_args = json.loads(f.read())
except Exception as exc:
logger.debug(str... | python | def configure_integration(path):
"""Configure and enable an integration."""
integration = register_integration(path)
integration_args = {}
try:
with open(os.path.join(path, ARGS_JSON)) as f:
integration_args = json.loads(f.read())
except Exception as exc:
logger.debug(str... | [
"def",
"configure_integration",
"(",
"path",
")",
":",
"integration",
"=",
"register_integration",
"(",
"path",
")",
"integration_args",
"=",
"{",
"}",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"ARGS_JSON",
")",
"... | Configure and enable an integration. | [
"Configure",
"and",
"enable",
"an",
"integration",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L39-L58 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | send_alert_to_subscribed_integrations | def send_alert_to_subscribed_integrations(alert):
"""Send Alert to relevant integrations."""
valid_configured_integrations = get_valid_configured_integrations(alert)
for configured_integration in valid_configured_integrations:
threading.Thread(target=create_integration_alert_and_call_send, args=(al... | python | def send_alert_to_subscribed_integrations(alert):
"""Send Alert to relevant integrations."""
valid_configured_integrations = get_valid_configured_integrations(alert)
for configured_integration in valid_configured_integrations:
threading.Thread(target=create_integration_alert_and_call_send, args=(al... | [
"def",
"send_alert_to_subscribed_integrations",
"(",
"alert",
")",
":",
"valid_configured_integrations",
"=",
"get_valid_configured_integrations",
"(",
"alert",
")",
"for",
"configured_integration",
"in",
"valid_configured_integrations",
":",
"threading",
".",
"Thread",
"(",
... | Send Alert to relevant integrations. | [
"Send",
"Alert",
"to",
"relevant",
"integrations",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L61-L66 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | get_valid_configured_integrations | def get_valid_configured_integrations(alert):
"""Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations
"""
if not configured_integrations:
return []
# Collect all integrations that are configured for specific alert_type
# or have no s... | python | def get_valid_configured_integrations(alert):
"""Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations
"""
if not configured_integrations:
return []
# Collect all integrations that are configured for specific alert_type
# or have no s... | [
"def",
"get_valid_configured_integrations",
"(",
"alert",
")",
":",
"if",
"not",
"configured_integrations",
":",
"return",
"[",
"]",
"# Collect all integrations that are configured for specific alert_type",
"# or have no specific supported_event_types (i.e., all alert types)",
"valid_c... | Return a list of integrations for alert filtered by alert_type.
:returns: A list of relevant integrations | [
"Return",
"a",
"list",
"of",
"integrations",
"for",
"alert",
"filtered",
"by",
"alert_type",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L74-L89 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | create_integration_alert_and_call_send | def create_integration_alert_and_call_send(alert, configured_integration):
"""Create an IntegrationAlert object and send it to Integration."""
integration_alert = IntegrationAlert(
alert=alert,
configured_integration=configured_integration,
status=IntegrationAlertStatuses.PENDING.name,
... | python | def create_integration_alert_and_call_send(alert, configured_integration):
"""Create an IntegrationAlert object and send it to Integration."""
integration_alert = IntegrationAlert(
alert=alert,
configured_integration=configured_integration,
status=IntegrationAlertStatuses.PENDING.name,
... | [
"def",
"create_integration_alert_and_call_send",
"(",
"alert",
",",
"configured_integration",
")",
":",
"integration_alert",
"=",
"IntegrationAlert",
"(",
"alert",
"=",
"alert",
",",
"configured_integration",
"=",
"configured_integration",
",",
"status",
"=",
"Integration... | Create an IntegrationAlert object and send it to Integration. | [
"Create",
"an",
"IntegrationAlert",
"object",
"and",
"send",
"it",
"to",
"Integration",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L92-L101 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | send_alert_to_configured_integration | def send_alert_to_configured_integration(integration_alert):
"""Send IntegrationAlert to configured integration."""
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_... | python | def send_alert_to_configured_integration(integration_alert):
"""Send IntegrationAlert to configured integration."""
try:
alert = integration_alert.alert
configured_integration = integration_alert.configured_integration
integration = configured_integration.integration
integration_... | [
"def",
"send_alert_to_configured_integration",
"(",
"integration_alert",
")",
":",
"try",
":",
"alert",
"=",
"integration_alert",
".",
"alert",
"configured_integration",
"=",
"integration_alert",
".",
"configured_integration",
"integration",
"=",
"configured_integration",
"... | Send IntegrationAlert to configured integration. | [
"Send",
"IntegrationAlert",
"to",
"configured",
"integration",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L104-L167 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/tasks.py | poll_integration_alert_data | def poll_integration_alert_data(integration_alert):
"""Poll for updates on waiting IntegrationAlerts."""
logger.info("Polling information for integration alert %s", integration_alert)
try:
configured_integration = integration_alert.configured_integration
integration_actions_instance = config... | python | def poll_integration_alert_data(integration_alert):
"""Poll for updates on waiting IntegrationAlerts."""
logger.info("Polling information for integration alert %s", integration_alert)
try:
configured_integration = integration_alert.configured_integration
integration_actions_instance = config... | [
"def",
"poll_integration_alert_data",
"(",
"integration_alert",
")",
":",
"logger",
".",
"info",
"(",
"\"Polling information for integration alert %s\"",
",",
"integration_alert",
")",
"try",
":",
"configured_integration",
"=",
"integration_alert",
".",
"configured_integratio... | Poll for updates on waiting IntegrationAlerts. | [
"Poll",
"for",
"updates",
"on",
"waiting",
"IntegrationAlerts",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/tasks.py#L191-L223 | train |
Cymmetria/honeycomb | honeycomb/utils/wait.py | wait_until | def wait_until(func,
check_return_value=True,
total_timeout=60,
interval=0.5,
exc_list=None,
error_message="",
*args,
**kwargs):
"""Run a command in a loop until desired result or timeout occurs.
:param fun... | python | def wait_until(func,
check_return_value=True,
total_timeout=60,
interval=0.5,
exc_list=None,
error_message="",
*args,
**kwargs):
"""Run a command in a loop until desired result or timeout occurs.
:param fun... | [
"def",
"wait_until",
"(",
"func",
",",
"check_return_value",
"=",
"True",
",",
"total_timeout",
"=",
"60",
",",
"interval",
"=",
"0.5",
",",
"exc_list",
"=",
"None",
",",
"error_message",
"=",
"\"\"",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":"... | Run a command in a loop until desired result or timeout occurs.
:param func: Function to call and wait for
:param bool check_return_value: Examine return value
:param int total_timeout: Wait timeout,
:param float interval: Sleep interval between retries
:param list exc_list: Acceptable exception li... | [
"Run",
"a",
"command",
"in",
"a",
"loop",
"until",
"desired",
"result",
"or",
"timeout",
"occurs",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/wait.py#L19-L55 | train |
Cymmetria/honeycomb | honeycomb/utils/wait.py | search_json_log | def search_json_log(filepath, key, value):
"""Search json log file for a key=value pair.
:param filepath: Valid path to a json file
:param key: key to match
:param value: value to match
:returns: First matching line in json log file, parsed by :py:func:`json.loads`
"""
try:
with ope... | python | def search_json_log(filepath, key, value):
"""Search json log file for a key=value pair.
:param filepath: Valid path to a json file
:param key: key to match
:param value: value to match
:returns: First matching line in json log file, parsed by :py:func:`json.loads`
"""
try:
with ope... | [
"def",
"search_json_log",
"(",
"filepath",
",",
"key",
",",
"value",
")",
":",
"try",
":",
"with",
"open",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
"fh",
":",
"for",
"line",
"in",
"fh",
".",
"readlines",
"(",
")",
":",
"log",
"=",
"json",
".",
"... | Search json log file for a key=value pair.
:param filepath: Valid path to a json file
:param key: key to match
:param value: value to match
:returns: First matching line in json log file, parsed by :py:func:`json.loads` | [
"Search",
"json",
"log",
"file",
"for",
"a",
"key",
"=",
"value",
"pair",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/utils/wait.py#L58-L74 | train |
Cymmetria/honeycomb | honeycomb/commands/__init__.py | MyGroup.list_commands | def list_commands(self, ctx):
"""List commands from folder."""
rv = []
files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith("_") and _.endswith(".py")]
for filename in files:
rv.append(filename[:-3])
rv.sort()
return rv | python | def list_commands(self, ctx):
"""List commands from folder."""
rv = []
files = [_ for _ in next(os.walk(self.folder))[2] if not _.startswith("_") and _.endswith(".py")]
for filename in files:
rv.append(filename[:-3])
rv.sort()
return rv | [
"def",
"list_commands",
"(",
"self",
",",
"ctx",
")",
":",
"rv",
"=",
"[",
"]",
"files",
"=",
"[",
"_",
"for",
"_",
"in",
"next",
"(",
"os",
".",
"walk",
"(",
"self",
".",
"folder",
")",
")",
"[",
"2",
"]",
"if",
"not",
"_",
".",
"startswith"... | List commands from folder. | [
"List",
"commands",
"from",
"folder",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/__init__.py#L27-L34 | train |
Cymmetria/honeycomb | honeycomb/commands/__init__.py | MyGroup.get_command | def get_command(self, ctx, name):
"""Fetch command from folder."""
plugin = os.path.basename(self.folder)
try:
command = importlib.import_module("honeycomb.commands.{}.{}".format(plugin, name))
except ImportError:
raise click.UsageError("No such command {} {}\n\n{... | python | def get_command(self, ctx, name):
"""Fetch command from folder."""
plugin = os.path.basename(self.folder)
try:
command = importlib.import_module("honeycomb.commands.{}.{}".format(plugin, name))
except ImportError:
raise click.UsageError("No such command {} {}\n\n{... | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"name",
")",
":",
"plugin",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"self",
".",
"folder",
")",
"try",
":",
"command",
"=",
"importlib",
".",
"import_module",
"(",
"\"honeycomb.commands.{}.{}\"",
... | Fetch command from folder. | [
"Fetch",
"command",
"from",
"folder",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/__init__.py#L36-L43 | train |
Cymmetria/honeycomb | honeycomb/cli.py | cli | def cli(ctx, home, iamroot, config, verbose):
"""Honeycomb is a honeypot framework."""
_mkhome(home)
setup_logging(home, verbose)
logger.debug("Honeycomb v%s", __version__, extra={"version": __version__})
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={... | python | def cli(ctx, home, iamroot, config, verbose):
"""Honeycomb is a honeypot framework."""
_mkhome(home)
setup_logging(home, verbose)
logger.debug("Honeycomb v%s", __version__, extra={"version": __version__})
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={... | [
"def",
"cli",
"(",
"ctx",
",",
"home",
",",
"iamroot",
",",
"config",
",",
"verbose",
")",
":",
"_mkhome",
"(",
"home",
")",
"setup_logging",
"(",
"home",
",",
"verbose",
")",
"logger",
".",
"debug",
"(",
"\"Honeycomb v%s\"",
",",
"__version__",
",",
"... | Honeycomb is a honeypot framework. | [
"Honeycomb",
"is",
"a",
"honeypot",
"framework",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L40-L66 | train |
Cymmetria/honeycomb | honeycomb/cli.py | setup_logging | def setup_logging(home, verbose):
"""Configure logging for honeycomb."""
logging.setLoggerClass(MyLogger)
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(levelname)-8s [%(asctime)s %(na... | python | def setup_logging(home, verbose):
"""Configure logging for honeycomb."""
logging.setLoggerClass(MyLogger)
logging.config.dictConfig({
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"console": {
"format": "%(levelname)-8s [%(asctime)s %(na... | [
"def",
"setup_logging",
"(",
"home",
",",
"verbose",
")",
":",
"logging",
".",
"setLoggerClass",
"(",
"MyLogger",
")",
"logging",
".",
"config",
".",
"dictConfig",
"(",
"{",
"\"version\"",
":",
"1",
",",
"\"disable_existing_loggers\"",
":",
"False",
",",
"\"... | Configure logging for honeycomb. | [
"Configure",
"logging",
"for",
"honeycomb",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L91-L126 | train |
Cymmetria/honeycomb | honeycomb/cli.py | MyLogger.makeRecord | def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
"""Override default logger to allow overriding of internal attributes."""
# See below commented section for a simple example of what the docstring refers to
if six.PY2:
rv = logging.Lo... | python | def makeRecord(self, name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None):
"""Override default logger to allow overriding of internal attributes."""
# See below commented section for a simple example of what the docstring refers to
if six.PY2:
rv = logging.Lo... | [
"def",
"makeRecord",
"(",
"self",
",",
"name",
",",
"level",
",",
"fn",
",",
"lno",
",",
"msg",
",",
"args",
",",
"exc_info",
",",
"func",
"=",
"None",
",",
"extra",
"=",
"None",
",",
"sinfo",
"=",
"None",
")",
":",
"# See below commented section for a... | Override default logger to allow overriding of internal attributes. | [
"Override",
"default",
"logger",
"to",
"allow",
"overriding",
"of",
"internal",
"attributes",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/cli.py#L72-L88 | train |
Cymmetria/honeycomb | honeycomb/commands/service/stop.py | stop | def stop(ctx, service, editable):
"""Stop a running service daemon."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, ser... | python | def stop(ctx, service, editable):
"""Stop a running service daemon."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, ser... | [
"def",
"stop",
"(",
"ctx",
",",
"service",
",",
"editable",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\"command\"",
":",
"ctx",
"."... | Stop a running service daemon. | [
"Stop",
"a",
"running",
"service",
"daemon",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/stop.py#L24-L57 | train |
Cymmetria/honeycomb | honeycomb/commands/service/logs.py | logs | def logs(ctx, services, num, follow):
"""Show logs of daemonized service."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
services_path = os.path.join(home, SERVICES)
tail_th... | python | def logs(ctx, services, num, follow):
"""Show logs of daemonized service."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
services_path = os.path.join(home, SERVICES)
tail_th... | [
"def",
"logs",
"(",
"ctx",
",",
"services",
",",
"num",
",",
"follow",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\"command\"",
":",... | Show logs of daemonized service. | [
"Show",
"logs",
"of",
"daemonized",
"service",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/logs.py#L22-L46 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/registration.py | get_integration_module | def get_integration_module(integration_path):
"""Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder
"""
# add custom paths so imports would work
paths = [
os.path.join(__file__, "..", ".."), # to import integrationmanager
os.p... | python | def get_integration_module(integration_path):
"""Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder
"""
# add custom paths so imports would work
paths = [
os.path.join(__file__, "..", ".."), # to import integrationmanager
os.p... | [
"def",
"get_integration_module",
"(",
"integration_path",
")",
":",
"# add custom paths so imports would work",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"__file__",
",",
"\"..\"",
",",
"\"..\"",
")",
",",
"# to import integrationmanager",
"os",
".",
... | Add custom paths to sys and import integration module.
:param integration_path: Path to integration folder | [
"Add",
"custom",
"paths",
"to",
"sys",
"and",
"import",
"integration",
"module",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/registration.py#L25-L45 | train |
Cymmetria/honeycomb | honeycomb/integrationmanager/registration.py | register_integration | def register_integration(package_folder):
"""Register a honeycomb integration.
:param package_folder: Path to folder with integration to load
:returns: Validated integration object
:rtype: :func:`honeycomb.utils.defs.Integration`
"""
logger.debug("registering integration %s", package_folder)
... | python | def register_integration(package_folder):
"""Register a honeycomb integration.
:param package_folder: Path to folder with integration to load
:returns: Validated integration object
:rtype: :func:`honeycomb.utils.defs.Integration`
"""
logger.debug("registering integration %s", package_folder)
... | [
"def",
"register_integration",
"(",
"package_folder",
")",
":",
"logger",
".",
"debug",
"(",
"\"registering integration %s\"",
",",
"package_folder",
")",
"package_folder",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"package_folder",
")",
"if",
"not",
"os",
"... | Register a honeycomb integration.
:param package_folder: Path to folder with integration to load
:returns: Validated integration object
:rtype: :func:`honeycomb.utils.defs.Integration` | [
"Register",
"a",
"honeycomb",
"integration",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/integrationmanager/registration.py#L48-L75 | train |
Cymmetria/honeycomb | honeycomb/commands/integration/list.py | list | def list(ctx, remote):
"""List integrations."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
click.secho("[*] Installed integrations:")
home = ctx.obj["HOME"]
integrations_path = os.path.join(home, ... | python | def list(ctx, remote):
"""List integrations."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
click.secho("[*] Installed integrations:")
home = ctx.obj["HOME"]
integrations_path = os.path.join(home, ... | [
"def",
"list",
"(",
"ctx",
",",
"remote",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\"command\"",
":",
"ctx",
".",
"command",
".",
... | List integrations. | [
"List",
"integrations",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/list.py#L20-L46 | train |
Cymmetria/honeycomb | honeycomb/commands/service/run.py | run | def run(ctx, service, args, show_args, daemon, editable, integration):
"""Load and run a specific service."""
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, service, editable)
service_log_path = os.path.join(service_path, LOGS_DIR)
logger.debug("running command %... | python | def run(ctx, service, args, show_args, daemon, editable, integration):
"""Load and run a specific service."""
home = ctx.obj["HOME"]
service_path = plugin_utils.get_plugin_path(home, SERVICES, service, editable)
service_log_path = os.path.join(service_path, LOGS_DIR)
logger.debug("running command %... | [
"def",
"run",
"(",
"ctx",
",",
"service",
",",
"args",
",",
"show_args",
",",
"daemon",
",",
"editable",
",",
"integration",
")",
":",
"home",
"=",
"ctx",
".",
"obj",
"[",
"\"HOME\"",
"]",
"service_path",
"=",
"plugin_utils",
".",
"get_plugin_path",
"(",... | Load and run a specific service. | [
"Load",
"and",
"run",
"a",
"specific",
"service",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/run.py#L30-L88 | train |
Cymmetria/honeycomb | honeycomb/servicemanager/base_service.py | DockerService.read_lines | def read_lines(self, file_path, empty_lines=False, signal_ready=True):
"""Fetch lines from file.
In case the file handler changes (logrotate), reopen the file.
:param file_path: Path to file
:param empty_lines: Return empty lines
:param signal_ready: Report signal ready on star... | python | def read_lines(self, file_path, empty_lines=False, signal_ready=True):
"""Fetch lines from file.
In case the file handler changes (logrotate), reopen the file.
:param file_path: Path to file
:param empty_lines: Return empty lines
:param signal_ready: Report signal ready on star... | [
"def",
"read_lines",
"(",
"self",
",",
"file_path",
",",
"empty_lines",
"=",
"False",
",",
"signal_ready",
"=",
"True",
")",
":",
"file_handler",
",",
"file_id",
"=",
"self",
".",
"_get_file",
"(",
"file_path",
")",
"file_handler",
".",
"seek",
"(",
"0",
... | Fetch lines from file.
In case the file handler changes (logrotate), reopen the file.
:param file_path: Path to file
:param empty_lines: Return empty lines
:param signal_ready: Report signal ready on start | [
"Fetch",
"lines",
"from",
"file",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L171-L197 | train |
Cymmetria/honeycomb | honeycomb/servicemanager/base_service.py | DockerService.on_server_start | def on_server_start(self):
"""Service run loop function.
Run the desired docker container with parameters and start parsing the monitored file for alerts.
"""
self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params)
self.sig... | python | def on_server_start(self):
"""Service run loop function.
Run the desired docker container with parameters and start parsing the monitored file for alerts.
"""
self._container = self._docker_client.containers.run(self.docker_image_name, detach=True, **self.docker_params)
self.sig... | [
"def",
"on_server_start",
"(",
"self",
")",
":",
"self",
".",
"_container",
"=",
"self",
".",
"_docker_client",
".",
"containers",
".",
"run",
"(",
"self",
".",
"docker_image_name",
",",
"detach",
"=",
"True",
",",
"*",
"*",
"self",
".",
"docker_params",
... | Service run loop function.
Run the desired docker container with parameters and start parsing the monitored file for alerts. | [
"Service",
"run",
"loop",
"function",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L212-L226 | train |
Cymmetria/honeycomb | honeycomb/servicemanager/base_service.py | DockerService.on_server_shutdown | def on_server_shutdown(self):
"""Stop the container before shutting down."""
if not self._container:
return
self._container.stop()
self._container.remove(v=True, force=True) | python | def on_server_shutdown(self):
"""Stop the container before shutting down."""
if not self._container:
return
self._container.stop()
self._container.remove(v=True, force=True) | [
"def",
"on_server_shutdown",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_container",
":",
"return",
"self",
".",
"_container",
".",
"stop",
"(",
")",
"self",
".",
"_container",
".",
"remove",
"(",
"v",
"=",
"True",
",",
"force",
"=",
"True",
"... | Stop the container before shutting down. | [
"Stop",
"the",
"container",
"before",
"shutting",
"down",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/base_service.py#L228-L233 | train |
Cymmetria/honeycomb | honeycomb/commands/integration/uninstall.py | uninstall | def uninstall(ctx, yes, integrations):
"""Uninstall a integration."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for integration in integrations:
integration_path = plu... | python | def uninstall(ctx, yes, integrations):
"""Uninstall a integration."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for integration in integrations:
integration_path = plu... | [
"def",
"uninstall",
"(",
"ctx",
",",
"yes",
",",
"integrations",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\"command\"",
":",
"ctx",
... | Uninstall a integration. | [
"Uninstall",
"a",
"integration",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/uninstall.py#L18-L27 | train |
Cymmetria/honeycomb | honeycomb/commands/service/install.py | install | def install(ctx, services, delete_after_install=False):
"""Install a honeypot service from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
... | python | def install(ctx, services, delete_after_install=False):
"""Install a honeypot service from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
... | [
"def",
"install",
"(",
"ctx",
",",
"services",
",",
"delete_after_install",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\... | Install a honeypot service from the online library, local path or zipfile. | [
"Install",
"a",
"honeypot",
"service",
"from",
"the",
"online",
"library",
"local",
"path",
"or",
"zipfile",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/install.py#L21-L38 | train |
Cymmetria/honeycomb | honeycomb/commands/service/uninstall.py | uninstall | def uninstall(ctx, yes, services):
"""Uninstall a service."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for service in services:
service_path = plugin_utils.get_plugin... | python | def uninstall(ctx, yes, services):
"""Uninstall a service."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj["HOME"]
for service in services:
service_path = plugin_utils.get_plugin... | [
"def",
"uninstall",
"(",
"ctx",
",",
"yes",
",",
"services",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
"\"command\"",
":",
"ctx",
".... | Uninstall a service. | [
"Uninstall",
"a",
"service",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/service/uninstall.py#L18-L27 | train |
Cymmetria/honeycomb | honeycomb/servicemanager/registration.py | get_service_module | def get_service_module(service_path):
"""Add custom paths to sys and import service module.
:param service_path: Path to service folder
"""
# add custom paths so imports would work
paths = [
os.path.dirname(__file__), # this folder, to catch base_service
os.path.realpath(os.path.jo... | python | def get_service_module(service_path):
"""Add custom paths to sys and import service module.
:param service_path: Path to service folder
"""
# add custom paths so imports would work
paths = [
os.path.dirname(__file__), # this folder, to catch base_service
os.path.realpath(os.path.jo... | [
"def",
"get_service_module",
"(",
"service_path",
")",
":",
"# add custom paths so imports would work",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"# this folder, to catch base_service",
"os",
".",
"path",
".",
"realpath",
"(",
... | Add custom paths to sys and import service module.
:param service_path: Path to service folder | [
"Add",
"custom",
"paths",
"to",
"sys",
"and",
"import",
"service",
"module",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/registration.py#L26-L48 | train |
Cymmetria/honeycomb | honeycomb/servicemanager/registration.py | register_service | def register_service(package_folder):
"""Register a honeycomb service.
:param package_folder: Path to folder with service to load
:returns: Validated service object
:rtype: :func:`honeycomb.utils.defs.ServiceType`
"""
logger.debug("registering service %s", package_folder)
package_folder = o... | python | def register_service(package_folder):
"""Register a honeycomb service.
:param package_folder: Path to folder with service to load
:returns: Validated service object
:rtype: :func:`honeycomb.utils.defs.ServiceType`
"""
logger.debug("registering service %s", package_folder)
package_folder = o... | [
"def",
"register_service",
"(",
"package_folder",
")",
":",
"logger",
".",
"debug",
"(",
"\"registering service %s\"",
",",
"package_folder",
")",
"package_folder",
"=",
"os",
".",
"path",
".",
"realpath",
"(",
"package_folder",
")",
"if",
"not",
"os",
".",
"p... | Register a honeycomb service.
:param package_folder: Path to folder with service to load
:returns: Validated service object
:rtype: :func:`honeycomb.utils.defs.ServiceType` | [
"Register",
"a",
"honeycomb",
"service",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/servicemanager/registration.py#L51-L84 | train |
Cymmetria/honeycomb | honeycomb/commands/integration/install.py | install | def install(ctx, integrations, delete_after_install=False):
"""Install a honeycomb integration from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj[... | python | def install(ctx, integrations, delete_after_install=False):
"""Install a honeycomb integration from the online library, local path or zipfile."""
logger.debug("running command %s (%s)", ctx.command.name, ctx.params,
extra={"command": ctx.command.name, "params": ctx.params})
home = ctx.obj[... | [
"def",
"install",
"(",
"ctx",
",",
"integrations",
",",
"delete_after_install",
"=",
"False",
")",
":",
"logger",
".",
"debug",
"(",
"\"running command %s (%s)\"",
",",
"ctx",
".",
"command",
".",
"name",
",",
"ctx",
".",
"params",
",",
"extra",
"=",
"{",
... | Install a honeycomb integration from the online library, local path or zipfile. | [
"Install",
"a",
"honeycomb",
"integration",
"from",
"the",
"online",
"library",
"local",
"path",
"or",
"zipfile",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/install.py#L21-L38 | train |
Cymmetria/honeycomb | honeycomb/commands/integration/configure.py | configure | def configure(ctx, integration, args, show_args, editable):
"""Configure an integration with default parameters.
You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required.
"""
home = ctx.obj["HOME"]
integration_path = plugin_utils.get_plugin_path(home... | python | def configure(ctx, integration, args, show_args, editable):
"""Configure an integration with default parameters.
You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required.
"""
home = ctx.obj["HOME"]
integration_path = plugin_utils.get_plugin_path(home... | [
"def",
"configure",
"(",
"ctx",
",",
"integration",
",",
"args",
",",
"show_args",
",",
"editable",
")",
":",
"home",
"=",
"ctx",
".",
"obj",
"[",
"\"HOME\"",
"]",
"integration_path",
"=",
"plugin_utils",
".",
"get_plugin_path",
"(",
"home",
",",
"defs",
... | Configure an integration with default parameters.
You can still provide one-off integration arguments to :func:`honeycomb.commands.service.run` if required. | [
"Configure",
"an",
"integration",
"with",
"default",
"parameters",
"."
] | 33ea91b5cf675000e4e85dd02efe580ea6e95c86 | https://github.com/Cymmetria/honeycomb/blob/33ea91b5cf675000e4e85dd02efe580ea6e95c86/honeycomb/commands/integration/configure.py#L24-L51 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_match_history | def get_match_history(self, account_id=None, **kwargs):
"""Returns a dictionary containing a list of the most recent Dota matches
:param account_id: (int, optional)
:param hero_id: (int, optional)
:param game_mode: (int, optional) see ``ref/modes.json``
:param skill: (int, optio... | python | def get_match_history(self, account_id=None, **kwargs):
"""Returns a dictionary containing a list of the most recent Dota matches
:param account_id: (int, optional)
:param hero_id: (int, optional)
:param game_mode: (int, optional) see ``ref/modes.json``
:param skill: (int, optio... | [
"def",
"get_match_history",
"(",
"self",
",",
"account_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'account_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'account_id'",
"]",
"=",
"account_id",
"url",
"=",
"self",
".",
"__build_url",
"... | Returns a dictionary containing a list of the most recent Dota matches
:param account_id: (int, optional)
:param hero_id: (int, optional)
:param game_mode: (int, optional) see ``ref/modes.json``
:param skill: (int, optional) see ``ref/skill.json``
:param min_players: (int, optio... | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"list",
"of",
"the",
"most",
"recent",
"Dota",
"matches"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L66-L90 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_match_history_by_seq_num | def get_match_history_by_seq_num(self, start_at_match_seq_num=None, **kwargs):
"""Returns a dictionary containing a list of Dota matches in the order they were recorded
:param start_at_match_seq_num: (int, optional) start at matches equal to or
older than this match id
:param matche... | python | def get_match_history_by_seq_num(self, start_at_match_seq_num=None, **kwargs):
"""Returns a dictionary containing a list of Dota matches in the order they were recorded
:param start_at_match_seq_num: (int, optional) start at matches equal to or
older than this match id
:param matche... | [
"def",
"get_match_history_by_seq_num",
"(",
"self",
",",
"start_at_match_seq_num",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'start_at_match_seq_num'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'start_at_match_seq_num'",
"]",
"=",
"start_at_match_seq_... | Returns a dictionary containing a list of Dota matches in the order they were recorded
:param start_at_match_seq_num: (int, optional) start at matches equal to or
older than this match id
:param matches_requested: (int, optional) defaults to ``100``
:return: dictionary of matches, s... | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"list",
"of",
"Dota",
"matches",
"in",
"the",
"order",
"they",
"were",
"recorded"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L92-L107 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_match_details | def get_match_details(self, match_id=None, **kwargs):
"""Returns a dictionary containing the details for a Dota 2 match
:param match_id: (int, optional)
:return: dictionary of matches, see :doc:`responses </responses>`
"""
if 'match_id' not in kwargs:
kwargs['match_i... | python | def get_match_details(self, match_id=None, **kwargs):
"""Returns a dictionary containing the details for a Dota 2 match
:param match_id: (int, optional)
:return: dictionary of matches, see :doc:`responses </responses>`
"""
if 'match_id' not in kwargs:
kwargs['match_i... | [
"def",
"get_match_details",
"(",
"self",
",",
"match_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'match_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'match_id'",
"]",
"=",
"match_id",
"url",
"=",
"self",
".",
"__build_url",
"(",
"u... | Returns a dictionary containing the details for a Dota 2 match
:param match_id: (int, optional)
:return: dictionary of matches, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"containing",
"the",
"details",
"for",
"a",
"Dota",
"2",
"match"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L109-L122 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_league_listing | def get_league_listing(self):
"""Returns a dictionary containing a list of all ticketed leagues
:return: dictionary of ticketed leagues, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_LEAGUE_LISTING)
req = self.executor(url)
if self.logger:
... | python | def get_league_listing(self):
"""Returns a dictionary containing a list of all ticketed leagues
:return: dictionary of ticketed leagues, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_LEAGUE_LISTING)
req = self.executor(url)
if self.logger:
... | [
"def",
"get_league_listing",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"__build_url",
"(",
"urls",
".",
"GET_LEAGUE_LISTING",
")",
"req",
"=",
"self",
".",
"executor",
"(",
"url",
")",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",... | Returns a dictionary containing a list of all ticketed leagues
:return: dictionary of ticketed leagues, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"list",
"of",
"all",
"ticketed",
"leagues"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L124-L134 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_live_league_games | def get_live_league_games(self):
"""Returns a dictionary containing a list of ticked games in progress
:return: dictionary of live games, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES)
req = self.executor(url)
if self.logger:
... | python | def get_live_league_games(self):
"""Returns a dictionary containing a list of ticked games in progress
:return: dictionary of live games, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_LIVE_LEAGUE_GAMES)
req = self.executor(url)
if self.logger:
... | [
"def",
"get_live_league_games",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"__build_url",
"(",
"urls",
".",
"GET_LIVE_LEAGUE_GAMES",
")",
"req",
"=",
"self",
".",
"executor",
"(",
"url",
")",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
... | Returns a dictionary containing a list of ticked games in progress
:return: dictionary of live games, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"list",
"of",
"ticked",
"games",
"in",
"progress"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L136-L146 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_team_info_by_team_id | def get_team_info_by_team_id(self, start_at_team_id=None, **kwargs):
"""Returns a dictionary containing a in-game teams
:param start_at_team_id: (int, optional)
:param teams_requested: (int, optional)
:return: dictionary of teams, see :doc:`responses </responses>`
"""
if... | python | def get_team_info_by_team_id(self, start_at_team_id=None, **kwargs):
"""Returns a dictionary containing a in-game teams
:param start_at_team_id: (int, optional)
:param teams_requested: (int, optional)
:return: dictionary of teams, see :doc:`responses </responses>`
"""
if... | [
"def",
"get_team_info_by_team_id",
"(",
"self",
",",
"start_at_team_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'start_at_team_id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'start_at_team_id'",
"]",
"=",
"start_at_team_id",
"url",
"=",
"sel... | Returns a dictionary containing a in-game teams
:param start_at_team_id: (int, optional)
:param teams_requested: (int, optional)
:return: dictionary of teams, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"in",
"-",
"game",
"teams"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L148-L162 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_player_summaries | def get_player_summaries(self, steamids=None, **kwargs):
"""Returns a dictionary containing a player summaries
:param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice
that api will convert if ``32-bit`` are given
:return: dictionary of player s... | python | def get_player_summaries(self, steamids=None, **kwargs):
"""Returns a dictionary containing a player summaries
:param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice
that api will convert if ``32-bit`` are given
:return: dictionary of player s... | [
"def",
"get_player_summaries",
"(",
"self",
",",
"steamids",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"steamids",
",",
"collections",
".",
"Iterable",
")",
":",
"steamids",
"=",
"[",
"steamids",
"]",
"base64_ids",
"... | Returns a dictionary containing a player summaries
:param steamids: (list) list of ``32-bit`` or ``64-bit`` steam ids, notice
that api will convert if ``32-bit`` are given
:return: dictionary of player summaries, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"containing",
"a",
"player",
"summaries"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L164-L183 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_heroes | def get_heroes(self, **kwargs):
"""Returns a dictionary of in-game heroes, used to parse ids into localised names
:return: dictionary of heroes, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_HEROES, language=self.language, **kwargs)
req = self.executor(ur... | python | def get_heroes(self, **kwargs):
"""Returns a dictionary of in-game heroes, used to parse ids into localised names
:return: dictionary of heroes, see :doc:`responses </responses>`
"""
url = self.__build_url(urls.GET_HEROES, language=self.language, **kwargs)
req = self.executor(ur... | [
"def",
"get_heroes",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"__build_url",
"(",
"urls",
".",
"GET_HEROES",
",",
"language",
"=",
"self",
".",
"language",
",",
"*",
"*",
"kwargs",
")",
"req",
"=",
"self",
".",
"exec... | Returns a dictionary of in-game heroes, used to parse ids into localised names
:return: dictionary of heroes, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"of",
"in",
"-",
"game",
"heroes",
"used",
"to",
"parse",
"ids",
"into",
"localised",
"names"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L185-L195 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_tournament_prize_pool | def get_tournament_prize_pool(self, leagueid=None, **kwargs):
"""Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>`
"""
if 'leagueid' not in kwargs:
... | python | def get_tournament_prize_pool(self, leagueid=None, **kwargs):
"""Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>`
"""
if 'leagueid' not in kwargs:
... | [
"def",
"get_tournament_prize_pool",
"(",
"self",
",",
"leagueid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'leagueid'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'leagueid'",
"]",
"=",
"leagueid",
"url",
"=",
"self",
".",
"__build_url",
"... | Returns a dictionary that includes community funded tournament prize pools
:param leagueid: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"that",
"includes",
"community",
"funded",
"tournament",
"prize",
"pools"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L209-L222 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.get_top_live_games | def get_top_live_games(self, partner='', **kwargs):
"""Returns a dictionary that includes top MMR live games
:param partner: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>`
"""
if 'partner' not in kwargs:
kwargs['partner'] = part... | python | def get_top_live_games(self, partner='', **kwargs):
"""Returns a dictionary that includes top MMR live games
:param partner: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>`
"""
if 'partner' not in kwargs:
kwargs['partner'] = part... | [
"def",
"get_top_live_games",
"(",
"self",
",",
"partner",
"=",
"''",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'partner'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'partner'",
"]",
"=",
"partner",
"url",
"=",
"self",
".",
"__build_url",
"(",
"urls",... | Returns a dictionary that includes top MMR live games
:param partner: (int, optional)
:return: dictionary of prize pools, see :doc:`responses </responses>` | [
"Returns",
"a",
"dictionary",
"that",
"includes",
"top",
"MMR",
"live",
"games"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L224-L237 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.__build_url | def __build_url(self, api_call, **kwargs):
"""Builds the api query"""
kwargs['key'] = self.api_key
if 'language' not in kwargs:
kwargs['language'] = self.language
if 'format' not in kwargs:
kwargs['format'] = self.__format
api_query = urlencode(kwargs)
... | python | def __build_url(self, api_call, **kwargs):
"""Builds the api query"""
kwargs['key'] = self.api_key
if 'language' not in kwargs:
kwargs['language'] = self.language
if 'format' not in kwargs:
kwargs['format'] = self.__format
api_query = urlencode(kwargs)
... | [
"def",
"__build_url",
"(",
"self",
",",
"api_call",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'key'",
"]",
"=",
"self",
".",
"api_key",
"if",
"'language'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'language'",
"]",
"=",
"self",
".",
"lang... | Builds the api query | [
"Builds",
"the",
"api",
"query"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L251-L262 | train |
joshuaduffy/dota2api | dota2api/__init__.py | Initialise.__check_http_err | def __check_http_err(self, status_code):
"""Raises an exception if we get a http error"""
if status_code == 403:
raise exceptions.APIAuthenticationError(self.api_key)
elif status_code == 503:
raise exceptions.APITimeoutError()
else:
return False | python | def __check_http_err(self, status_code):
"""Raises an exception if we get a http error"""
if status_code == 403:
raise exceptions.APIAuthenticationError(self.api_key)
elif status_code == 503:
raise exceptions.APITimeoutError()
else:
return False | [
"def",
"__check_http_err",
"(",
"self",
",",
"status_code",
")",
":",
"if",
"status_code",
"==",
"403",
":",
"raise",
"exceptions",
".",
"APIAuthenticationError",
"(",
"self",
".",
"api_key",
")",
"elif",
"status_code",
"==",
"503",
":",
"raise",
"exceptions",... | Raises an exception if we get a http error | [
"Raises",
"an",
"exception",
"if",
"we",
"get",
"a",
"http",
"error"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/__init__.py#L264-L271 | train |
joshuaduffy/dota2api | dota2api/src/parse.py | item_id | def item_id(response):
"""
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on
"""
dict_keys = ['item_0', 'item_1', 'item_2',
'item_3', 'item_4', 'item_5']
new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
'... | python | def item_id(response):
"""
Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on
"""
dict_keys = ['item_0', 'item_1', 'item_2',
'item_3', 'item_4', 'item_5']
new_keys = ['item_0_name', 'item_1_name', 'item_2_name',
'... | [
"def",
"item_id",
"(",
"response",
")",
":",
"dict_keys",
"=",
"[",
"'item_0'",
",",
"'item_1'",
",",
"'item_2'",
",",
"'item_3'",
",",
"'item_4'",
",",
"'item_5'",
"]",
"new_keys",
"=",
"[",
"'item_0_name'",
",",
"'item_1_name'",
",",
"'item_2_name'",
",",
... | Parse the item ids, will be available as ``item_0_name``, ``item_1_name``,
``item_2_name`` and so on | [
"Parse",
"the",
"item",
"ids",
"will",
"be",
"available",
"as",
"item_0_name",
"item_1_name",
"item_2_name",
"and",
"so",
"on"
] | 03c9e1c609ec36728805bbd3ada0a53ec8f51e86 | https://github.com/joshuaduffy/dota2api/blob/03c9e1c609ec36728805bbd3ada0a53ec8f51e86/dota2api/src/parse.py#L40-L56 | train |
bitlabstudio/django-review | review/templatetags/review_tags.py | get_reviews | def get_reviews(obj):
"""Simply returns the reviews for an object."""
ctype = ContentType.objects.get_for_model(obj)
return models.Review.objects.filter(content_type=ctype, object_id=obj.id) | python | def get_reviews(obj):
"""Simply returns the reviews for an object."""
ctype = ContentType.objects.get_for_model(obj)
return models.Review.objects.filter(content_type=ctype, object_id=obj.id) | [
"def",
"get_reviews",
"(",
"obj",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"return",
"models",
".",
"Review",
".",
"objects",
".",
"filter",
"(",
"content_type",
"=",
"ctype",
",",
"object_id",
"=",
"o... | Simply returns the reviews for an object. | [
"Simply",
"returns",
"the",
"reviews",
"for",
"an",
"object",
"."
] | 70d4b5c8d52d9a5615e5d0f5c7f147e15573c566 | https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L12-L15 | train |
bitlabstudio/django-review | review/templatetags/review_tags.py | get_review_average | def get_review_average(obj):
"""Returns the review average for an object."""
total = 0
reviews = get_reviews(obj)
if not reviews:
return False
for review in reviews:
average = review.get_average_rating()
if average:
total += review.get_average_rating()
if tota... | python | def get_review_average(obj):
"""Returns the review average for an object."""
total = 0
reviews = get_reviews(obj)
if not reviews:
return False
for review in reviews:
average = review.get_average_rating()
if average:
total += review.get_average_rating()
if tota... | [
"def",
"get_review_average",
"(",
"obj",
")",
":",
"total",
"=",
"0",
"reviews",
"=",
"get_reviews",
"(",
"obj",
")",
"if",
"not",
"reviews",
":",
"return",
"False",
"for",
"review",
"in",
"reviews",
":",
"average",
"=",
"review",
".",
"get_average_rating"... | Returns the review average for an object. | [
"Returns",
"the",
"review",
"average",
"for",
"an",
"object",
"."
] | 70d4b5c8d52d9a5615e5d0f5c7f147e15573c566 | https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L19-L31 | train |
bitlabstudio/django-review | review/templatetags/review_tags.py | render_category_averages | def render_category_averages(obj, normalize_to=100):
"""Renders all the sub-averages for each category."""
context = {'reviewed_item': obj}
ctype = ContentType.objects.get_for_model(obj)
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
category_averages = {}
... | python | def render_category_averages(obj, normalize_to=100):
"""Renders all the sub-averages for each category."""
context = {'reviewed_item': obj}
ctype = ContentType.objects.get_for_model(obj)
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
category_averages = {}
... | [
"def",
"render_category_averages",
"(",
"obj",
",",
"normalize_to",
"=",
"100",
")",
":",
"context",
"=",
"{",
"'reviewed_item'",
":",
"obj",
"}",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"reviews",
"=",
"models",
... | Renders all the sub-averages for each category. | [
"Renders",
"all",
"the",
"sub",
"-",
"averages",
"for",
"each",
"category",
"."
] | 70d4b5c8d52d9a5615e5d0f5c7f147e15573c566 | https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L41-L71 | train |
bitlabstudio/django-review | review/templatetags/review_tags.py | total_review_average | def total_review_average(obj, normalize_to=100):
"""Returns the average for all reviews of the given object."""
ctype = ContentType.objects.get_for_model(obj)
total_average = 0
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
for review in reviews:
total_... | python | def total_review_average(obj, normalize_to=100):
"""Returns the average for all reviews of the given object."""
ctype = ContentType.objects.get_for_model(obj)
total_average = 0
reviews = models.Review.objects.filter(
content_type=ctype, object_id=obj.id)
for review in reviews:
total_... | [
"def",
"total_review_average",
"(",
"obj",
",",
"normalize_to",
"=",
"100",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"total_average",
"=",
"0",
"reviews",
"=",
"models",
".",
"Review",
".",
"objects",
".... | Returns the average for all reviews of the given object. | [
"Returns",
"the",
"average",
"for",
"all",
"reviews",
"of",
"the",
"given",
"object",
"."
] | 70d4b5c8d52d9a5615e5d0f5c7f147e15573c566 | https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L75-L85 | train |
bitlabstudio/django-review | review/templatetags/review_tags.py | user_has_reviewed | def user_has_reviewed(obj, user):
"""Returns True if the user has already reviewed the object."""
ctype = ContentType.objects.get_for_model(obj)
try:
models.Review.objects.get(user=user, content_type=ctype,
object_id=obj.id)
except models.Review.DoesNotExist:
... | python | def user_has_reviewed(obj, user):
"""Returns True if the user has already reviewed the object."""
ctype = ContentType.objects.get_for_model(obj)
try:
models.Review.objects.get(user=user, content_type=ctype,
object_id=obj.id)
except models.Review.DoesNotExist:
... | [
"def",
"user_has_reviewed",
"(",
"obj",
",",
"user",
")",
":",
"ctype",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"obj",
")",
"try",
":",
"models",
".",
"Review",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"user",
",",
"content_... | Returns True if the user has already reviewed the object. | [
"Returns",
"True",
"if",
"the",
"user",
"has",
"already",
"reviewed",
"the",
"object",
"."
] | 70d4b5c8d52d9a5615e5d0f5c7f147e15573c566 | https://github.com/bitlabstudio/django-review/blob/70d4b5c8d52d9a5615e5d0f5c7f147e15573c566/review/templatetags/review_tags.py#L89-L97 | train |
ahawker/ulid | ulid/base32.py | str_to_bytes | def str_to_bytes(value: str, expected_length: int) -> bytes:
"""
Convert the given string to bytes and validate it is within the Base32 character set.
:param value: String to convert to bytes
:type value: :class:`~str`
:param expected_length: Expected length of the input string
:type expected_l... | python | def str_to_bytes(value: str, expected_length: int) -> bytes:
"""
Convert the given string to bytes and validate it is within the Base32 character set.
:param value: String to convert to bytes
:type value: :class:`~str`
:param expected_length: Expected length of the input string
:type expected_l... | [
"def",
"str_to_bytes",
"(",
"value",
":",
"str",
",",
"expected_length",
":",
"int",
")",
"->",
"bytes",
":",
"length",
"=",
"len",
"(",
"value",
")",
"if",
"length",
"!=",
"expected_length",
":",
"raise",
"ValueError",
"(",
"'Expects {} characters for decodin... | Convert the given string to bytes and validate it is within the Base32 character set.
:param value: String to convert to bytes
:type value: :class:`~str`
:param expected_length: Expected length of the input string
:type expected_length: :class:`~int`
:return: Value converted to bytes.
:rtype: :... | [
"Convert",
"the",
"given",
"string",
"to",
"bytes",
"and",
"validate",
"it",
"is",
"within",
"the",
"Base32",
"character",
"set",
"."
] | f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f | https://github.com/ahawker/ulid/blob/f6459bafebbd1a1ffd71a8718bd5592c2e4dd59f/ulid/base32.py#L340-L368 | train |
noxdafox/pebble | setup.py | package_version | def package_version():
"""Get the package version via Git Tag."""
version_path = os.path.join(os.path.dirname(__file__), 'version.py')
version = read_version(version_path)
write_version(version_path, version)
return version | python | def package_version():
"""Get the package version via Git Tag."""
version_path = os.path.join(os.path.dirname(__file__), 'version.py')
version = read_version(version_path)
write_version(version_path, version)
return version | [
"def",
"package_version",
"(",
")",
":",
"version_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'version.py'",
")",
"version",
"=",
"read_version",
"(",
"version_path",
")",
"write_version",... | Get the package version via Git Tag. | [
"Get",
"the",
"package",
"version",
"via",
"Git",
"Tag",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/setup.py#L10-L17 | train |
noxdafox/pebble | pebble/decorators.py | synchronized | def synchronized(*args):
"""A synchronized function prevents two or more callers to interleave
its execution preventing race conditions.
The synchronized decorator accepts as optional parameter a Lock, RLock or
Semaphore object which will be employed to ensure the function's atomicity.
If no synch... | python | def synchronized(*args):
"""A synchronized function prevents two or more callers to interleave
its execution preventing race conditions.
The synchronized decorator accepts as optional parameter a Lock, RLock or
Semaphore object which will be employed to ensure the function's atomicity.
If no synch... | [
"def",
"synchronized",
"(",
"*",
"args",
")",
":",
"if",
"callable",
"(",
"args",
"[",
"0",
"]",
")",
":",
"return",
"decorate_synchronized",
"(",
"args",
"[",
"0",
"]",
",",
"_synchronized_lock",
")",
"else",
":",
"def",
"wrap",
"(",
"function",
")",
... | A synchronized function prevents two or more callers to interleave
its execution preventing race conditions.
The synchronized decorator accepts as optional parameter a Lock, RLock or
Semaphore object which will be employed to ensure the function's atomicity.
If no synchronization object is given, a si... | [
"A",
"synchronized",
"function",
"prevents",
"two",
"or",
"more",
"callers",
"to",
"interleave",
"its",
"execution",
"preventing",
"race",
"conditions",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/decorators.py#L26-L44 | train |
noxdafox/pebble | pebble/pool/thread.py | worker_thread | def worker_thread(context):
"""The worker thread routines."""
queue = context.task_queue
parameters = context.worker_parameters
if parameters.initializer is not None:
if not run_initializer(parameters.initializer, parameters.initargs):
context.state = ERROR
return
f... | python | def worker_thread(context):
"""The worker thread routines."""
queue = context.task_queue
parameters = context.worker_parameters
if parameters.initializer is not None:
if not run_initializer(parameters.initializer, parameters.initargs):
context.state = ERROR
return
f... | [
"def",
"worker_thread",
"(",
"context",
")",
":",
"queue",
"=",
"context",
".",
"task_queue",
"parameters",
"=",
"context",
".",
"worker_parameters",
"if",
"parameters",
".",
"initializer",
"is",
"not",
"None",
":",
"if",
"not",
"run_initializer",
"(",
"parame... | The worker thread routines. | [
"The",
"worker",
"thread",
"routines",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/thread.py#L155-L167 | train |
noxdafox/pebble | pebble/common.py | stop_process | def stop_process(process):
"""Does its best to stop the process."""
process.terminate()
process.join(3)
if process.is_alive() and os.name != 'nt':
try:
os.kill(process.pid, signal.SIGKILL)
process.join()
except OSError:
return
if process.is_alive... | python | def stop_process(process):
"""Does its best to stop the process."""
process.terminate()
process.join(3)
if process.is_alive() and os.name != 'nt':
try:
os.kill(process.pid, signal.SIGKILL)
process.join()
except OSError:
return
if process.is_alive... | [
"def",
"stop_process",
"(",
"process",
")",
":",
"process",
".",
"terminate",
"(",
")",
"process",
".",
"join",
"(",
"3",
")",
"if",
"process",
".",
"is_alive",
"(",
")",
"and",
"os",
".",
"name",
"!=",
"'nt'",
":",
"try",
":",
"os",
".",
"kill",
... | Does its best to stop the process. | [
"Does",
"its",
"best",
"to",
"stop",
"the",
"process",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/common.py#L143-L156 | train |
noxdafox/pebble | pebble/common.py | send_result | def send_result(pipe, data):
"""Send result handling pickling and communication errors."""
try:
pipe.send(data)
except (pickle.PicklingError, TypeError) as error:
error.traceback = format_exc()
pipe.send(RemoteException(error, error.traceback)) | python | def send_result(pipe, data):
"""Send result handling pickling and communication errors."""
try:
pipe.send(data)
except (pickle.PicklingError, TypeError) as error:
error.traceback = format_exc()
pipe.send(RemoteException(error, error.traceback)) | [
"def",
"send_result",
"(",
"pipe",
",",
"data",
")",
":",
"try",
":",
"pipe",
".",
"send",
"(",
"data",
")",
"except",
"(",
"pickle",
".",
"PicklingError",
",",
"TypeError",
")",
"as",
"error",
":",
"error",
".",
"traceback",
"=",
"format_exc",
"(",
... | Send result handling pickling and communication errors. | [
"Send",
"result",
"handling",
"pickling",
"and",
"communication",
"errors",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/common.py#L177-L183 | train |
noxdafox/pebble | pebble/concurrent/process.py | process | def process(*args, **kwargs):
"""Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated functi... | python | def process(*args, **kwargs):
"""Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated functi... | [
"def",
"process",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"get",
"(",
"'timeout'",
")",
"# decorator without parameters",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"len",
"(",
"kwargs",
")",
"==",
"0... | Runs the decorated function in a concurrent process,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
The timeout parameter will set a maximum execution time
for the decorated function. If the execution exceeds the time... | [
"Runs",
"the",
"decorated",
"function",
"in",
"a",
"concurrent",
"process",
"taking",
"care",
"of",
"the",
"result",
"and",
"error",
"management",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L36-L61 | train |
noxdafox/pebble | pebble/concurrent/process.py | _worker_handler | def _worker_handler(future, worker, pipe, timeout):
"""Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process.
"""
result = _get_result(future, pipe, timeout)
if isinstance(result, BaseException):
if isinstan... | python | def _worker_handler(future, worker, pipe, timeout):
"""Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process.
"""
result = _get_result(future, pipe, timeout)
if isinstance(result, BaseException):
if isinstan... | [
"def",
"_worker_handler",
"(",
"future",
",",
"worker",
",",
"pipe",
",",
"timeout",
")",
":",
"result",
"=",
"_get_result",
"(",
"future",
",",
"pipe",
",",
"timeout",
")",
"if",
"isinstance",
"(",
"result",
",",
"BaseException",
")",
":",
"if",
"isinst... | Worker lifecycle manager.
Waits for the worker to be perform its task,
collects result, runs the callback and cleans up the process. | [
"Worker",
"lifecycle",
"manager",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L92-L110 | train |
noxdafox/pebble | pebble/concurrent/process.py | _function_handler | def _function_handler(function, args, kwargs, pipe):
"""Runs the actual function in separate process and returns its result."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
result = process_execute(function, *args, **kwargs)
send_result(pipe, result) | python | def _function_handler(function, args, kwargs, pipe):
"""Runs the actual function in separate process and returns its result."""
signal.signal(signal.SIGINT, signal.SIG_IGN)
result = process_execute(function, *args, **kwargs)
send_result(pipe, result) | [
"def",
"_function_handler",
"(",
"function",
",",
"args",
",",
"kwargs",
",",
"pipe",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"result",
"=",
"process_execute",
"(",
"function",
",",
"*",
"args"... | Runs the actual function in separate process and returns its result. | [
"Runs",
"the",
"actual",
"function",
"in",
"separate",
"process",
"and",
"returns",
"its",
"result",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L113-L119 | train |
noxdafox/pebble | pebble/concurrent/process.py | _get_result | def _get_result(future, pipe, timeout):
"""Waits for result and handles communication errors."""
counter = count(step=SLEEP_UNIT)
try:
while not pipe.poll(SLEEP_UNIT):
if timeout is not None and next(counter) >= timeout:
return TimeoutError('Task Timeout', timeout)
... | python | def _get_result(future, pipe, timeout):
"""Waits for result and handles communication errors."""
counter = count(step=SLEEP_UNIT)
try:
while not pipe.poll(SLEEP_UNIT):
if timeout is not None and next(counter) >= timeout:
return TimeoutError('Task Timeout', timeout)
... | [
"def",
"_get_result",
"(",
"future",
",",
"pipe",
",",
"timeout",
")",
":",
"counter",
"=",
"count",
"(",
"step",
"=",
"SLEEP_UNIT",
")",
"try",
":",
"while",
"not",
"pipe",
".",
"poll",
"(",
"SLEEP_UNIT",
")",
":",
"if",
"timeout",
"is",
"not",
"Non... | Waits for result and handles communication errors. | [
"Waits",
"for",
"result",
"and",
"handles",
"communication",
"errors",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L122-L137 | train |
noxdafox/pebble | pebble/concurrent/process.py | _trampoline | def _trampoline(name, module, *args, **kwargs):
"""Trampoline function for decorators.
Lookups the function between the registered ones;
if not found, forces its registering and then executes it.
"""
function = _function_lookup(name, module)
return function(*args, **kwargs) | python | def _trampoline(name, module, *args, **kwargs):
"""Trampoline function for decorators.
Lookups the function between the registered ones;
if not found, forces its registering and then executes it.
"""
function = _function_lookup(name, module)
return function(*args, **kwargs) | [
"def",
"_trampoline",
"(",
"name",
",",
"module",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"function",
"=",
"_function_lookup",
"(",
"name",
",",
"module",
")",
"return",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Trampoline function for decorators.
Lookups the function between the registered ones;
if not found, forces its registering and then executes it. | [
"Trampoline",
"function",
"for",
"decorators",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L152-L161 | train |
noxdafox/pebble | pebble/concurrent/process.py | _function_lookup | def _function_lookup(name, module):
"""Searches the function between the registered ones.
If not found, it imports the module forcing its registration.
"""
try:
return _registered_functions[name]
except KeyError: # force function registering
__import__(module)
mod = sys.mod... | python | def _function_lookup(name, module):
"""Searches the function between the registered ones.
If not found, it imports the module forcing its registration.
"""
try:
return _registered_functions[name]
except KeyError: # force function registering
__import__(module)
mod = sys.mod... | [
"def",
"_function_lookup",
"(",
"name",
",",
"module",
")",
":",
"try",
":",
"return",
"_registered_functions",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# force function registering",
"__import__",
"(",
"module",
")",
"mod",
"=",
"sys",
".",
"modules",
"[... | Searches the function between the registered ones.
If not found, it imports the module forcing its registration. | [
"Searches",
"the",
"function",
"between",
"the",
"registered",
"ones",
".",
"If",
"not",
"found",
"it",
"imports",
"the",
"module",
"forcing",
"its",
"registration",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/process.py#L164-L176 | train |
noxdafox/pebble | pebble/pool/process.py | worker_process | def worker_process(params, channel):
"""The worker process routines."""
signal(SIGINT, SIG_IGN)
if params.initializer is not None:
if not run_initializer(params.initializer, params.initargs):
os._exit(1)
try:
for task in worker_get_next_task(channel, params.max_tasks):
... | python | def worker_process(params, channel):
"""The worker process routines."""
signal(SIGINT, SIG_IGN)
if params.initializer is not None:
if not run_initializer(params.initializer, params.initargs):
os._exit(1)
try:
for task in worker_get_next_task(channel, params.max_tasks):
... | [
"def",
"worker_process",
"(",
"params",
",",
"channel",
")",
":",
"signal",
"(",
"SIGINT",
",",
"SIG_IGN",
")",
"if",
"params",
".",
"initializer",
"is",
"not",
"None",
":",
"if",
"not",
"run_initializer",
"(",
"params",
".",
"initializer",
",",
"params",
... | The worker process routines. | [
"The",
"worker",
"process",
"routines",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L375-L392 | train |
noxdafox/pebble | pebble/pool/process.py | task_transaction | def task_transaction(channel):
"""Ensures a task is fetched and acknowledged atomically."""
with channel.lock:
if channel.poll(0):
task = channel.recv()
channel.send(Acknowledgement(os.getpid(), task.id))
else:
raise RuntimeError("Race condition between worker... | python | def task_transaction(channel):
"""Ensures a task is fetched and acknowledged atomically."""
with channel.lock:
if channel.poll(0):
task = channel.recv()
channel.send(Acknowledgement(os.getpid(), task.id))
else:
raise RuntimeError("Race condition between worker... | [
"def",
"task_transaction",
"(",
"channel",
")",
":",
"with",
"channel",
".",
"lock",
":",
"if",
"channel",
".",
"poll",
"(",
"0",
")",
":",
"task",
"=",
"channel",
".",
"recv",
"(",
")",
"channel",
".",
"send",
"(",
"Acknowledgement",
"(",
"os",
".",... | Ensures a task is fetched and acknowledged atomically. | [
"Ensures",
"a",
"task",
"is",
"fetched",
"and",
"acknowledged",
"atomically",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L410-L419 | train |
noxdafox/pebble | pebble/pool/process.py | PoolManager.schedule | def schedule(self, task):
"""Schedules a new Task in the PoolManager."""
self.task_manager.register(task)
self.worker_manager.dispatch(task) | python | def schedule(self, task):
"""Schedules a new Task in the PoolManager."""
self.task_manager.register(task)
self.worker_manager.dispatch(task) | [
"def",
"schedule",
"(",
"self",
",",
"task",
")",
":",
"self",
".",
"task_manager",
".",
"register",
"(",
"task",
")",
"self",
".",
"worker_manager",
".",
"dispatch",
"(",
"task",
")"
] | Schedules a new Task in the PoolManager. | [
"Schedules",
"a",
"new",
"Task",
"in",
"the",
"PoolManager",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L194-L197 | train |
noxdafox/pebble | pebble/pool/process.py | PoolManager.process_next_message | def process_next_message(self, timeout):
"""Processes the next message coming from the workers."""
message = self.worker_manager.receive(timeout)
if isinstance(message, Acknowledgement):
self.task_manager.task_start(message.task, message.worker)
elif isinstance(message, Resu... | python | def process_next_message(self, timeout):
"""Processes the next message coming from the workers."""
message = self.worker_manager.receive(timeout)
if isinstance(message, Acknowledgement):
self.task_manager.task_start(message.task, message.worker)
elif isinstance(message, Resu... | [
"def",
"process_next_message",
"(",
"self",
",",
"timeout",
")",
":",
"message",
"=",
"self",
".",
"worker_manager",
".",
"receive",
"(",
"timeout",
")",
"if",
"isinstance",
"(",
"message",
",",
"Acknowledgement",
")",
":",
"self",
".",
"task_manager",
".",
... | Processes the next message coming from the workers. | [
"Processes",
"the",
"next",
"message",
"coming",
"from",
"the",
"workers",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L199-L206 | train |
noxdafox/pebble | pebble/pool/process.py | PoolManager.update_tasks | def update_tasks(self):
"""Handles timing out Tasks."""
for task in self.task_manager.timeout_tasks():
self.task_manager.task_done(
task.id, TimeoutError("Task timeout", task.timeout))
self.worker_manager.stop_worker(task.worker_id)
for task in self.task_... | python | def update_tasks(self):
"""Handles timing out Tasks."""
for task in self.task_manager.timeout_tasks():
self.task_manager.task_done(
task.id, TimeoutError("Task timeout", task.timeout))
self.worker_manager.stop_worker(task.worker_id)
for task in self.task_... | [
"def",
"update_tasks",
"(",
"self",
")",
":",
"for",
"task",
"in",
"self",
".",
"task_manager",
".",
"timeout_tasks",
"(",
")",
":",
"self",
".",
"task_manager",
".",
"task_done",
"(",
"task",
".",
"id",
",",
"TimeoutError",
"(",
"\"Task timeout\"",
",",
... | Handles timing out Tasks. | [
"Handles",
"timing",
"out",
"Tasks",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L212-L222 | train |
noxdafox/pebble | pebble/pool/process.py | PoolManager.update_workers | def update_workers(self):
"""Handles unexpected processes termination."""
for expiration in self.worker_manager.inspect_workers():
self.handle_worker_expiration(expiration)
self.worker_manager.create_workers() | python | def update_workers(self):
"""Handles unexpected processes termination."""
for expiration in self.worker_manager.inspect_workers():
self.handle_worker_expiration(expiration)
self.worker_manager.create_workers() | [
"def",
"update_workers",
"(",
"self",
")",
":",
"for",
"expiration",
"in",
"self",
".",
"worker_manager",
".",
"inspect_workers",
"(",
")",
":",
"self",
".",
"handle_worker_expiration",
"(",
"expiration",
")",
"self",
".",
"worker_manager",
".",
"create_workers"... | Handles unexpected processes termination. | [
"Handles",
"unexpected",
"processes",
"termination",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L224-L229 | train |
noxdafox/pebble | pebble/pool/process.py | TaskManager.task_done | def task_done(self, task_id, result):
"""Set the tasks result and run the callback."""
try:
task = self.tasks.pop(task_id)
except KeyError:
return # result of previously timeout Task
else:
if task.future.cancelled():
task.set_running_o... | python | def task_done(self, task_id, result):
"""Set the tasks result and run the callback."""
try:
task = self.tasks.pop(task_id)
except KeyError:
return # result of previously timeout Task
else:
if task.future.cancelled():
task.set_running_o... | [
"def",
"task_done",
"(",
"self",
",",
"task_id",
",",
"result",
")",
":",
"try",
":",
"task",
"=",
"self",
".",
"tasks",
".",
"pop",
"(",
"task_id",
")",
"except",
"KeyError",
":",
"return",
"# result of previously timeout Task",
"else",
":",
"if",
"task",... | Set the tasks result and run the callback. | [
"Set",
"the",
"tasks",
"result",
"and",
"run",
"the",
"callback",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L271-L285 | train |
noxdafox/pebble | pebble/pool/process.py | WorkerManager.inspect_workers | def inspect_workers(self):
"""Updates the workers status.
Returns the workers which have unexpectedly ended.
"""
workers = tuple(self.workers.values())
expired = tuple(w for w in workers if not w.is_alive())
for worker in expired:
self.workers.pop(worker.pi... | python | def inspect_workers(self):
"""Updates the workers status.
Returns the workers which have unexpectedly ended.
"""
workers = tuple(self.workers.values())
expired = tuple(w for w in workers if not w.is_alive())
for worker in expired:
self.workers.pop(worker.pi... | [
"def",
"inspect_workers",
"(",
"self",
")",
":",
"workers",
"=",
"tuple",
"(",
"self",
".",
"workers",
".",
"values",
"(",
")",
")",
"expired",
"=",
"tuple",
"(",
"w",
"for",
"w",
"in",
"workers",
"if",
"not",
"w",
".",
"is_alive",
"(",
")",
")",
... | Updates the workers status.
Returns the workers which have unexpectedly ended. | [
"Updates",
"the",
"workers",
"status",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/process.py#L328-L340 | train |
noxdafox/pebble | pebble/pool/base_pool.py | iter_chunks | def iter_chunks(chunksize, *iterables):
"""Iterates over zipped iterables in chunks."""
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | python | def iter_chunks(chunksize, *iterables):
"""Iterates over zipped iterables in chunks."""
iterables = iter(zip(*iterables))
while 1:
chunk = tuple(islice(iterables, chunksize))
if not chunk:
return
yield chunk | [
"def",
"iter_chunks",
"(",
"chunksize",
",",
"*",
"iterables",
")",
":",
"iterables",
"=",
"iter",
"(",
"zip",
"(",
"*",
"iterables",
")",
")",
"while",
"1",
":",
"chunk",
"=",
"tuple",
"(",
"islice",
"(",
"iterables",
",",
"chunksize",
")",
")",
"if... | Iterates over zipped iterables in chunks. | [
"Iterates",
"over",
"zipped",
"iterables",
"in",
"chunks",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/base_pool.py#L218-L228 | train |
noxdafox/pebble | pebble/pool/base_pool.py | run_initializer | def run_initializer(initializer, initargs):
"""Runs the Pool initializer dealing with errors."""
try:
initializer(*initargs)
return True
except Exception as error:
logging.exception(error)
return False | python | def run_initializer(initializer, initargs):
"""Runs the Pool initializer dealing with errors."""
try:
initializer(*initargs)
return True
except Exception as error:
logging.exception(error)
return False | [
"def",
"run_initializer",
"(",
"initializer",
",",
"initargs",
")",
":",
"try",
":",
"initializer",
"(",
"*",
"initargs",
")",
"return",
"True",
"except",
"Exception",
"as",
"error",
":",
"logging",
".",
"exception",
"(",
"error",
")",
"return",
"False"
] | Runs the Pool initializer dealing with errors. | [
"Runs",
"the",
"Pool",
"initializer",
"dealing",
"with",
"errors",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/base_pool.py#L239-L246 | train |
noxdafox/pebble | pebble/pool/base_pool.py | BasePool.join | def join(self, timeout=None):
"""Joins the pool waiting until all workers exited.
If *timeout* is set, it block until all workers are done
or raises TimeoutError.
"""
if self._context.state == RUNNING:
raise RuntimeError('The Pool is still running')
if self._... | python | def join(self, timeout=None):
"""Joins the pool waiting until all workers exited.
If *timeout* is set, it block until all workers are done
or raises TimeoutError.
"""
if self._context.state == RUNNING:
raise RuntimeError('The Pool is still running')
if self._... | [
"def",
"join",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"self",
".",
"_context",
".",
"state",
"==",
"RUNNING",
":",
"raise",
"RuntimeError",
"(",
"'The Pool is still running'",
")",
"if",
"self",
".",
"_context",
".",
"state",
"==",
"CL... | Joins the pool waiting until all workers exited.
If *timeout* is set, it block until all workers are done
or raises TimeoutError. | [
"Joins",
"the",
"pool",
"waiting",
"until",
"all",
"workers",
"exited",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/pool/base_pool.py#L63-L77 | train |
noxdafox/pebble | pebble/concurrent/thread.py | thread | def thread(function):
"""Runs the decorated function within a concurrent thread,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
"""
@wraps(function)
def wrapper(*args, **kwargs):
future = Future()
... | python | def thread(function):
"""Runs the decorated function within a concurrent thread,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called.
"""
@wraps(function)
def wrapper(*args, **kwargs):
future = Future()
... | [
"def",
"thread",
"(",
"function",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"future",
"=",
"Future",
"(",
")",
"launch_thread",
"(",
"_function_handler",
",",
"function",
",",
... | Runs the decorated function within a concurrent thread,
taking care of the result and error management.
Decorated functions will return a concurrent.futures.Future object
once called. | [
"Runs",
"the",
"decorated",
"function",
"within",
"a",
"concurrent",
"thread",
"taking",
"care",
"of",
"the",
"result",
"and",
"error",
"management",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/thread.py#L24-L40 | train |
noxdafox/pebble | pebble/concurrent/thread.py | _function_handler | def _function_handler(function, args, kwargs, future):
"""Runs the actual function in separate thread and returns its result."""
future.set_running_or_notify_cancel()
try:
result = function(*args, **kwargs)
except BaseException as error:
error.traceback = format_exc()
future.set... | python | def _function_handler(function, args, kwargs, future):
"""Runs the actual function in separate thread and returns its result."""
future.set_running_or_notify_cancel()
try:
result = function(*args, **kwargs)
except BaseException as error:
error.traceback = format_exc()
future.set... | [
"def",
"_function_handler",
"(",
"function",
",",
"args",
",",
"kwargs",
",",
"future",
")",
":",
"future",
".",
"set_running_or_notify_cancel",
"(",
")",
"try",
":",
"result",
"=",
"function",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"B... | Runs the actual function in separate thread and returns its result. | [
"Runs",
"the",
"actual",
"function",
"in",
"separate",
"thread",
"and",
"returns",
"its",
"result",
"."
] | d8f3d989655715754f0a65d7419cfa584491f614 | https://github.com/noxdafox/pebble/blob/d8f3d989655715754f0a65d7419cfa584491f614/pebble/concurrent/thread.py#L43-L53 | train |
SwoopSearch/pyaddress | address/address.py | create_cities_csv | def create_cities_csv(filename="places2k.txt", output="cities.csv"):
"""
Takes the places2k.txt from USPS and creates a simple file of all cities.
"""
with open(filename, 'r') as city_file:
with open(output, 'w') as out:
for line in city_file:
# Drop Puerto Rico (just... | python | def create_cities_csv(filename="places2k.txt", output="cities.csv"):
"""
Takes the places2k.txt from USPS and creates a simple file of all cities.
"""
with open(filename, 'r') as city_file:
with open(output, 'w') as out:
for line in city_file:
# Drop Puerto Rico (just... | [
"def",
"create_cities_csv",
"(",
"filename",
"=",
"\"places2k.txt\"",
",",
"output",
"=",
"\"cities.csv\"",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"city_file",
":",
"with",
"open",
"(",
"output",
",",
"'w'",
")",
"as",
"out",
"... | Takes the places2k.txt from USPS and creates a simple file of all cities. | [
"Takes",
"the",
"places2k",
".",
"txt",
"from",
"USPS",
"and",
"creates",
"a",
"simple",
"file",
"of",
"all",
"cities",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L674-L686 | train |
SwoopSearch/pyaddress | address/address.py | AddressParser.parse_address | def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger) | python | def parse_address(self, address, line_number=-1):
"""
Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc.
"""
return Address(address, self, line_number, self.logger) | [
"def",
"parse_address",
"(",
"self",
",",
"address",
",",
"line_number",
"=",
"-",
"1",
")",
":",
"return",
"Address",
"(",
"address",
",",
"self",
",",
"line_number",
",",
"self",
".",
"logger",
")"
] | Return an Address object from the given address. Passes itself to the Address constructor to use all the custom
loaded suffixes, cities, etc. | [
"Return",
"an",
"Address",
"object",
"from",
"the",
"given",
"address",
".",
"Passes",
"itself",
"to",
"the",
"Address",
"constructor",
"to",
"use",
"all",
"the",
"custom",
"loaded",
"suffixes",
"cities",
"etc",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L83-L88 | train |
SwoopSearch/pyaddress | address/address.py | AddressParser.load_cities | def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line... | python | def load_cities(self, filename):
"""
Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for line... | [
"def",
"load_cities",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"self",
".",
"cities",
".",
"append",
"(",
"line",
".",
"strip",
"(",
")",
".",
"lower"... | Load up all cities in lowercase for easier matching. The file should have one city per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy. | [
"Load",
"up",
"all",
"cities",
"in",
"lowercase",
"for",
"easier",
"matching",
".",
"The",
"file",
"should",
"have",
"one",
"city",
"per",
"line",
"with",
"no",
"extra",
"characters",
".",
"This",
"isn",
"t",
"strictly",
"required",
"but",
"will",
"vastly"... | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L128-L135 | train |
SwoopSearch/pyaddress | address/address.py | AddressParser.load_streets | def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for ... | python | def load_streets(self, filename):
"""
Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy.
"""
with open(filename, 'r') as f:
for ... | [
"def",
"load_streets",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"self",
".",
"streets",
".",
"append",
"(",
"line",
".",
"strip",
"(",
")",
".",
"lowe... | Load up all streets in lowercase for easier matching. The file should have one street per line, with no extra
characters. This isn't strictly required, but will vastly increase the accuracy. | [
"Load",
"up",
"all",
"streets",
"in",
"lowercase",
"for",
"easier",
"matching",
".",
"The",
"file",
"should",
"have",
"one",
"street",
"per",
"line",
"with",
"no",
"extra",
"characters",
".",
"This",
"isn",
"t",
"strictly",
"required",
"but",
"will",
"vast... | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L137-L144 | train |
SwoopSearch/pyaddress | address/address.py | Address.preprocess_address | def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
... | python | def preprocess_address(self, address):
"""
Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address.
"""
# Run some basic cleaning
address = address.replace("# ", "#")
... | [
"def",
"preprocess_address",
"(",
"self",
",",
"address",
")",
":",
"# Run some basic cleaning",
"address",
"=",
"address",
".",
"replace",
"(",
"\"# \"",
",",
"\"#\"",
")",
"address",
"=",
"address",
".",
"replace",
"(",
"\" & \"",
",",
"\"&\"",
")",
"# Cle... | Takes a basic address and attempts to clean it up, extract reasonably assured bits that may throw off the
rest of the parsing, and return the cleaned address. | [
"Takes",
"a",
"basic",
"address",
"and",
"attempts",
"to",
"clean",
"it",
"up",
"extract",
"reasonably",
"assured",
"bits",
"that",
"may",
"throw",
"off",
"the",
"rest",
"of",
"the",
"parsing",
"and",
"return",
"the",
"cleaned",
"address",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L250-L279 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_state | def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
... | python | def check_state(self, token):
"""
Check if state is in either the keys or values of our states list. Must come before the suffix.
"""
# print "zip", self.zip
if len(token) == 2 and self.state is None:
if token.capitalize() in self.parser.states.keys():
... | [
"def",
"check_state",
"(",
"self",
",",
"token",
")",
":",
"# print \"zip\", self.zip",
"if",
"len",
"(",
"token",
")",
"==",
"2",
"and",
"self",
".",
"state",
"is",
"None",
":",
"if",
"token",
".",
"capitalize",
"(",
")",
"in",
"self",
".",
"parser",
... | Check if state is in either the keys or values of our states list. Must come before the suffix. | [
"Check",
"if",
"state",
"is",
"in",
"either",
"the",
"keys",
"or",
"values",
"of",
"our",
"states",
"list",
".",
"Must",
"come",
"before",
"the",
"suffix",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L297-L316 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_city | def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cit... | python | def check_city(self, token):
"""
Check if there is a known city from our city list. Must come before the suffix.
"""
shortened_cities = {'saint': 'st.'}
if self.city is None and self.state is not None and self.street_suffix is None:
if token.lower() in self.parser.cit... | [
"def",
"check_city",
"(",
"self",
",",
"token",
")",
":",
"shortened_cities",
"=",
"{",
"'saint'",
":",
"'st.'",
"}",
"if",
"self",
".",
"city",
"is",
"None",
"and",
"self",
".",
"state",
"is",
"not",
"None",
"and",
"self",
".",
"street_suffix",
"is",
... | Check if there is a known city from our city list. Must come before the suffix. | [
"Check",
"if",
"there",
"is",
"a",
"known",
"city",
"from",
"our",
"city",
"list",
".",
"Must",
"come",
"before",
"the",
"suffix",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L318-L346 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_street_suffix | def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffi... | python | def check_street_suffix(self, token):
"""
Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave."
"""
# Suffix must come before street
# print "Suffix check", token, "suffi... | [
"def",
"check_street_suffix",
"(",
"self",
",",
"token",
")",
":",
"# Suffix must come before street",
"# print \"Suffix check\", token, \"suffix\", self.street_suffix, \"street\", self.street",
"if",
"self",
".",
"street_suffix",
"is",
"None",
"and",
"self",
".",
"street",
"... | Attempts to match a street suffix. If found, it will return the abbreviation, with the first letter capitalized
and a period after it. E.g. "St." or "Ave." | [
"Attempts",
"to",
"match",
"a",
"street",
"suffix",
".",
"If",
"found",
"it",
"will",
"return",
"the",
"abbreviation",
"with",
"the",
"first",
"letter",
"capitalized",
"and",
"a",
"period",
"after",
"it",
".",
"E",
".",
"g",
".",
"St",
".",
"or",
"Ave"... | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L377-L393 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_street | def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to... | python | def check_street(self, token):
"""
Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to... | [
"def",
"check_street",
"(",
"self",
",",
"token",
")",
":",
"# First check for single word streets between a prefix and a suffix",
"if",
"self",
".",
"street",
"is",
"None",
"and",
"self",
".",
"street_suffix",
"is",
"not",
"None",
"and",
"self",
".",
"street_prefix... | Let's assume a street comes before a prefix and after a suffix. This isn't always the case, but we'll deal
with that in our guessing game. Also, two word street names...well...
This check must come after the checks for house_number and street_prefix to help us deal with multi word streets. | [
"Let",
"s",
"assume",
"a",
"street",
"comes",
"before",
"a",
"prefix",
"and",
"after",
"a",
"suffix",
".",
"This",
"isn",
"t",
"always",
"the",
"case",
"but",
"we",
"ll",
"deal",
"with",
"that",
"in",
"our",
"guessing",
"game",
".",
"Also",
"two",
"w... | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L395-L413 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_street_prefix | def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():... | python | def check_street_prefix(self, token):
"""
Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period.
"""
if self.street and not self.street_prefix and token.lower().replace('.', '') in self.parser.prefixes.keys():... | [
"def",
"check_street_prefix",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"street",
"and",
"not",
"self",
".",
"street_prefix",
"and",
"token",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"in",
"self",
".",
"parser... | Finds street prefixes, such as N. or Northwest, before a street name. Standardizes to 1 or two letters, followed
by a period. | [
"Finds",
"street",
"prefixes",
"such",
"as",
"N",
".",
"or",
"Northwest",
"before",
"a",
"street",
"name",
".",
"Standardizes",
"to",
"1",
"or",
"two",
"letters",
"followed",
"by",
"a",
"period",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L415-L423 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_house_number | def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
... | python | def check_house_number(self, token):
"""
Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name.
"""
if self.street and self.house_number is None and re.match(street_num_regex, token.lower()):
... | [
"def",
"check_house_number",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"street",
"and",
"self",
".",
"house_number",
"is",
"None",
"and",
"re",
".",
"match",
"(",
"street_num_regex",
",",
"token",
".",
"lower",
"(",
")",
")",
":",
"if",
... | Attempts to find a house number, generally the first thing in an address. If anything is in front of it,
we assume it is a building name. | [
"Attempts",
"to",
"find",
"a",
"house",
"number",
"generally",
"the",
"first",
"thing",
"in",
"an",
"address",
".",
"If",
"anything",
"is",
"in",
"front",
"of",
"it",
"we",
"assume",
"it",
"is",
"a",
"building",
"name",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L425-L437 | train |
SwoopSearch/pyaddress | address/address.py | Address.check_building | def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = sel... | python | def check_building(self, token):
"""
Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names.
"""
if self.street and self.house_number:
if not self.building:
self.building = sel... | [
"def",
"check_building",
"(",
"self",
",",
"token",
")",
":",
"if",
"self",
".",
"street",
"and",
"self",
".",
"house_number",
":",
"if",
"not",
"self",
".",
"building",
":",
"self",
".",
"building",
"=",
"self",
".",
"_clean",
"(",
"token",
")",
"el... | Building name check. If we have leftover and everything else is set, probably building names.
Allows for multi word building names. | [
"Building",
"name",
"check",
".",
"If",
"we",
"have",
"leftover",
"and",
"everything",
"else",
"is",
"set",
"probably",
"building",
"names",
".",
"Allows",
"for",
"multi",
"word",
"building",
"names",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L439-L450 | train |
SwoopSearch/pyaddress | address/address.py | Address.guess_unmatched | def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likel... | python | def guess_unmatched(self, token):
"""
When we find something that doesn't match, we can make an educated guess and log it as such.
"""
# Check if this is probably an apartment:
if token.lower() in ['apt', 'apartment']:
return False
# Stray dashes are likel... | [
"def",
"guess_unmatched",
"(",
"self",
",",
"token",
")",
":",
"# Check if this is probably an apartment:",
"if",
"token",
".",
"lower",
"(",
")",
"in",
"[",
"'apt'",
",",
"'apartment'",
"]",
":",
"return",
"False",
"# Stray dashes are likely useless",
"if",
"toke... | When we find something that doesn't match, we can make an educated guess and log it as such. | [
"When",
"we",
"find",
"something",
"that",
"doesn",
"t",
"match",
"we",
"can",
"make",
"an",
"educated",
"guess",
"and",
"log",
"it",
"as",
"such",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L452-L477 | train |
SwoopSearch/pyaddress | address/address.py | Address.full_address | def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
a... | python | def full_address(self):
"""
Print the address in a human readable format
"""
addr = ""
# if self.building:
# addr = addr + "(" + self.building + ") "
if self.house_number:
addr = addr + self.house_number
if self.street_prefix:
a... | [
"def",
"full_address",
"(",
"self",
")",
":",
"addr",
"=",
"\"\"",
"# if self.building:",
"# addr = addr + \"(\" + self.building + \") \"",
"if",
"self",
".",
"house_number",
":",
"addr",
"=",
"addr",
"+",
"self",
".",
"house_number",
"if",
"self",
".",
"stree... | Print the address in a human readable format | [
"Print",
"the",
"address",
"in",
"a",
"human",
"readable",
"format"
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L479-L502 | train |
SwoopSearch/pyaddress | address/address.py | Address._get_dstk_intersections | def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
... | python | def _get_dstk_intersections(self, address, dstk_address):
"""
Find the unique tokens in the original address and the returned address.
"""
# Normalize both addresses
normalized_address = self._normalize(address)
normalized_dstk_address = self._normalize(dstk_address)
... | [
"def",
"_get_dstk_intersections",
"(",
"self",
",",
"address",
",",
"dstk_address",
")",
":",
"# Normalize both addresses",
"normalized_address",
"=",
"self",
".",
"_normalize",
"(",
"address",
")",
"normalized_dstk_address",
"=",
"self",
".",
"_normalize",
"(",
"ds... | Find the unique tokens in the original address and the returned address. | [
"Find",
"the",
"unique",
"tokens",
"in",
"the",
"original",
"address",
"and",
"the",
"returned",
"address",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L637-L648 | train |
SwoopSearch/pyaddress | address/address.py | Address._normalize | def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if t... | python | def _normalize(self, address):
"""
Normalize prefixes, suffixes and other to make matching original to returned easier.
"""
normalized_address = []
if self.logger: self.logger.debug("Normalizing Address: {0}".format(address))
for token in address.split():
if t... | [
"def",
"_normalize",
"(",
"self",
",",
"address",
")",
":",
"normalized_address",
"=",
"[",
"]",
"if",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Normalizing Address: {0}\"",
".",
"format",
"(",
"address",
")",
")",
"for",
"... | Normalize prefixes, suffixes and other to make matching original to returned easier. | [
"Normalize",
"prefixes",
"suffixes",
"and",
"other",
"to",
"make",
"matching",
"original",
"to",
"returned",
"easier",
"."
] | 62ebb07a6840e710d256406a8ec1d06abec0e1c4 | https://github.com/SwoopSearch/pyaddress/blob/62ebb07a6840e710d256406a8ec1d06abec0e1c4/address/address.py#L650-L671 | train |
AlexandreDecan/python-intervals | intervals.py | empty | def empty():
"""
Create an empty set.
"""
if not hasattr(empty, '_instance'):
empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN))
return empty._instance | python | def empty():
"""
Create an empty set.
"""
if not hasattr(empty, '_instance'):
empty._instance = Interval(AtomicInterval(OPEN, inf, -inf, OPEN))
return empty._instance | [
"def",
"empty",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"empty",
",",
"'_instance'",
")",
":",
"empty",
".",
"_instance",
"=",
"Interval",
"(",
"AtomicInterval",
"(",
"OPEN",
",",
"inf",
",",
"-",
"inf",
",",
"OPEN",
")",
")",
"return",
"empty",
... | Create an empty set. | [
"Create",
"an",
"empty",
"set",
"."
] | eda4da7dd39afabab2c1689e0b5158abae08c831 | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L115-L121 | train |
AlexandreDecan/python-intervals | intervals.py | from_data | def from_data(data, conv=None, pinf=float('inf'), ninf=float('-inf')):
"""
Import an interval from a piece of data.
:param data: a list of 4-uples (left, lower, upper, right).
:param conv: function that is used to convert "lower" and "upper" to bounds, default to identity.
:param pinf: value used t... | python | def from_data(data, conv=None, pinf=float('inf'), ninf=float('-inf')):
"""
Import an interval from a piece of data.
:param data: a list of 4-uples (left, lower, upper, right).
:param conv: function that is used to convert "lower" and "upper" to bounds, default to identity.
:param pinf: value used t... | [
"def",
"from_data",
"(",
"data",
",",
"conv",
"=",
"None",
",",
"pinf",
"=",
"float",
"(",
"'inf'",
")",
",",
"ninf",
"=",
"float",
"(",
"'-inf'",
")",
")",
":",
"intervals",
"=",
"[",
"]",
"conv",
"=",
"(",
"lambda",
"v",
":",
"v",
")",
"if",
... | Import an interval from a piece of data.
:param data: a list of 4-uples (left, lower, upper, right).
:param conv: function that is used to convert "lower" and "upper" to bounds, default to identity.
:param pinf: value used to represent positive infinity.
:param ninf: value used to represent negative in... | [
"Import",
"an",
"interval",
"from",
"a",
"piece",
"of",
"data",
"."
] | eda4da7dd39afabab2c1689e0b5158abae08c831 | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L228-L257 | train |
AlexandreDecan/python-intervals | intervals.py | AtomicInterval.is_empty | def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
return (
self._lower > self._upper or
(self._lower == self._upper and (self._left == OPEN or self._right == OPEN))
) | python | def is_empty(self):
"""
Test interval emptiness.
:return: True if interval is empty, False otherwise.
"""
return (
self._lower > self._upper or
(self._lower == self._upper and (self._left == OPEN or self._right == OPEN))
) | [
"def",
"is_empty",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_lower",
">",
"self",
".",
"_upper",
"or",
"(",
"self",
".",
"_lower",
"==",
"self",
".",
"_upper",
"and",
"(",
"self",
".",
"_left",
"==",
"OPEN",
"or",
"self",
".",
"_right",
... | Test interval emptiness.
:return: True if interval is empty, False otherwise. | [
"Test",
"interval",
"emptiness",
"."
] | eda4da7dd39afabab2c1689e0b5158abae08c831 | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L355-L364 | train |
AlexandreDecan/python-intervals | intervals.py | Interval.to_atomic | def to_atomic(self):
"""
Return the smallest atomic interval containing this interval.
:return: an AtomicInterval instance.
"""
lower = self._intervals[0].lower
left = self._intervals[0].left
upper = self._intervals[-1].upper
right = self._intervals[-1].r... | python | def to_atomic(self):
"""
Return the smallest atomic interval containing this interval.
:return: an AtomicInterval instance.
"""
lower = self._intervals[0].lower
left = self._intervals[0].left
upper = self._intervals[-1].upper
right = self._intervals[-1].r... | [
"def",
"to_atomic",
"(",
"self",
")",
":",
"lower",
"=",
"self",
".",
"_intervals",
"[",
"0",
"]",
".",
"lower",
"left",
"=",
"self",
".",
"_intervals",
"[",
"0",
"]",
".",
"left",
"upper",
"=",
"self",
".",
"_intervals",
"[",
"-",
"1",
"]",
".",... | Return the smallest atomic interval containing this interval.
:return: an AtomicInterval instance. | [
"Return",
"the",
"smallest",
"atomic",
"interval",
"containing",
"this",
"interval",
"."
] | eda4da7dd39afabab2c1689e0b5158abae08c831 | https://github.com/AlexandreDecan/python-intervals/blob/eda4da7dd39afabab2c1689e0b5158abae08c831/intervals.py#L730-L741 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.