hexsha stringlengths 40 40 | repo stringlengths 7 114 | path stringlengths 4 124 | license listlengths 1 9 | language stringclasses 1
value | identifier stringlengths 1 71 | return_type stringlengths 1 749 ⌀ | original_string stringlengths 76 22.7k | original_docstring stringlengths 16 7.61k | docstring stringlengths 16 2.47k | docstring_tokens listlengths 6 477 | code stringlengths 14 10.2k | code_tokens listlengths 6 996 | short_docstring stringlengths 2 644 | short_docstring_tokens listlengths 1 116 | comment listlengths 1 89 | parameters listlengths 0 64 | docstring_params dict |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6a88b9f26a8a20121162c5474c09f2e23fce6154 | ivan866/smoothPursuitClassification | parsers/MultiData.py | [
"MIT"
] | Python | check | bool | def check(self) -> bool:
"""Helper method that checks if multiData present at all.
:return: True if it is, False otherwise.
"""
#self.main.logger.debug('check data')
if not self.empty:
return True
else:
self.main.printToOut('WARNING: No da... | Helper method that checks if multiData present at all.
:return: True if it is, False otherwise.
| Helper method that checks if multiData present at all. | [
"Helper",
"method",
"that",
"checks",
"if",
"multiData",
"present",
"at",
"all",
"."
] | def check(self) -> bool:
if not self.empty:
return True
else:
self.main.printToOut('WARNING: No data loaded yet. Read data first!')
return False | [
"def",
"check",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"not",
"self",
".",
"empty",
":",
"return",
"True",
"else",
":",
"self",
".",
"main",
".",
"printToOut",
"(",
"'WARNING: No data loaded yet. Read data first!'",
")",
"return",
"False"
] | Helper method that checks if multiData present at all. | [
"Helper",
"method",
"that",
"checks",
"if",
"multiData",
"present",
"at",
"all",
"."
] | [
"\"\"\"Helper method that checks if multiData present at all.\n \n :return: True if it is, False otherwise.\n \"\"\"",
"#self.main.logger.debug('check data')"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "True if it is, False otherwise.",
"docstring_tokens": [
"True",
"if",
"it",
"is",
"False",
"otherwise",
"."
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
... |
4f6afb5ad583d0b28a254fb1d92b1c2a472f5428 | ivan866/smoothPursuitClassification | utils/Utils.py | [
"MIT"
] | Python | guessTimeFormat | str | def guessTimeFormat(val:object) -> str:
"""Helper method to determine the time strf string.
:param val: Time string to try to parse.
:return: Format string.
"""
if type(val) is not str:
val=str(val)
formats = ['%H:%M:%S.%f', '%M:%S.%f', '%M:%S', '%S.%f', '%S']
for fmt in format... | Helper method to determine the time strf string.
:param val: Time string to try to parse.
:return: Format string.
| Helper method to determine the time strf string. | [
"Helper",
"method",
"to",
"determine",
"the",
"time",
"strf",
"string",
"."
] | def guessTimeFormat(val:object) -> str:
if type(val) is not str:
val=str(val)
formats = ['%H:%M:%S.%f', '%M:%S.%f', '%M:%S', '%S.%f', '%S']
for fmt in formats:
try:
datetime.strptime(val, fmt)
except ValueError:
try:
pandas.to_datetime(val, uni... | [
"def",
"guessTimeFormat",
"(",
"val",
":",
"object",
")",
"->",
"str",
":",
"if",
"type",
"(",
"val",
")",
"is",
"not",
"str",
":",
"val",
"=",
"str",
"(",
"val",
")",
"formats",
"=",
"[",
"'%H:%M:%S.%f'",
",",
"'%M:%S.%f'",
",",
"'%M:%S'",
",",
"'... | Helper method to determine the time strf string. | [
"Helper",
"method",
"to",
"determine",
"the",
"time",
"strf",
"string",
"."
] | [
"\"\"\"Helper method to determine the time strf string.\n \n :param val: Time string to try to parse.\n :return: Format string.\n \"\"\"",
"#print('Time format of ' + val + ' string is guessed as ' + fmt + '.')"
] | [
{
"param": "val",
"type": "object"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "val",
"type": "object",
"docstring": "Time string to try to parse.",
"docstring_tokens": [
"Time",
... |
4f6afb5ad583d0b28a254fb1d92b1c2a472f5428 | ivan866/smoothPursuitClassification | utils/Utils.py | [
"MIT"
] | Python | parseTime | timedelta | def parseTime(val:object = 0) -> timedelta:
"""Helper method to convert time strings to datetime objects.
Agnostic of time string format.
:param val: Time string or float.
:return: timedelta object.
"""
val=str(val)
fmt=guessTimeFormat(val)
try:
parsed=datetime.strptime(val, fm... | Helper method to convert time strings to datetime objects.
Agnostic of time string format.
:param val: Time string or float.
:return: timedelta object.
| Helper method to convert time strings to datetime objects.
Agnostic of time string format. | [
"Helper",
"method",
"to",
"convert",
"time",
"strings",
"to",
"datetime",
"objects",
".",
"Agnostic",
"of",
"time",
"string",
"format",
"."
] | def parseTime(val:object = 0) -> timedelta:
val=str(val)
fmt=guessTimeFormat(val)
try:
parsed=datetime.strptime(val, fmt)
except ValueError:
parsed=pandas.to_datetime(val, unit='s')
return datetime.combine(date.min,parsed.time())-datetime.min | [
"def",
"parseTime",
"(",
"val",
":",
"object",
"=",
"0",
")",
"->",
"timedelta",
":",
"val",
"=",
"str",
"(",
"val",
")",
"fmt",
"=",
"guessTimeFormat",
"(",
"val",
")",
"try",
":",
"parsed",
"=",
"datetime",
".",
"strptime",
"(",
"val",
",",
"fmt"... | Helper method to convert time strings to datetime objects. | [
"Helper",
"method",
"to",
"convert",
"time",
"strings",
"to",
"datetime",
"objects",
"."
] | [
"\"\"\"Helper method to convert time strings to datetime objects.\n\n Agnostic of time string format.\n\n :param val: Time string or float.\n :return: timedelta object.\n \"\"\""
] | [
{
"param": "val",
"type": "object"
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "val",
"type": "object",
"docstring": "Time string or float.",
"docstring_tokens": [
"Time",
"string... |
4f6afb5ad583d0b28a254fb1d92b1c2a472f5428 | ivan866/smoothPursuitClassification | utils/Utils.py | [
"MIT"
] | Python | parseTimeV | Series | def parseTimeV(data:Series) -> Series:
"""Vectorized version of parseTime method.
:param data: pandas Series object.
:return: Same object with values converted to timedelta.
"""
if data.name=='Time' or data.name=='Recording timestamp':
return pandas.to_timedelta(data.astype(float), unit='s'... | Vectorized version of parseTime method.
:param data: pandas Series object.
:return: Same object with values converted to timedelta.
| Vectorized version of parseTime method. | [
"Vectorized",
"version",
"of",
"parseTime",
"method",
"."
] | def parseTimeV(data:Series) -> Series:
if data.name=='Time' or data.name=='Recording timestamp':
return pandas.to_timedelta(data.astype(float), unit='s')
else:
return pandas.to_datetime(data.astype(str), infer_datetime_format=True) - date.today() | [
"def",
"parseTimeV",
"(",
"data",
":",
"Series",
")",
"->",
"Series",
":",
"if",
"data",
".",
"name",
"==",
"'Time'",
"or",
"data",
".",
"name",
"==",
"'Recording timestamp'",
":",
"return",
"pandas",
".",
"to_timedelta",
"(",
"data",
".",
"astype",
"(",... | Vectorized version of parseTime method. | [
"Vectorized",
"version",
"of",
"parseTime",
"method",
"."
] | [
"\"\"\"Vectorized version of parseTime method.\n\n :param data: pandas Series object.\n :return: Same object with values converted to timedelta.\n \"\"\""
] | [
{
"param": "data",
"type": "Series"
}
] | {
"returns": [
{
"docstring": "Same object with values converted to timedelta.",
"docstring_tokens": [
"Same",
"object",
"with",
"values",
"converted",
"to",
"timedelta",
"."
],
"type": null
}
],
"raises": [],
"param... |
f9391a82b6ac7936e865c317f53715e3dfe03cf8 | mcx/core | tests/components/google/test_init.py | [
"Apache-2.0"
] | Python | add_event_call_service | Callable[dict[str, Any], Awaitable[None]] | def add_event_call_service(
hass: HomeAssistant,
request: Any,
) -> Callable[dict[str, Any], Awaitable[None]]:
"""Fixture for calling the add or create event service."""
(service_call, data, target) = request.param
async def call_service(params: dict[str, Any]) -> None:
await hass.services.... | Fixture for calling the add or create event service. | Fixture for calling the add or create event service. | [
"Fixture",
"for",
"calling",
"the",
"add",
"or",
"create",
"event",
"service",
"."
] | def add_event_call_service(
hass: HomeAssistant,
request: Any,
) -> Callable[dict[str, Any], Awaitable[None]]:
(service_call, data, target) = request.param
async def call_service(params: dict[str, Any]) -> None:
await hass.services.async_call(
DOMAIN,
service_call,
... | [
"def",
"add_event_call_service",
"(",
"hass",
":",
"HomeAssistant",
",",
"request",
":",
"Any",
",",
")",
"->",
"Callable",
"[",
"dict",
"[",
"str",
",",
"Any",
"]",
",",
"Awaitable",
"[",
"None",
"]",
"]",
":",
"(",
"service_call",
",",
"data",
",",
... | Fixture for calling the add or create event service. | [
"Fixture",
"for",
"calling",
"the",
"add",
"or",
"create",
"event",
"service",
"."
] | [
"\"\"\"Fixture for calling the add or create event service.\"\"\""
] | [
{
"param": "hass",
"type": "HomeAssistant"
},
{
"param": "request",
"type": "Any"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hass",
"type": "HomeAssistant",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "request",
"type": "Any",
"docstring": null,
"docst... |
cfea49881f4ec5cad4bde47974b80131d41ac54f | mcx/core | homeassistant/components/overkiz/climate_entities/somfy_thermostat.py | [
"Apache-2.0"
] | Python | hvac_mode | str | def hvac_mode(self) -> str:
"""Return hvac operation ie. heat, cool mode."""
return OVERKIZ_TO_HVAC_MODES[
cast(
str, self.executor.select_state(OverkizState.CORE_DEROGATION_ACTIVATION)
)
] | Return hvac operation ie. heat, cool mode. | Return hvac operation ie. heat, cool mode. | [
"Return",
"hvac",
"operation",
"ie",
".",
"heat",
"cool",
"mode",
"."
] | def hvac_mode(self) -> str:
return OVERKIZ_TO_HVAC_MODES[
cast(
str, self.executor.select_state(OverkizState.CORE_DEROGATION_ACTIVATION)
)
] | [
"def",
"hvac_mode",
"(",
"self",
")",
"->",
"str",
":",
"return",
"OVERKIZ_TO_HVAC_MODES",
"[",
"cast",
"(",
"str",
",",
"self",
".",
"executor",
".",
"select_state",
"(",
"OverkizState",
".",
"CORE_DEROGATION_ACTIVATION",
")",
")",
"]"
] | Return hvac operation ie. | [
"Return",
"hvac",
"operation",
"ie",
"."
] | [
"\"\"\"Return hvac operation ie. heat, cool mode.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cfea49881f4ec5cad4bde47974b80131d41ac54f | mcx/core | homeassistant/components/overkiz/climate_entities/somfy_thermostat.py | [
"Apache-2.0"
] | Python | hvac_action | str | def hvac_action(self) -> str:
"""Return the current running hvac operation if supported."""
if not self.current_temperature or not self.target_temperature:
return HVACAction.IDLE
if self.current_temperature < self.target_temperature:
return HVACAction.HEATING
retu... | Return the current running hvac operation if supported. | Return the current running hvac operation if supported. | [
"Return",
"the",
"current",
"running",
"hvac",
"operation",
"if",
"supported",
"."
] | def hvac_action(self) -> str:
if not self.current_temperature or not self.target_temperature:
return HVACAction.IDLE
if self.current_temperature < self.target_temperature:
return HVACAction.HEATING
return HVACAction.IDLE | [
"def",
"hvac_action",
"(",
"self",
")",
"->",
"str",
":",
"if",
"not",
"self",
".",
"current_temperature",
"or",
"not",
"self",
".",
"target_temperature",
":",
"return",
"HVACAction",
".",
"IDLE",
"if",
"self",
".",
"current_temperature",
"<",
"self",
".",
... | Return the current running hvac operation if supported. | [
"Return",
"the",
"current",
"running",
"hvac",
"operation",
"if",
"supported",
"."
] | [
"\"\"\"Return the current running hvac operation if supported.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cfea49881f4ec5cad4bde47974b80131d41ac54f | mcx/core | homeassistant/components/overkiz/climate_entities/somfy_thermostat.py | [
"Apache-2.0"
] | Python | target_temperature | float | None | def target_temperature(self) -> float | None:
"""Return the temperature we try to reach."""
if self.hvac_mode == HVACMode.AUTO:
if self.preset_mode == PRESET_NONE:
return None
return cast(
float,
self.executor.select_state(TARGET_TE... | Return the temperature we try to reach. | Return the temperature we try to reach. | [
"Return",
"the",
"temperature",
"we",
"try",
"to",
"reach",
"."
] | def target_temperature(self) -> float | None:
if self.hvac_mode == HVACMode.AUTO:
if self.preset_mode == PRESET_NONE:
return None
return cast(
float,
self.executor.select_state(TARGET_TEMP_TO_OVERKIZ[self.preset_mode]),
)
... | [
"def",
"target_temperature",
"(",
"self",
")",
"->",
"float",
"|",
"None",
":",
"if",
"self",
".",
"hvac_mode",
"==",
"HVACMode",
".",
"AUTO",
":",
"if",
"self",
".",
"preset_mode",
"==",
"PRESET_NONE",
":",
"return",
"None",
"return",
"cast",
"(",
"floa... | Return the temperature we try to reach. | [
"Return",
"the",
"temperature",
"we",
"try",
"to",
"reach",
"."
] | [
"\"\"\"Return the temperature we try to reach.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
cfea49881f4ec5cad4bde47974b80131d41ac54f | mcx/core | homeassistant/components/overkiz/climate_entities/somfy_thermostat.py | [
"Apache-2.0"
] | Python | async_set_hvac_mode | None | async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
"""Set new target hvac mode."""
if hvac_mode == HVACMode.AUTO:
await self.executor.async_execute_command(OverkizCommand.EXIT_DEROGATION)
await self.executor.async_execute_command(OverkizCommand.REFRESH_STATE)
... | Set new target hvac mode. | Set new target hvac mode. | [
"Set",
"new",
"target",
"hvac",
"mode",
"."
] | async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None:
if hvac_mode == HVACMode.AUTO:
await self.executor.async_execute_command(OverkizCommand.EXIT_DEROGATION)
await self.executor.async_execute_command(OverkizCommand.REFRESH_STATE)
else:
await self.async_se... | [
"async",
"def",
"async_set_hvac_mode",
"(",
"self",
",",
"hvac_mode",
":",
"HVACMode",
")",
"->",
"None",
":",
"if",
"hvac_mode",
"==",
"HVACMode",
".",
"AUTO",
":",
"await",
"self",
".",
"executor",
".",
"async_execute_command",
"(",
"OverkizCommand",
".",
... | Set new target hvac mode. | [
"Set",
"new",
"target",
"hvac",
"mode",
"."
] | [
"\"\"\"Set new target hvac mode.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "hvac_mode",
"type": "HVACMode"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "hvac_mode",
"type": "HVACMode",
"docstring": null,
"docstring... |
fc7be8ba8e879fab0fc5a256e64902aaff31de51 | mcx/core | pylint/plugins/hass_enforce_type_hints.py | [
"Apache-2.0"
] | Python | visit_module | None | def visit_module(self, node: nodes.Module) -> None:
"""Called when a Module node is visited."""
self._function_matchers = []
self._class_matchers = []
if (module_platform := _get_module_platform(node.name)) is None:
return
if module_platform in _PLATFORMS:
... | Called when a Module node is visited. | Called when a Module node is visited. | [
"Called",
"when",
"a",
"Module",
"node",
"is",
"visited",
"."
] | def visit_module(self, node: nodes.Module) -> None:
self._function_matchers = []
self._class_matchers = []
if (module_platform := _get_module_platform(node.name)) is None:
return
if module_platform in _PLATFORMS:
self._function_matchers.extend(_FUNCTION_MATCH["__a... | [
"def",
"visit_module",
"(",
"self",
",",
"node",
":",
"nodes",
".",
"Module",
")",
"->",
"None",
":",
"self",
".",
"_function_matchers",
"=",
"[",
"]",
"self",
".",
"_class_matchers",
"=",
"[",
"]",
"if",
"(",
"module_platform",
":=",
"_get_module_platform... | Called when a Module node is visited. | [
"Called",
"when",
"a",
"Module",
"node",
"is",
"visited",
"."
] | [
"\"\"\"Called when a Module node is visited.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "node",
"type": "nodes.Module"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "node",
"type": "nodes.Module",
"docstring": null,
"docstring_... |
fc7be8ba8e879fab0fc5a256e64902aaff31de51 | mcx/core | pylint/plugins/hass_enforce_type_hints.py | [
"Apache-2.0"
] | Python | visit_functiondef | None | def visit_functiondef(self, node: nodes.FunctionDef) -> None:
"""Called when a FunctionDef node is visited."""
for match in self._function_matchers:
if node.name != match.function_name or node.is_method():
continue
self._check_function(node, match) | Called when a FunctionDef node is visited. | Called when a FunctionDef node is visited. | [
"Called",
"when",
"a",
"FunctionDef",
"node",
"is",
"visited",
"."
] | def visit_functiondef(self, node: nodes.FunctionDef) -> None:
for match in self._function_matchers:
if node.name != match.function_name or node.is_method():
continue
self._check_function(node, match) | [
"def",
"visit_functiondef",
"(",
"self",
",",
"node",
":",
"nodes",
".",
"FunctionDef",
")",
"->",
"None",
":",
"for",
"match",
"in",
"self",
".",
"_function_matchers",
":",
"if",
"node",
".",
"name",
"!=",
"match",
".",
"function_name",
"or",
"node",
".... | Called when a FunctionDef node is visited. | [
"Called",
"when",
"a",
"FunctionDef",
"node",
"is",
"visited",
"."
] | [
"\"\"\"Called when a FunctionDef node is visited.\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "node",
"type": "nodes.FunctionDef"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "node",
"type": "nodes.FunctionDef",
"docstring": null,
"docst... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | calendars_config_entity | dict[str, Any] | def calendars_config_entity(
calendars_config_track: bool, calendars_config_ignore_availability: bool | None
) -> dict[str, Any]:
"""Fixture that creates an entity within the yaml configuration."""
entity = {
"device_id": "backyard_light",
"name": "Backyard Light",
"search": "#Backya... | Fixture that creates an entity within the yaml configuration. | Fixture that creates an entity within the yaml configuration. | [
"Fixture",
"that",
"creates",
"an",
"entity",
"within",
"the",
"yaml",
"configuration",
"."
] | def calendars_config_entity(
calendars_config_track: bool, calendars_config_ignore_availability: bool | None
) -> dict[str, Any]:
entity = {
"device_id": "backyard_light",
"name": "Backyard Light",
"search": "#Backyard",
"track": calendars_config_track,
}
if calendars_con... | [
"def",
"calendars_config_entity",
"(",
"calendars_config_track",
":",
"bool",
",",
"calendars_config_ignore_availability",
":",
"bool",
"|",
"None",
")",
"->",
"dict",
"[",
"str",
",",
"Any",
"]",
":",
"entity",
"=",
"{",
"\"device_id\"",
":",
"\"backyard_light\""... | Fixture that creates an entity within the yaml configuration. | [
"Fixture",
"that",
"creates",
"an",
"entity",
"within",
"the",
"yaml",
"configuration",
"."
] | [
"\"\"\"Fixture that creates an entity within the yaml configuration.\"\"\""
] | [
{
"param": "calendars_config_track",
"type": "bool"
},
{
"param": "calendars_config_ignore_availability",
"type": "bool | None"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "calendars_config_track",
"type": "bool",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "calendars_config_ignore_availability",
"type": "bool ... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | calendars_config | list[dict[str, Any]] | def calendars_config(calendars_config_entity: dict[str, Any]) -> list[dict[str, Any]]:
"""Fixture that specifies the calendar yaml configuration."""
return [
{
"cal_id": CALENDAR_ID,
"entities": [calendars_config_entity],
}
] | Fixture that specifies the calendar yaml configuration. | Fixture that specifies the calendar yaml configuration. | [
"Fixture",
"that",
"specifies",
"the",
"calendar",
"yaml",
"configuration",
"."
] | def calendars_config(calendars_config_entity: dict[str, Any]) -> list[dict[str, Any]]:
return [
{
"cal_id": CALENDAR_ID,
"entities": [calendars_config_entity],
}
] | [
"def",
"calendars_config",
"(",
"calendars_config_entity",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"list",
"[",
"dict",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"return",
"[",
"{",
"\"cal_id\"",
":",
"CALENDAR_ID",
",",
"\"entities\"",
":",
... | Fixture that specifies the calendar yaml configuration. | [
"Fixture",
"that",
"specifies",
"the",
"calendar",
"yaml",
"configuration",
"."
] | [
"\"\"\"Fixture that specifies the calendar yaml configuration.\"\"\""
] | [
{
"param": "calendars_config_entity",
"type": "dict[str, Any]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "calendars_config_entity",
"type": "dict[str, Any]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_calendars_yaml | Generator[Mock, None, None] | def mock_calendars_yaml(
hass: HomeAssistant,
calendars_config: list[dict[str, Any]],
) -> Generator[Mock, None, None]:
"""Fixture that prepares the google_calendars.yaml mocks."""
mocked_open_function = mock_open(read_data=yaml.dump(calendars_config))
with patch("homeassistant.components.google.ope... | Fixture that prepares the google_calendars.yaml mocks. | Fixture that prepares the google_calendars.yaml mocks. | [
"Fixture",
"that",
"prepares",
"the",
"google_calendars",
".",
"yaml",
"mocks",
"."
] | def mock_calendars_yaml(
hass: HomeAssistant,
calendars_config: list[dict[str, Any]],
) -> Generator[Mock, None, None]:
mocked_open_function = mock_open(read_data=yaml.dump(calendars_config))
with patch("homeassistant.components.google.open", mocked_open_function):
yield mocked_open_function | [
"def",
"mock_calendars_yaml",
"(",
"hass",
":",
"HomeAssistant",
",",
"calendars_config",
":",
"list",
"[",
"dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
")",
"->",
"Generator",
"[",
"Mock",
",",
"None",
",",
"None",
"]",
":",
"mocked_open_function",
"=... | Fixture that prepares the google_calendars.yaml mocks. | [
"Fixture",
"that",
"prepares",
"the",
"google_calendars",
".",
"yaml",
"mocks",
"."
] | [
"\"\"\"Fixture that prepares the google_calendars.yaml mocks.\"\"\""
] | [
{
"param": "hass",
"type": "HomeAssistant"
},
{
"param": "calendars_config",
"type": "list[dict[str, Any]]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hass",
"type": "HomeAssistant",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "calendars_config",
"type": "list[dict[str, Any]]",
"docs... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | token_expiry | datetime.datetime | def token_expiry() -> datetime.datetime:
"""Expiration time for credentials used in the test."""
# OAuth library returns an offset-naive timestamp
return datetime.datetime.fromtimestamp(
datetime.datetime.utcnow().timestamp()
) + datetime.timedelta(hours=1) | Expiration time for credentials used in the test. | Expiration time for credentials used in the test. | [
"Expiration",
"time",
"for",
"credentials",
"used",
"in",
"the",
"test",
"."
] | def token_expiry() -> datetime.datetime:
return datetime.datetime.fromtimestamp(
datetime.datetime.utcnow().timestamp()
) + datetime.timedelta(hours=1) | [
"def",
"token_expiry",
"(",
")",
"->",
"datetime",
".",
"datetime",
":",
"return",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"datetime",
".",
"datetime",
".",
"utcnow",
"(",
")",
".",
"timestamp",
"(",
")",
")",
"+",
"datetime",
".",
"timed... | Expiration time for credentials used in the test. | [
"Expiration",
"time",
"for",
"credentials",
"used",
"in",
"the",
"test",
"."
] | [
"\"\"\"Expiration time for credentials used in the test.\"\"\"",
"# OAuth library returns an offset-naive timestamp"
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | creds | OAuth2Credentials | def creds(
token_scopes: list[str], token_expiry: datetime.datetime
) -> OAuth2Credentials:
"""Fixture that defines creds used in the test."""
return OAuth2Credentials(
access_token="ACCESS_TOKEN",
client_id="client-id",
client_secret="client-secret",
refresh_token="REFRESH_T... | Fixture that defines creds used in the test. | Fixture that defines creds used in the test. | [
"Fixture",
"that",
"defines",
"creds",
"used",
"in",
"the",
"test",
"."
] | def creds(
token_scopes: list[str], token_expiry: datetime.datetime
) -> OAuth2Credentials:
return OAuth2Credentials(
access_token="ACCESS_TOKEN",
client_id="client-id",
client_secret="client-secret",
refresh_token="REFRESH_TOKEN",
token_expiry=token_expiry,
token... | [
"def",
"creds",
"(",
"token_scopes",
":",
"list",
"[",
"str",
"]",
",",
"token_expiry",
":",
"datetime",
".",
"datetime",
")",
"->",
"OAuth2Credentials",
":",
"return",
"OAuth2Credentials",
"(",
"access_token",
"=",
"\"ACCESS_TOKEN\"",
",",
"client_id",
"=",
"... | Fixture that defines creds used in the test. | [
"Fixture",
"that",
"defines",
"creds",
"used",
"in",
"the",
"test",
"."
] | [
"\"\"\"Fixture that defines creds used in the test.\"\"\""
] | [
{
"param": "token_scopes",
"type": "list[str]"
},
{
"param": "token_expiry",
"type": "datetime.datetime"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "token_scopes",
"type": "list[str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "token_expiry",
"type": "datetime.datetime",
"docstri... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | storage | YieldFixture[FakeStorage] | def storage() -> YieldFixture[FakeStorage]:
"""Fixture to populate an existing token file for read on startup."""
storage = FakeStorage()
with patch("homeassistant.components.google.Storage", return_value=storage):
yield storage | Fixture to populate an existing token file for read on startup. | Fixture to populate an existing token file for read on startup. | [
"Fixture",
"to",
"populate",
"an",
"existing",
"token",
"file",
"for",
"read",
"on",
"startup",
"."
] | def storage() -> YieldFixture[FakeStorage]:
storage = FakeStorage()
with patch("homeassistant.components.google.Storage", return_value=storage):
yield storage | [
"def",
"storage",
"(",
")",
"->",
"YieldFixture",
"[",
"FakeStorage",
"]",
":",
"storage",
"=",
"FakeStorage",
"(",
")",
"with",
"patch",
"(",
"\"homeassistant.components.google.Storage\"",
",",
"return_value",
"=",
"storage",
")",
":",
"yield",
"storage"
] | Fixture to populate an existing token file for read on startup. | [
"Fixture",
"to",
"populate",
"an",
"existing",
"token",
"file",
"for",
"read",
"on",
"startup",
"."
] | [
"\"\"\"Fixture to populate an existing token file for read on startup.\"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | config_entry | MockConfigEntry | def config_entry(
token_scopes: list[str],
config_entry_token_expiry: float,
config_entry_options: dict[str, Any] | None,
) -> MockConfigEntry:
"""Fixture to create a config entry for the integration."""
return MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation":... | Fixture to create a config entry for the integration. | Fixture to create a config entry for the integration. | [
"Fixture",
"to",
"create",
"a",
"config",
"entry",
"for",
"the",
"integration",
"."
] | def config_entry(
token_scopes: list[str],
config_entry_token_expiry: float,
config_entry_options: dict[str, Any] | None,
) -> MockConfigEntry:
return MockConfigEntry(
domain=DOMAIN,
data={
"auth_implementation": "device_auth",
"token": {
"access_t... | [
"def",
"config_entry",
"(",
"token_scopes",
":",
"list",
"[",
"str",
"]",
",",
"config_entry_token_expiry",
":",
"float",
",",
"config_entry_options",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
"|",
"None",
",",
")",
"->",
"MockConfigEntry",
":",
"return",
... | Fixture to create a config entry for the integration. | [
"Fixture",
"to",
"create",
"a",
"config",
"entry",
"for",
"the",
"integration",
"."
] | [
"\"\"\"Fixture to create a config entry for the integration.\"\"\""
] | [
{
"param": "token_scopes",
"type": "list[str]"
},
{
"param": "config_entry_token_expiry",
"type": "float"
},
{
"param": "config_entry_options",
"type": "dict[str, Any] | None"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "token_scopes",
"type": "list[str]",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "config_entry_token_expiry",
"type": "float",
"docstr... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_token_read | None | def mock_token_read(
hass: HomeAssistant,
creds: OAuth2Credentials,
storage: FakeStorage,
) -> None:
"""Fixture to populate an existing token file for read on startup."""
storage.put(creds) | Fixture to populate an existing token file for read on startup. | Fixture to populate an existing token file for read on startup. | [
"Fixture",
"to",
"populate",
"an",
"existing",
"token",
"file",
"for",
"read",
"on",
"startup",
"."
] | def mock_token_read(
hass: HomeAssistant,
creds: OAuth2Credentials,
storage: FakeStorage,
) -> None:
storage.put(creds) | [
"def",
"mock_token_read",
"(",
"hass",
":",
"HomeAssistant",
",",
"creds",
":",
"OAuth2Credentials",
",",
"storage",
":",
"FakeStorage",
",",
")",
"->",
"None",
":",
"storage",
".",
"put",
"(",
"creds",
")"
] | Fixture to populate an existing token file for read on startup. | [
"Fixture",
"to",
"populate",
"an",
"existing",
"token",
"file",
"for",
"read",
"on",
"startup",
"."
] | [
"\"\"\"Fixture to populate an existing token file for read on startup.\"\"\""
] | [
{
"param": "hass",
"type": "HomeAssistant"
},
{
"param": "creds",
"type": "OAuth2Credentials"
},
{
"param": "storage",
"type": "FakeStorage"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hass",
"type": "HomeAssistant",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "creds",
"type": "OAuth2Credentials",
"docstring": null,
... |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_events_list | ApiResult | def mock_events_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
"""Fixture to construct a fake event list API response."""
def _put_result(
response: dict[str, Any],
calendar_id: str = None,
exc: ClientError | None = None,
) -> None:
if calendar_id is None:
... | Fixture to construct a fake event list API response. | Fixture to construct a fake event list API response. | [
"Fixture",
"to",
"construct",
"a",
"fake",
"event",
"list",
"API",
"response",
"."
] | def mock_events_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
def _put_result(
response: dict[str, Any],
calendar_id: str = None,
exc: ClientError | None = None,
) -> None:
if calendar_id is None:
calendar_id = CALENDAR_ID
aioclient_mock.get(
... | [
"def",
"mock_events_list",
"(",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
")",
"->",
"ApiResult",
":",
"def",
"_put_result",
"(",
"response",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
",",
"calendar_id",
":",
"str",
"=",
"None",
",",
"exc",
":",
... | Fixture to construct a fake event list API response. | [
"Fixture",
"to",
"construct",
"a",
"fake",
"event",
"list",
"API",
"response",
"."
] | [
"\"\"\"Fixture to construct a fake event list API response.\"\"\""
] | [
{
"param": "aioclient_mock",
"type": "AiohttpClientMocker"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "aioclient_mock",
"type": "AiohttpClientMocker",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_calendars_list | ApiResult | def mock_calendars_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
"""Fixture to construct a fake calendar list API response."""
def _result(response: dict[str, Any], exc: ClientError | None = None) -> None:
aioclient_mock.get(
f"{API_BASE_URL}/users/me/calendarList",
... | Fixture to construct a fake calendar list API response. | Fixture to construct a fake calendar list API response. | [
"Fixture",
"to",
"construct",
"a",
"fake",
"calendar",
"list",
"API",
"response",
"."
] | def mock_calendars_list(
aioclient_mock: AiohttpClientMocker,
) -> ApiResult:
def _result(response: dict[str, Any], exc: ClientError | None = None) -> None:
aioclient_mock.get(
f"{API_BASE_URL}/users/me/calendarList",
json=response,
exc=exc,
)
return
... | [
"def",
"mock_calendars_list",
"(",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
")",
"->",
"ApiResult",
":",
"def",
"_result",
"(",
"response",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
",",
"exc",
":",
"ClientError",
"|",
"None",
"=",
"None",
")",
... | Fixture to construct a fake calendar list API response. | [
"Fixture",
"to",
"construct",
"a",
"fake",
"calendar",
"list",
"API",
"response",
"."
] | [
"\"\"\"Fixture to construct a fake calendar list API response.\"\"\""
] | [
{
"param": "aioclient_mock",
"type": "AiohttpClientMocker"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "aioclient_mock",
"type": "AiohttpClientMocker",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_calendar_get | Callable[[...], None] | def mock_calendar_get(
aioclient_mock: AiohttpClientMocker,
) -> Callable[[...], None]:
"""Fixture for returning a calendar get response."""
def _result(
calendar_id: str, response: dict[str, Any], exc: ClientError | None = None
) -> None:
aioclient_mock.get(
f"{API_BASE_URL... | Fixture for returning a calendar get response. | Fixture for returning a calendar get response. | [
"Fixture",
"for",
"returning",
"a",
"calendar",
"get",
"response",
"."
] | def mock_calendar_get(
aioclient_mock: AiohttpClientMocker,
) -> Callable[[...], None]:
def _result(
calendar_id: str, response: dict[str, Any], exc: ClientError | None = None
) -> None:
aioclient_mock.get(
f"{API_BASE_URL}/calendars/{calendar_id}",
json=response,
... | [
"def",
"mock_calendar_get",
"(",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
")",
"->",
"Callable",
"[",
"[",
"...",
"]",
",",
"None",
"]",
":",
"def",
"_result",
"(",
"calendar_id",
":",
"str",
",",
"response",
":",
"dict",
"[",
"str",
",",
"Any"... | Fixture for returning a calendar get response. | [
"Fixture",
"for",
"returning",
"a",
"calendar",
"get",
"response",
"."
] | [
"\"\"\"Fixture for returning a calendar get response.\"\"\""
] | [
{
"param": "aioclient_mock",
"type": "AiohttpClientMocker"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "aioclient_mock",
"type": "AiohttpClientMocker",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | mock_insert_event | Callable[[...], None] | def mock_insert_event(
aioclient_mock: AiohttpClientMocker,
) -> Callable[[...], None]:
"""Fixture for capturing event creation."""
def _expect_result(calendar_id: str = CALENDAR_ID) -> None:
aioclient_mock.post(
f"{API_BASE_URL}/calendars/{calendar_id}/events",
)
return... | Fixture for capturing event creation. | Fixture for capturing event creation. | [
"Fixture",
"for",
"capturing",
"event",
"creation",
"."
] | def mock_insert_event(
aioclient_mock: AiohttpClientMocker,
) -> Callable[[...], None]:
def _expect_result(calendar_id: str = CALENDAR_ID) -> None:
aioclient_mock.post(
f"{API_BASE_URL}/calendars/{calendar_id}/events",
)
return
return _expect_result | [
"def",
"mock_insert_event",
"(",
"aioclient_mock",
":",
"AiohttpClientMocker",
",",
")",
"->",
"Callable",
"[",
"[",
"...",
"]",
",",
"None",
"]",
":",
"def",
"_expect_result",
"(",
"calendar_id",
":",
"str",
"=",
"CALENDAR_ID",
")",
"->",
"None",
":",
"ai... | Fixture for capturing event creation. | [
"Fixture",
"for",
"capturing",
"event",
"creation",
"."
] | [
"\"\"\"Fixture for capturing event creation.\"\"\""
] | [
{
"param": "aioclient_mock",
"type": "AiohttpClientMocker"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "aioclient_mock",
"type": "AiohttpClientMocker",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | google_config | dict[str, Any] | def google_config(google_config_track_new: bool | None) -> dict[str, Any]:
"""Fixture for overriding component config."""
google_config = {CONF_CLIENT_ID: "client-id", CONF_CLIENT_SECRET: "client-secret"}
if google_config_track_new is not None:
google_config[CONF_TRACK_NEW] = google_config_track_new... | Fixture for overriding component config. | Fixture for overriding component config. | [
"Fixture",
"for",
"overriding",
"component",
"config",
"."
] | def google_config(google_config_track_new: bool | None) -> dict[str, Any]:
google_config = {CONF_CLIENT_ID: "client-id", CONF_CLIENT_SECRET: "client-secret"}
if google_config_track_new is not None:
google_config[CONF_TRACK_NEW] = google_config_track_new
return google_config | [
"def",
"google_config",
"(",
"google_config_track_new",
":",
"bool",
"|",
"None",
")",
"->",
"dict",
"[",
"str",
",",
"Any",
"]",
":",
"google_config",
"=",
"{",
"CONF_CLIENT_ID",
":",
"\"client-id\"",
",",
"CONF_CLIENT_SECRET",
":",
"\"client-secret\"",
"}",
... | Fixture for overriding component config. | [
"Fixture",
"for",
"overriding",
"component",
"config",
"."
] | [
"\"\"\"Fixture for overriding component config.\"\"\""
] | [
{
"param": "google_config_track_new",
"type": "bool | None"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "google_config_track_new",
"type": "bool | None",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
27fb6c993ffc843da142056f835e86c80233016c | mcx/core | tests/components/google/conftest.py | [
"Apache-2.0"
] | Python | component_setup | ComponentSetup | def component_setup(hass: HomeAssistant, config: dict[str, Any]) -> ComponentSetup:
"""Fixture for setting up the integration."""
async def _setup_func() -> bool:
result = await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
return result
return _set... | Fixture for setting up the integration. | Fixture for setting up the integration. | [
"Fixture",
"for",
"setting",
"up",
"the",
"integration",
"."
] | def component_setup(hass: HomeAssistant, config: dict[str, Any]) -> ComponentSetup:
async def _setup_func() -> bool:
result = await async_setup_component(hass, DOMAIN, config)
await hass.async_block_till_done()
return result
return _setup_func | [
"def",
"component_setup",
"(",
"hass",
":",
"HomeAssistant",
",",
"config",
":",
"dict",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"ComponentSetup",
":",
"async",
"def",
"_setup_func",
"(",
")",
"->",
"bool",
":",
"result",
"=",
"await",
"async_setup_compone... | Fixture for setting up the integration. | [
"Fixture",
"for",
"setting",
"up",
"the",
"integration",
"."
] | [
"\"\"\"Fixture for setting up the integration.\"\"\""
] | [
{
"param": "hass",
"type": "HomeAssistant"
},
{
"param": "config",
"type": "dict[str, Any]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hass",
"type": "HomeAssistant",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "config",
"type": "dict[str, Any]",
"docstring": null,
... |
a089163a826fe978ab2ef3c5eb1ee98392a92c0e | mcx/core | homeassistant/components/nest/camera_sdm.py | [
"Apache-2.0"
] | Python | frontend_stream_type | StreamType | None | def frontend_stream_type(self) -> StreamType | None:
"""Return the type of stream supported by this camera."""
if CameraLiveStreamTrait.NAME not in self._device.traits:
return None
trait = self._device.traits[CameraLiveStreamTrait.NAME]
if StreamingProtocol.WEB_RTC in trait.s... | Return the type of stream supported by this camera. | Return the type of stream supported by this camera. | [
"Return",
"the",
"type",
"of",
"stream",
"supported",
"by",
"this",
"camera",
"."
] | def frontend_stream_type(self) -> StreamType | None:
if CameraLiveStreamTrait.NAME not in self._device.traits:
return None
trait = self._device.traits[CameraLiveStreamTrait.NAME]
if StreamingProtocol.WEB_RTC in trait.supported_protocols:
return StreamType.WEB_RTC
... | [
"def",
"frontend_stream_type",
"(",
"self",
")",
"->",
"StreamType",
"|",
"None",
":",
"if",
"CameraLiveStreamTrait",
".",
"NAME",
"not",
"in",
"self",
".",
"_device",
".",
"traits",
":",
"return",
"None",
"trait",
"=",
"self",
".",
"_device",
".",
"traits... | Return the type of stream supported by this camera. | [
"Return",
"the",
"type",
"of",
"stream",
"supported",
"by",
"this",
"camera",
"."
] | [
"\"\"\"Return the type of stream supported by this camera.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a089163a826fe978ab2ef3c5eb1ee98392a92c0e | mcx/core | homeassistant/components/nest/camera_sdm.py | [
"Apache-2.0"
] | Python | stream_source | str | None | async def stream_source(self) -> str | None:
"""Return the source of the stream."""
if not self.supported_features & CameraEntityFeature.STREAM:
return None
if CameraLiveStreamTrait.NAME not in self._device.traits:
return None
trait = self._device.traits[CameraLiv... | Return the source of the stream. | Return the source of the stream. | [
"Return",
"the",
"source",
"of",
"the",
"stream",
"."
] | async def stream_source(self) -> str | None:
if not self.supported_features & CameraEntityFeature.STREAM:
return None
if CameraLiveStreamTrait.NAME not in self._device.traits:
return None
trait = self._device.traits[CameraLiveStreamTrait.NAME]
if StreamingProtocol... | [
"async",
"def",
"stream_source",
"(",
"self",
")",
"->",
"str",
"|",
"None",
":",
"if",
"not",
"self",
".",
"supported_features",
"&",
"CameraEntityFeature",
".",
"STREAM",
":",
"return",
"None",
"if",
"CameraLiveStreamTrait",
".",
"NAME",
"not",
"in",
"self... | Return the source of the stream. | [
"Return",
"the",
"source",
"of",
"the",
"stream",
"."
] | [
"\"\"\"Return the source of the stream.\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
a089163a826fe978ab2ef3c5eb1ee98392a92c0e | mcx/core | homeassistant/components/nest/camera_sdm.py | [
"Apache-2.0"
] | Python | _handle_stream_refresh | None | async def _handle_stream_refresh(self, now: datetime.datetime) -> None:
"""Alarm that fires to check if the stream should be refreshed."""
if not self._stream:
return
_LOGGER.debug("Extending stream url")
try:
self._stream = await self._stream.extend_rtsp_stream()... | Alarm that fires to check if the stream should be refreshed. | Alarm that fires to check if the stream should be refreshed. | [
"Alarm",
"that",
"fires",
"to",
"check",
"if",
"the",
"stream",
"should",
"be",
"refreshed",
"."
] | async def _handle_stream_refresh(self, now: datetime.datetime) -> None:
if not self._stream:
return
_LOGGER.debug("Extending stream url")
try:
self._stream = await self._stream.extend_rtsp_stream()
except ApiException as err:
_LOGGER.debug("Failed to e... | [
"async",
"def",
"_handle_stream_refresh",
"(",
"self",
",",
"now",
":",
"datetime",
".",
"datetime",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"_stream",
":",
"return",
"_LOGGER",
".",
"debug",
"(",
"\"Extending stream url\"",
")",
"try",
":",
"sel... | Alarm that fires to check if the stream should be refreshed. | [
"Alarm",
"that",
"fires",
"to",
"check",
"if",
"the",
"stream",
"should",
"be",
"refreshed",
"."
] | [
"\"\"\"Alarm that fires to check if the stream should be refreshed.\"\"\"",
"# Next attempt to catch a url will get a new one",
"# Update the stream worker with the latest valid url"
] | [
{
"param": "self",
"type": null
},
{
"param": "now",
"type": "datetime.datetime"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "now",
"type": "datetime.datetime",
"docstring": null,
"docstr... |
a089163a826fe978ab2ef3c5eb1ee98392a92c0e | mcx/core | homeassistant/components/nest/camera_sdm.py | [
"Apache-2.0"
] | Python | async_camera_image | bytes | None | async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
"""Return bytes of camera image."""
# Use the thumbnail from RTSP stream, or a placeholder if stream is
# not supported (e.g. WebRTC)
stream = await self.async_create_st... | Return bytes of camera image. | Return bytes of camera image. | [
"Return",
"bytes",
"of",
"camera",
"image",
"."
] | async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
stream = await self.async_create_stream()
if stream:
return await stream.async_get_image(width, height)
return await self.hass.async_add_executor_job(self.placeholde... | [
"async",
"def",
"async_camera_image",
"(",
"self",
",",
"width",
":",
"int",
"|",
"None",
"=",
"None",
",",
"height",
":",
"int",
"|",
"None",
"=",
"None",
")",
"->",
"bytes",
"|",
"None",
":",
"stream",
"=",
"await",
"self",
".",
"async_create_stream"... | Return bytes of camera image. | [
"Return",
"bytes",
"of",
"camera",
"image",
"."
] | [
"\"\"\"Return bytes of camera image.\"\"\"",
"# Use the thumbnail from RTSP stream, or a placeholder if stream is",
"# not supported (e.g. WebRTC)"
] | [
{
"param": "self",
"type": null
},
{
"param": "width",
"type": "int | None"
},
{
"param": "height",
"type": "int | None"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "width",
"type": "int | None",
"docstring": null,
"docstring_t... |
3b9915d0a89f60f95b9169102c0a230284d724e6 | mcx/core | homeassistant/components/sensibo/switch.py | [
"Apache-2.0"
] | Python | build_params | dict[str, Any] | None | def build_params(command: str, device_data: SensiboDevice) -> dict[str, Any] | None:
"""Build params for turning on switch."""
if command == "set_timer":
new_state = bool(device_data.ac_states["on"] is False)
params = {
"minutesFromNow": 60,
"acState": {**device_data.ac_s... | Build params for turning on switch. | Build params for turning on switch. | [
"Build",
"params",
"for",
"turning",
"on",
"switch",
"."
] | def build_params(command: str, device_data: SensiboDevice) -> dict[str, Any] | None:
if command == "set_timer":
new_state = bool(device_data.ac_states["on"] is False)
params = {
"minutesFromNow": 60,
"acState": {**device_data.ac_states, "on": new_state},
}
ret... | [
"def",
"build_params",
"(",
"command",
":",
"str",
",",
"device_data",
":",
"SensiboDevice",
")",
"->",
"dict",
"[",
"str",
",",
"Any",
"]",
"|",
"None",
":",
"if",
"command",
"==",
"\"set_timer\"",
":",
"new_state",
"=",
"bool",
"(",
"device_data",
".",... | Build params for turning on switch. | [
"Build",
"params",
"for",
"turning",
"on",
"switch",
"."
] | [
"\"\"\"Build params for turning on switch.\"\"\""
] | [
{
"param": "command",
"type": "str"
},
{
"param": "device_data",
"type": "SensiboDevice"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "command",
"type": "str",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "device_data",
"type": "SensiboDevice",
"docstring": null,
... |
3b9915d0a89f60f95b9169102c0a230284d724e6 | mcx/core | homeassistant/components/sensibo/switch.py | [
"Apache-2.0"
] | Python | async_setup_entry | None | async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up Sensibo binary sensor platform."""
coordinator: SensiboDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
entities: list[SensiboDeviceSwitch] = []
entities.ext... | Set up Sensibo binary sensor platform. | Set up Sensibo binary sensor platform. | [
"Set",
"up",
"Sensibo",
"binary",
"sensor",
"platform",
"."
] | async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
coordinator: SensiboDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
entities: list[SensiboDeviceSwitch] = []
entities.extend(
SensiboDeviceSwitch(coordinator, device... | [
"async",
"def",
"async_setup_entry",
"(",
"hass",
":",
"HomeAssistant",
",",
"entry",
":",
"ConfigEntry",
",",
"async_add_entities",
":",
"AddEntitiesCallback",
")",
"->",
"None",
":",
"coordinator",
":",
"SensiboDataUpdateCoordinator",
"=",
"hass",
".",
"data",
"... | Set up Sensibo binary sensor platform. | [
"Set",
"up",
"Sensibo",
"binary",
"sensor",
"platform",
"."
] | [
"\"\"\"Set up Sensibo binary sensor platform.\"\"\""
] | [
{
"param": "hass",
"type": "HomeAssistant"
},
{
"param": "entry",
"type": "ConfigEntry"
},
{
"param": "async_add_entities",
"type": "AddEntitiesCallback"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "hass",
"type": "HomeAssistant",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "entry",
"type": "ConfigEntry",
"docstring": null,
... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _load_stim | <not_specific> | def _load_stim(stim_model):
""" Load Stimulus model to Pliers Stimulus object """
stims = []
if stim_model.path is None:
stims.append(
(stim_model, ComplexTextStim(text=stim_model.content)))
stims.append(
(stim_model, TextStim(text=stims[-1][1].data)))
else:
... | Load Stimulus model to Pliers Stimulus object | Load Stimulus model to Pliers Stimulus object | [
"Load",
"Stimulus",
"model",
"to",
"Pliers",
"Stimulus",
"object"
] | def _load_stim(stim_model):
stims = []
if stim_model.path is None:
stims.append(
(stim_model, ComplexTextStim(text=stim_model.content)))
stims.append(
(stim_model, TextStim(text=stims[-1][1].data)))
else:
stims.append(
(stim_model, load_stims(stim_... | [
"def",
"_load_stim",
"(",
"stim_model",
")",
":",
"stims",
"=",
"[",
"]",
"if",
"stim_model",
".",
"path",
"is",
"None",
":",
"stims",
".",
"append",
"(",
"(",
"stim_model",
",",
"ComplexTextStim",
"(",
"text",
"=",
"stim_model",
".",
"content",
")",
"... | Load Stimulus model to Pliers Stimulus object | [
"Load",
"Stimulus",
"model",
"to",
"Pliers",
"Stimulus",
"object"
] | [
"\"\"\" Load Stimulus model to Pliers Stimulus object \"\"\""
] | [
{
"param": "stim_model",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stim_model",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _query_stim_models | <not_specific> | def _query_stim_models(dataset_name, task_name=None, graphs=None):
""" Given a dataset and task, query all matching stimuli.
Optionally a list of graphs can be provided which further restrict
the stimuli to only those necessary for those graphs """
stim_models = Stimulus.query.filter_by(active=True).fi... | Given a dataset and task, query all matching stimuli.
Optionally a list of graphs can be provided which further restrict
the stimuli to only those necessary for those graphs | Given a dataset and task, query all matching stimuli.
Optionally a list of graphs can be provided which further restrict
the stimuli to only those necessary for those graphs | [
"Given",
"a",
"dataset",
"and",
"task",
"query",
"all",
"matching",
"stimuli",
".",
"Optionally",
"a",
"list",
"of",
"graphs",
"can",
"be",
"provided",
"which",
"further",
"restrict",
"the",
"stimuli",
"to",
"only",
"those",
"necessary",
"for",
"those",
"gra... | def _query_stim_models(dataset_name, task_name=None, graphs=None):
stim_models = Stimulus.query.filter_by(active=True).filter(
Stimulus.mimetype != 'text/csv')
if graphs is not None:
mimetypes = []
for g in graphs:
it = g.roots[0].transformer._input_type
if not is... | [
"def",
"_query_stim_models",
"(",
"dataset_name",
",",
"task_name",
"=",
"None",
",",
"graphs",
"=",
"None",
")",
":",
"stim_models",
"=",
"Stimulus",
".",
"query",
".",
"filter_by",
"(",
"active",
"=",
"True",
")",
".",
"filter",
"(",
"Stimulus",
".",
"... | Given a dataset and task, query all matching stimuli. | [
"Given",
"a",
"dataset",
"and",
"task",
"query",
"all",
"matching",
"stimuli",
"."
] | [
"\"\"\" Given a dataset and task, query all matching stimuli.\n Optionally a list of graphs can be provided which further restrict\n the stimuli to only those necessary for those graphs \"\"\"",
"# Determine the necessary stimuli to load"
] | [
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
},
{
"param": "graphs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task_name",
"type": null,
"docstring": null,
"docstri... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _extract_to_serial | <not_specific> | def _extract_to_serial(graphs, stim_object, serializer):
""" For a stim_object, load stim and apply graphs, and serialize """
results = []
for stim_obj, pliers_stim in _load_stim(stim_object):
# For each graph, check compatability, and then extract
for graph in graphs:
ext = grap... | For a stim_object, load stim and apply graphs, and serialize | For a stim_object, load stim and apply graphs, and serialize | [
"For",
"a",
"stim_object",
"load",
"stim",
"and",
"apply",
"graphs",
"and",
"serialize"
] | def _extract_to_serial(graphs, stim_object, serializer):
results = []
for stim_obj, pliers_stim in _load_stim(stim_object):
for graph in graphs:
ext = graph.roots[0].transformer
if ext._stim_matches_input_types(pliers_stim):
if 'GoogleVideoAPIShotDetectionExtracto... | [
"def",
"_extract_to_serial",
"(",
"graphs",
",",
"stim_object",
",",
"serializer",
")",
":",
"results",
"=",
"[",
"]",
"for",
"stim_obj",
",",
"pliers_stim",
"in",
"_load_stim",
"(",
"stim_object",
")",
":",
"for",
"graph",
"in",
"graphs",
":",
"ext",
"=",... | For a stim_object, load stim and apply graphs, and serialize | [
"For",
"a",
"stim_object",
"load",
"stim",
"and",
"apply",
"graphs",
"and",
"serialize"
] | [
"\"\"\" For a stim_object, load stim and apply graphs, and serialize \"\"\"",
"# For each graph, check compatability, and then extract",
"# Hacky workaround. Look for compatible AVI",
"# Try again (may be connection error)"
] | [
{
"param": "graphs",
"type": null
},
{
"param": "stim_object",
"type": null
},
{
"param": "serializer",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "graphs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "stim_object",
"type": null,
"docstring": null,
"docstring_t... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _create_efs | <not_specific> | def _create_efs(results):
""" Create ExtractedFeature models from Pliers results.
Only creates one object per unique feature
Args:
results - list of zipped pairs of Stimulus objects and ExtractedResult
objects
Returns:
ext_feats - dictionary of hash of ExtractedFeat... | Create ExtractedFeature models from Pliers results.
Only creates one object per unique feature
Args:
results - list of zipped pairs of Stimulus objects and ExtractedResult
objects
Returns:
ext_feats - dictionary of hash of ExtractedFeatures to EF objects
| Create ExtractedFeature models from Pliers results.
Only creates one object per unique feature
Args:
results - list of zipped pairs of Stimulus objects and ExtractedResult
objects
Returns:
ext_feats - dictionary of hash of ExtractedFeatures to EF objects | [
"Create",
"ExtractedFeature",
"models",
"from",
"Pliers",
"results",
".",
"Only",
"creates",
"one",
"object",
"per",
"unique",
"feature",
"Args",
":",
"results",
"-",
"list",
"of",
"zipped",
"pairs",
"of",
"Stimulus",
"objects",
"and",
"ExtractedResult",
"object... | def _create_efs(results):
ext_feats = {}
bulk_ees = []
print("Creating ExtractedFeatures...")
for stim_id, ser in tqdm(results):
for ee_props, ef_props in ser:
feat_hash = ef_props['sha1_hash']
if feat_hash not in ext_feats:
ef_model = ExtractedFeature(**e... | [
"def",
"_create_efs",
"(",
"results",
")",
":",
"ext_feats",
"=",
"{",
"}",
"bulk_ees",
"=",
"[",
"]",
"print",
"(",
"\"Creating ExtractedFeatures...\"",
")",
"for",
"stim_id",
",",
"ser",
"in",
"tqdm",
"(",
"results",
")",
":",
"for",
"ee_props",
",",
"... | Create ExtractedFeature models from Pliers results. | [
"Create",
"ExtractedFeature",
"models",
"from",
"Pliers",
"results",
"."
] | [
"\"\"\" Create ExtractedFeature models from Pliers results.\n Only creates one object per unique feature\n Args:\n results - list of zipped pairs of Stimulus objects and ExtractedResult\n objects\n Returns:\n ext_feats - dictionary of hash of ExtractedFeatures to EF objec... | [
{
"param": "results",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "results",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | extract_features | <not_specific> | def extract_features(graphs, dataset_name=None, task_name=None, n_jobs=1,
**serializer_kwargs):
""" Extract features using pliers for a dataset/task
Args:
graphs - List of Graphs to apply to stimuli
dataset_name - dataset name (optional;)
task_name - ... | Extract features using pliers for a dataset/task
Args:
graphs - List of Graphs to apply to stimuli
dataset_name - dataset name (optional;)
task_name - task name (optional)
serializer_kwargs - Arguments to pass to FeatureSerializer
Output:
list... | Extract features using pliers for a dataset/task
Args:
graphs - List of Graphs to apply to stimuli
dataset_name - dataset name (optional;)
task_name - task name (optional)
serializer_kwargs - Arguments to pass to FeatureSerializer
Output:
list of db ids of extracted features | [
"Extract",
"features",
"using",
"pliers",
"for",
"a",
"dataset",
"/",
"task",
"Args",
":",
"graphs",
"-",
"List",
"of",
"Graphs",
"to",
"apply",
"to",
"stimuli",
"dataset_name",
"-",
"dataset",
"name",
"(",
"optional",
";",
")",
"task_name",
"-",
"task",
... | def extract_features(graphs, dataset_name=None, task_name=None, n_jobs=1,
**serializer_kwargs):
serializer = FeatureSerializer(**serializer_kwargs)
if dataset_name is None:
return [extract_features(
graphs, dataset.name, None, **serializer_kwargs)
for dat... | [
"def",
"extract_features",
"(",
"graphs",
",",
"dataset_name",
"=",
"None",
",",
"task_name",
"=",
"None",
",",
"n_jobs",
"=",
"1",
",",
"**",
"serializer_kwargs",
")",
":",
"serializer",
"=",
"FeatureSerializer",
"(",
"**",
"serializer_kwargs",
")",
"if",
"... | Extract features using pliers for a dataset/task
Args:
graphs - List of Graphs to apply to stimuli
dataset_name - dataset name (optional;)
task_name - task name (optional)
serializer_kwargs - Arguments to pass to FeatureSerializer
Output:
list of db ids of extracted features | [
"Extract",
"features",
"using",
"pliers",
"for",
"a",
"dataset",
"/",
"task",
"Args",
":",
"graphs",
"-",
"List",
"of",
"Graphs",
"to",
"apply",
"to",
"stimuli",
"dataset_name",
"-",
"dataset",
"name",
"(",
"optional",
";",
")",
"task_name",
"-",
"task",
... | [
"\"\"\" Extract features using pliers for a dataset/task\n Args:\n graphs - List of Graphs to apply to stimuli\n dataset_name - dataset name (optional;)\n task_name - task name (optional)\n serializer_kwargs - Arguments to pass to FeatureSerializer\n Output:... | [
{
"param": "graphs",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
},
{
"param": "n_jobs",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "graphs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstring_... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _load_complex_text_stim_models | <not_specific> | def _load_complex_text_stim_models(dataset_name, task_name=None):
""" Reconstruct ComplexTextStim object of complete run transcript
for each run in a task """
stim_models = Stimulus.query.filter_by(
active=True, mimetype='text/csv').join(
RunStimulus).join(Run).join(Task)
if... | Reconstruct ComplexTextStim object of complete run transcript
for each run in a task | Reconstruct ComplexTextStim object of complete run transcript
for each run in a task | [
"Reconstruct",
"ComplexTextStim",
"object",
"of",
"complete",
"run",
"transcript",
"for",
"each",
"run",
"in",
"a",
"task"
] | def _load_complex_text_stim_models(dataset_name, task_name=None):
stim_models = Stimulus.query.filter_by(
active=True, mimetype='text/csv').join(
RunStimulus).join(Run).join(Task)
if task_name is not None:
stim_models = stim_models.filter_by(name=task_name)
stim_models = stim_mod... | [
"def",
"_load_complex_text_stim_models",
"(",
"dataset_name",
",",
"task_name",
"=",
"None",
")",
":",
"stim_models",
"=",
"Stimulus",
".",
"query",
".",
"filter_by",
"(",
"active",
"=",
"True",
",",
"mimetype",
"=",
"'text/csv'",
")",
".",
"join",
"(",
"Run... | Reconstruct ComplexTextStim object of complete run transcript
for each run in a task | [
"Reconstruct",
"ComplexTextStim",
"object",
"of",
"complete",
"run",
"transcript",
"for",
"each",
"run",
"in",
"a",
"task"
] | [
"\"\"\" Reconstruct ComplexTextStim object of complete run transcript\n for each run in a task \"\"\"",
"# Reconstruct complete ComplexTextStim"
] | [
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task_name",
"type": null,
"docstring": null,
"docstri... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | _window_stim | <not_specific> | def _window_stim(cts, n):
""" Return windowed slices from a ComplexTextStim
Args:
cts - _load_complex_text_stim_models
n - size of window prior to current stimulus
Output:
list of ComplexTextStim with n elements
"""
ix_high = n
ix_low = 0
slices = ... | Return windowed slices from a ComplexTextStim
Args:
cts - _load_complex_text_stim_models
n - size of window prior to current stimulus
Output:
list of ComplexTextStim with n elements
| Return windowed slices from a ComplexTextStim
Args:
cts - _load_complex_text_stim_models
n - size of window prior to current stimulus
Output:
list of ComplexTextStim with n elements | [
"Return",
"windowed",
"slices",
"from",
"a",
"ComplexTextStim",
"Args",
":",
"cts",
"-",
"_load_complex_text_stim_models",
"n",
"-",
"size",
"of",
"window",
"prior",
"to",
"current",
"stimulus",
"Output",
":",
"list",
"of",
"ComplexTextStim",
"with",
"n",
"eleme... | def _window_stim(cts, n):
ix_high = n
ix_low = 0
slices = []
while ix_high <= len(cts.elements):
subset_stim = ComplexTextStim(elements=cts.elements[ix_low:ix_high])
slices.append(subset_stim)
ix_high += 1
ix_low = ix_high - n
return slices | [
"def",
"_window_stim",
"(",
"cts",
",",
"n",
")",
":",
"ix_high",
"=",
"n",
"ix_low",
"=",
"0",
"slices",
"=",
"[",
"]",
"while",
"ix_high",
"<=",
"len",
"(",
"cts",
".",
"elements",
")",
":",
"subset_stim",
"=",
"ComplexTextStim",
"(",
"elements",
"... | Return windowed slices from a ComplexTextStim
Args:
cts - _load_complex_text_stim_models
n - size of window prior to current stimulus
Output:
list of ComplexTextStim with n elements | [
"Return",
"windowed",
"slices",
"from",
"a",
"ComplexTextStim",
"Args",
":",
"cts",
"-",
"_load_complex_text_stim_models",
"n",
"-",
"size",
"of",
"window",
"prior",
"to",
"current",
"stimulus",
"Output",
":",
"list",
"of",
"ComplexTextStim",
"with",
"n",
"eleme... | [
"\"\"\" Return windowed slices from a ComplexTextStim\n Args:\n cts - _load_complex_text_stim_models\n n - size of window prior to current stimulus\n Output:\n list of ComplexTextStim with n elements\n \"\"\""
] | [
{
"param": "cts",
"type": null
},
{
"param": "n",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "cts",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "n",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
9c3dfb7f96a3600c0aeb55401bf3ef70d375fe7c | neuroscout/neuroscout | neuroscout/populate/extract.py | [
"BSD-3-Clause"
] | Python | extract_tokenized_features | <not_specific> | def extract_tokenized_features(extractors, dataset_name=None, task_name=None):
""" Extract features that require a ComplexTextStim to give context to
individual words within a run """
if dataset_name is None:
return [extract_features(
extractors, dataset.name, None)
for ... | Extract features that require a ComplexTextStim to give context to
individual words within a run | Extract features that require a ComplexTextStim to give context to
individual words within a run | [
"Extract",
"features",
"that",
"require",
"a",
"ComplexTextStim",
"to",
"give",
"context",
"to",
"individual",
"words",
"within",
"a",
"run"
] | def extract_tokenized_features(extractors, dataset_name=None, task_name=None):
if dataset_name is None:
return [extract_features(
extractors, dataset.name, None)
for dataset in Dataset.query.filter_by(active=True)]
stims = _load_complex_text_stim_models(dataset_name, task_nam... | [
"def",
"extract_tokenized_features",
"(",
"extractors",
",",
"dataset_name",
"=",
"None",
",",
"task_name",
"=",
"None",
")",
":",
"if",
"dataset_name",
"is",
"None",
":",
"return",
"[",
"extract_features",
"(",
"extractors",
",",
"dataset",
".",
"name",
",",
... | Extract features that require a ComplexTextStim to give context to
individual words within a run | [
"Extract",
"features",
"that",
"require",
"a",
"ComplexTextStim",
"to",
"give",
"context",
"to",
"individual",
"words",
"within",
"a",
"run"
] | [
"\"\"\" Extract features that require a ComplexTextStim to give context to\n individual words within a run \"\"\"",
"# For every extractor, extract from complex stims",
"# Save window params as Graph attributes",
"# Slice stims if window type is \"pre\"",
"# Extract for every windowed slice",
"# Serial... | [
{
"param": "extractors",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "extractors",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstr... |
193d5cdc11803d4335410aa9a443dd363ae558f6 | neuroscout/neuroscout | neuroscout/populate/utils.py | [
"BSD-3-Clause"
] | Python | compute_pred_stats | <not_specific> | def compute_pred_stats(session, pred, commit=False):
""" Computes hard coded pre-computed metrics upon ingestion (or on demand)
for a Predictor """
def get_max(vals):
if vals:
vals = max(vals)
return vals
def get_min(vals):
if vals:
vals = min(vals)
... | Computes hard coded pre-computed metrics upon ingestion (or on demand)
for a Predictor | Computes hard coded pre-computed metrics upon ingestion (or on demand)
for a Predictor | [
"Computes",
"hard",
"coded",
"pre",
"-",
"computed",
"metrics",
"upon",
"ingestion",
"(",
"or",
"on",
"demand",
")",
"for",
"a",
"Predictor"
] | def compute_pred_stats(session, pred, commit=False):
def get_max(vals):
if vals:
vals = max(vals)
return vals
def get_min(vals):
if vals:
vals = min(vals)
return vals
def remove_nas(vals):
return [v for v in vals if v == 'n/a']
def num_na... | [
"def",
"compute_pred_stats",
"(",
"session",
",",
"pred",
",",
"commit",
"=",
"False",
")",
":",
"def",
"get_max",
"(",
"vals",
")",
":",
"if",
"vals",
":",
"vals",
"=",
"max",
"(",
"vals",
")",
"return",
"vals",
"def",
"get_min",
"(",
"vals",
")",
... | Computes hard coded pre-computed metrics upon ingestion (or on demand)
for a Predictor | [
"Computes",
"hard",
"coded",
"pre",
"-",
"computed",
"metrics",
"upon",
"ingestion",
"(",
"or",
"on",
"demand",
")",
"for",
"a",
"Predictor"
] | [
"\"\"\" Computes hard coded pre-computed metrics upon ingestion (or on demand)\n for a Predictor \"\"\""
] | [
{
"param": "session",
"type": null
},
{
"param": "pred",
"type": null
},
{
"param": "commit",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "session",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pred",
"type": null,
"docstring": null,
"docstring_tokens"... |
fa32ff00aada97cc502bfe00802058848b797af1 | neuroscout/neuroscout | neuroscout/populate/annotate.py | [
"BSD-3-Clause"
] | Python | load | <not_specific> | def load(self, variable):
"""" Load and annotate a BIDSVariable
Args:
res - BIDSVariableCollection object
Returns a dictionary of annotated features
"""
if self.include is not None and variable.name not in self.include:
return None
if self.exclude ... | Load and annotate a BIDSVariable
Args:
res - BIDSVariableCollection object
Returns a dictionary of annotated features
| Load and annotate a BIDSVariable
Args:
res - BIDSVariableCollection object
Returns a dictionary of annotated features | [
"Load",
"and",
"annotate",
"a",
"BIDSVariable",
"Args",
":",
"res",
"-",
"BIDSVariableCollection",
"object",
"Returns",
"a",
"dictionary",
"of",
"annotated",
"features"
] | def load(self, variable):
if self.include is not None and variable.name not in self.include:
return None
if self.exclude is not None and variable.name in self.exclude:
return None
annotated = {}
annotated['original_name'] = variable.name
annotated['source'... | [
"def",
"load",
"(",
"self",
",",
"variable",
")",
":",
"if",
"self",
".",
"include",
"is",
"not",
"None",
"and",
"variable",
".",
"name",
"not",
"in",
"self",
".",
"include",
":",
"return",
"None",
"if",
"self",
".",
"exclude",
"is",
"not",
"None",
... | Load and annotate a BIDSVariable
Args:
res - BIDSVariableCollection object
Returns a dictionary of annotated features | [
"Load",
"and",
"annotate",
"a",
"BIDSVariable",
"Args",
":",
"res",
"-",
"BIDSVariableCollection",
"object",
"Returns",
"a",
"dictionary",
"of",
"annotated",
"features"
] | [
"\"\"\"\" Load and annotate a BIDSVariable\n Args:\n res - BIDSVariableCollection object\n Returns a dictionary of annotated features\n \"\"\"",
"# Add any additional attributes",
"# If SparseVariable",
"# If Dense, resample, and sparsify"
] | [
{
"param": "self",
"type": null
},
{
"param": "variable",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "variable",
"type": null,
"docstring": null,
"docstring_tokens... |
fa32ff00aada97cc502bfe00802058848b797af1 | neuroscout/neuroscout | neuroscout/populate/annotate.py | [
"BSD-3-Clause"
] | Python | load | <not_specific> | def load(self, res):
"""" Load and annotate features in an extractor result object.
Args:
res - Pliers ExtractorResult object
Returns a dictionary of annotated features
"""
res_df = res.to_df(format='long')
if self.object_id == 'max':
res_df = res... | Load and annotate features in an extractor result object.
Args:
res - Pliers ExtractorResult object
Returns a dictionary of annotated features
| Load and annotate features in an extractor result object.
Args:
res - Pliers ExtractorResult object
Returns a dictionary of annotated features | [
"Load",
"and",
"annotate",
"features",
"in",
"an",
"extractor",
"result",
"object",
".",
"Args",
":",
"res",
"-",
"Pliers",
"ExtractorResult",
"object",
"Returns",
"a",
"dictionary",
"of",
"annotated",
"features"
] | def load(self, res):
res_df = res.to_df(format='long')
if self.object_id == 'max':
res_df = res_df[res_df.object_id == res_df.object_id.max()]
features = res_df['feature'].unique().tolist()
ext_schema = {}
for candidate in self.schema.get(res.extractor.name, []):
... | [
"def",
"load",
"(",
"self",
",",
"res",
")",
":",
"res_df",
"=",
"res",
".",
"to_df",
"(",
"format",
"=",
"'long'",
")",
"if",
"self",
".",
"object_id",
"==",
"'max'",
":",
"res_df",
"=",
"res_df",
"[",
"res_df",
".",
"object_id",
"==",
"res_df",
"... | Load and annotate features in an extractor result object. | [
"Load",
"and",
"annotate",
"features",
"in",
"an",
"extractor",
"result",
"object",
"."
] | [
"\"\"\"\" Load and annotate features in an extractor result object.\n Args:\n res - Pliers ExtractorResult object\n\n Returns a dictionary of annotated features\n \"\"\"",
"# Find matching extractor schema + attribute combination",
"# Entries with no attributes will match any",
... | [
{
"param": "self",
"type": null
},
{
"param": "res",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "res",
"type": null,
"docstring": null,
"docstring_tokens": []... |
8d1c3eda10a823cfb8d901708d84f9e59ae6db08 | neuroscout/neuroscout | manage.py | [
"BSD-3-Clause"
] | Python | add_user | null | def add_user(email, password, confirm=True):
""" Add a user to the database.
email - A valid email address (primary login key)
password - Any string
"""
user = user_datastore.create_user(
email=email, password=encrypt_password(password))
if confirm:
user.confirmed_at = datetime.d... | Add a user to the database.
email - A valid email address (primary login key)
password - Any string
| Add a user to the database.
email - A valid email address (primary login key)
password - Any string | [
"Add",
"a",
"user",
"to",
"the",
"database",
".",
"email",
"-",
"A",
"valid",
"email",
"address",
"(",
"primary",
"login",
"key",
")",
"password",
"-",
"Any",
"string"
] | def add_user(email, password, confirm=True):
user = user_datastore.create_user(
email=email, password=encrypt_password(password))
if confirm:
user.confirmed_at = datetime.datetime.now()
db.session.commit() | [
"def",
"add_user",
"(",
"email",
",",
"password",
",",
"confirm",
"=",
"True",
")",
":",
"user",
"=",
"user_datastore",
".",
"create_user",
"(",
"email",
"=",
"email",
",",
"password",
"=",
"encrypt_password",
"(",
"password",
")",
")",
"if",
"confirm",
... | Add a user to the database. | [
"Add",
"a",
"user",
"to",
"the",
"database",
"."
] | [
"\"\"\" Add a user to the database.\n email - A valid email address (primary login key)\n password - Any string\n \"\"\""
] | [
{
"param": "email",
"type": null
},
{
"param": "password",
"type": null
},
{
"param": "confirm",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "email",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "password",
"type": null,
"docstring": null,
"docstring_token... |
8d1c3eda10a823cfb8d901708d84f9e59ae6db08 | neuroscout/neuroscout | manage.py | [
"BSD-3-Clause"
] | Python | ingest_from_json | null | def ingest_from_json(config, reingest=False):
""" Ingest/update datasets and extracted features from a json config file.
config_file - json config file detailing datasets and pliers graph_json
automagic - Force enable datalad automagic
"""
populate.ingest_from_json(config, reingest=reingest) | Ingest/update datasets and extracted features from a json config file.
config_file - json config file detailing datasets and pliers graph_json
automagic - Force enable datalad automagic
| Ingest/update datasets and extracted features from a json config file.
config_file - json config file detailing datasets and pliers graph_json
automagic - Force enable datalad automagic | [
"Ingest",
"/",
"update",
"datasets",
"and",
"extracted",
"features",
"from",
"a",
"json",
"config",
"file",
".",
"config_file",
"-",
"json",
"config",
"file",
"detailing",
"datasets",
"and",
"pliers",
"graph_json",
"automagic",
"-",
"Force",
"enable",
"datalad",... | def ingest_from_json(config, reingest=False):
populate.ingest_from_json(config, reingest=reingest) | [
"def",
"ingest_from_json",
"(",
"config",
",",
"reingest",
"=",
"False",
")",
":",
"populate",
".",
"ingest_from_json",
"(",
"config",
",",
"reingest",
"=",
"reingest",
")"
] | Ingest/update datasets and extracted features from a json config file. | [
"Ingest",
"/",
"update",
"datasets",
"and",
"extracted",
"features",
"from",
"a",
"json",
"config",
"file",
"."
] | [
"\"\"\" Ingest/update datasets and extracted features from a json config file.\n config_file - json config file detailing datasets and pliers graph_json\n automagic - Force enable datalad automagic\n \"\"\""
] | [
{
"param": "config",
"type": null
},
{
"param": "reingest",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "reingest",
"type": null,
"docstring": null,
"docstring_toke... |
8d1c3eda10a823cfb8d901708d84f9e59ae6db08 | neuroscout/neuroscout | manage.py | [
"BSD-3-Clause"
] | Python | extract_features | null | def extract_features(extractor_graphs, dataset_name=None, task_name=None,
resample_frequency=None):
""" Extract features from a BIDS dataset.
extractor_graphs - List of Graphs to apply to relevant stimuli
dataset_name - Dataset name - By default applies to all active datasets
task -... | Extract features from a BIDS dataset.
extractor_graphs - List of Graphs to apply to relevant stimuli
dataset_name - Dataset name - By default applies to all active datasets
task - Task name
resample_frequency - None
| Extract features from a BIDS dataset. | [
"Extract",
"features",
"from",
"a",
"BIDS",
"dataset",
"."
] | def extract_features(extractor_graphs, dataset_name=None, task_name=None,
resample_frequency=None):
populate.extract_features(
extractor_graphs, dataset_name, task_name,
resample_frequency=resample_frequency) | [
"def",
"extract_features",
"(",
"extractor_graphs",
",",
"dataset_name",
"=",
"None",
",",
"task_name",
"=",
"None",
",",
"resample_frequency",
"=",
"None",
")",
":",
"populate",
".",
"extract_features",
"(",
"extractor_graphs",
",",
"dataset_name",
",",
"task_nam... | Extract features from a BIDS dataset. | [
"Extract",
"features",
"from",
"a",
"BIDS",
"dataset",
"."
] | [
"\"\"\" Extract features from a BIDS dataset.\n extractor_graphs - List of Graphs to apply to relevant stimuli\n dataset_name - Dataset name - By default applies to all active datasets\n task - Task name\n resample_frequency - None\n \"\"\""
] | [
{
"param": "extractor_graphs",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
},
{
"param": "resample_frequency",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "extractor_graphs",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"... |
7f88e5da1c1c7171956b39475ea0427a69b8c833 | neuroscout/neuroscout | neuroscout/utils/misc.py | [
"BSD-3-Clause"
] | Python | distinct_extractors | <not_specific> | def distinct_extractors(count=True, active=True):
""" Tool to count unique number of predictors for each Dataset/Task """
active_datasets = ms.Dataset.query.filter_by(active=active)
superset = set([v for (v, ) in ms.Predictor.query.filter_by(active=True).filter(
ms.Predictor.dataset_id.in_(
... | Tool to count unique number of predictors for each Dataset/Task | Tool to count unique number of predictors for each Dataset/Task | [
"Tool",
"to",
"count",
"unique",
"number",
"of",
"predictors",
"for",
"each",
"Dataset",
"/",
"Task"
] | def distinct_extractors(count=True, active=True):
active_datasets = ms.Dataset.query.filter_by(active=active)
superset = set([v for (v, ) in ms.Predictor.query.filter_by(active=True).filter(
ms.Predictor.dataset_id.in_(
active_datasets.with_entities('id'))).join(
ms.Extracted... | [
"def",
"distinct_extractors",
"(",
"count",
"=",
"True",
",",
"active",
"=",
"True",
")",
":",
"active_datasets",
"=",
"ms",
".",
"Dataset",
".",
"query",
".",
"filter_by",
"(",
"active",
"=",
"active",
")",
"superset",
"=",
"set",
"(",
"[",
"v",
"for"... | Tool to count unique number of predictors for each Dataset/Task | [
"Tool",
"to",
"count",
"unique",
"number",
"of",
"predictors",
"for",
"each",
"Dataset",
"/",
"Task"
] | [
"\"\"\" Tool to count unique number of predictors for each Dataset/Task \"\"\""
] | [
{
"param": "count",
"type": null
},
{
"param": "active",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "count",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "active",
"type": null,
"docstring": null,
"docstring_tokens"... |
71d24453e01d49aaad0d3503a82821b34ca63565 | neuroscout/neuroscout | neuroscout/populate/convert.py | [
"BSD-3-Clause"
] | Python | save_stim_filename | <not_specific> | def save_stim_filename(stimulus):
""" Given a pliers stimulus object, create a hash, filename, and save.
If type if TextStim or ComplexTextStim, return content rather than path
"""
if isinstance(stimulus, TextStim):
stimulus = ComplexTextStim(text=stimulus.data, onset=stimulus.onset,
... | Given a pliers stimulus object, create a hash, filename, and save.
If type if TextStim or ComplexTextStim, return content rather than path
| Given a pliers stimulus object, create a hash, filename, and save.
If type if TextStim or ComplexTextStim, return content rather than path | [
"Given",
"a",
"pliers",
"stimulus",
"object",
"create",
"a",
"hash",
"filename",
"and",
"save",
".",
"If",
"type",
"if",
"TextStim",
"or",
"ComplexTextStim",
"return",
"content",
"rather",
"than",
"path"
] | def save_stim_filename(stimulus):
if isinstance(stimulus, TextStim):
stimulus = ComplexTextStim(text=stimulus.data, onset=stimulus.onset,
duration=stimulus.duration)
stim_hash = hash_stim(stimulus)
if isinstance(stimulus, ComplexTextStim):
return stim_hash,... | [
"def",
"save_stim_filename",
"(",
"stimulus",
")",
":",
"if",
"isinstance",
"(",
"stimulus",
",",
"TextStim",
")",
":",
"stimulus",
"=",
"ComplexTextStim",
"(",
"text",
"=",
"stimulus",
".",
"data",
",",
"onset",
"=",
"stimulus",
".",
"onset",
",",
"durati... | Given a pliers stimulus object, create a hash, filename, and save. | [
"Given",
"a",
"pliers",
"stimulus",
"object",
"create",
"a",
"hash",
"filename",
"and",
"save",
"."
] | [
"\"\"\" Given a pliers stimulus object, create a hash, filename, and save.\n If type if TextStim or ComplexTextStim, return content rather than path\n \"\"\""
] | [
{
"param": "stimulus",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "stimulus",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
71d24453e01d49aaad0d3503a82821b34ca63565 | neuroscout/neuroscout | neuroscout/populate/convert.py | [
"BSD-3-Clause"
] | Python | convert_stimuli | <not_specific> | def convert_stimuli(converters, dataset_name=None, task_name=None):
""" Convert stimuli to different modality using pliers.
Args:
converters - dictionary of converter names to parameters
dataset_name - dataset name
task_name - task name
Output:
list of... | Convert stimuli to different modality using pliers.
Args:
converters - dictionary of converter names to parameters
dataset_name - dataset name
task_name - task name
Output:
list of db ids of converted stimuli
| Convert stimuli to different modality using pliers.
Args:
converters - dictionary of converter names to parameters
dataset_name - dataset name
task_name - task name
Output:
list of db ids of converted stimuli | [
"Convert",
"stimuli",
"to",
"different",
"modality",
"using",
"pliers",
".",
"Args",
":",
"converters",
"-",
"dictionary",
"of",
"converter",
"names",
"to",
"parameters",
"dataset_name",
"-",
"dataset",
"name",
"task_name",
"-",
"task",
"name",
"Output",
":",
... | def convert_stimuli(converters, dataset_name=None, task_name=None):
if dataset_name is None:
return [convert_stimuli(
converters, dataset.name, None)
for dataset in Dataset.query.filter_by(active=True)]
dataset = Dataset.query.filter_by(name=dataset_name).one()
dataset_id... | [
"def",
"convert_stimuli",
"(",
"converters",
",",
"dataset_name",
"=",
"None",
",",
"task_name",
"=",
"None",
")",
":",
"if",
"dataset_name",
"is",
"None",
":",
"return",
"[",
"convert_stimuli",
"(",
"converters",
",",
"dataset",
".",
"name",
",",
"None",
... | Convert stimuli to different modality using pliers. | [
"Convert",
"stimuli",
"to",
"different",
"modality",
"using",
"pliers",
"."
] | [
"\"\"\" Convert stimuli to different modality using pliers.\n Args:\n converters - dictionary of converter names to parameters\n dataset_name - dataset name\n task_name - task name\n Output:\n list of db ids of converted stimuli\n \"\"\"",
"# Load all a... | [
{
"param": "converters",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "converters",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstr... |
71d24453e01d49aaad0d3503a82821b34ca63565 | neuroscout/neuroscout | neuroscout/populate/convert.py | [
"BSD-3-Clause"
] | Python | ingest_text_stimuli | null | def ingest_text_stimuli(filename, dataset_name, task_name, parent_ids=None,
transformer='FAVEAlign', params=None, onsets=None,
resample_ratio=1, complete_only=False, col_name='text'):
""" Ingest converted text stimuli from file.
Args:
filename - aligned tr... | Ingest converted text stimuli from file.
Args:
filename - aligned transcript, with onset, duration and text columns
dataset_name - Name of dataset in debug
task_name - Task name
parent_ids - Parent stimulus db id(s)
transformer - Transformer name
params - Extra param... | Ingest converted text stimuli from file. | [
"Ingest",
"converted",
"text",
"stimuli",
"from",
"file",
"."
] | def ingest_text_stimuli(filename, dataset_name, task_name, parent_ids=None,
transformer='FAVEAlign', params=None, onsets=None,
resample_ratio=1, complete_only=False, col_name='text'):
dataset_id = Dataset.query.filter_by(name=dataset_name).one().id
if parent_ids i... | [
"def",
"ingest_text_stimuli",
"(",
"filename",
",",
"dataset_name",
",",
"task_name",
",",
"parent_ids",
"=",
"None",
",",
"transformer",
"=",
"'FAVEAlign'",
",",
"params",
"=",
"None",
",",
"onsets",
"=",
"None",
",",
"resample_ratio",
"=",
"1",
",",
"compl... | Ingest converted text stimuli from file. | [
"Ingest",
"converted",
"text",
"stimuli",
"from",
"file",
"."
] | [
"\"\"\" Ingest converted text stimuli from file.\n Args:\n filename - aligned transcript, with onset, duration and text columns\n dataset_name - Name of dataset in debug\n task_name - Task name\n parent_ids - Parent stimulus db id(s)\n transformer - Transformer name\n pa... | [
{
"param": "filename",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
},
{
"param": "parent_ids",
"type": null
},
{
"param": "transformer",
"type": null
},
{
"param": "params",
"type": null
},
{
... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataset_name",
"type": null,
"docstring": null,
"docstrin... |
71d24453e01d49aaad0d3503a82821b34ca63565 | neuroscout/neuroscout | neuroscout/populate/convert.py | [
"BSD-3-Clause"
] | Python | predictor_to_text_stim | null | def predictor_to_text_stim(predictor_id, task_name, transformer='reading',
params=None):
""" Convert Predictors that were ingested from the original dataset's
event files into a Stimulus. This is useful for Predictors which are
speech or reading transcripts with word specific onse... | Convert Predictors that were ingested from the original dataset's
event files into a Stimulus. This is useful for Predictors which are
speech or reading transcripts with word specific onsets and durations | Convert Predictors that were ingested from the original dataset's
event files into a Stimulus. This is useful for Predictors which are
speech or reading transcripts with word specific onsets and durations | [
"Convert",
"Predictors",
"that",
"were",
"ingested",
"from",
"the",
"original",
"dataset",
"'",
"s",
"event",
"files",
"into",
"a",
"Stimulus",
".",
"This",
"is",
"useful",
"for",
"Predictors",
"which",
"are",
"speech",
"or",
"reading",
"transcripts",
"with",
... | def predictor_to_text_stim(predictor_id, task_name, transformer='reading',
params=None):
predictor = Predictor.query.filter_by(id=predictor_id).one()
dataset_id = predictor.dataset_id
rst = namedtuple('RunStimulus', ['onset', 'duration', 'run_id'])
if params is None:
p... | [
"def",
"predictor_to_text_stim",
"(",
"predictor_id",
",",
"task_name",
",",
"transformer",
"=",
"'reading'",
",",
"params",
"=",
"None",
")",
":",
"predictor",
"=",
"Predictor",
".",
"query",
".",
"filter_by",
"(",
"id",
"=",
"predictor_id",
")",
".",
"one"... | Convert Predictors that were ingested from the original dataset's
event files into a Stimulus. | [
"Convert",
"Predictors",
"that",
"were",
"ingested",
"from",
"the",
"original",
"dataset",
"'",
"s",
"event",
"files",
"into",
"a",
"Stimulus",
"."
] | [
"\"\"\" Convert Predictors that were ingested from the original dataset's\n event files into a Stimulus. This is useful for Predictors which are\n speech or reading transcripts with word specific onsets and durations \"\"\"",
"# Uniquify",
"# Calculate run duration",
"# Create new stimuli",
"# Complet... | [
{
"param": "predictor_id",
"type": null
},
{
"param": "task_name",
"type": null
},
{
"param": "transformer",
"type": null
},
{
"param": "params",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "predictor_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "task_name",
"type": null,
"docstring": null,
"docstri... |
c6cfac78c0f116a692fdcf216e679dcc63ee8498 | neuroscout/neuroscout | neuroscout/populate/setup.py | [
"BSD-3-Clause"
] | Python | ingest_from_json | <not_specific> | def ingest_from_json(config_file, reingest=False, auto_fetch=False):
""" Adds a dataset from a JSON configuration file
Args:
config_file - a path to a json file
reingest - force reingest tasks
auto_fetch - Automatically fetch and then drop nifti files
Output:
... | Adds a dataset from a JSON configuration file
Args:
config_file - a path to a json file
reingest - force reingest tasks
auto_fetch - Automatically fetch and then drop nifti files
Output:
list of dataset model ids
| Adds a dataset from a JSON configuration file
Args:
config_file - a path to a json file
reingest - force reingest tasks
auto_fetch - Automatically fetch and then drop nifti files
Output:
list of dataset model ids | [
"Adds",
"a",
"dataset",
"from",
"a",
"JSON",
"configuration",
"file",
"Args",
":",
"config_file",
"-",
"a",
"path",
"to",
"a",
"json",
"file",
"reingest",
"-",
"force",
"reingest",
"tasks",
"auto_fetch",
"-",
"Automatically",
"fetch",
"and",
"then",
"drop",
... | def ingest_from_json(config_file, reingest=False, auto_fetch=False):
with open(config_file, 'r') as f:
config = json.load(f)
dataset_name = config['name']
local_path = config['path']
dataset_id = add_dataset(
dataset_name=dataset_name,
dataset_address=config.get('dataset_... | [
"def",
"ingest_from_json",
"(",
"config_file",
",",
"reingest",
"=",
"False",
",",
"auto_fetch",
"=",
"False",
")",
":",
"with",
"open",
"(",
"config_file",
",",
"'r'",
")",
"as",
"f",
":",
"config",
"=",
"json",
".",
"load",
"(",
"f",
")",
"dataset_na... | Adds a dataset from a JSON configuration file
Args:
config_file - a path to a json file
reingest - force reingest tasks
auto_fetch - Automatically fetch and then drop nifti files
Output:
list of dataset model ids | [
"Adds",
"a",
"dataset",
"from",
"a",
"JSON",
"configuration",
"file",
"Args",
":",
"config_file",
"-",
"a",
"path",
"to",
"a",
"json",
"file",
"reingest",
"-",
"force",
"reingest",
"tasks",
"auto_fetch",
"-",
"Automatically",
"fetch",
"and",
"then",
"drop",
... | [
"\"\"\" Adds a dataset from a JSON configuration file\n Args:\n config_file - a path to a json file\n reingest - force reingest tasks\n auto_fetch - Automatically fetch and then drop nifti files\n Output:\n list of dataset model ids\n \"\"\"",
"# Add da... | [
{
"param": "config_file",
"type": null
},
{
"param": "reingest",
"type": null
},
{
"param": "auto_fetch",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "config_file",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "reingest",
"type": null,
"docstring": null,
"docstring... |
c6cfac78c0f116a692fdcf216e679dcc63ee8498 | neuroscout/neuroscout | neuroscout/populate/setup.py | [
"BSD-3-Clause"
] | Python | extract_from_json | null | def extract_from_json(extract_config, dataset_name=None, task_name=None):
""" Applies JSON file specifying conversion and extractions to
specifed tasks.
Args:
extract_config: JSON specifying the arguments to each step
See: config/transformers.json for full example
dataset_name: da... | Applies JSON file specifying conversion and extractions to
specifed tasks.
Args:
extract_config: JSON specifying the arguments to each step
See: config/transformers.json for full example
dataset_name: dataset name. If none, applied to all datasets / tasks
task_name: If datase... | Applies JSON file specifying conversion and extractions to
specifed tasks. | [
"Applies",
"JSON",
"file",
"specifying",
"conversion",
"and",
"extractions",
"to",
"specifed",
"tasks",
"."
] | def extract_from_json(extract_config, dataset_name=None, task_name=None):
if dataset_name is None and task_name is not None:
raise Exception(
"If no dataset_name is specified, no task_name can be set.")
with open(extract_config, 'r') as f:
config = json.load(f)
converters = confi... | [
"def",
"extract_from_json",
"(",
"extract_config",
",",
"dataset_name",
"=",
"None",
",",
"task_name",
"=",
"None",
")",
":",
"if",
"dataset_name",
"is",
"None",
"and",
"task_name",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"If no dataset_name is sp... | Applies JSON file specifying conversion and extractions to
specifed tasks. | [
"Applies",
"JSON",
"file",
"specifying",
"conversion",
"and",
"extractions",
"to",
"specifed",
"tasks",
"."
] | [
"\"\"\" Applies JSON file specifying conversion and extractions to\n specifed tasks.\n\n Args:\n extract_config: JSON specifying the arguments to each step\n See: config/transformers.json for full example\n dataset_name: dataset name. If none, applied to all datasets / tasks\n ta... | [
{
"param": "extract_config",
"type": null
},
{
"param": "dataset_name",
"type": null
},
{
"param": "task_name",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "extract_config",
"type": null,
"docstring": "JSON specifying the arguments to each step\nSee: config/transformers.json for full example",
"docstring_tokens": [
"JSON",
"specifying",
"the",
"argu... |
54ac903c5d420c16aae715b7cfc2751488bf41d4 | neuroscout/neuroscout | neuroscout/utils/db.py | [
"BSD-3-Clause"
] | Python | dump_pe | <not_specific> | def dump_pe(pes):
""" Serialize PredictorEvents, with *SPEED*, using core SQL.
Warning: relies on attributes being in correct order. """
statement = str(pes.statement.compile(dialect=postgresql.dialect()))
params = pes.statement.compile(dialect=postgresql.dialect()).params
res = db.session.connectio... | Serialize PredictorEvents, with *SPEED*, using core SQL.
Warning: relies on attributes being in correct order. | Serialize PredictorEvents, with *SPEED*, using core SQL.
Warning: relies on attributes being in correct order. | [
"Serialize",
"PredictorEvents",
"with",
"*",
"SPEED",
"*",
"using",
"core",
"SQL",
".",
"Warning",
":",
"relies",
"on",
"attributes",
"being",
"in",
"correct",
"order",
"."
] | def dump_pe(pes):
statement = str(pes.statement.compile(dialect=postgresql.dialect()))
params = pes.statement.compile(dialect=postgresql.dialect()).params
res = db.session.connection().execute(statement, params)
return [
dict(
zip(('id', 'onset', 'duration', 'value', 'object_id', 'ru... | [
"def",
"dump_pe",
"(",
"pes",
")",
":",
"statement",
"=",
"str",
"(",
"pes",
".",
"statement",
".",
"compile",
"(",
"dialect",
"=",
"postgresql",
".",
"dialect",
"(",
")",
")",
")",
"params",
"=",
"pes",
".",
"statement",
".",
"compile",
"(",
"dialec... | Serialize PredictorEvents, with *SPEED*, using core SQL. | [
"Serialize",
"PredictorEvents",
"with",
"*",
"SPEED",
"*",
"using",
"core",
"SQL",
"."
] | [
"\"\"\" Serialize PredictorEvents, with *SPEED*, using core SQL.\n Warning: relies on attributes being in correct order. \"\"\""
] | [
{
"param": "pes",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "pes",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
54ac903c5d420c16aae715b7cfc2751488bf41d4 | neuroscout/neuroscout | neuroscout/utils/db.py | [
"BSD-3-Clause"
] | Python | dump_predictor_events | <not_specific> | def dump_predictor_events(predictor_ids, run_ids=None, stimulus_timing=False):
""" Query & serialize PredictorEvents, for both Raw and Extracted
Predictors (which require creating PEs from EEs)
"""
# Query Predictors
all_preds = Predictor.query.filter(Predictor.id.in_(predictor_ids))
# Separat... | Query & serialize PredictorEvents, for both Raw and Extracted
Predictors (which require creating PEs from EEs)
| Query & serialize PredictorEvents, for both Raw and Extracted
Predictors (which require creating PEs from EEs) | [
"Query",
"&",
"serialize",
"PredictorEvents",
"for",
"both",
"Raw",
"and",
"Extracted",
"Predictors",
"(",
"which",
"require",
"creating",
"PEs",
"from",
"EEs",
")"
] | def dump_predictor_events(predictor_ids, run_ids=None, stimulus_timing=False):
all_preds = Predictor.query.filter(Predictor.id.in_(predictor_ids))
raw_pred_ids = [p.id for p in all_preds.filter_by(ef_id=None)]
ext_preds = Predictor.query.filter(
Predictor.id.in_(set(predictor_ids) - set(raw_pred_ids... | [
"def",
"dump_predictor_events",
"(",
"predictor_ids",
",",
"run_ids",
"=",
"None",
",",
"stimulus_timing",
"=",
"False",
")",
":",
"all_preds",
"=",
"Predictor",
".",
"query",
".",
"filter",
"(",
"Predictor",
".",
"id",
".",
"in_",
"(",
"predictor_ids",
")",... | Query & serialize PredictorEvents, for both Raw and Extracted
Predictors (which require creating PEs from EEs) | [
"Query",
"&",
"serialize",
"PredictorEvents",
"for",
"both",
"Raw",
"and",
"Extracted",
"Predictors",
"(",
"which",
"require",
"creating",
"PEs",
"from",
"EEs",
")"
] | [
"\"\"\" Query & serialize PredictorEvents, for both Raw and Extracted\n Predictors (which require creating PEs from EEs)\n \"\"\"",
"# Query Predictors",
"# Separate raw and extracted predictors",
"# Query & dump raw PEs",
"# Create & dump Extracted PEs"
] | [
{
"param": "predictor_ids",
"type": null
},
{
"param": "run_ids",
"type": null
},
{
"param": "stimulus_timing",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "predictor_ids",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "run_ids",
"type": null,
"docstring": null,
"docstrin... |
69f868729eec40ac91d963c1537b15179fa09044 | neuroscout/neuroscout | neuroscout/tasks/utils/build.py | [
"BSD-3-Clause"
] | Python | writeout_events | <not_specific> | def writeout_events(analysis, pes, outdir, run_ids=None):
""" Writeout predictor_events into BIDS event files """
analysis_runs = analysis.get('runs', [])
if run_ids is not None:
analysis_runs = [r for r in analysis_runs if r['id'] in run_ids]
desc = {
'Name': analysis['hash_id'],
... | Writeout predictor_events into BIDS event files | Writeout predictor_events into BIDS event files | [
"Writeout",
"predictor_events",
"into",
"BIDS",
"event",
"files"
] | def writeout_events(analysis, pes, outdir, run_ids=None):
analysis_runs = analysis.get('runs', [])
if run_ids is not None:
analysis_runs = [r for r in analysis_runs if r['id'] in run_ids]
desc = {
'Name': analysis['hash_id'],
'BIDSVersion': '1.1.1',
'PipelineDescription': {'N... | [
"def",
"writeout_events",
"(",
"analysis",
",",
"pes",
",",
"outdir",
",",
"run_ids",
"=",
"None",
")",
":",
"analysis_runs",
"=",
"analysis",
".",
"get",
"(",
"'runs'",
",",
"[",
"]",
")",
"if",
"run_ids",
"is",
"not",
"None",
":",
"analysis_runs",
"=... | Writeout predictor_events into BIDS event files | [
"Writeout",
"predictor_events",
"into",
"BIDS",
"event",
"files"
] | [
"\"\"\" Writeout predictor_events into BIDS event files \"\"\"",
"# Load events and rename columns to human-readable",
"# Write out event files",
"# Write out event files for each run_id",
"# For any columns that don't have events, output n/a file",
"# Write out files",
"# Write out BIDS path"
] | [
{
"param": "analysis",
"type": null
},
{
"param": "pes",
"type": null
},
{
"param": "outdir",
"type": null
},
{
"param": "run_ids",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "analysis",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "pes",
"type": null,
"docstring": null,
"docstring_tokens"... |
69f868729eec40ac91d963c1537b15179fa09044 | neuroscout/neuroscout | neuroscout/tasks/utils/build.py | [
"BSD-3-Clause"
] | Python | build_analysis | <not_specific> | def build_analysis(analysis, predictor_events, bids_dir,
run_ids=None, build=True):
""" Write out and build analysis object """
if predictor_events == []:
raise Exception("Error: Predictor events are null")
tmp_dir = Path(mkdtemp())
# Get durations and set of entities acros... | Write out and build analysis object | Write out and build analysis object | [
"Write",
"out",
"and",
"build",
"analysis",
"object"
] | def build_analysis(analysis, predictor_events, bids_dir,
run_ids=None, build=True):
if predictor_events == []:
raise Exception("Error: Predictor events are null")
tmp_dir = Path(mkdtemp())
if run_ids is None:
run_entities = [(run['duration'], _get_entities(run)) for run in... | [
"def",
"build_analysis",
"(",
"analysis",
",",
"predictor_events",
",",
"bids_dir",
",",
"run_ids",
"=",
"None",
",",
"build",
"=",
"True",
")",
":",
"if",
"predictor_events",
"==",
"[",
"]",
":",
"raise",
"Exception",
"(",
"\"Error: Predictor events are null\""... | Write out and build analysis object | [
"Write",
"out",
"and",
"build",
"analysis",
"object"
] | [
"\"\"\" Write out and build analysis object \"\"\"",
"# Get durations and set of entities across analysis runs",
"# Write out all events"
] | [
{
"param": "analysis",
"type": null
},
{
"param": "predictor_events",
"type": null
},
{
"param": "bids_dir",
"type": null
},
{
"param": "run_ids",
"type": null
},
{
"param": "build",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "analysis",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "predictor_events",
"type": null,
"docstring": null,
"docs... |
69f868729eec40ac91d963c1537b15179fa09044 | neuroscout/neuroscout | neuroscout/tasks/utils/build.py | [
"BSD-3-Clause"
] | Python | _get_entities | <not_specific> | def _get_entities(run, **kwargs):
""" Get BIDS-entities from run object """
valid = ['number', 'session', 'subject', 'acquisition', 'task_name']
entities = {
r: v
for r, v in run.items()
if r in valid and v is not None
}
if 'number' in entities:
entities['run'] =... | Get BIDS-entities from run object | Get BIDS-entities from run object | [
"Get",
"BIDS",
"-",
"entities",
"from",
"run",
"object"
] | def _get_entities(run, **kwargs):
valid = ['number', 'session', 'subject', 'acquisition', 'task_name']
entities = {
r: v
for r, v in run.items()
if r in valid and v is not None
}
if 'number' in entities:
entities['run'] = entities.pop('number')
if 'task_name' in e... | [
"def",
"_get_entities",
"(",
"run",
",",
"**",
"kwargs",
")",
":",
"valid",
"=",
"[",
"'number'",
",",
"'session'",
",",
"'subject'",
",",
"'acquisition'",
",",
"'task_name'",
"]",
"entities",
"=",
"{",
"r",
":",
"v",
"for",
"r",
",",
"v",
"in",
"run... | Get BIDS-entities from run object | [
"Get",
"BIDS",
"-",
"entities",
"from",
"run",
"object"
] | [
"\"\"\" Get BIDS-entities from run object \"\"\""
] | [
{
"param": "run",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "run",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
69f868729eec40ac91d963c1537b15179fa09044 | neuroscout/neuroscout | neuroscout/tasks/utils/build.py | [
"BSD-3-Clause"
] | Python | impute_confounds | <not_specific> | def impute_confounds(dense):
""" Impute first TR for confounds that may have n/as """
for imputable in ('framewise_displacement', 'std_dvars', 'dvars'):
if imputable in dense.columns:
vals = dense[imputable].values
if not np.isnan(vals[0]):
continue
#... | Impute first TR for confounds that may have n/as | Impute first TR for confounds that may have n/as | [
"Impute",
"first",
"TR",
"for",
"confounds",
"that",
"may",
"have",
"n",
"/",
"as"
] | def impute_confounds(dense):
for imputable in ('framewise_displacement', 'std_dvars', 'dvars'):
if imputable in dense.columns:
vals = dense[imputable].values
if not np.isnan(vals[0]):
continue
dense[imputable][0] = np.nanmean(vals[vals != 0])
return de... | [
"def",
"impute_confounds",
"(",
"dense",
")",
":",
"for",
"imputable",
"in",
"(",
"'framewise_displacement'",
",",
"'std_dvars'",
",",
"'dvars'",
")",
":",
"if",
"imputable",
"in",
"dense",
".",
"columns",
":",
"vals",
"=",
"dense",
"[",
"imputable",
"]",
... | Impute first TR for confounds that may have n/as | [
"Impute",
"first",
"TR",
"for",
"confounds",
"that",
"may",
"have",
"n",
"/",
"as"
] | [
"\"\"\" Impute first TR for confounds that may have n/as \"\"\"",
"# Impute the mean non-zero, non-NaN value"
] | [
{
"param": "dense",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "dense",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
59e5fc6fec06a0f54c3f2e3a56e22d31d2074721 | neuroscout/neuroscout | neuroscout/tasks/upload.py | [
"BSD-3-Clause"
] | Python | upload_collection | <not_specific> | def upload_collection(flask_app, filenames, runs, dataset_id, collection_id,
descriptions=None, cache=None):
""" Create new Predictors from TSV files
Args:
filenames list of (str): List of paths to TSVs
runs list of (int): List of run ids to apply events to
dataset_... | Create new Predictors from TSV files
Args:
filenames list of (str): List of paths to TSVs
runs list of (int): List of run ids to apply events to
dataset_id (int): Dataset id.
collection_id (int): Id of collection object
descriptions (dict): Optional descriptions for each col... | Create new Predictors from TSV files | [
"Create",
"new",
"Predictors",
"from",
"TSV",
"files"
] | def upload_collection(flask_app, filenames, runs, dataset_id, collection_id,
descriptions=None, cache=None):
if cache is None:
from ..core import cache as cache
if descriptions is None:
descriptions = {}
collection_object = PredictorCollection.query.filter_by(
i... | [
"def",
"upload_collection",
"(",
"flask_app",
",",
"filenames",
",",
"runs",
",",
"dataset_id",
",",
"collection_id",
",",
"descriptions",
"=",
"None",
",",
"cache",
"=",
"None",
")",
":",
"if",
"cache",
"is",
"None",
":",
"from",
".",
".",
"core",
"impo... | Create new Predictors from TSV files | [
"Create",
"new",
"Predictors",
"from",
"TSV",
"files"
] | [
"\"\"\" Create new Predictors from TSV files\n Args:\n filenames list of (str): List of paths to TSVs\n runs list of (int): List of run ids to apply events to\n dataset_id (int): Dataset id.\n collection_id (int): Id of collection object\n descriptions (dict): Optional descript... | [
{
"param": "flask_app",
"type": null
},
{
"param": "filenames",
"type": null
},
{
"param": "runs",
"type": null
},
{
"param": "dataset_id",
"type": null
},
{
"param": "collection_id",
"type": null
},
{
"param": "descriptions",
"type": null
},
{... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "flask_app",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "filenames",
"type": null,
"docstring": null,
"docstring_... |
bd0d23aad6d008f68287758765ee7bf2aa6a5efc | neuroscout/neuroscout | neuroscout/populate/transform.py | [
"BSD-3-Clause"
] | Python | num_objects | <not_specific> | def num_objects(ee_df, threshold=None):
""" Counts the number of Extracted Events for each stimulus.
Args:
ee_df - ExtractedEvents in pandas df format
threshold - filter threshold for ExtractedEvent value
"""
if threshold is not None:
ee_df... | Counts the number of Extracted Events for each stimulus.
Args:
ee_df - ExtractedEvents in pandas df format
threshold - filter threshold for ExtractedEvent value
| Counts the number of Extracted Events for each stimulus.
Args:
ee_df - ExtractedEvents in pandas df format
threshold - filter threshold for ExtractedEvent value | [
"Counts",
"the",
"number",
"of",
"Extracted",
"Events",
"for",
"each",
"stimulus",
".",
"Args",
":",
"ee_df",
"-",
"ExtractedEvents",
"in",
"pandas",
"df",
"format",
"threshold",
"-",
"filter",
"threshold",
"for",
"ExtractedEvent",
"value"
] | def num_objects(ee_df, threshold=None):
if threshold is not None:
ee_df.value = ee_df.value.astype('float')
ee_df = ee_df[ee_df.value > threshold]
counts = ee_df.groupby('stimulus_id').count()['value'].reset_index()
return counts.to_dict('index').values() | [
"def",
"num_objects",
"(",
"ee_df",
",",
"threshold",
"=",
"None",
")",
":",
"if",
"threshold",
"is",
"not",
"None",
":",
"ee_df",
".",
"value",
"=",
"ee_df",
".",
"value",
".",
"astype",
"(",
"'float'",
")",
"ee_df",
"=",
"ee_df",
"[",
"ee_df",
".",... | Counts the number of Extracted Events for each stimulus. | [
"Counts",
"the",
"number",
"of",
"Extracted",
"Events",
"for",
"each",
"stimulus",
"."
] | [
"\"\"\" Counts the number of Extracted Events for each stimulus.\n Args:\n ee_df - ExtractedEvents in pandas df format\n threshold - filter threshold for ExtractedEvent value\n \"\"\""
] | [
{
"param": "ee_df",
"type": null
},
{
"param": "threshold",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ee_df",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "threshold",
"type": null,
"docstring": null,
"docstring_toke... |
bd0d23aad6d008f68287758765ee7bf2aa6a5efc | neuroscout/neuroscout | neuroscout/populate/transform.py | [
"BSD-3-Clause"
] | Python | dummy | <not_specific> | def dummy(ee_df):
""" Returns a dummy feature of 1s for each stimulus
Args:
ee_df - ExtractedEvents in pandas df format
"""
dummy = ee_df.groupby('stimulus_id').apply(lambda x: 1).reset_index()
return dummy.rename(columns={0: 'value'}).to_dict('index').values(... | Returns a dummy feature of 1s for each stimulus
Args:
ee_df - ExtractedEvents in pandas df format
| Returns a dummy feature of 1s for each stimulus
Args:
ee_df - ExtractedEvents in pandas df format | [
"Returns",
"a",
"dummy",
"feature",
"of",
"1s",
"for",
"each",
"stimulus",
"Args",
":",
"ee_df",
"-",
"ExtractedEvents",
"in",
"pandas",
"df",
"format"
] | def dummy(ee_df):
dummy = ee_df.groupby('stimulus_id').apply(lambda x: 1).reset_index()
return dummy.rename(columns={0: 'value'}).to_dict('index').values() | [
"def",
"dummy",
"(",
"ee_df",
")",
":",
"dummy",
"=",
"ee_df",
".",
"groupby",
"(",
"'stimulus_id'",
")",
".",
"apply",
"(",
"lambda",
"x",
":",
"1",
")",
".",
"reset_index",
"(",
")",
"return",
"dummy",
".",
"rename",
"(",
"columns",
"=",
"{",
"0"... | Returns a dummy feature of 1s for each stimulus
Args:
ee_df - ExtractedEvents in pandas df format | [
"Returns",
"a",
"dummy",
"feature",
"of",
"1s",
"for",
"each",
"stimulus",
"Args",
":",
"ee_df",
"-",
"ExtractedEvents",
"in",
"pandas",
"df",
"format"
] | [
"\"\"\" Returns a dummy feature of 1s for each stimulus\n Args:\n ee_df - ExtractedEvents in pandas df format\n \"\"\""
] | [
{
"param": "ee_df",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ee_df",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
bd0d23aad6d008f68287758765ee7bf2aa6a5efc | neuroscout/neuroscout | neuroscout/populate/transform.py | [
"BSD-3-Clause"
] | Python | dummy_value | <not_specific> | def dummy_value(ee_df):
""" Sets the values to one
Args:
ee_df - ExtractedEvents in pandas df format
"""
ee_df['value'] = 1
ee_df['duration'] = 1
return ee_df[['onset', 'duration', 'value', 'stimulus_id']].to_dict('index').values() | Sets the values to one
Args:
ee_df - ExtractedEvents in pandas df format
| Sets the values to one
Args:
ee_df - ExtractedEvents in pandas df format | [
"Sets",
"the",
"values",
"to",
"one",
"Args",
":",
"ee_df",
"-",
"ExtractedEvents",
"in",
"pandas",
"df",
"format"
] | def dummy_value(ee_df):
ee_df['value'] = 1
ee_df['duration'] = 1
return ee_df[['onset', 'duration', 'value', 'stimulus_id']].to_dict('index').values() | [
"def",
"dummy_value",
"(",
"ee_df",
")",
":",
"ee_df",
"[",
"'value'",
"]",
"=",
"1",
"ee_df",
"[",
"'duration'",
"]",
"=",
"1",
"return",
"ee_df",
"[",
"[",
"'onset'",
",",
"'duration'",
",",
"'value'",
",",
"'stimulus_id'",
"]",
"]",
".",
"to_dict",
... | Sets the values to one
Args:
ee_df - ExtractedEvents in pandas df format | [
"Sets",
"the",
"values",
"to",
"one",
"Args",
":",
"ee_df",
"-",
"ExtractedEvents",
"in",
"pandas",
"df",
"format"
] | [
"\"\"\" Sets the values to one\n Args:\n ee_df - ExtractedEvents in pandas df format\n \"\"\""
] | [
{
"param": "ee_df",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "ee_df",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
bd0d23aad6d008f68287758765ee7bf2aa6a5efc | neuroscout/neuroscout | neuroscout/populate/transform.py | [
"BSD-3-Clause"
] | Python | apply_transformation | <not_specific> | def apply_transformation(self, new_name, function, func_args={}, **filter):
""" Queries EFs, applies transformation, and saves as new EF/Predictor
Args:
new_name - Feature/predictor name for transformed results
func - Function name to apply
func_args - keyword args fo... | Queries EFs, applies transformation, and saves as new EF/Predictor
Args:
new_name - Feature/predictor name for transformed results
func - Function name to apply
func_args - keyword args for transformation function
filter - arguments to filter ExtractedFeatures
... | Queries EFs, applies transformation, and saves as new EF/Predictor
Args:
new_name - Feature/predictor name for transformed results
func - Function name to apply
func_args - keyword args for transformation function
filter - arguments to filter ExtractedFeatures
Returns:
Database id of new ExtractedFeature | [
"Queries",
"EFs",
"applies",
"transformation",
"and",
"saves",
"as",
"new",
"EF",
"/",
"Predictor",
"Args",
":",
"new_name",
"-",
"Feature",
"/",
"predictor",
"name",
"for",
"transformed",
"results",
"func",
"-",
"Function",
"name",
"to",
"apply",
"func_args",... | def apply_transformation(self, new_name, function, func_args={}, **filter):
efs = self.efs.filter_by(**filter)
if efs.count() > 0:
ext_name = efs.first().extractor_name
new_ef = ExtractedFeature(
extractor_name=ext_name, feature_name=new_name,
acti... | [
"def",
"apply_transformation",
"(",
"self",
",",
"new_name",
",",
"function",
",",
"func_args",
"=",
"{",
"}",
",",
"**",
"filter",
")",
":",
"efs",
"=",
"self",
".",
"efs",
".",
"filter_by",
"(",
"**",
"filter",
")",
"if",
"efs",
".",
"count",
"(",
... | Queries EFs, applies transformation, and saves as new EF/Predictor
Args:
new_name - Feature/predictor name for transformed results
func - Function name to apply
func_args - keyword args for transformation function
filter - arguments to filter ExtractedFeatures
Returns:
Database id of new ExtractedFeature | [
"Queries",
"EFs",
"applies",
"transformation",
"and",
"saves",
"as",
"new",
"EF",
"/",
"Predictor",
"Args",
":",
"new_name",
"-",
"Feature",
"/",
"predictor",
"name",
"for",
"transformed",
"results",
"func",
"-",
"Function",
"name",
"to",
"apply",
"func_args",... | [
"\"\"\" Queries EFs, applies transformation, and saves as new EF/Predictor\n Args:\n new_name - Feature/predictor name for transformed results\n func - Function name to apply\n func_args - keyword args for transformation function\n filter - arguments to filter Extr... | [
{
"param": "self",
"type": null
},
{
"param": "new_name",
"type": null
},
{
"param": "function",
"type": null
},
{
"param": "func_args",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "new_name",
"type": null,
"docstring": null,
"docstring_tokens... |
0b21ca4864db6d80254691cac2ec3b9edbc3a831 | neuroscout/neuroscout | neuroscout/tasks/utils/io.py | [
"BSD-3-Clause"
] | Python | analysis_to_json | <not_specific> | def analysis_to_json(analysis_id, run_id=None):
"""" Serialize analysis and related PredictorEvents to JSON.
Queries PredictorEvents to get all events for all runs and predictors. """
# Query for analysis
analysis = Analysis.query.filter_by(hash_id=analysis_id).one()
# Dump analysis JSON
analy... | Serialize analysis and related PredictorEvents to JSON.
Queries PredictorEvents to get all events for all runs and predictors. | Serialize analysis and related PredictorEvents to JSON.
Queries PredictorEvents to get all events for all runs and predictors. | [
"Serialize",
"analysis",
"and",
"related",
"PredictorEvents",
"to",
"JSON",
".",
"Queries",
"PredictorEvents",
"to",
"get",
"all",
"events",
"for",
"all",
"runs",
"and",
"predictors",
"."
] | def analysis_to_json(analysis_id, run_id=None):
analysis = Analysis.query.filter_by(hash_id=analysis_id).one()
analysis_json = AnalysisFullSchema().dump(analysis)
resources_json = AnalysisResourcesSchema().dump(analysis)
all_runs = [r['id'] for r in analysis_json['runs']]
if run_id is None:
... | [
"def",
"analysis_to_json",
"(",
"analysis_id",
",",
"run_id",
"=",
"None",
")",
":",
"analysis",
"=",
"Analysis",
".",
"query",
".",
"filter_by",
"(",
"hash_id",
"=",
"analysis_id",
")",
".",
"one",
"(",
")",
"analysis_json",
"=",
"AnalysisFullSchema",
"(",
... | Serialize analysis and related PredictorEvents to JSON. | [
"Serialize",
"analysis",
"and",
"related",
"PredictorEvents",
"to",
"JSON",
"."
] | [
"\"\"\"\" Serialize analysis and related PredictorEvents to JSON.\n Queries PredictorEvents to get all events for all runs and predictors. \"\"\"",
"# Query for analysis",
"# Dump analysis JSON",
"# Get run IDs"
] | [
{
"param": "analysis_id",
"type": null
},
{
"param": "run_id",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "analysis_id",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "run_id",
"type": null,
"docstring": null,
"docstring_t... |
d45568ce8557390cd19bd04d0b8d29a4cf0e0705 | neuroscout/neuroscout | neuroscout/tests/conftest.py | [
"BSD-3-Clause"
] | Python | add_users | null | def add_users(app, db, session):
""" Adds a test user to db """
from flask_security import SQLAlchemyUserDatastore
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
user1 = 'test1@gmail.com'
pass1 = 'test1'
user2 = 'test2@gmail.com'
pass2 = 'test2'
user_datastore.create_user(e... | Adds a test user to db | Adds a test user to db | [
"Adds",
"a",
"test",
"user",
"to",
"db"
] | def add_users(app, db, session):
from flask_security import SQLAlchemyUserDatastore
user_datastore = SQLAlchemyUserDatastore(db, User, Role)
user1 = 'test1@gmail.com'
pass1 = 'test1'
user2 = 'test2@gmail.com'
pass2 = 'test2'
user_datastore.create_user(email=user1, password=encrypt_password(p... | [
"def",
"add_users",
"(",
"app",
",",
"db",
",",
"session",
")",
":",
"from",
"flask_security",
"import",
"SQLAlchemyUserDatastore",
"user_datastore",
"=",
"SQLAlchemyUserDatastore",
"(",
"db",
",",
"User",
",",
"Role",
")",
"user1",
"=",
"'test1@gmail.com'",
"pa... | Adds a test user to db | [
"Adds",
"a",
"test",
"user",
"to",
"db"
] | [
"\"\"\" Adds a test user to db \"\"\""
] | [
{
"param": "app",
"type": null
},
{
"param": "db",
"type": null
},
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "app",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "db",
"type": null,
"docstring": null,
"docstring_tokens": [],
... |
d45568ce8557390cd19bd04d0b8d29a4cf0e0705 | neuroscout/neuroscout | neuroscout/tests/conftest.py | [
"BSD-3-Clause"
] | Python | add_task | <not_specific> | def add_task(session):
""" Add a dataset with two subjects """
dataset_id = populate.add_dataset(
'Test Dataset',
'example dataset',
'///datalad/preproc/address',
DATASET_PATH
)
populate.add_task('bidstest', 'Test Dataset', DATASET_PATH)
return dataset_id | Add a dataset with two subjects | Add a dataset with two subjects | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects"
] | def add_task(session):
dataset_id = populate.add_dataset(
'Test Dataset',
'example dataset',
'///datalad/preproc/address',
DATASET_PATH
)
populate.add_task('bidstest', 'Test Dataset', DATASET_PATH)
return dataset_id | [
"def",
"add_task",
"(",
"session",
")",
":",
"dataset_id",
"=",
"populate",
".",
"add_dataset",
"(",
"'Test Dataset'",
",",
"'example dataset'",
",",
"'///datalad/preproc/address'",
",",
"DATASET_PATH",
")",
"populate",
".",
"add_task",
"(",
"'bidstest'",
",",
"'T... | Add a dataset with two subjects | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects"
] | [
"\"\"\" Add a dataset with two subjects \"\"\""
] | [
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "session",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d45568ce8557390cd19bd04d0b8d29a4cf0e0705 | neuroscout/neuroscout | neuroscout/tests/conftest.py | [
"BSD-3-Clause"
] | Python | add_task_remote | <not_specific> | def add_task_remote(session):
""" Add a dataset with two subjects. """
config_path = populate.setup_dataset(
'///fake/dataset',
raw_address='https://github.com/adelavega/bids_test',
dataset_summary="A test dataset",
skip_preproc=True,
url="https://github.com/adelavega/bids_test... | Add a dataset with two subjects. | Add a dataset with two subjects. | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects",
"."
] | def add_task_remote(session):
config_path = populate.setup_dataset(
'///fake/dataset',
raw_address='https://github.com/adelavega/bids_test',
dataset_summary="A test dataset",
skip_preproc=True,
url="https://github.com/adelavega/bids_test", subject="01", run=1
)
return pop... | [
"def",
"add_task_remote",
"(",
"session",
")",
":",
"config_path",
"=",
"populate",
".",
"setup_dataset",
"(",
"'///fake/dataset'",
",",
"raw_address",
"=",
"'https://github.com/adelavega/bids_test'",
",",
"dataset_summary",
"=",
"\"A test dataset\"",
",",
"skip_preproc",... | Add a dataset with two subjects. | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects",
"."
] | [
"\"\"\" Add a dataset with two subjects. \"\"\""
] | [
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "session",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
d45568ce8557390cd19bd04d0b8d29a4cf0e0705 | neuroscout/neuroscout | neuroscout/tests/conftest.py | [
"BSD-3-Clause"
] | Python | add_local_task_json | <not_specific> | def add_local_task_json(session):
""" Add a dataset with two subjects. """
config_path = populate.setup_dataset(
'///fake/dataset',
path="./neuroscout/tests/data/bids_test",
dataset_summary="A test dataset",
skip_preproc=True,
url="https://github.com/adelavega/bids_test", subject... | Add a dataset with two subjects. | Add a dataset with two subjects. | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects",
"."
] | def add_local_task_json(session):
config_path = populate.setup_dataset(
'///fake/dataset',
path="./neuroscout/tests/data/bids_test",
dataset_summary="A test dataset",
skip_preproc=True,
url="https://github.com/adelavega/bids_test", subject="01", run=1
)
return populate.inge... | [
"def",
"add_local_task_json",
"(",
"session",
")",
":",
"config_path",
"=",
"populate",
".",
"setup_dataset",
"(",
"'///fake/dataset'",
",",
"path",
"=",
"\"./neuroscout/tests/data/bids_test\"",
",",
"dataset_summary",
"=",
"\"A test dataset\"",
",",
"skip_preproc",
"="... | Add a dataset with two subjects. | [
"Add",
"a",
"dataset",
"with",
"two",
"subjects",
"."
] | [
"\"\"\" Add a dataset with two subjects. \"\"\""
] | [
{
"param": "session",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "session",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
e4767b2fa0e2fbd0e9e32ebc1946a5dfc79fd8b9 | adamchainz/structlog | conftest.py | [
"Apache-2.0",
"MIT"
] | Python | event_dict | <not_specific> | def event_dict():
"""
An example event dictionary with multiple value types w/o the event itself.
"""
class A:
def __repr__(self):
return r"<A(\o/)>"
return {"a": A(), "b": [3, 4], "x": 7, "y": "test", "z": (1, 2)} |
An example event dictionary with multiple value types w/o the event itself.
| An example event dictionary with multiple value types w/o the event itself. | [
"An",
"example",
"event",
"dictionary",
"with",
"multiple",
"value",
"types",
"w",
"/",
"o",
"the",
"event",
"itself",
"."
] | def event_dict():
class A:
def __repr__(self):
return r"<A(\o/)>"
return {"a": A(), "b": [3, 4], "x": 7, "y": "test", "z": (1, 2)} | [
"def",
"event_dict",
"(",
")",
":",
"class",
"A",
":",
"def",
"__repr__",
"(",
"self",
")",
":",
"return",
"r\"<A(\\o/)>\"",
"return",
"{",
"\"a\"",
":",
"A",
"(",
")",
",",
"\"b\"",
":",
"[",
"3",
",",
"4",
"]",
",",
"\"x\"",
":",
"7",
",",
"\... | An example event dictionary with multiple value types w/o the event itself. | [
"An",
"example",
"event",
"dictionary",
"with",
"multiple",
"value",
"types",
"w",
"/",
"o",
"the",
"event",
"itself",
"."
] | [
"\"\"\"\n An example event dictionary with multiple value types w/o the event itself.\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
7a479d25c396294825dc354eb9770077007105ca | adamchainz/structlog | src/structlog/threadlocal.py | [
"Apache-2.0",
"MIT"
] | Python | wrap_dict | <not_specific> | def wrap_dict(dict_class):
"""
Wrap a dict-like class and return the resulting class.
The wrapped class and used to keep global in the current thread.
:param type dict_class: Class used for keeping context.
:rtype: `type`
"""
Wrapped = type(
"WrappedDict-" + str(uuid.uuid4()), (_T... |
Wrap a dict-like class and return the resulting class.
The wrapped class and used to keep global in the current thread.
:param type dict_class: Class used for keeping context.
:rtype: `type`
| Wrap a dict-like class and return the resulting class.
The wrapped class and used to keep global in the current thread. | [
"Wrap",
"a",
"dict",
"-",
"like",
"class",
"and",
"return",
"the",
"resulting",
"class",
".",
"The",
"wrapped",
"class",
"and",
"used",
"to",
"keep",
"global",
"in",
"the",
"current",
"thread",
"."
] | def wrap_dict(dict_class):
Wrapped = type(
"WrappedDict-" + str(uuid.uuid4()), (_ThreadLocalDictWrapper,), {}
)
Wrapped._tl = ThreadLocal()
Wrapped._dict_class = dict_class
return Wrapped | [
"def",
"wrap_dict",
"(",
"dict_class",
")",
":",
"Wrapped",
"=",
"type",
"(",
"\"WrappedDict-\"",
"+",
"str",
"(",
"uuid",
".",
"uuid4",
"(",
")",
")",
",",
"(",
"_ThreadLocalDictWrapper",
",",
")",
",",
"{",
"}",
")",
"Wrapped",
".",
"_tl",
"=",
"Th... | Wrap a dict-like class and return the resulting class. | [
"Wrap",
"a",
"dict",
"-",
"like",
"class",
"and",
"return",
"the",
"resulting",
"class",
"."
] | [
"\"\"\"\n Wrap a dict-like class and return the resulting class.\n\n The wrapped class and used to keep global in the current thread.\n\n :param type dict_class: Class used for keeping context.\n\n :rtype: `type`\n \"\"\""
] | [
{
"param": "dict_class",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": "`type`"
}
],
"raises": [],
"params": [
{
"identifier": "dict_class",
"type": null,
"docstring": "Class used for keeping context.",
"docstring_tokens": [
"Class... |
7a479d25c396294825dc354eb9770077007105ca | adamchainz/structlog | src/structlog/threadlocal.py | [
"Apache-2.0",
"MIT"
] | Python | as_immutable | <not_specific> | def as_immutable(logger):
"""
Extract the context from a thread local logger into an immutable logger.
:param structlog.BoundLogger logger: A logger with *possibly* thread local
state.
:rtype: :class:`~structlog.BoundLogger` with an immutable context.
"""
if isinstance(logger, BoundLogg... |
Extract the context from a thread local logger into an immutable logger.
:param structlog.BoundLogger logger: A logger with *possibly* thread local
state.
:rtype: :class:`~structlog.BoundLogger` with an immutable context.
| Extract the context from a thread local logger into an immutable logger. | [
"Extract",
"the",
"context",
"from",
"a",
"thread",
"local",
"logger",
"into",
"an",
"immutable",
"logger",
"."
] | def as_immutable(logger):
if isinstance(logger, BoundLoggerLazyProxy):
logger = logger.bind()
try:
ctx = logger._context._tl.dict_.__class__(logger._context._dict)
bl = logger.__class__(
logger._logger, processors=logger._processors, context={}
)
bl._context =... | [
"def",
"as_immutable",
"(",
"logger",
")",
":",
"if",
"isinstance",
"(",
"logger",
",",
"BoundLoggerLazyProxy",
")",
":",
"logger",
"=",
"logger",
".",
"bind",
"(",
")",
"try",
":",
"ctx",
"=",
"logger",
".",
"_context",
".",
"_tl",
".",
"dict_",
".",
... | Extract the context from a thread local logger into an immutable logger. | [
"Extract",
"the",
"context",
"from",
"a",
"thread",
"local",
"logger",
"into",
"an",
"immutable",
"logger",
"."
] | [
"\"\"\"\n Extract the context from a thread local logger into an immutable logger.\n\n :param structlog.BoundLogger logger: A logger with *possibly* thread local\n state.\n :rtype: :class:`~structlog.BoundLogger` with an immutable context.\n \"\"\""
] | [
{
"param": "logger",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": ":class:`~structlog.BoundLogger` with an immutable context."
}
],
"raises": [],
"params": [
{
"identifier": "logger",
"type": null,
"docstring": "A logger with *possibly* thr... |
7a479d25c396294825dc354eb9770077007105ca | adamchainz/structlog | src/structlog/threadlocal.py | [
"Apache-2.0",
"MIT"
] | Python | clear_threadlocal | null | def clear_threadlocal():
"""
Clear the thread-local context.
The typical use-case for this function is to invoke it early in
request-handling code.
.. versionadded:: 19.2.0
"""
_CONTEXT.context = {} |
Clear the thread-local context.
The typical use-case for this function is to invoke it early in
request-handling code.
.. versionadded:: 19.2.0
| Clear the thread-local context.
The typical use-case for this function is to invoke it early in
request-handling code.
| [
"Clear",
"the",
"thread",
"-",
"local",
"context",
".",
"The",
"typical",
"use",
"-",
"case",
"for",
"this",
"function",
"is",
"to",
"invoke",
"it",
"early",
"in",
"request",
"-",
"handling",
"code",
"."
] | def clear_threadlocal():
_CONTEXT.context = {} | [
"def",
"clear_threadlocal",
"(",
")",
":",
"_CONTEXT",
".",
"context",
"=",
"{",
"}"
] | Clear the thread-local context. | [
"Clear",
"the",
"thread",
"-",
"local",
"context",
"."
] | [
"\"\"\"\n Clear the thread-local context.\n\n The typical use-case for this function is to invoke it early in\n request-handling code.\n\n .. versionadded:: 19.2.0\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
7a479d25c396294825dc354eb9770077007105ca | adamchainz/structlog | src/structlog/threadlocal.py | [
"Apache-2.0",
"MIT"
] | Python | unbind_threadlocal | null | def unbind_threadlocal(*keys):
"""
Tries to remove bound *keys* from threadlocal logging context if present.
.. versionadded:: 20.1.0
"""
context = _get_context()
for key in keys:
context.pop(key, None) |
Tries to remove bound *keys* from threadlocal logging context if present.
.. versionadded:: 20.1.0
| Tries to remove bound *keys* from threadlocal logging context if present. | [
"Tries",
"to",
"remove",
"bound",
"*",
"keys",
"*",
"from",
"threadlocal",
"logging",
"context",
"if",
"present",
"."
] | def unbind_threadlocal(*keys):
context = _get_context()
for key in keys:
context.pop(key, None) | [
"def",
"unbind_threadlocal",
"(",
"*",
"keys",
")",
":",
"context",
"=",
"_get_context",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"context",
".",
"pop",
"(",
"key",
",",
"None",
")"
] | Tries to remove bound *keys* from threadlocal logging context if present. | [
"Tries",
"to",
"remove",
"bound",
"*",
"keys",
"*",
"from",
"threadlocal",
"logging",
"context",
"if",
"present",
"."
] | [
"\"\"\"\n Tries to remove bound *keys* from threadlocal logging context if present.\n\n .. versionadded:: 20.1.0\n \"\"\""
] | [] | {
"returns": [],
"raises": [],
"params": [],
"outlier_params": [],
"others": []
} |
3528932a08ba43096436b3049db996174310eb9c | aditya95sriram/bn-slim | slim.py | [
"MIT"
] | Python | find_subtree | <not_specific> | def find_subtree(td: TreeDecomposition, budget: int, history: Counter = None,
debug=False):
"""
finds a subtree that fits within the budget
:param td: tree decomposition in which to find the subtree
:param budget: max number of vertices allowed in the union of selected bags
:param ... |
finds a subtree that fits within the budget
:param td: tree decomposition in which to find the subtree
:param budget: max number of vertices allowed in the union of selected bags
:param history: tally of bags picked in previous iterations
:param debug: debug mode
:return: (selected_bag_ids, se... | finds a subtree that fits within the budget | [
"finds",
"a",
"subtree",
"that",
"fits",
"within",
"the",
"budget"
] | def find_subtree(td: TreeDecomposition, budget: int, history: Counter = None,
debug=False):
start_bag_id = find_start_bag(td, history, debug)
selected = {start_bag_id}
seen = set(td.bags[start_bag_id])
if debug: print(f"starting bag {start_bag_id}: {td.bags[start_bag_id]}")
queue = ... | [
"def",
"find_subtree",
"(",
"td",
":",
"TreeDecomposition",
",",
"budget",
":",
"int",
",",
"history",
":",
"Counter",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"start_bag_id",
"=",
"find_start_bag",
"(",
"td",
",",
"history",
",",
"debug",
")",... | finds a subtree that fits within the budget | [
"finds",
"a",
"subtree",
"that",
"fits",
"within",
"the",
"budget"
] | [
"\"\"\"\n finds a subtree that fits within the budget\n\n :param td: tree decomposition in which to find the subtree\n :param budget: max number of vertices allowed in the union of selected bags\n :param history: tally of bags picked in previous iterations\n :param debug: debug mode\n :return: (se... | [
{
"param": "td",
"type": "TreeDecomposition"
},
{
"param": "budget",
"type": "int"
},
{
"param": "history",
"type": "Counter"
},
{
"param": "debug",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "td",
"type": "TreeDecomposition",
"docstring": "tree decomposition in which to find the subtree",
"docstring_tokens... |
8b4d320920ea73c87cc32952829adc8cadeece48 | aditya95sriram/bn-slim | blip.py | [
"MIT"
] | Python | done | null | def done(self):
"""
compute and store tree decomp and width based on
elim_order(default: reverse topological order of the dag)
"""
if self.elim_order is None:
self.elim_order = list(nx.topological_sort(self.dag))[::-1]
self._td = TreeDecomposition(self.get_mor... |
compute and store tree decomp and width based on
elim_order(default: reverse topological order of the dag)
| compute and store tree decomp and width based on
elim_order(default: reverse topological order of the dag) | [
"compute",
"and",
"store",
"tree",
"decomp",
"and",
"width",
"based",
"on",
"elim_order",
"(",
"default",
":",
"reverse",
"topological",
"order",
"of",
"the",
"dag",
")"
] | def done(self):
if self.elim_order is None:
self.elim_order = list(nx.topological_sort(self.dag))[::-1]
self._td = TreeDecomposition(self.get_moralized(), self.elim_order, self.tw)
if self.tw <= 0:
self.tw = self.td.width | [
"def",
"done",
"(",
"self",
")",
":",
"if",
"self",
".",
"elim_order",
"is",
"None",
":",
"self",
".",
"elim_order",
"=",
"list",
"(",
"nx",
".",
"topological_sort",
"(",
"self",
".",
"dag",
")",
")",
"[",
":",
":",
"-",
"1",
"]",
"self",
".",
... | compute and store tree decomp and width based on
elim_order(default: reverse topological order of the dag) | [
"compute",
"and",
"store",
"tree",
"decomp",
"and",
"width",
"based",
"on",
"elim_order",
"(",
"default",
":",
"reverse",
"topological",
"order",
"of",
"the",
"dag",
")"
] | [
"\"\"\"\n compute and store tree decomp and width based on\n elim_order(default: reverse topological order of the dag)\n \"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
8b4d320920ea73c87cc32952829adc8cadeece48 | aditya95sriram/bn-slim | blip.py | [
"MIT"
] | Python | parse_res | TWBayesianNetwork | def parse_res(filename: str, treewidth: int, outfile: str, cwidth=-1,
add_extra_tuples=False, augfile: str = "augmented.jkl",
datfile=None, retry=True, debug=False) -> TWBayesianNetwork:
"""
Parse a .res file containing a solution BN. Optionally merge the parent set
tuples from t... |
Parse a .res file containing a solution BN. Optionally merge the parent set
tuples from the jkl file `filename` and the the res file `outfile` and
save as a temporary file `augfile` (only when `add_extra_tuples` is True)
:param filename: input jkl file
:param treewidth: treewidth bound
:param ... | Parse a .res file containing a solution BN. | [
"Parse",
"a",
".",
"res",
"file",
"containing",
"a",
"solution",
"BN",
"."
] | def parse_res(filename: str, treewidth: int, outfile: str, cwidth=-1,
add_extra_tuples=False, augfile: str = "augmented.jkl",
datfile=None, retry=True, debug=False) -> TWBayesianNetwork:
elim_order = None
tuples = []
extra_tuples = dict()
score = None
while retry and os.p... | [
"def",
"parse_res",
"(",
"filename",
":",
"str",
",",
"treewidth",
":",
"int",
",",
"outfile",
":",
"str",
",",
"cwidth",
"=",
"-",
"1",
",",
"add_extra_tuples",
"=",
"False",
",",
"augfile",
":",
"str",
"=",
"\"augmented.jkl\"",
",",
"datfile",
"=",
"... | Parse a .res file containing a solution BN. | [
"Parse",
"a",
".",
"res",
"file",
"containing",
"a",
"solution",
"BN",
"."
] | [
"\"\"\"\n Parse a .res file containing a solution BN. Optionally merge the parent set\n tuples from the jkl file `filename` and the the res file `outfile` and\n save as a temporary file `augfile` (only when `add_extra_tuples` is True)\n\n :param filename: input jkl file\n :param treewidth: treewidth ... | [
{
"param": "filename",
"type": "str"
},
{
"param": "treewidth",
"type": "int"
},
{
"param": "outfile",
"type": "str"
},
{
"param": "cwidth",
"type": null
},
{
"param": "add_extra_tuples",
"type": null
},
{
"param": "augfile",
"type": "str"
},
{... | {
"returns": [
{
"docstring": "parsed BN as a TWBayesianNetwork",
"docstring_tokens": [
"parsed",
"BN",
"as",
"a",
"TWBayesianNetwork"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "filename",
"type": "str",... |
8b4d320920ea73c87cc32952829adc8cadeece48 | aditya95sriram/bn-slim | blip.py | [
"MIT"
] | Python | monitor_blip | null | def monitor_blip(filename, treewidth, logger: Callable, outfile="temp.res",
timeout=10, seed=0, solver="kg", datfile=None,
cwidth=0, onlyfilter=False, save_as="", debug=False):
"""
Run BLIP in monitoring mode, where each new score update is logged
:param filename: path to ... |
Run BLIP in monitoring mode, where each new score update is logged
:param filename: path to jkl file
:param treewidth: treewidth bound (ignored if in CWIDTH_MODE)
:param logger: logging function to be used
:param outfile: path to .res file containing learned network (volatile)
:param timeout: ... | Run BLIP in monitoring mode, where each new score update is logged | [
"Run",
"BLIP",
"in",
"monitoring",
"mode",
"where",
"each",
"new",
"score",
"update",
"is",
"logged"
] | def monitor_blip(filename, treewidth, logger: Callable, outfile="temp.res",
timeout=10, seed=0, solver="kg", datfile=None,
cwidth=0, onlyfilter=False, save_as="", debug=False):
CWIDTH_MODE = cwidth > 0
if CWIDTH_MODE:
assert solver in ("old", "greedy", "max"), \
... | [
"def",
"monitor_blip",
"(",
"filename",
",",
"treewidth",
",",
"logger",
":",
"Callable",
",",
"outfile",
"=",
"\"temp.res\"",
",",
"timeout",
"=",
"10",
",",
"seed",
"=",
"0",
",",
"solver",
"=",
"\"kg\"",
",",
"datfile",
"=",
"None",
",",
"cwidth",
"... | Run BLIP in monitoring mode, where each new score update is logged | [
"Run",
"BLIP",
"in",
"monitoring",
"mode",
"where",
"each",
"new",
"score",
"update",
"is",
"logged"
] | [
"\"\"\"\n Run BLIP in monitoring mode, where each new score update is logged\n\n :param filename: path to jkl file\n :param treewidth: treewidth bound (ignored if in CWIDTH_MODE)\n :param logger: logging function to be used\n :param outfile: path to .res file containing learned network (volatile)\n ... | [
{
"param": "filename",
"type": null
},
{
"param": "treewidth",
"type": null
},
{
"param": "logger",
"type": "Callable"
},
{
"param": "outfile",
"type": null
},
{
"param": "timeout",
"type": null
},
{
"param": "seed",
"type": null
},
{
"para... | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "filename",
"type": null,
"docstring": "path to jkl file",
"docstring_tokens": [
"path",
"to",
"jkl",
"file"
],
"default": null,
"is_optional": null
},
{
"identifi... |
53ec4b5caec3e4fd200d3cf64f568025c6437b51 | aditya95sriram/bn-slim | samer_veith.py | [
"MIT"
] | Python | encode_transitivity | null | def encode_transitivity(self, func: Callable[[int, int], int]):
"""
encode transitivity for a set of variables
:param func: arity 2 function for which transitivity must be encoded
"""
for i, j, l in ord_triples(range(self.num_nodes)):
self._add_clause(-func(i, j), -f... |
encode transitivity for a set of variables
:param func: arity 2 function for which transitivity must be encoded
| encode transitivity for a set of variables | [
"encode",
"transitivity",
"for",
"a",
"set",
"of",
"variables"
] | def encode_transitivity(self, func: Callable[[int, int], int]):
for i, j, l in ord_triples(range(self.num_nodes)):
self._add_clause(-func(i, j), -func(j, l), func(i, l)) | [
"def",
"encode_transitivity",
"(",
"self",
",",
"func",
":",
"Callable",
"[",
"[",
"int",
",",
"int",
"]",
",",
"int",
"]",
")",
":",
"for",
"i",
",",
"j",
",",
"l",
"in",
"ord_triples",
"(",
"range",
"(",
"self",
".",
"num_nodes",
")",
")",
":",... | encode transitivity for a set of variables | [
"encode",
"transitivity",
"for",
"a",
"set",
"of",
"variables"
] | [
"\"\"\"\n encode transitivity for a set of variables\n\n :param func: arity 2 function for which transitivity must be encoded\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "func",
"type": "Callable[[int, int], int]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "func",
"type": "Callable[[int, int], int]",
"docstring": "arity 2 f... |
53ec4b5caec3e4fd200d3cf64f568025c6437b51 | aditya95sriram/bn-slim | samer_veith.py | [
"MIT"
] | Python | encode_cardinality_sat | null | def encode_cardinality_sat(self, bound, variables):
"""Enforces cardinality constraints. Cardinality of 2-D structure variables must not exceed bound"""
# Counter works like this: ctr[i][j][0] states that an arc from i to j exists
# These are then summed up incrementally edge by edge
# ... | Enforces cardinality constraints. Cardinality of 2-D structure variables must not exceed bound | Enforces cardinality constraints. Cardinality of 2-D structure variables must not exceed bound | [
"Enforces",
"cardinality",
"constraints",
".",
"Cardinality",
"of",
"2",
"-",
"D",
"structure",
"variables",
"must",
"not",
"exceed",
"bound"
] | def encode_cardinality_sat(self, bound, variables):
ctr = [[[self._add_var()
for _ in range(0, min(j, bound))]
for j in range(1, len(variables[0]))]
for _ in range(0, len(variables))]
for i in range(0, len(variables)):
for j in range(1, len(var... | [
"def",
"encode_cardinality_sat",
"(",
"self",
",",
"bound",
",",
"variables",
")",
":",
"ctr",
"=",
"[",
"[",
"[",
"self",
".",
"_add_var",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"min",
"(",
"j",
",",
"bound",
")",
")",
"]",
"for",
... | Enforces cardinality constraints. | [
"Enforces",
"cardinality",
"constraints",
"."
] | [
"\"\"\"Enforces cardinality constraints. Cardinality of 2-D structure variables must not exceed bound\"\"\"",
"# Counter works like this: ctr[i][j][0] states that an arc from i to j exists",
"# These are then summed up incrementally edge by edge",
"# Define counter variables ctr[i][j][l] with 1 <= i <= n, 1 <... | [
{
"param": "self",
"type": null
},
{
"param": "bound",
"type": null
},
{
"param": "variables",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bound",
"type": null,
"docstring": null,
"docstring_tokens": ... |
cbc50d7626440c88de38f03471f03553fb61fe4f | aditya95sriram/bn-slim | complexity_encoding.py | [
"MIT"
] | Python | encode_single_cardinality | <not_specific> | def encode_single_cardinality(self, bound, variables: OrderedDict):
"""Enforces cardinality constraint on list of variables (repeats allowed)"""
if bound <= 0:
if self.debug:
print(f"warning: non-positive bound {bound} provided, forcing UNSAT")
self._add_clause(-1... | Enforces cardinality constraint on list of variables (repeats allowed) | Enforces cardinality constraint on list of variables (repeats allowed) | [
"Enforces",
"cardinality",
"constraint",
"on",
"list",
"of",
"variables",
"(",
"repeats",
"allowed",
")"
] | def encode_single_cardinality(self, bound, variables: OrderedDict):
if bound <= 0:
if self.debug:
print(f"warning: non-positive bound {bound} provided, forcing UNSAT")
self._add_clause(-1)
self._add_clause(1)
return
variables = replicate(va... | [
"def",
"encode_single_cardinality",
"(",
"self",
",",
"bound",
",",
"variables",
":",
"OrderedDict",
")",
":",
"if",
"bound",
"<=",
"0",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"f\"warning: non-positive bound {bound} provided, forcing UNSAT\"",
")",
"s... | Enforces cardinality constraint on list of variables (repeats allowed) | [
"Enforces",
"cardinality",
"constraint",
"on",
"list",
"of",
"variables",
"(",
"repeats",
"allowed",
")"
] | [
"\"\"\"Enforces cardinality constraint on list of variables (repeats allowed)\"\"\"",
"# never decrements",
"# increment if variable and ctr",
"# initialize first counter if corr variable is true",
"# conflict if target exceeded"
] | [
{
"param": "self",
"type": null
},
{
"param": "bound",
"type": null
},
{
"param": "variables",
"type": "OrderedDict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bound",
"type": null,
"docstring": null,
"docstring_tokens": ... |
cbc50d7626440c88de38f03471f03553fb61fe4f | aditya95sriram/bn-slim | complexity_encoding.py | [
"MIT"
] | Python | encode_cardinality_sat | null | def encode_cardinality_sat(self, bound, variables: Dict[int, Dict[int, int]]):
"""
Enforce weighted cardinality constraint on 2-d structure of variables
* weights are read from self.weights
* bound is adjusted by weight of the outer variable
* inner variable is replicated as many... |
Enforce weighted cardinality constraint on 2-d structure of variables
* weights are read from self.weights
* bound is adjusted by weight of the outer variable
* inner variable is replicated as many times as its weight to form final
list of variables to be cardinally constraine... | Enforce weighted cardinality constraint on 2-d structure of variables
weights are read from self.weights
bound is adjusted by weight of the outer variable
inner variable is replicated as many times as its weight to form final
list of variables to be cardinally constrained | [
"Enforce",
"weighted",
"cardinality",
"constraint",
"on",
"2",
"-",
"d",
"structure",
"of",
"variables",
"weights",
"are",
"read",
"from",
"self",
".",
"weights",
"bound",
"is",
"adjusted",
"by",
"weight",
"of",
"the",
"outer",
"variable",
"inner",
"variable",... | def encode_cardinality_sat(self, bound, variables: Dict[int, Dict[int, int]]):
old = self.num_clauses
for i in range(len(variables)):
node = self.node_reverse_lookup[i]
varcounts = OrderedDict()
if self.debug:
self.current_cardinality_outer_var = node
... | [
"def",
"encode_cardinality_sat",
"(",
"self",
",",
"bound",
",",
"variables",
":",
"Dict",
"[",
"int",
",",
"Dict",
"[",
"int",
",",
"int",
"]",
"]",
")",
":",
"old",
"=",
"self",
".",
"num_clauses",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"var... | Enforce weighted cardinality constraint on 2-d structure of variables
weights are read from self.weights
bound is adjusted by weight of the outer variable
inner variable is replicated as many times as its weight to form final
list of variables to be cardinally constrained | [
"Enforce",
"weighted",
"cardinality",
"constraint",
"on",
"2",
"-",
"d",
"structure",
"of",
"variables",
"weights",
"are",
"read",
"from",
"self",
".",
"weights",
"bound",
"is",
"adjusted",
"by",
"weight",
"of",
"the",
"outer",
"variable",
"inner",
"variable",... | [
"\"\"\"\n Enforce weighted cardinality constraint on 2-d structure of variables\n * weights are read from self.weights\n * bound is adjusted by weight of the outer variable\n * inner variable is replicated as many times as its weight to form final\n list of variables to be cardi... | [
{
"param": "self",
"type": null
},
{
"param": "bound",
"type": null
},
{
"param": "variables",
"type": "Dict[int, Dict[int, int]]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bound",
"type": null,
"docstring": null,
"docstring_tokens": ... |
cbc50d7626440c88de38f03471f03553fb61fe4f | aditya95sriram/bn-slim | complexity_encoding.py | [
"MIT"
] | Python | encode_single_cardinality_with_dd | <not_specific> | def encode_single_cardinality_with_dd(self, bound, variables: OrderedDict):
"""
Enforces weighted cardinality constraint on list of variables
(repeats allowed)
"""
if bound <= 0:
if self.debug:
print(f"warning: non-positive bound {bound} provided, forc... |
Enforces weighted cardinality constraint on list of variables
(repeats allowed)
| Enforces weighted cardinality constraint on list of variables
(repeats allowed) | [
"Enforces",
"weighted",
"cardinality",
"constraint",
"on",
"list",
"of",
"variables",
"(",
"repeats",
"allowed",
")"
] | def encode_single_cardinality_with_dd(self, bound, variables: OrderedDict):
if bound <= 0:
if self.debug:
print(f"warning: non-positive bound {bound} provided, forcing UNSAT")
self._add_clause(-1)
self._add_clause(1)
return
dd = make_decisi... | [
"def",
"encode_single_cardinality_with_dd",
"(",
"self",
",",
"bound",
",",
"variables",
":",
"OrderedDict",
")",
":",
"if",
"bound",
"<=",
"0",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"f\"warning: non-positive bound {bound} provided, forcing UNSAT\"",
"... | Enforces weighted cardinality constraint on list of variables
(repeats allowed) | [
"Enforces",
"weighted",
"cardinality",
"constraint",
"on",
"list",
"of",
"variables",
"(",
"repeats",
"allowed",
")"
] | [
"\"\"\"\n Enforces weighted cardinality constraint on list of variables\n (repeats allowed)\n \"\"\"",
"# if NO is ever true, this results in contradiction",
"# initialize root node as true",
"# nothing to do",
"# clause: u & var => v",
"# clause: u & !var => v"
] | [
{
"param": "self",
"type": null
},
{
"param": "bound",
"type": null
},
{
"param": "variables",
"type": "OrderedDict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "bound",
"type": null,
"docstring": null,
"docstring_tokens": ... |
33299eef40ce740b83cb03d3dc869e24f451ee7b | aditya95sriram/bn-slim | utils.py | [
"MIT"
] | Python | replicate | <not_specific> | def replicate(d: OrderedDict):
"""
convert a dict with (element, count) into a list
with each element replicated count many times
"""
l = []
for element, count in d.items():
l.extend([element]*count)
return l |
convert a dict with (element, count) into a list
with each element replicated count many times
| convert a dict with (element, count) into a list
with each element replicated count many times | [
"convert",
"a",
"dict",
"with",
"(",
"element",
"count",
")",
"into",
"a",
"list",
"with",
"each",
"element",
"replicated",
"count",
"many",
"times"
] | def replicate(d: OrderedDict):
l = []
for element, count in d.items():
l.extend([element]*count)
return l | [
"def",
"replicate",
"(",
"d",
":",
"OrderedDict",
")",
":",
"l",
"=",
"[",
"]",
"for",
"element",
",",
"count",
"in",
"d",
".",
"items",
"(",
")",
":",
"l",
".",
"extend",
"(",
"[",
"element",
"]",
"*",
"count",
")",
"return",
"l"
] | convert a dict with (element, count) into a list
with each element replicated count many times | [
"convert",
"a",
"dict",
"with",
"(",
"element",
"count",
")",
"into",
"a",
"list",
"with",
"each",
"element",
"replicated",
"count",
"many",
"times"
] | [
"\"\"\"\n convert a dict with (element, count) into a list\n with each element replicated count many times\n \"\"\""
] | [
{
"param": "d",
"type": "OrderedDict"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "d",
"type": "OrderedDict",
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
}
],
"outlier_params": [],
"others": []
} |
33299eef40ce740b83cb03d3dc869e24f451ee7b | aditya95sriram/bn-slim | utils.py | [
"MIT"
] | Python | bag_containing | int | def bag_containing(self, members: Union[set, frozenset],
exclude: Set[int] = None) -> int:
"""
returns the id of a bag containing given members
if no such bag exists, returns -1
"""
exclude = set() if exclude is None else exclude
for bag_id, bag in ... |
returns the id of a bag containing given members
if no such bag exists, returns -1
| returns the id of a bag containing given members
if no such bag exists, returns -1 | [
"returns",
"the",
"id",
"of",
"a",
"bag",
"containing",
"given",
"members",
"if",
"no",
"such",
"bag",
"exists",
"returns",
"-",
"1"
] | def bag_containing(self, members: Union[set, frozenset],
exclude: Set[int] = None) -> int:
exclude = set() if exclude is None else exclude
for bag_id, bag in self.bags.items():
if bag_id in exclude: continue
if bag.issuperset(members):
retur... | [
"def",
"bag_containing",
"(",
"self",
",",
"members",
":",
"Union",
"[",
"set",
",",
"frozenset",
"]",
",",
"exclude",
":",
"Set",
"[",
"int",
"]",
"=",
"None",
")",
"->",
"int",
":",
"exclude",
"=",
"set",
"(",
")",
"if",
"exclude",
"is",
"None",
... | returns the id of a bag containing given members
if no such bag exists, returns -1 | [
"returns",
"the",
"id",
"of",
"a",
"bag",
"containing",
"given",
"members",
"if",
"no",
"such",
"bag",
"exists",
"returns",
"-",
"1"
] | [
"\"\"\"\n returns the id of a bag containing given members\n if no such bag exists, returns -1\n \"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "members",
"type": "Union[set, frozenset]"
},
{
"param": "exclude",
"type": "Set[int]"
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "members",
"type": "Union[set, frozenset]",
"docstring": null,
... |
33299eef40ce740b83cb03d3dc869e24f451ee7b | aditya95sriram/bn-slim | utils.py | [
"MIT"
] | Python | recompute_elim_order | list | def recompute_elim_order(self) -> list:
"""
recomputes elimination ordering based on possibly modified
decomposition bags
:return: new elim_order as list
"""
rootbag = first(self.bags) # arbitrarily choose a root bag
elim_order = list(self.bags[rootbag]) # init... |
recomputes elimination ordering based on possibly modified
decomposition bags
:return: new elim_order as list
| recomputes elimination ordering based on possibly modified
decomposition bags | [
"recomputes",
"elimination",
"ordering",
"based",
"on",
"possibly",
"modified",
"decomposition",
"bags"
] | def recompute_elim_order(self) -> list:
rootbag = first(self.bags)
elim_order = list(self.bags[rootbag])
for u, v in nx.dfs_edges(self.decomp, source=rootbag):
forgotten = self.bags[v] - self.bags[u]
elim_order.extend(forgotten)
elim_order.reverse()
re... | [
"def",
"recompute_elim_order",
"(",
"self",
")",
"->",
"list",
":",
"rootbag",
"=",
"first",
"(",
"self",
".",
"bags",
")",
"elim_order",
"=",
"list",
"(",
"self",
".",
"bags",
"[",
"rootbag",
"]",
")",
"for",
"u",
",",
"v",
"in",
"nx",
".",
"dfs_e... | recomputes elimination ordering based on possibly modified
decomposition bags | [
"recomputes",
"elimination",
"ordering",
"based",
"on",
"possibly",
"modified",
"decomposition",
"bags"
] | [
"\"\"\"\n recomputes elimination ordering based on possibly modified\n decomposition bags\n\n :return: new elim_order as list\n \"\"\"",
"# arbitrarily choose a root bag",
"# initialize eo with rootbag"
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "new elim_order as list",
"docstring_tokens": [
"new",
"elim_order",
"as",
"list"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"doc... |
92a173853c254dfff2225eb10697443a84e527a6 | aditya95sriram/bn-slim | hcet.py | [
"MIT"
] | Python | export_et | <not_specific> | def export_et(et, dataframe, basename):
"""
writes out given elimination tree as a .res file containing the BN and
a .jkl file containing the parent set scores
"""
data = data_type.data(dataframe)
total_score = 0.0
all_scores = {}
with open(basename + '.res', 'w') as outfile:
eo ... |
writes out given elimination tree as a .res file containing the BN and
a .jkl file containing the parent set scores
| writes out given elimination tree as a .res file containing the BN and
a .jkl file containing the parent set scores | [
"writes",
"out",
"given",
"elimination",
"tree",
"as",
"a",
".",
"res",
"file",
"containing",
"the",
"BN",
"and",
"a",
".",
"jkl",
"file",
"containing",
"the",
"parent",
"set",
"scores"
] | def export_et(et, dataframe, basename):
data = data_type.data(dataframe)
total_score = 0.0
all_scores = {}
with open(basename + '.res', 'w') as outfile:
eo = extract_eo(et)
outfile.write("elim-order: ({})\n".format(",".join(map(str, eo))))
for i in range(et.nodes.num_nds):
... | [
"def",
"export_et",
"(",
"et",
",",
"dataframe",
",",
"basename",
")",
":",
"data",
"=",
"data_type",
".",
"data",
"(",
"dataframe",
")",
"total_score",
"=",
"0.0",
"all_scores",
"=",
"{",
"}",
"with",
"open",
"(",
"basename",
"+",
"'.res'",
",",
"'w'"... | writes out given elimination tree as a .res file containing the BN and
a .jkl file containing the parent set scores | [
"writes",
"out",
"given",
"elimination",
"tree",
"as",
"a",
".",
"res",
"file",
"containing",
"the",
"BN",
"and",
"a",
".",
"jkl",
"file",
"containing",
"the",
"parent",
"set",
"scores"
] | [
"\"\"\"\n writes out given elimination tree as a .res file containing the BN and\n a .jkl file containing the parent set scores\n \"\"\""
] | [
{
"param": "et",
"type": null
},
{
"param": "dataframe",
"type": null
},
{
"param": "basename",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "et",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "dataframe",
"type": null,
"docstring": null,
"docstring_tokens"... |
1a67d0af9effa374593fb479bce248a24e6f9708 | clementbosc/iot-tweet-search-engine | recommendation/model_reco.py | [
"Apache-2.0"
] | Python | load_corpus | <not_specific> | def load_corpus(self, corpus_path=os.path.join(ROOT_DIR, 'corpus/iot-tweets-vector-v31.tsv'),
like_rt_graph=os.path.join(ROOT_DIR, 'corpus/like_rt_graph.adj')):
"""
Load the corpus and the Favorite/RT adjancy matrix
:param corpus_path: absolute path
:param like_rt_graph: absolute path
:return: pd.DataFra... |
Load the corpus and the Favorite/RT adjancy matrix
:param corpus_path: absolute path
:param like_rt_graph: absolute path
:return: pd.DataFrame object
| Load the corpus and the Favorite/RT adjancy matrix | [
"Load",
"the",
"corpus",
"and",
"the",
"Favorite",
"/",
"RT",
"adjancy",
"matrix"
] | def load_corpus(self, corpus_path=os.path.join(ROOT_DIR, 'corpus/iot-tweets-vector-v31.tsv'),
like_rt_graph=os.path.join(ROOT_DIR, 'corpus/like_rt_graph.adj')):
original_corpus = Parser.parsing_base_corpus_pandas(corpus_path, categorize=True)
self.num_users = len(original_corpus.User_Name.unique())
self.num_... | [
"def",
"load_corpus",
"(",
"self",
",",
"corpus_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ROOT_DIR",
",",
"'corpus/iot-tweets-vector-v31.tsv'",
")",
",",
"like_rt_graph",
"=",
"os",
".",
"path",
".",
"join",
"(",
"ROOT_DIR",
",",
"'corpus/like_rt_graph... | Load the corpus and the Favorite/RT adjancy matrix | [
"Load",
"the",
"corpus",
"and",
"the",
"Favorite",
"/",
"RT",
"adjancy",
"matrix"
] | [
"\"\"\"\n\t\tLoad the corpus and the Favorite/RT adjancy matrix\n\t\t:param corpus_path: absolute path\n\t\t:param like_rt_graph: absolute path\n\t\t:return: pd.DataFrame object\n\t\t\"\"\"",
"# like or RT tweets",
"# negative instances"
] | [
{
"param": "self",
"type": null
},
{
"param": "corpus_path",
"type": null
},
{
"param": "like_rt_graph",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
1a67d0af9effa374593fb479bce248a24e6f9708 | clementbosc/iot-tweet-search-engine | recommendation/model_reco.py | [
"Apache-2.0"
] | Python | create_model | null | def create_model(self):
"""
Build and compile a MasterModel depending on the method asked
:return:
"""
if self.method == "gmf":
self.model = GMFModel(self.num_users, self.num_tweets, self.num_factors_user, self.num_factors_item,
self.regs).get_model()
elif self.method == "mf":
self.model = M... |
Build and compile a MasterModel depending on the method asked
:return:
| Build and compile a MasterModel depending on the method asked | [
"Build",
"and",
"compile",
"a",
"MasterModel",
"depending",
"on",
"the",
"method",
"asked"
] | def create_model(self):
if self.method == "gmf":
self.model = GMFModel(self.num_users, self.num_tweets, self.num_factors_user, self.num_factors_item,
self.regs).get_model()
elif self.method == "mf":
self.model = MFModel(self.num_users, self.num_tweets, self.num_factors_user, self.num_factors_item,
... | [
"def",
"create_model",
"(",
"self",
")",
":",
"if",
"self",
".",
"method",
"==",
"\"gmf\"",
":",
"self",
".",
"model",
"=",
"GMFModel",
"(",
"self",
".",
"num_users",
",",
"self",
".",
"num_tweets",
",",
"self",
".",
"num_factors_user",
",",
"self",
".... | Build and compile a MasterModel depending on the method asked | [
"Build",
"and",
"compile",
"a",
"MasterModel",
"depending",
"on",
"the",
"method",
"asked"
] | [
"\"\"\"\n\t\tBuild and compile a MasterModel depending on the method asked\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
1a67d0af9effa374593fb479bce248a24e6f9708 | clementbosc/iot-tweet-search-engine | recommendation/model_reco.py | [
"Apache-2.0"
] | Python | predict | <not_specific> | def predict(self):
"""
Predict values based on test corpus
:return: predictions, 1-d array
"""
return self.model.predict([self.test_corpus.User_ID_u, self.test_corpus.TweetID_u]) |
Predict values based on test corpus
:return: predictions, 1-d array
| Predict values based on test corpus | [
"Predict",
"values",
"based",
"on",
"test",
"corpus"
] | def predict(self):
return self.model.predict([self.test_corpus.User_ID_u, self.test_corpus.TweetID_u]) | [
"def",
"predict",
"(",
"self",
")",
":",
"return",
"self",
".",
"model",
".",
"predict",
"(",
"[",
"self",
".",
"test_corpus",
".",
"User_ID_u",
",",
"self",
".",
"test_corpus",
".",
"TweetID_u",
"]",
")"
] | Predict values based on test corpus | [
"Predict",
"values",
"based",
"on",
"test",
"corpus"
] | [
"\"\"\"\n\t\tPredict values based on test corpus\n\t\t:return: predictions, 1-d array\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
}
] | {
"returns": [
{
"docstring": "predictions, 1-d array",
"docstring_tokens": [
"predictions",
"1",
"-",
"d",
"array"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null... |
1a67d0af9effa374593fb479bce248a24e6f9708 | clementbosc/iot-tweet-search-engine | recommendation/model_reco.py | [
"Apache-2.0"
] | Python | mae_metric | <not_specific> | def mae_metric(self, predictions):
"""
Return the MAE metrics based on predictions
:param predictions:
:return:
"""
y_true = self.test_corpus.Rating
y_hat = np.round(predictions, 0)
mae = mean_absolute_error(y_true, y_hat)
return mae |
Return the MAE metrics based on predictions
:param predictions:
:return:
| Return the MAE metrics based on predictions | [
"Return",
"the",
"MAE",
"metrics",
"based",
"on",
"predictions"
] | def mae_metric(self, predictions):
y_true = self.test_corpus.Rating
y_hat = np.round(predictions, 0)
mae = mean_absolute_error(y_true, y_hat)
return mae | [
"def",
"mae_metric",
"(",
"self",
",",
"predictions",
")",
":",
"y_true",
"=",
"self",
".",
"test_corpus",
".",
"Rating",
"y_hat",
"=",
"np",
".",
"round",
"(",
"predictions",
",",
"0",
")",
"mae",
"=",
"mean_absolute_error",
"(",
"y_true",
",",
"y_hat",... | Return the MAE metrics based on predictions | [
"Return",
"the",
"MAE",
"metrics",
"based",
"on",
"predictions"
] | [
"\"\"\"\n\t\tReturn the MAE metrics based on predictions\n\t\t:param predictions:\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "predictions",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
ad64bf0a43f998c756905fbbe157063f8cae3628 | clementbosc/iot-tweet-search-engine | recommendation/user_reco.py | [
"Apache-2.0"
] | Python | rerank_authors | <not_specific> | def rerank_authors(self, authors_prio):
"""
rerank results from authors_prio based on their similarity with the user
:param authors_prio: the jaccard coefficient for the link prediction between the user and each kept author
:return:
"""
reranked_reco = []
for a, p in authors_prio:
author = DB.get_insta... |
rerank results from authors_prio based on their similarity with the user
:param authors_prio: the jaccard coefficient for the link prediction between the user and each kept author
:return:
| rerank results from authors_prio based on their similarity with the user | [
"rerank",
"results",
"from",
"authors_prio",
"based",
"on",
"their",
"similarity",
"with",
"the",
"user"
] | def rerank_authors(self, authors_prio):
reranked_reco = []
for a, p in authors_prio:
author = DB.get_instance().query(Author).filter(Author.name == a).first()
author_vec = ProfileOneHotEncoder.add_info_to_vec(author.vector, author.gender, author.localisation,
... | [
"def",
"rerank_authors",
"(",
"self",
",",
"authors_prio",
")",
":",
"reranked_reco",
"=",
"[",
"]",
"for",
"a",
",",
"p",
"in",
"authors_prio",
":",
"author",
"=",
"DB",
".",
"get_instance",
"(",
")",
".",
"query",
"(",
"Author",
")",
".",
"filter",
... | rerank results from authors_prio based on their similarity with the user | [
"rerank",
"results",
"from",
"authors_prio",
"based",
"on",
"their",
"similarity",
"with",
"the",
"user"
] | [
"\"\"\"\n\t\trerank results from authors_prio based on their similarity with the user\n\t\t:param authors_prio: the jaccard coefficient for the link prediction between the user and each kept author\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "authors_prio",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
ad64bf0a43f998c756905fbbe157063f8cae3628 | clementbosc/iot-tweet-search-engine | recommendation/user_reco.py | [
"Apache-2.0"
] | Python | users_to_recommend | <not_specific> | def users_to_recommend(self, nb_reco_user=5):
"""
compute the authors to recommend to the user based on link prediction and similarity
:param nb_reco_user: number of users to recommend
:return:
"""
ebunch = []
authors = set(self.graph.nodes())
authors.remove(self.user.id)
for a in self.authors_liked:
... |
compute the authors to recommend to the user based on link prediction and similarity
:param nb_reco_user: number of users to recommend
:return:
| compute the authors to recommend to the user based on link prediction and similarity | [
"compute",
"the",
"authors",
"to",
"recommend",
"to",
"the",
"user",
"based",
"on",
"link",
"prediction",
"and",
"similarity"
] | def users_to_recommend(self, nb_reco_user=5):
ebunch = []
authors = set(self.graph.nodes())
authors.remove(self.user.id)
for a in self.authors_liked:
authors.remove(a)
for author in authors:
ebunch.append((self.user.id, author))
preds = nx.jaccard_coefficient(self.graph, ebunch)
reco_prio = []
for... | [
"def",
"users_to_recommend",
"(",
"self",
",",
"nb_reco_user",
"=",
"5",
")",
":",
"ebunch",
"=",
"[",
"]",
"authors",
"=",
"set",
"(",
"self",
".",
"graph",
".",
"nodes",
"(",
")",
")",
"authors",
".",
"remove",
"(",
"self",
".",
"user",
".",
"id"... | compute the authors to recommend to the user based on link prediction and similarity | [
"compute",
"the",
"authors",
"to",
"recommend",
"to",
"the",
"user",
"based",
"on",
"link",
"prediction",
"and",
"similarity"
] | [
"\"\"\"\n\t\tcompute the authors to recommend to the user based on link prediction and similarity\n\t\t:param nb_reco_user: number of users to recommend\n\t\t:return:\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "nb_reco_user",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
... |
695418e1c8494356d80261057597b95376d5d190 | clementbosc/iot-tweet-search-engine | query_lucene.py | [
"Apache-2.0"
] | Python | query_parser_filter | null | def query_parser_filter(self, field_values, field_filter=['Vector']):
"""
Filtering queries according to field values
:param field_values: values of the fields
:param field_filter: fields to filter
"""
assert len(field_filter) == len(field_values), "Number of fields different from number of values"
for i ... |
Filtering queries according to field values
:param field_values: values of the fields
:param field_filter: fields to filter
| Filtering queries according to field values | [
"Filtering",
"queries",
"according",
"to",
"field",
"values"
] | def query_parser_filter(self, field_values, field_filter=['Vector']):
assert len(field_filter) == len(field_values), "Number of fields different from number of values"
for i in range(len(field_filter)):
query_parser = QueryParser(field_filter[i], self.analyzer)
query = query_parser.parse(field_values[i])
s... | [
"def",
"query_parser_filter",
"(",
"self",
",",
"field_values",
",",
"field_filter",
"=",
"[",
"'Vector'",
"]",
")",
":",
"assert",
"len",
"(",
"field_filter",
")",
"==",
"len",
"(",
"field_values",
")",
",",
"\"Number of fields different from number of values\"",
... | Filtering queries according to field values | [
"Filtering",
"queries",
"according",
"to",
"field",
"values"
] | [
"\"\"\"\n\t\tFiltering queries according to field values\n\t\t:param field_values: values of the fields\n\t\t:param field_filter: fields to filter\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "field_values",
"type": null
},
{
"param": "field_filter",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "field_values",
"type": null,
"docstring": "values of the fields",
... |
695418e1c8494356d80261057597b95376d5d190 | clementbosc/iot-tweet-search-engine | query_lucene.py | [
"Apache-2.0"
] | Python | query_parser_must | null | def query_parser_must(self, field_values, field_must=['Text']):
"""
The values that the fields must match
:param field_values: values of the fields
:param field_must: fields that must match
"""
assert len(field_must) == len(field_values), "Number of fields different from number of values"
for i in range(l... |
The values that the fields must match
:param field_values: values of the fields
:param field_must: fields that must match
| The values that the fields must match | [
"The",
"values",
"that",
"the",
"fields",
"must",
"match"
] | def query_parser_must(self, field_values, field_must=['Text']):
assert len(field_must) == len(field_values), "Number of fields different from number of values"
for i in range(len(field_must)):
query_parser = QueryParser(field_must[i], self.analyzer)
query = query_parser.parse(field_values[i])
self.constrai... | [
"def",
"query_parser_must",
"(",
"self",
",",
"field_values",
",",
"field_must",
"=",
"[",
"'Text'",
"]",
")",
":",
"assert",
"len",
"(",
"field_must",
")",
"==",
"len",
"(",
"field_values",
")",
",",
"\"Number of fields different from number of values\"",
"for",
... | The values that the fields must match | [
"The",
"values",
"that",
"the",
"fields",
"must",
"match"
] | [
"\"\"\"\n\t\tThe values that the fields must match\n\t\t:param field_values: values of the fields\n\t\t:param field_must: fields that must match\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "field_values",
"type": null
},
{
"param": "field_must",
"type": null
}
] | {
"returns": [],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docstring_tokens": [],
"default": null,
"is_optional": null
},
{
"identifier": "field_values",
"type": null,
"docstring": "values of the fields",
... |
695418e1c8494356d80261057597b95376d5d190 | clementbosc/iot-tweet-search-engine | query_lucene.py | [
"Apache-2.0"
] | Python | remove_duplicates | <not_specific> | def remove_duplicates(self, hits):
"""
remove duplicates (regarding the text field) from a scoreDocs object
:param hits: the scoreDocs object resulting from a query
:return: the scoreDocs object without duplicates
"""
seen = set()
keep = []
for i in range(len(hits)):
if hits[i]["Text"] not in seen:
... |
remove duplicates (regarding the text field) from a scoreDocs object
:param hits: the scoreDocs object resulting from a query
:return: the scoreDocs object without duplicates
| remove duplicates (regarding the text field) from a scoreDocs object | [
"remove",
"duplicates",
"(",
"regarding",
"the",
"text",
"field",
")",
"from",
"a",
"scoreDocs",
"object"
] | def remove_duplicates(self, hits):
seen = set()
keep = []
for i in range(len(hits)):
if hits[i]["Text"] not in seen:
seen.add(hits[i]["Text"])
keep.append(hits[i])
return keep | [
"def",
"remove_duplicates",
"(",
"self",
",",
"hits",
")",
":",
"seen",
"=",
"set",
"(",
")",
"keep",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"hits",
")",
")",
":",
"if",
"hits",
"[",
"i",
"]",
"[",
"\"Text\"",
"]",
"not",
... | remove duplicates (regarding the text field) from a scoreDocs object | [
"remove",
"duplicates",
"(",
"regarding",
"the",
"text",
"field",
")",
"from",
"a",
"scoreDocs",
"object"
] | [
"\"\"\"\n\t\tremove duplicates (regarding the text field) from a scoreDocs object\n\t\t:param hits: the scoreDocs object resulting from a query\n\t\t:return: the scoreDocs object without duplicates\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "hits",
"type": null
}
] | {
"returns": [
{
"docstring": "the scoreDocs object without duplicates",
"docstring_tokens": [
"the",
"scoreDocs",
"object",
"without",
"duplicates"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"typ... |
695418e1c8494356d80261057597b95376d5d190 | clementbosc/iot-tweet-search-engine | query_lucene.py | [
"Apache-2.0"
] | Python | rerank_results | <not_specific> | def rerank_results(self, results, user_vector, user_gender, user_location, user_sentiment):
"""
reranks the results of a query by using the similarity between the user thematic vector and the vector from the tweets
:param results: the documents resulting from a query
:param user_vector: the thematic vector of a... |
reranks the results of a query by using the similarity between the user thematic vector and the vector from the tweets
:param results: the documents resulting from a query
:param user_vector: the thematic vector of a user
:param user_gender: the gender of a user
:param user_location: the location of a user
... | reranks the results of a query by using the similarity between the user thematic vector and the vector from the tweets | [
"reranks",
"the",
"results",
"of",
"a",
"query",
"by",
"using",
"the",
"similarity",
"between",
"the",
"user",
"thematic",
"vector",
"and",
"the",
"vector",
"from",
"the",
"tweets"
] | def rerank_results(self, results, user_vector, user_gender, user_location, user_sentiment):
reranked = []
user_vec = ProfileOneHotEncoder.add_info_to_vec(user_vector, user_gender, user_location,
user_sentiment).reshape(1, -1)
for i in range(len(results)):
doc_i... | [
"def",
"rerank_results",
"(",
"self",
",",
"results",
",",
"user_vector",
",",
"user_gender",
",",
"user_location",
",",
"user_sentiment",
")",
":",
"reranked",
"=",
"[",
"]",
"user_vec",
"=",
"ProfileOneHotEncoder",
".",
"add_info_to_vec",
"(",
"user_vector",
"... | reranks the results of a query by using the similarity between the user thematic vector and the vector from the tweets | [
"reranks",
"the",
"results",
"of",
"a",
"query",
"by",
"using",
"the",
"similarity",
"between",
"the",
"user",
"thematic",
"vector",
"and",
"the",
"vector",
"from",
"the",
"tweets"
] | [
"\"\"\"\n\t\treranks the results of a query by using the similarity between the user thematic vector and the vector from the tweets\n\t\t:param results: the documents resulting from a query\n\t\t:param user_vector: the thematic vector of a user\n\t\t:param user_gender: the gender of a user\n\t\t:param user_location... | [
{
"param": "self",
"type": null
},
{
"param": "results",
"type": null
},
{
"param": "user_vector",
"type": null
},
{
"param": "user_gender",
"type": null
},
{
"param": "user_location",
"type": null
},
{
"param": "user_sentiment",
"type": null
}
] | {
"returns": [
{
"docstring": "the reranked list of documents",
"docstring_tokens": [
"the",
"reranked",
"list",
"of",
"documents"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"d... |
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | clean_tweet | <not_specific> | def clean_tweet(self, tweet_text):
"""
Taking a raw tweet, return a cleaned list of tweets tokens
:param tweet_text:
:return: array of tokens words
"""
tweet = preprocessor.clean(tweet_text)
tokens = [word[1:] if word.startswith('#') else word for word in tweet.split(' ')]
tokens = self.replace_abbrev... |
Taking a raw tweet, return a cleaned list of tweets tokens
:param tweet_text:
:return: array of tokens words
| Taking a raw tweet, return a cleaned list of tweets tokens | [
"Taking",
"a",
"raw",
"tweet",
"return",
"a",
"cleaned",
"list",
"of",
"tweets",
"tokens"
] | def clean_tweet(self, tweet_text):
tweet = preprocessor.clean(tweet_text)
tokens = [word[1:] if word.startswith('#') else word for word in tweet.split(' ')]
tokens = self.replace_abbreviations(tokens)
tokens = self.remove_stopwords_spelling_mistakes(tokens)
tokens = gensim.utils.simple_preprocess(' '.join(tok... | [
"def",
"clean_tweet",
"(",
"self",
",",
"tweet_text",
")",
":",
"tweet",
"=",
"preprocessor",
".",
"clean",
"(",
"tweet_text",
")",
"tokens",
"=",
"[",
"word",
"[",
"1",
":",
"]",
"if",
"word",
".",
"startswith",
"(",
"'#'",
")",
"else",
"word",
"for... | Taking a raw tweet, return a cleaned list of tweets tokens | [
"Taking",
"a",
"raw",
"tweet",
"return",
"a",
"cleaned",
"list",
"of",
"tweets",
"tokens"
] | [
"\"\"\"\n\t\tTaking a raw tweet, return a cleaned list of tweets tokens\n\t\t:param tweet_text:\n\t\t:return: array of tokens words\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "tweet_text",
"type": null
}
] | {
"returns": [
{
"docstring": "array of tokens words",
"docstring_tokens": [
"array",
"of",
"tokens",
"words"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
"docst... |
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | replace_abbreviations | <not_specific> | def replace_abbreviations(self, tokens):
"""
Replace the abbreviations (OMG -> Oh My God) based on the dictionary in slang.txt
:param tokens: words of the tweet
:return: words with abbreviations replaced by their meaning
"""
self.load_abbreviations()
for i in range(len(tokens)):
tokens[i] = self.abbr... |
Replace the abbreviations (OMG -> Oh My God) based on the dictionary in slang.txt
:param tokens: words of the tweet
:return: words with abbreviations replaced by their meaning
| Replace the abbreviations (OMG -> Oh My God) based on the dictionary in slang.txt | [
"Replace",
"the",
"abbreviations",
"(",
"OMG",
"-",
">",
"Oh",
"My",
"God",
")",
"based",
"on",
"the",
"dictionary",
"in",
"slang",
".",
"txt"
] | def replace_abbreviations(self, tokens):
self.load_abbreviations()
for i in range(len(tokens)):
tokens[i] = self.abbreviations[tokens[i]] if tokens[i] in self.abbreviations else tokens[i]
return tokens | [
"def",
"replace_abbreviations",
"(",
"self",
",",
"tokens",
")",
":",
"self",
".",
"load_abbreviations",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"tokens",
")",
")",
":",
"tokens",
"[",
"i",
"]",
"=",
"self",
".",
"abbreviations",
"[",
"... | Replace the abbreviations (OMG -> Oh My God) based on the dictionary in slang.txt | [
"Replace",
"the",
"abbreviations",
"(",
"OMG",
"-",
">",
"Oh",
"My",
"God",
")",
"based",
"on",
"the",
"dictionary",
"in",
"slang",
".",
"txt"
] | [
"\"\"\"\n\t\tReplace the abbreviations (OMG -> Oh My God) based on the dictionary in slang.txt\n\t\t:param tokens: words of the tweet\n\t\t:return: words with abbreviations replaced by their meaning\n\t\t\"\"\""
] | [
{
"param": "self",
"type": null
},
{
"param": "tokens",
"type": null
}
] | {
"returns": [
{
"docstring": "words with abbreviations replaced by their meaning",
"docstring_tokens": [
"words",
"with",
"abbreviations",
"replaced",
"by",
"their",
"meaning"
],
"type": null
}
],
"raises": [],
"params": [
... |
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | remove_stopwords_spelling_mistakes | <not_specific> | def remove_stopwords_spelling_mistakes(self, tokens):
"""
Remove stopwords and corrects spelling mistakes
:param spell: Object to correct spelling mistakes
:param tokens: words of the tweet
:return: words cleaned and corrected
"""
# self.load_spell_check()
return list(filter(lambda token: token not in... |
Remove stopwords and corrects spelling mistakes
:param spell: Object to correct spelling mistakes
:param tokens: words of the tweet
:return: words cleaned and corrected
| Remove stopwords and corrects spelling mistakes | [
"Remove",
"stopwords",
"and",
"corrects",
"spelling",
"mistakes"
] | def remove_stopwords_spelling_mistakes(self, tokens):
return list(filter(lambda token: token not in nltk.corpus.stopwords.words('english'), tokens)) | [
"def",
"remove_stopwords_spelling_mistakes",
"(",
"self",
",",
"tokens",
")",
":",
"return",
"list",
"(",
"filter",
"(",
"lambda",
"token",
":",
"token",
"not",
"in",
"nltk",
".",
"corpus",
".",
"stopwords",
".",
"words",
"(",
"'english'",
")",
",",
"token... | Remove stopwords and corrects spelling mistakes | [
"Remove",
"stopwords",
"and",
"corrects",
"spelling",
"mistakes"
] | [
"\"\"\"\n\t\tRemove stopwords and corrects spelling mistakes\n\t\t:param spell: Object to correct spelling mistakes\n\t\t:param tokens: words of the tweet\n\t\t:return: words cleaned and corrected\n\t\t\"\"\"",
"# self.load_spell_check()"
] | [
{
"param": "self",
"type": null
},
{
"param": "tokens",
"type": null
}
] | {
"returns": [
{
"docstring": "words cleaned and corrected",
"docstring_tokens": [
"words",
"cleaned",
"and",
"corrected"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "self",
"type": null,
"docstring": null,
... |
3d49984e35cd982e10a8e5e461a1af5a7427d2c7 | clementbosc/iot-tweet-search-engine | parser.py | [
"Apache-2.0"
] | Python | parsing_vector_corpus_pandas | <not_specific> | def parsing_vector_corpus_pandas(corpus_path, separator='\t', categorize=False, vector_asarray=True):
"""
Parse the corpus and return a Pandas DataFrame
:param categorize: boolean to make the tweet and user ids start to 0
:param separator:
:param corpus_path: path of the corpus
:return: pandas.DataFrame
"... |
Parse the corpus and return a Pandas DataFrame
:param categorize: boolean to make the tweet and user ids start to 0
:param separator:
:param corpus_path: path of the corpus
:return: pandas.DataFrame
| Parse the corpus and return a Pandas DataFrame | [
"Parse",
"the",
"corpus",
"and",
"return",
"a",
"Pandas",
"DataFrame"
] | def parsing_vector_corpus_pandas(corpus_path, separator='\t', categorize=False, vector_asarray=True):
df = pd.read_csv(corpus_path, sep=separator, dtype={'User_ID': object})
df = df.dropna(subset=['User_ID'])
if categorize:
df['User_ID_u'] = df.User_ID.astype('category').cat.codes.values
df['TweetID_u']... | [
"def",
"parsing_vector_corpus_pandas",
"(",
"corpus_path",
",",
"separator",
"=",
"'\\t'",
",",
"categorize",
"=",
"False",
",",
"vector_asarray",
"=",
"True",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"corpus_path",
",",
"sep",
"=",
"separator",
",",... | Parse the corpus and return a Pandas DataFrame | [
"Parse",
"the",
"corpus",
"and",
"return",
"a",
"Pandas",
"DataFrame"
] | [
"\"\"\"\n\t\tParse the corpus and return a Pandas DataFrame\n\t\t:param categorize: boolean to make the tweet and user ids start to 0\n\t\t:param separator:\n\t\t:param corpus_path: path of the corpus\n\t\t:return: pandas.DataFrame\n\t\t\"\"\"",
"# , index_col=\"TweetID\"",
"# remove tweets without users",
"#... | [
{
"param": "corpus_path",
"type": null
},
{
"param": "separator",
"type": null
},
{
"param": "categorize",
"type": null
},
{
"param": "vector_asarray",
"type": null
}
] | {
"returns": [
{
"docstring": null,
"docstring_tokens": [
"None"
],
"type": null
}
],
"raises": [],
"params": [
{
"identifier": "corpus_path",
"type": null,
"docstring": "path of the corpus",
"docstring_tokens": [
"path",
"of",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.