Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
ApnsNotificationService.write_devices
(self)
Write all known devices to file.
Write all known devices to file.
def write_devices(self): """Write all known devices to file.""" with open(self.yaml_path, "w+") as out: for device in self.devices.values(): _write_device(out, device)
[ "def", "write_devices", "(", "self", ")", ":", "with", "open", "(", "self", ".", "yaml_path", ",", "\"w+\"", ")", "as", "out", ":", "for", "device", "in", "self", ".", "devices", ".", "values", "(", ")", ":", "_write_device", "(", "out", ",", "device...
[ 185, 4 ]
[ 189, 42 ]
python
en
['en', 'en', 'en']
True
ApnsNotificationService.register
(self, call)
Register a device to receive push messages.
Register a device to receive push messages.
def register(self, call): """Register a device to receive push messages.""" push_id = call.data.get(ATTR_PUSH_ID) device_name = call.data.get(ATTR_NAME) current_device = self.devices.get(push_id) current_tracking_id = ( None if current_device is None else current_dev...
[ "def", "register", "(", "self", ",", "call", ")", ":", "push_id", "=", "call", ".", "data", ".", "get", "(", "ATTR_PUSH_ID", ")", "device_name", "=", "call", ".", "data", ".", "get", "(", "ATTR_NAME", ")", "current_device", "=", "self", ".", "devices",...
[ 191, 4 ]
[ 213, 19 ]
python
en
['en', 'en', 'en']
True
ApnsNotificationService.send_message
(self, message=None, **kwargs)
Send push message to registered devices.
Send push message to registered devices.
def send_message(self, message=None, **kwargs): """Send push message to registered devices.""" apns = APNsClient( self.certificate, use_sandbox=self.sandbox, use_alternative_port=False ) device_state = kwargs.get(ATTR_TARGET) message_data = kwargs.get(ATTR_DATA) ...
[ "def", "send_message", "(", "self", ",", "message", "=", "None", ",", "*", "*", "kwargs", ")", ":", "apns", "=", "APNsClient", "(", "self", ".", "certificate", ",", "use_sandbox", "=", "self", ".", "sandbox", ",", "use_alternative_port", "=", "False", ")...
[ 215, 4 ]
[ 263, 19 ]
python
en
['en', 'en', 'en']
True
async_get_conditions
( hass: HomeAssistant, device_id: str )
List device conditions for Media player devices.
List device conditions for Media player devices.
async def async_get_conditions( hass: HomeAssistant, device_id: str ) -> List[Dict[str, str]]: """List device conditions for Media player devices.""" registry = await entity_registry.async_get_registry(hass) conditions = [] # Get all the integrations entities for this device for entry in entity...
[ "async", "def", "async_get_conditions", "(", "hass", ":", "HomeAssistant", ",", "device_id", ":", "str", ")", "->", "List", "[", "Dict", "[", "str", ",", "str", "]", "]", ":", "registry", "=", "await", "entity_registry", ".", "async_get_registry", "(", "ha...
[ 35, 0 ]
[ 94, 21 ]
python
en
['fr', 'en', 'en']
True
async_condition_from_config
( config: ConfigType, config_validation: bool )
Create a function to test a device condition.
Create a function to test a device condition.
def async_condition_from_config( config: ConfigType, config_validation: bool ) -> condition.ConditionCheckerType: """Create a function to test a device condition.""" if config_validation: config = CONDITION_SCHEMA(config) if config[CONF_TYPE] == "is_playing": state = STATE_PLAYING el...
[ "def", "async_condition_from_config", "(", "config", ":", "ConfigType", ",", "config_validation", ":", "bool", ")", "->", "condition", ".", "ConditionCheckerType", ":", "if", "config_validation", ":", "config", "=", "CONDITION_SCHEMA", "(", "config", ")", "if", "c...
[ 98, 0 ]
[ 119, 24 ]
python
en
['en', 'en', 'en']
True
test_form
(hass)
Test we get the form.
Test we get the form.
async def test_form(hass): """Test we get the form.""" await setup.async_setup_component(hass, "persistent_notification", {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] == "form" assert result["errors...
[ "async", "def", "test_form", "(", "hass", ")", ":", "await", "setup", ".", "async_setup_component", "(", "hass", ",", "\"persistent_notification\"", ",", "{", "}", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(...
[ 8, 0 ]
[ 36, 48 ]
python
en
['en', 'en', 'en']
True
test_form_cannot_connect
(hass)
Test we handle cannot connect error.
Test we handle cannot connect error.
async def test_form_cannot_connect(hass): """Test we handle cannot connect error.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) with patch( "homeassistant.components.epson.Projector.get_property", return_value=STA...
[ "async", "def", "test_form_cannot_connect", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_USER", "}", "...
[ 39, 0 ]
[ 55, 58 ]
python
en
['en', 'en', 'en']
True
test_import
(hass)
Test config.yaml import.
Test config.yaml import.
async def test_import(hass): """Test config.yaml import.""" with patch( "homeassistant.components.epson.Projector.get_property", return_value="04", ), patch("homeassistant.components.epson.async_setup", return_value=True), patch( "homeassistant.components.epson.async_setup_entry", ...
[ "async", "def", "test_import", "(", "hass", ")", ":", "with", "patch", "(", "\"homeassistant.components.epson.Projector.get_property\"", ",", "return_value", "=", "\"04\"", ",", ")", ",", "patch", "(", "\"homeassistant.components.epson.async_setup\"", ",", "return_value",...
[ 58, 0 ]
[ 74, 70 ]
python
da
['da', 'en', 'sw']
False
test_import_cannot_connect
(hass)
Test we handle cannot connect error with import.
Test we handle cannot connect error with import.
async def test_import_cannot_connect(hass): """Test we handle cannot connect error with import.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_IMPORT} ) with patch( "homeassistant.components.epson.Projector.get_property", ...
[ "async", "def", "test_import_cannot_connect", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "config_entries", ".", "SOURCE_IMPORT", "}",...
[ 77, 0 ]
[ 93, 58 ]
python
en
['en', 'en', 'en']
True
setup_component
(hass)
Set up Toon component.
Set up Toon component.
async def setup_component(hass): """Set up Toon component.""" await async_process_ha_core_config( hass, {"external_url": "https://example.com"}, ) with patch("os.path.isfile", return_value=False): assert await async_setup_component( hass, DOMAIN, ...
[ "async", "def", "setup_component", "(", "hass", ")", ":", "await", "async_process_ha_core_config", "(", "hass", ",", "{", "\"external_url\"", ":", "\"https://example.com\"", "}", ",", ")", "with", "patch", "(", "\"os.path.isfile\"", ",", "return_value", "=", "Fals...
[ 15, 0 ]
[ 28, 42 ]
python
en
['en', 'en', 'en']
True
test_abort_if_no_configuration
(hass)
Test abort if no app is configured.
Test abort if no app is configured.
async def test_abort_if_no_configuration(hass): """Test abort if no app is configured.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT assert result["reason"] == "missing_configuratio...
[ "async", "def", "test_abort_if_no_configuration", "(", "hass", ")", ":", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", "(", "DOMAIN", ",", "context", "=", "{", "\"source\"", ":", "SOURCE_USER", "}", ")", "assert", "re...
[ 31, 0 ]
[ 38, 54 ]
python
en
['en', 'nl', 'en']
True
test_full_flow_implementation
( hass, aiohttp_client, aioclient_mock, current_request )
Test registering an integration and finishing flow works.
Test registering an integration and finishing flow works.
async def test_full_flow_implementation( hass, aiohttp_client, aioclient_mock, current_request ): """Test registering an integration and finishing flow works.""" await setup_component(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) as...
[ "async", "def", "test_full_flow_implementation", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "await", "setup_component", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "...
[ 41, 0 ]
[ 96, 5 ]
python
en
['en', 'en', 'en']
True
test_no_agreements
(hass, aiohttp_client, aioclient_mock, current_request)
Test abort when there are no displays.
Test abort when there are no displays.
async def test_no_agreements(hass, aiohttp_client, aioclient_mock, current_request): """Test abort when there are no displays.""" await setup_component(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # pylint: disable=protected-access ...
[ "async", "def", "test_no_agreements", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "await", "setup_component", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init"...
[ 99, 0 ]
[ 128, 47 ]
python
en
['en', 'en', 'en']
True
test_multiple_agreements
( hass, aiohttp_client, aioclient_mock, current_request )
Test abort when there are no displays.
Test abort when there are no displays.
async def test_multiple_agreements( hass, aiohttp_client, aioclient_mock, current_request ): """Test abort when there are no displays.""" await setup_component(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # pylint: disable=protected...
[ "async", "def", "test_multiple_agreements", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "await", "setup_component", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async...
[ 131, 0 ]
[ 172, 51 ]
python
en
['en', 'en', 'en']
True
test_agreement_already_set_up
( hass, aiohttp_client, aioclient_mock, current_request )
Test showing display form again if display already exists.
Test showing display form again if display already exists.
async def test_agreement_already_set_up( hass, aiohttp_client, aioclient_mock, current_request ): """Test showing display form again if display already exists.""" await setup_component(hass) MockConfigEntry(domain=DOMAIN, unique_id=123).add_to_hass(hass) result = await hass.config_entries.flow.async...
[ "async", "def", "test_agreement_already_set_up", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "await", "setup_component", "(", "hass", ")", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "unique_id", "=", "123...
[ 175, 0 ]
[ 207, 56 ]
python
en
['en', 'en', 'en']
True
test_toon_abort
(hass, aiohttp_client, aioclient_mock, current_request)
Test we abort on Toon error.
Test we abort on Toon error.
async def test_toon_abort(hass, aiohttp_client, aioclient_mock, current_request): """Test we abort on Toon error.""" await setup_component(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) # pylint: disable=protected-access state = config...
[ "async", "def", "test_toon_abort", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "await", "setup_component", "(", "hass", ")", "result", "=", "await", "hass", ".", "config_entries", ".", "flow", ".", "async_init", ...
[ 210, 0 ]
[ 238, 54 ]
python
en
['en', 'de', 'en']
True
test_import
(hass)
Test if importing step works.
Test if importing step works.
async def test_import(hass): """Test if importing step works.""" await setup_component(hass) # Setting up the component without entries, should already have triggered # it. Hence, expect this to throw an already_in_progress. result = await hass.config_entries.flow.async_init( DOMAIN, contex...
[ "async", "def", "test_import", "(", "hass", ")", ":", "await", "setup_component", "(", "hass", ")", "# Setting up the component without entries, should already have triggered", "# it. Hence, expect this to throw an already_in_progress.", "result", "=", "await", "hass", ".", "co...
[ 241, 0 ]
[ 252, 52 ]
python
en
['nl', 'en', 'en']
True
test_import_migration
(hass, aiohttp_client, aioclient_mock, current_request)
Test if importing step with migration works.
Test if importing step with migration works.
async def test_import_migration(hass, aiohttp_client, aioclient_mock, current_request): """Test if importing step with migration works.""" old_entry = MockConfigEntry(domain=DOMAIN, unique_id=123, version=1) old_entry.add_to_hass(hass) await setup_component(hass) entries = hass.config_entries.asyn...
[ "async", "def", "test_import_migration", "(", "hass", ",", "aiohttp_client", ",", "aioclient_mock", ",", "current_request", ")", ":", "old_entry", "=", "MockConfigEntry", "(", "domain", "=", "DOMAIN", ",", "unique_id", "=", "123", ",", "version", "=", "1", ")"...
[ 255, 0 ]
[ 295, 34 ]
python
en
['en', 'en', 'en']
True
UserManager.create_superuser
(self, username, email, password)
Create and return a `User` with admin power
Create and return a `User` with admin power
def create_superuser(self, username, email, password): """ Create and return a `User` with admin power """ if password is None: raise TypeError('Admin users must have a password.') user = self.create_user(username, email, password) user.is_superuser = True ...
[ "def", "create_superuser", "(", "self", ",", "username", ",", "email", ",", "password", ")", ":", "if", "password", "is", "None", ":", "raise", "TypeError", "(", "'Admin users must have a password.'", ")", "user", "=", "self", ".", "create_user", "(", "usernam...
[ 23, 4 ]
[ 33, 19 ]
python
en
['en', 'error', 'th']
False
_base_gw_schema
(discovery_info)
Generate base schema for gateways.
Generate base schema for gateways.
def _base_gw_schema(discovery_info): """Generate base schema for gateways.""" base_gw_schema = {} if not discovery_info: base_gw_schema[vol.Required(CONF_HOST)] = str base_gw_schema[vol.Optional(CONF_PORT, default=DEFAULT_PORT)] = int base_gw_schema.update( { vol.Re...
[ "def", "_base_gw_schema", "(", "discovery_info", ")", ":", "base_gw_schema", "=", "{", "}", "if", "not", "discovery_info", ":", "base_gw_schema", "[", "vol", ".", "Required", "(", "CONF_HOST", ")", "]", "=", "str", "base_gw_schema", "[", "vol", ".", "Optiona...
[ 30, 0 ]
[ 47, 37 ]
python
de
['de', 'de', 'en']
True
validate_gw_input
(hass: core.HomeAssistant, data)
Validate whether the user input allows us to connect to the gateray. Data has the keys from _base_gw_schema() with values provided by the user.
Validate whether the user input allows us to connect to the gateray.
async def validate_gw_input(hass: core.HomeAssistant, data): """ Validate whether the user input allows us to connect to the gateray. Data has the keys from _base_gw_schema() with values provided by the user. """ websession = async_get_clientsession(hass, verify_ssl=False) api = Smile( ...
[ "async", "def", "validate_gw_input", "(", "hass", ":", "core", ".", "HomeAssistant", ",", "data", ")", ":", "websession", "=", "async_get_clientsession", "(", "hass", ",", "verify_ssl", "=", "False", ")", "api", "=", "Smile", "(", "host", "=", "data", "[",...
[ 50, 0 ]
[ 74, 14 ]
python
en
['en', 'error', 'th']
False
PlugwiseConfigFlow.__init__
(self)
Initialize the Plugwise config flow.
Initialize the Plugwise config flow.
def __init__(self): """Initialize the Plugwise config flow.""" self.discovery_info = {}
[ "def", "__init__", "(", "self", ")", ":", "self", ".", "discovery_info", "=", "{", "}" ]
[ 86, 4 ]
[ 88, 32 ]
python
en
['en', 'en', 'en']
True
PlugwiseConfigFlow.async_step_zeroconf
(self, discovery_info: DiscoveryInfoType)
Prepare configuration for a discovered Plugwise Smile.
Prepare configuration for a discovered Plugwise Smile.
async def async_step_zeroconf(self, discovery_info: DiscoveryInfoType): """Prepare configuration for a discovered Plugwise Smile.""" self.discovery_info = discovery_info _properties = self.discovery_info.get("properties") unique_id = self.discovery_info.get("hostname").split(".")[0] ...
[ "async", "def", "async_step_zeroconf", "(", "self", ",", "discovery_info", ":", "DiscoveryInfoType", ")", ":", "self", ".", "discovery_info", "=", "discovery_info", "_properties", "=", "self", ".", "discovery_info", ".", "get", "(", "\"properties\"", ")", "unique_...
[ 90, 4 ]
[ 109, 43 ]
python
en
['en', 'en', 'en']
True
PlugwiseConfigFlow.async_step_user_gateway
(self, user_input=None)
Handle the initial step for gateways.
Handle the initial step for gateways.
async def async_step_user_gateway(self, user_input=None): """Handle the initial step for gateways.""" errors = {} if user_input is not None: if self.discovery_info: user_input[CONF_HOST] = self.discovery_info[CONF_HOST] user_input[CONF_PORT] = self.d...
[ "async", "def", "async_step_user_gateway", "(", "self", ",", "user_input", "=", "None", ")", ":", "errors", "=", "{", "}", "if", "user_input", "is", "not", "None", ":", "if", "self", ".", "discovery_info", ":", "user_input", "[", "CONF_HOST", "]", "=", "...
[ 111, 4 ]
[ 147, 9 ]
python
en
['en', 'en', 'en']
True
PlugwiseConfigFlow.async_step_user
(self, user_input=None)
Handle the initial step.
Handle the initial step.
async def async_step_user(self, user_input=None): """Handle the initial step.""" # PLACEHOLDER USB vs Gateway Logic return await self.async_step_user_gateway()
[ "async", "def", "async_step_user", "(", "self", ",", "user_input", "=", "None", ")", ":", "# PLACEHOLDER USB vs Gateway Logic", "return", "await", "self", ".", "async_step_user_gateway", "(", ")" ]
[ 151, 4 ]
[ 155, 51 ]
python
en
['en', 'en', 'en']
True
PlugwiseConfigFlow.async_get_options_flow
(config_entry)
Get the options flow for this handler.
Get the options flow for this handler.
def async_get_options_flow(config_entry): """Get the options flow for this handler.""" return PlugwiseOptionsFlowHandler(config_entry)
[ "def", "async_get_options_flow", "(", "config_entry", ")", ":", "return", "PlugwiseOptionsFlowHandler", "(", "config_entry", ")" ]
[ 159, 4 ]
[ 161, 55 ]
python
en
['en', 'en', 'en']
True
PlugwiseOptionsFlowHandler.__init__
(self, config_entry)
Initialize options flow.
Initialize options flow.
def __init__(self, config_entry): """Initialize options flow.""" self.config_entry = config_entry
[ "def", "__init__", "(", "self", ",", "config_entry", ")", ":", "self", ".", "config_entry", "=", "config_entry" ]
[ 167, 4 ]
[ 169, 40 ]
python
en
['en', 'en', 'en']
True
PlugwiseOptionsFlowHandler.async_step_init
(self, user_input=None)
Manage the Plugwise options.
Manage the Plugwise options.
async def async_step_init(self, user_input=None): """Manage the Plugwise options.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) api = self.hass.data[DOMAIN][self.config_entry.entry_id]["api"] interval = DEFAULT_SCAN_INTERVAL[api.smil...
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", "=", "None", ")", ":", "if", "user_input", "is", "not", "None", ":", "return", "self", ".", "async_create_entry", "(", "title", "=", "\"\"", ",", "data", "=", "user_input", ")", "api", "=...
[ 171, 4 ]
[ 185, 81 ]
python
en
['en', 'en', 'en']
True
PrepareData.__init__
(self, path_data=None, data_format=constants.DataFormat.NUMPY, D=None, N=None, classification=True, ordinal=False, balanced=True, preprocess=None, n_to_estimate=None, ...
Dataset class with helpful features and functions for being included in a dataloader and managing memory usage. can read following formats: svm: svm light format (sklearn.datasets.load_svmlight_file) numpy: Pass X and y as numpy or sparse arrays assu...
Dataset class with helpful features and functions for being included in a dataloader and managing memory usage. can read following formats: svm: svm light format (sklearn.datasets.load_svmlight_file) numpy: Pass X and y as numpy or sparse arrays
def __init__(self, path_data=None, data_format=constants.DataFormat.NUMPY, D=None, N=None, classification=True, ordinal=False, balanced=True, preprocess=None, n_to_estimate=None, ...
[ "def", "__init__", "(", "self", ",", "path_data", "=", "None", ",", "data_format", "=", "constants", ".", "DataFormat", ".", "NUMPY", ",", "D", "=", "None", ",", "N", "=", "None", ",", "classification", "=", "True", ",", "ordinal", "=", "False", ",", ...
[ 47, 4 ]
[ 233, 37 ]
python
en
['en', 'error', 'th']
False
PrepareData.save_data_stats
(self, path_data_stats)
Dumps dataset statistics to pickle file.
Dumps dataset statistics to pickle file.
def save_data_stats(self, path_data_stats): """ Dumps dataset statistics to pickle file. """ data_stats = { 'Xmn': self.Xmn, 'sv1': self.sv1, 'Xsd': self.Xsd, 'ymn': self.ymn, 'ysd': self.ysd, 'ix_statistics': self....
[ "def", "save_data_stats", "(", "self", ",", "path_data_stats", ")", ":", "data_stats", "=", "{", "'Xmn'", ":", "self", ".", "Xmn", ",", "'sv1'", ":", "self", ".", "sv1", ",", "'Xsd'", ":", "self", ".", "Xsd", ",", "'ymn'", ":", "self", ".", "ymn", ...
[ 255, 4 ]
[ 268, 60 ]
python
en
['en', 'error', 'th']
False
PrepareData.reset
(self)
Resets the dataloader. Only implemented for disk StorageLevel.
Resets the dataloader. Only implemented for disk StorageLevel.
def reset(self): """ Resets the dataloader. Only implemented for disk StorageLevel. """ if self.storage_level == constants.StorageLevel.DENSE: pass elif self.storage_level == constants.StorageLevel.SPARSE: pass elif self.storage_level == constants...
[ "def", "reset", "(", "self", ")", ":", "if", "self", ".", "storage_level", "==", "constants", ".", "StorageLevel", ".", "DENSE", ":", "pass", "elif", "self", ".", "storage_level", "==", "constants", ".", "StorageLevel", ".", "SPARSE", ":", "pass", "elif", ...
[ 287, 4 ]
[ 300, 41 ]
python
en
['en', 'error', 'th']
False
PrepareData.sparse_std
(X, X_mean)
Calculate the column wise standard deviations of a sparse matrix.
Calculate the column wise standard deviations of a sparse matrix.
def sparse_std(X, X_mean): """ Calculate the column wise standard deviations of a sparse matrix. """ X_copy = X.copy() X_copy.data **= 2 # square non zero elements E_x_squared = np.array(X_copy.mean(axis=0)).ravel() Xsd = np.sqrt(E_x_squared - X_mean**2) ...
[ "def", "sparse_std", "(", "X", ",", "X_mean", ")", ":", "X_copy", "=", "X", ".", "copy", "(", ")", "X_copy", ".", "data", "**=", "2", "# square non zero elements", "E_x_squared", "=", "np", ".", "array", "(", "X_copy", ".", "mean", "(", "axis", "=", ...
[ 389, 4 ]
[ 397, 18 ]
python
en
['en', 'error', 'th']
False
PrepareData.compute_data_stats
(self)
1. computes/estimates feature means 2. if preprocess == 'zscore', computes/estimates feature standard devs 3. if not classification, computes/estimates target mean/standard dev 4. estimates largest singular value of data matrix
1. computes/estimates feature means 2. if preprocess == 'zscore', computes/estimates feature standard devs 3. if not classification, computes/estimates target mean/standard dev 4. estimates largest singular value of data matrix
def compute_data_stats(self): """ 1. computes/estimates feature means 2. if preprocess == 'zscore', computes/estimates feature standard devs 3. if not classification, computes/estimates target mean/standard dev 4. estimates largest singular value of data matrix """ ...
[ "def", "compute_data_stats", "(", "self", ")", ":", "t", "=", "time", ".", "time", "(", ")", "X", ",", "y", "=", "self", ".", "X", "[", "self", ".", "ix_statistics", "]", ",", "self", ".", "y", "[", "self", ".", "ix_statistics", "]", "preprocess", ...
[ 399, 4 ]
[ 451, 38 ]
python
en
['en', 'error', 'th']
False
PrepareData.set_data_stats
(self, Xmn, sv1, Xsd=1., ymn=0., ysd=1.)
Saves dataset stats to self to be used for preprocessing.
Saves dataset stats to self to be used for preprocessing.
def set_data_stats(self, Xmn, sv1, Xsd=1., ymn=0., ysd=1.): """ Saves dataset stats to self to be used for preprocessing. """ self.Xmn = torch.as_tensor( Xmn, dtype=torch.get_default_dtype()).to(self.device) self.sv1 = torch.as_tensor( sv1, dtype=torch.ge...
[ "def", "set_data_stats", "(", "self", ",", "Xmn", ",", "sv1", ",", "Xsd", "=", "1.", ",", "ymn", "=", "0.", ",", "ysd", "=", "1.", ")", ":", "self", ".", "Xmn", "=", "torch", ".", "as_tensor", "(", "Xmn", ",", "dtype", "=", "torch", ".", "get_d...
[ 454, 4 ]
[ 468, 65 ]
python
en
['en', 'error', 'th']
False
PrepareData.apply_preprocess
(self, X, y)
Faster on gpu device, while dataloading takes up a large portion of the time.
Faster on gpu device, while dataloading takes up a large portion of the time.
def apply_preprocess(self, X, y): """ Faster on gpu device, while dataloading takes up a large portion of the time. """ with torch.no_grad(): if not self.classification: y = (y.reshape((-1, 1)) - self.ymn) / self.ysd else: y = y.re...
[ "def", "apply_preprocess", "(", "self", ",", "X", ",", "y", ")", ":", "with", "torch", ".", "no_grad", "(", ")", ":", "if", "not", "self", ".", "classification", ":", "y", "=", "(", "y", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", ...
[ 471, 4 ]
[ 486, 23 ]
python
en
['en', 'error', 'th']
False
PrepareData.max_batch_size
(self)
Return the maximum batchsize for the dataset.
Return the maximum batchsize for the dataset.
def max_batch_size(self): """ Return the maximum batchsize for the dataset. """ return int(np.min([self.max_rows, self.N]))
[ "def", "max_batch_size", "(", "self", ")", ":", "return", "int", "(", "np", ".", "min", "(", "[", "self", ".", "max_rows", ",", "self", ".", "N", "]", ")", ")" ]
[ 489, 4 ]
[ 494, 51 ]
python
en
['en', 'error', 'th']
False
load_vocab
(vocab_file)
Loads a vocabulary file into a dictionary.
Loads a vocabulary file into a dictionary.
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = collections.OrderedDict() with open(vocab_file, "r", encoding="utf-8") as reader: tokens = reader.readlines() for index, token in enumerate(tokens): token = token.rstrip("\n") vocab[token] = inde...
[ "def", "load_vocab", "(", "vocab_file", ")", ":", "vocab", "=", "collections", ".", "OrderedDict", "(", ")", "with", "open", "(", "vocab_file", ",", "\"r\"", ",", "encoding", "=", "\"utf-8\"", ")", "as", "reader", ":", "tokens", "=", "reader", ".", "read...
[ 127, 0 ]
[ 135, 16 ]
python
en
['en', 'en', 'en']
True
whitespace_tokenize
(text)
Runs basic whitespace cleaning and splitting on a piece of text.
Runs basic whitespace cleaning and splitting on a piece of text.
def whitespace_tokenize(text): """Runs basic whitespace cleaning and splitting on a piece of text.""" text = text.strip() if not text: return [] tokens = text.split() return tokens
[ "def", "whitespace_tokenize", "(", "text", ")", ":", "text", "=", "text", ".", "strip", "(", ")", "if", "not", "text", ":", "return", "[", "]", "tokens", "=", "text", ".", "split", "(", ")", "return", "tokens" ]
[ 138, 0 ]
[ 144, 17 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._convert_token_to_id
(self, token)
Converts a token (str) in an id using the vocab.
Converts a token (str) in an id using the vocab.
def _convert_token_to_id(self, token): """ Converts a token (str) in an id using the vocab. """ return self.vocab.get(token, self.vocab.get(self.unk_token))
[ "def", "_convert_token_to_id", "(", "self", ",", "token", ")", ":", "return", "self", ".", "vocab", ".", "get", "(", "token", ",", "self", ".", "vocab", ".", "get", "(", "self", ".", "unk_token", ")", ")" ]
[ 375, 4 ]
[ 377, 68 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._convert_id_to_token
(self, index)
Converts an index (integer) in a token (str) using the vocab.
Converts an index (integer) in a token (str) using the vocab.
def _convert_id_to_token(self, index): """Converts an index (integer) in a token (str) using the vocab.""" return self.ids_to_tokens.get(index, self.unk_token)
[ "def", "_convert_id_to_token", "(", "self", ",", "index", ")", ":", "return", "self", ".", "ids_to_tokens", ".", "get", "(", "index", ",", "self", ".", "unk_token", ")" ]
[ 379, 4 ]
[ 381, 60 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer.convert_tokens_to_string
(self, tokens)
Converts a sequence of tokens (string) in a single string.
Converts a sequence of tokens (string) in a single string.
def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. """ out_string = " ".join(tokens).replace(" ##", "").strip() return out_string
[ "def", "convert_tokens_to_string", "(", "self", ",", "tokens", ")", ":", "out_string", "=", "\" \"", ".", "join", "(", "tokens", ")", ".", "replace", "(", "\" ##\"", ",", "\"\"", ")", ".", "strip", "(", ")", "return", "out_string" ]
[ 383, 4 ]
[ 386, 25 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer.create_attention_mask_from_sequences
(self, query_ids: List[int], table_values: List[TableValue])
Creates the attention mask according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs corresponding to the ID. table_values (:obj:`List[TableValue]`): lift of table values, which are named tuples containing the ...
Creates the attention mask according to the query token IDs and a list of table values.
def create_attention_mask_from_sequences(self, query_ids: List[int], table_values: List[TableValue]) -> List[int]: """ Creates the attention mask according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs corresponding to the I...
[ "def", "create_attention_mask_from_sequences", "(", "self", ",", "query_ids", ":", "List", "[", "int", "]", ",", "table_values", ":", "List", "[", "TableValue", "]", ")", "->", "List", "[", "int", "]", ":", "return", "[", "1", "]", "*", "(", "1", "+", ...
[ 408, 4 ]
[ 420, 65 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.create_segment_token_type_ids_from_sequences
( self, query_ids: List[int], table_values: List[TableValue] )
Creates the segment token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs corresponding to the ID. table_values (:obj:`List[TableValue]`): lift of table values, which are named tuples containing the ...
Creates the segment token type IDs according to the query token IDs and a list of table values.
def create_segment_token_type_ids_from_sequences( self, query_ids: List[int], table_values: List[TableValue] ) -> List[int]: """ Creates the segment token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of to...
[ "def", "create_segment_token_type_ids_from_sequences", "(", "self", ",", "query_ids", ":", "List", "[", "int", "]", ",", "table_values", ":", "List", "[", "TableValue", "]", ")", "->", "List", "[", "int", "]", ":", "table_ids", "=", "list", "(", "zip", "("...
[ 422, 4 ]
[ 437, 68 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.create_column_token_type_ids_from_sequences
( self, query_ids: List[int], table_values: List[TableValue] )
Creates the column token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs corresponding to the ID. table_values (:obj:`List[TableValue]`): lift of table values, which are named tuples containing the ...
Creates the column token type IDs according to the query token IDs and a list of table values.
def create_column_token_type_ids_from_sequences( self, query_ids: List[int], table_values: List[TableValue] ) -> List[int]: """ Creates the column token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of toke...
[ "def", "create_column_token_type_ids_from_sequences", "(", "self", ",", "query_ids", ":", "List", "[", "int", "]", ",", "table_values", ":", "List", "[", "TableValue", "]", ")", "->", "List", "[", "int", "]", ":", "table_column_ids", "=", "list", "(", "zip",...
[ 439, 4 ]
[ 454, 70 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.create_row_token_type_ids_from_sequences
( self, query_ids: List[int], table_values: List[TableValue] )
Creates the row token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs corresponding to the ID. table_values (:obj:`List[TableValue]`): lift of table values, which are named tuples containing the ...
Creates the row token type IDs according to the query token IDs and a list of table values.
def create_row_token_type_ids_from_sequences( self, query_ids: List[int], table_values: List[TableValue] ) -> List[int]: """ Creates the row token type IDs according to the query token IDs and a list of table values. Args: query_ids (:obj:`List[int]`): list of token IDs ...
[ "def", "create_row_token_type_ids_from_sequences", "(", "self", ",", "query_ids", ":", "List", "[", "int", "]", ",", "table_values", ":", "List", "[", "TableValue", "]", ")", "->", "List", "[", "int", "]", ":", "table_row_ids", "=", "list", "(", "zip", "("...
[ 456, 4 ]
[ 471, 67 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.build_inputs_with_special_tokens
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None )
Build model inputs from a question and flattened table for question answering or sequence classification tasks by concatenating and adding special tokens. Args: token_ids_0 (:obj:`List[int]`): The ids of the question. token_ids_1 (:obj:`List[int]`, `optional`): The ids ...
Build model inputs from a question and flattened table for question answering or sequence classification tasks by concatenating and adding special tokens.
def build_inputs_with_special_tokens( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None ) -> List[int]: """ Build model inputs from a question and flattened table for question answering or sequence classification tasks by concatenating and adding special tokens. ...
[ "def", "build_inputs_with_special_tokens", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ")", "->", "List", "[", "int", "]", ":", "if", "token_ids_1", ...
[ 473, 4 ]
[ 490, 84 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.get_special_tokens_mask
( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False )
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method. Args: token_ids_0 (:obj:`List[int]`): List of question IDs. token_ids_1 (:obj:`Li...
Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` method.
def get_special_tokens_mask( self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False ) -> List[int]: """ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding special tokens ...
[ "def", "get_special_tokens_mask", "(", "self", ",", "token_ids_0", ":", "List", "[", "int", "]", ",", "token_ids_1", ":", "Optional", "[", "List", "[", "int", "]", "]", "=", "None", ",", "already_has_special_tokens", ":", "bool", "=", "False", ")", "->", ...
[ 492, 4 ]
[ 521, 51 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.__call__
( self, table: "pd.DataFrame", queries: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, List[TextInput], List[PreTokenizedInput], List[EncodedInput], ] ] =...
Main method to tokenize and prepare for the model one or several sequence(s) related to a table. Args: table (:obj:`pd.DataFrame`): Table containing tabular data. Note that all cell values must be text. Use `.astype(str)` on a Pandas dataframe to convert it ...
Main method to tokenize and prepare for the model one or several sequence(s) related to a table.
def __call__( self, table: "pd.DataFrame", queries: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, List[TextInput], List[PreTokenizedInput], List[EncodedInput], ]...
[ "def", "__call__", "(", "self", ",", "table", ":", "\"pd.DataFrame\"", ",", "queries", ":", "Optional", "[", "Union", "[", "TextInput", ",", "PreTokenizedInput", ",", "EncodedInput", ",", "List", "[", "TextInput", "]", ",", "List", "[", "PreTokenizedInput", ...
[ 524, 4 ]
[ 637, 13 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.batch_encode_plus
( self, table: "pd.DataFrame", queries: Optional[ Union[ List[TextInput], List[PreTokenizedInput], List[EncodedInput], ] ] = None, answer_coordinates: Optional[List[List[Tuple]]] = None, answer_text: ...
Prepare a table and a list of strings for the model. .. warning:: This method is deprecated, ``__call__`` should be used instead. Args: table (:obj:`pd.DataFrame`): Table containing tabular data. Note that all cell values must be text. Use `.astype(str)...
Prepare a table and a list of strings for the model.
def batch_encode_plus( self, table: "pd.DataFrame", queries: Optional[ Union[ List[TextInput], List[PreTokenizedInput], List[EncodedInput], ] ] = None, answer_coordinates: Optional[List[List[Tuple]]] = None, ...
[ "def", "batch_encode_plus", "(", "self", ",", "table", ":", "\"pd.DataFrame\"", ",", "queries", ":", "Optional", "[", "Union", "[", "List", "[", "TextInput", "]", ",", "List", "[", "PreTokenizedInput", "]", ",", "List", "[", "EncodedInput", "]", ",", "]", ...
[ 640, 4 ]
[ 731, 9 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.encode
( self, table: "pd.DataFrame", query: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, ] ] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = False, ...
Prepare a table and a string for the model. This method does not return token type IDs, attention masks, etc. which are necessary for the model to work correctly. Use that method if you want to build your processing on your own, otherwise refer to ``__call__``. Args: table ...
Prepare a table and a string for the model. This method does not return token type IDs, attention masks, etc. which are necessary for the model to work correctly. Use that method if you want to build your processing on your own, otherwise refer to ``__call__``.
def encode( self, table: "pd.DataFrame", query: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, ] ] = None, add_special_tokens: bool = True, padding: Union[bool, str, PaddingStrategy] = F...
[ "def", "encode", "(", "self", ",", "table", ":", "\"pd.DataFrame\"", ",", "query", ":", "Optional", "[", "Union", "[", "TextInput", ",", "PreTokenizedInput", ",", "EncodedInput", ",", "]", "]", "=", "None", ",", "add_special_tokens", ":", "bool", "=", "Tru...
[ 861, 4 ]
[ 901, 42 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.encode_plus
( self, table: "pd.DataFrame", query: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, ] ] = None, answer_coordinates: Optional[List[Tuple]] = None, answer_text: Optional[List[TextInput]] ...
Prepare a table and a string for the model. Args: table (:obj:`pd.DataFrame`): Table containing tabular data. Note that all cell values must be text. Use `.astype(str)` on a Pandas dataframe to convert it to string. query (:obj:`str` or :obj:`Lis...
Prepare a table and a string for the model.
def encode_plus( self, table: "pd.DataFrame", query: Optional[ Union[ TextInput, PreTokenizedInput, EncodedInput, ] ] = None, answer_coordinates: Optional[List[Tuple]] = None, answer_text: Optional[Li...
[ "def", "encode_plus", "(", "self", ",", "table", ":", "\"pd.DataFrame\"", ",", "query", ":", "Optional", "[", "Union", "[", "TextInput", ",", "PreTokenizedInput", ",", "EncodedInput", ",", "]", "]", "=", "None", ",", "answer_coordinates", ":", "Optional", "[...
[ 904, 4 ]
[ 985, 9 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer.prepare_for_model
( self, raw_table: "pd.DataFrame", raw_query: Union[ TextInput, PreTokenizedInput, EncodedInput, ], tokenized_table: Optional[TokenizedTable] = None, query_tokens: Optional[TokenizedTable] = None, answer_coordinates: Optional[Li...
Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens. Args: raw_table (:obj:`pd.DataFrame`): The original table before any transformation (like to...
Prepares a sequence of input id so that it can be used by the model. It adds special tokens, truncates sequences if overflowing while taking into account the special tokens.
def prepare_for_model( self, raw_table: "pd.DataFrame", raw_query: Union[ TextInput, PreTokenizedInput, EncodedInput, ], tokenized_table: Optional[TokenizedTable] = None, query_tokens: Optional[TokenizedTable] = None, answer_coo...
[ "def", "prepare_for_model", "(", "self", ",", "raw_table", ":", "\"pd.DataFrame\"", ",", "raw_query", ":", "Union", "[", "TextInput", ",", "PreTokenizedInput", ",", "EncodedInput", ",", "]", ",", "tokenized_table", ":", "Optional", "[", "TokenizedTable", "]", "=...
[ 1043, 4 ]
[ 1233, 28 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_truncated_table_rows
( self, query_tokens: List[str], tokenized_table: TokenizedTable, num_rows: int, num_columns: int, max_length: int, truncation_strategy: Union[str, TapasTruncationStrategy], )
Truncates a sequence pair in-place following the strategy. Args: query_tokens (:obj:`List[str]`): List of strings corresponding to the tokenized query. tokenized_table (:obj:`TokenizedTable`): Tokenized table num_rows (:obj:`int`): ...
Truncates a sequence pair in-place following the strategy.
def _get_truncated_table_rows( self, query_tokens: List[str], tokenized_table: TokenizedTable, num_rows: int, num_columns: int, max_length: int, truncation_strategy: Union[str, TapasTruncationStrategy], ) -> Tuple[int, int]: """ Truncates a seq...
[ "def", "_get_truncated_table_rows", "(", "self", ",", "query_tokens", ":", "List", "[", "str", "]", ",", "tokenized_table", ":", "TokenizedTable", ",", "num_rows", ":", "int", ",", "num_columns", ":", "int", ",", "max_length", ":", "int", ",", "truncation_stra...
[ 1235, 4 ]
[ 1290, 40 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._tokenize_table
( self, table=None, )
Tokenizes column headers and cell texts of a table. Args: table (:obj:`pd.Dataframe`): Table. Returns: :obj:`TokenizedTable`: TokenizedTable object.
Tokenizes column headers and cell texts of a table.
def _tokenize_table( self, table=None, ): """ Tokenizes column headers and cell texts of a table. Args: table (:obj:`pd.Dataframe`): Table. Returns: :obj:`TokenizedTable`: TokenizedTable object. """ tokenized_rows = [] toke...
[ "def", "_tokenize_table", "(", "self", ",", "table", "=", "None", ",", ")", ":", "tokenized_rows", "=", "[", "]", "tokenized_row", "=", "[", "]", "# tokenize column headers", "for", "column", "in", "table", ":", "if", "self", ".", "strip_column_names", ":", ...
[ 1292, 4 ]
[ 1335, 9 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_token_budget
(self, question_tokens, max_length=None)
Computes the number of tokens left for the table after tokenizing a question, taking into account the max sequence length of the model. Args: question_tokens (:obj:`List[String]`): List of question tokens. Returns: :obj:`int`: the number of tokens left for the table...
Computes the number of tokens left for the table after tokenizing a question, taking into account the max sequence length of the model.
def _get_token_budget(self, question_tokens, max_length=None): """ Computes the number of tokens left for the table after tokenizing a question, taking into account the max sequence length of the model. Args: question_tokens (:obj:`List[String]`): List of que...
[ "def", "_get_token_budget", "(", "self", ",", "question_tokens", ",", "max_length", "=", "None", ")", ":", "return", "(", "max_length", "if", "max_length", "is", "not", "None", "else", "self", ".", "model_max_length", ")", "-", "self", ".", "_question_encoding...
[ 1341, 4 ]
[ 1353, 9 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_table_values
(self, table, num_columns, num_rows, num_tokens)
Iterates over partial table and returns token, column and row indexes.
Iterates over partial table and returns token, column and row indexes.
def _get_table_values(self, table, num_columns, num_rows, num_tokens) -> Generator[TableValue, None, None]: """Iterates over partial table and returns token, column and row indexes.""" for tc in table.selected_tokens: # First row is header row. if tc.row_index >= num_rows + 1: ...
[ "def", "_get_table_values", "(", "self", ",", "table", ",", "num_columns", ",", "num_rows", ",", "num_tokens", ")", "->", "Generator", "[", "TableValue", ",", "None", ",", "None", "]", ":", "for", "tc", "in", "table", ".", "selected_tokens", ":", "# First ...
[ 1355, 4 ]
[ 1372, 70 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_table_boundaries
(self, table)
Return maximal number of rows, columns and tokens.
Return maximal number of rows, columns and tokens.
def _get_table_boundaries(self, table): """Return maximal number of rows, columns and tokens.""" max_num_tokens = 0 max_num_columns = 0 max_num_rows = 0 for tc in table.selected_tokens: max_num_columns = max(max_num_columns, tc.column_index + 1) max_num_ro...
[ "def", "_get_table_boundaries", "(", "self", ",", "table", ")", ":", "max_num_tokens", "=", "0", "max_num_columns", "=", "0", "max_num_rows", "=", "0", "for", "tc", "in", "table", ".", "selected_tokens", ":", "max_num_columns", "=", "max", "(", "max_num_column...
[ 1374, 4 ]
[ 1385, 60 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_max_num_tokens
(self, question_tokens, tokenized_table, num_columns, num_rows, max_length)
Computes max number of tokens that can be squeezed into the budget.
Computes max number of tokens that can be squeezed into the budget.
def _get_max_num_tokens(self, question_tokens, tokenized_table, num_columns, num_rows, max_length): """Computes max number of tokens that can be squeezed into the budget.""" token_budget = self._get_token_budget(question_tokens, max_length) _, _, max_num_tokens = self._get_table_boundaries(token...
[ "def", "_get_max_num_tokens", "(", "self", ",", "question_tokens", ",", "tokenized_table", ",", "num_columns", ",", "num_rows", ",", "max_length", ")", ":", "token_budget", "=", "self", ".", "_get_token_budget", "(", "question_tokens", ",", "max_length", ")", "_",...
[ 1390, 4 ]
[ 1407, 25 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._serialize_text
(self, question_tokens)
Serializes texts in index arrays.
Serializes texts in index arrays.
def _serialize_text(self, question_tokens): """Serializes texts in index arrays.""" tokens = [] segment_ids = [] column_ids = [] row_ids = [] # add [CLS] token at the beginning tokens.append(self.cls_token) segment_ids.append(0) column_ids.append(...
[ "def", "_serialize_text", "(", "self", ",", "question_tokens", ")", ":", "tokens", "=", "[", "]", "segment_ids", "=", "[", "]", "column_ids", "=", "[", "]", "row_ids", "=", "[", "]", "# add [CLS] token at the beginning", "tokens", ".", "append", "(", "self",...
[ 1424, 4 ]
[ 1443, 55 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._serialize
( self, question_tokens, table, num_columns, num_rows, num_tokens, )
Serializes table and text.
Serializes table and text.
def _serialize( self, question_tokens, table, num_columns, num_rows, num_tokens, ): """Serializes table and text.""" tokens, segment_ids, column_ids, row_ids = self._serialize_text(question_tokens) # add [SEP] token between question and table ...
[ "def", "_serialize", "(", "self", ",", "question_tokens", ",", "table", ",", "num_columns", ",", "num_rows", ",", "num_tokens", ",", ")", ":", "tokens", ",", "segment_ids", ",", "column_ids", ",", "row_ids", "=", "self", ".", "_serialize_text", "(", "questio...
[ 1445, 4 ]
[ 1473, 9 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_numeric_column_ranks
(self, column_ids, row_ids, table)
Returns column ranks for all numeric columns.
Returns column ranks for all numeric columns.
def _get_numeric_column_ranks(self, column_ids, row_ids, table): """Returns column ranks for all numeric columns.""" ranks = [0] * len(column_ids) inv_ranks = [0] * len(column_ids) # original code from tf_example_utils.py of the original implementation if table is not None: ...
[ "def", "_get_numeric_column_ranks", "(", "self", ",", "column_ids", ",", "row_ids", ",", "table", ")", ":", "ranks", "=", "[", "0", "]", "*", "len", "(", "column_ids", ")", "inv_ranks", "=", "[", "0", "]", "*", "len", "(", "column_ids", ")", "# origina...
[ 1488, 4 ]
[ 1521, 31 ]
python
en
['en', 'no', 'en']
True
TapasTokenizer._get_numeric_sort_key_fn
(self, table_numeric_values, value)
Returns the sort key function for comparing value to table values. The function returned will be a suitable input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details Args: table_numeric_values: Numeric values of a column val...
Returns the sort key function for comparing value to table values. The function returned will be a suitable input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details
def _get_numeric_sort_key_fn(self, table_numeric_values, value): """ Returns the sort key function for comparing value to table values. The function returned will be a suitable input for the key param of the sort(). See number_annotation_utils._get_numeric_sort_key_fn for details Args: ...
[ "def", "_get_numeric_sort_key_fn", "(", "self", ",", "table_numeric_values", ",", "value", ")", ":", "if", "not", "table_numeric_values", ":", "return", "None", "all_values", "=", "list", "(", "table_numeric_values", ".", "values", "(", ")", ")", "all_values", "...
[ 1523, 4 ]
[ 1542, 23 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_numeric_relations
(self, question, column_ids, row_ids, table)
Returns numeric relations embeddings Args: question: Question object. column_ids: Maps word piece position to column id. row_ids: Maps word piece position to row id. table: The table containing the numeric cell values.
Returns numeric relations embeddings
def _get_numeric_relations(self, question, column_ids, row_ids, table): """ Returns numeric relations embeddings Args: question: Question object. column_ids: Maps word piece position to column id. row_ids: Maps word piece position to row id. table...
[ "def", "_get_numeric_relations", "(", "self", ",", "question", ",", "column_ids", ",", "row_ids", ",", "table", ")", ":", "numeric_relations", "=", "[", "0", "]", "*", "len", "(", "column_ids", ")", "# first, we add any numeric value spans to the question:", "# Crea...
[ 1544, 4 ]
[ 1583, 32 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_numeric_values
(self, table, column_ids, row_ids)
Returns numeric values for computation of answer loss.
Returns numeric values for computation of answer loss.
def _get_numeric_values(self, table, column_ids, row_ids): """Returns numeric values for computation of answer loss.""" numeric_values = [float("nan")] * len(column_ids) if table is not None: num_rows = table.shape[0] num_columns = table.shape[1] for col_in...
[ "def", "_get_numeric_values", "(", "self", ",", "table", ",", "column_ids", ",", "row_ids", ")", ":", "numeric_values", "=", "[", "float", "(", "\"nan\"", ")", "]", "*", "len", "(", "column_ids", ")", "if", "table", "is", "not", "None", ":", "num_rows", ...
[ 1585, 4 ]
[ 1606, 29 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_numeric_values_scale
(self, table, column_ids, row_ids)
Returns a scale to each token to down weigh the value of long words.
Returns a scale to each token to down weigh the value of long words.
def _get_numeric_values_scale(self, table, column_ids, row_ids): """Returns a scale to each token to down weigh the value of long words.""" numeric_values_scale = [1.0] * len(column_ids) if table is None: return numeric_values_scale num_rows = table.shape[0] num_co...
[ "def", "_get_numeric_values_scale", "(", "self", ",", "table", ",", "column_ids", ",", "row_ids", ")", ":", "numeric_values_scale", "=", "[", "1.0", "]", "*", "len", "(", "column_ids", ")", "if", "table", "is", "None", ":", "return", "numeric_values_scale", ...
[ 1608, 4 ]
[ 1627, 35 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_all_answer_ids_from_coordinates
( self, column_ids, row_ids, answers_list, )
Maps lists of answer coordinates to token indexes.
Maps lists of answer coordinates to token indexes.
def _get_all_answer_ids_from_coordinates( self, column_ids, row_ids, answers_list, ): """Maps lists of answer coordinates to token indexes.""" answer_ids = [0] * len(column_ids) found_answers = set() all_answers = set() for answers in answers_l...
[ "def", "_get_all_answer_ids_from_coordinates", "(", "self", ",", "column_ids", ",", "row_ids", ",", "answers_list", ",", ")", ":", "answer_ids", "=", "[", "0", "]", "*", "len", "(", "column_ids", ")", "found_answers", "=", "set", "(", ")", "all_answers", "="...
[ 1635, 4 ]
[ 1653, 40 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_all_answer_ids
(self, column_ids, row_ids, answer_coordinates)
Maps answer coordinates of a question to token indexes. In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to (column, row) format before calling _get_all_answer_ids_from_coordinates.
Maps answer coordinates of a question to token indexes.
def _get_all_answer_ids(self, column_ids, row_ids, answer_coordinates): """ Maps answer coordinates of a question to token indexes. In the SQA format (TSV), the coordinates are given as (row, column) tuples. Here, we first swap them to (column, row) format before calling _get_all_answer...
[ "def", "_get_all_answer_ids", "(", "self", ",", "column_ids", ",", "row_ids", ",", "answer_coordinates", ")", ":", "def", "_to_coordinates", "(", "answer_coordinates_question", ")", ":", "return", "[", "(", "coords", "[", "1", "]", ",", "coords", "[", "0", "...
[ 1655, 4 ]
[ 1668, 9 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._find_tokens
(self, text, segment)
Return start index of segment in text or None.
Return start index of segment in text or None.
def _find_tokens(self, text, segment): """Return start index of segment in text or None.""" logging.info("text: %s %s", text, segment) for index in range(1 + len(text) - len(segment)): for seg_index, seg_token in enumerate(segment): if text[index + seg_index].piece !=...
[ "def", "_find_tokens", "(", "self", ",", "text", ",", "segment", ")", ":", "logging", ".", "info", "(", "\"text: %s %s\"", ",", "text", ",", "segment", ")", "for", "index", "in", "range", "(", "1", "+", "len", "(", "text", ")", "-", "len", "(", "se...
[ 1670, 4 ]
[ 1679, 19 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._find_answer_coordinates_from_answer_text
( self, tokenized_table, answer_text, )
Returns all occurrences of answer_text in the table.
Returns all occurrences of answer_text in the table.
def _find_answer_coordinates_from_answer_text( self, tokenized_table, answer_text, ): """Returns all occurrences of answer_text in the table.""" logging.info("answer text: %s", answer_text) for row_index, row in enumerate(tokenized_table.rows): if row_inde...
[ "def", "_find_answer_coordinates_from_answer_text", "(", "self", ",", "tokenized_table", ",", "answer_text", ",", ")", ":", "logging", ".", "info", "(", "\"answer text: %s\"", ",", "answer_text", ")", "for", "row_index", ",", "row", "in", "enumerate", "(", "tokeni...
[ 1681, 4 ]
[ 1699, 21 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._find_answer_ids_from_answer_texts
( self, column_ids, row_ids, tokenized_table, answer_texts, )
Maps question with answer texts to the first matching token indexes.
Maps question with answer texts to the first matching token indexes.
def _find_answer_ids_from_answer_texts( self, column_ids, row_ids, tokenized_table, answer_texts, ): """Maps question with answer texts to the first matching token indexes.""" answer_ids = [0] * len(column_ids) for answer_text in answer_texts: ...
[ "def", "_find_answer_ids_from_answer_texts", "(", "self", ",", "column_ids", ",", "row_ids", ",", "tokenized_table", ",", "answer_texts", ",", ")", ":", "answer_ids", "=", "[", "0", "]", "*", "len", "(", "column_ids", ")", "for", "answer_text", "in", "answer_t...
[ 1701, 4 ]
[ 1737, 25 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._get_answer_ids
(self, column_ids, row_ids, answer_coordinates)
Maps answer coordinates of a question to token indexes.
Maps answer coordinates of a question to token indexes.
def _get_answer_ids(self, column_ids, row_ids, answer_coordinates): """Maps answer coordinates of a question to token indexes.""" answer_ids, missing_count = self._get_all_answer_ids(column_ids, row_ids, answer_coordinates) if missing_count: raise ValueError("Couldn't find all answe...
[ "def", "_get_answer_ids", "(", "self", ",", "column_ids", ",", "row_ids", ",", "answer_coordinates", ")", ":", "answer_ids", ",", "missing_count", "=", "self", ".", "_get_all_answer_ids", "(", "column_ids", ",", "row_ids", ",", "answer_coordinates", ")", "if", "...
[ 1739, 4 ]
[ 1745, 25 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer._pad
( self, encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding], max_length: Optional[int] = None, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, pad_to_multiple_of: Optional[int] = None, return_attention_mask: Optional[bool] = None, )
Pad encoded inputs (on left/right and up to predefined length or max length in the batch) Args: encoded_inputs: Dictionary of tokenized inputs (`List[int]`) or batch of tokenized inputs (`List[List[int]]`). max_length: maximum length of the returned list and optionally padding ...
Pad encoded inputs (on left/right and up to predefined length or max length in the batch)
def _pad( self, encoded_inputs: Union[Dict[str, EncodedInput], BatchEncoding], max_length: Optional[int] = None, padding_strategy: PaddingStrategy = PaddingStrategy.DO_NOT_PAD, pad_to_multiple_of: Optional[int] = None, return_attention_mask: Optional[bool] = None, ) -...
[ "def", "_pad", "(", "self", ",", "encoded_inputs", ":", "Union", "[", "Dict", "[", "str", ",", "EncodedInput", "]", ",", "BatchEncoding", "]", ",", "max_length", ":", "Optional", "[", "int", "]", "=", "None", ",", "padding_strategy", ":", "PaddingStrategy"...
[ 1757, 4 ]
[ 1844, 29 ]
python
en
['en', 'error', 'th']
False
TapasTokenizer._get_mean_cell_probs
(self, probabilities, segment_ids, row_ids, column_ids)
Computes average probability per cell, aggregating over tokens.
Computes average probability per cell, aggregating over tokens.
def _get_mean_cell_probs(self, probabilities, segment_ids, row_ids, column_ids): """Computes average probability per cell, aggregating over tokens.""" coords_to_probs = collections.defaultdict(list) for i, prob in self._get_cell_token_probs(probabilities, segment_ids, row_ids, column_ids): ...
[ "def", "_get_mean_cell_probs", "(", "self", ",", "probabilities", ",", "segment_ids", ",", "row_ids", ",", "column_ids", ")", ":", "coords_to_probs", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "i", ",", "prob", "in", "self", ".", "_get_...
[ 1856, 4 ]
[ 1863, 102 ]
python
en
['en', 'en', 'en']
True
TapasTokenizer.convert_logits_to_predictions
(self, data, logits, logits_agg=None, cell_classification_threshold=0.5)
Converts logits of :class:`~transformers.TapasForQuestionAnswering` to actual predicted answer coordinates and optional aggregation indices. The original implementation, on which this function is based, can be found `here <https://github.com/google-research/tapas/blob/4908213eb4df7aa98...
Converts logits of :class:`~transformers.TapasForQuestionAnswering` to actual predicted answer coordinates and optional aggregation indices.
def convert_logits_to_predictions(self, data, logits, logits_agg=None, cell_classification_threshold=0.5): """ Converts logits of :class:`~transformers.TapasForQuestionAnswering` to actual predicted answer coordinates and optional aggregation indices. The original implementation, on whi...
[ "def", "convert_logits_to_predictions", "(", "self", ",", "data", ",", "logits", ",", "logits_agg", "=", "None", ",", "cell_classification_threshold", "=", "0.5", ")", ":", "# input data is of type float32", "# np.log(np.finfo(np.float32).max) = 88.72284", "# Any value over 8...
[ 1865, 4 ]
[ 1958, 21 ]
python
en
['en', 'error', 'th']
False
BasicTokenizer.tokenize
(self, text, never_split=None)
Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list of str Kept for backward compatibility purposes. Now implemented directly at the base class level (see ...
Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer.
def tokenize(self, text, never_split=None): """ Basic Tokenization of a piece of text. Split on "white spaces" only, for sub-word tokenization, see WordPieceTokenizer. Args: **never_split**: (`optional`) list of str Kept for backward compatibility purposes. N...
[ "def", "tokenize", "(", "self", ",", "text", ",", "never_split", "=", "None", ")", ":", "# union() returns a new set by concatenating the two sets.", "never_split", "=", "self", ".", "never_split", ".", "union", "(", "set", "(", "never_split", ")", ")", "if", "n...
[ 1992, 4 ]
[ 2027, 28 ]
python
en
['en', 'error', 'th']
False
BasicTokenizer._run_strip_accents
(self, text)
Strips accents from a piece of text.
Strips accents from a piece of text.
def _run_strip_accents(self, text): """Strips accents from a piece of text.""" text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) ...
[ "def", "_run_strip_accents", "(", "self", ",", "text", ")", ":", "text", "=", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "text", ")", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cat", "=", "unicodedata", ".", "category", "(",...
[ 2029, 4 ]
[ 2038, 30 ]
python
en
['en', 'en', 'en']
True
BasicTokenizer._run_split_on_punc
(self, text, never_split=None)
Splits punctuation on a piece of text.
Splits punctuation on a piece of text.
def _run_split_on_punc(self, text, never_split=None): """Splits punctuation on a piece of text.""" if never_split is not None and text in never_split: return [text] chars = list(text) i = 0 start_new_word = True output = [] while i < len(chars): ...
[ "def", "_run_split_on_punc", "(", "self", ",", "text", ",", "never_split", "=", "None", ")", ":", "if", "never_split", "is", "not", "None", "and", "text", "in", "never_split", ":", "return", "[", "text", "]", "chars", "=", "list", "(", "text", ")", "i"...
[ 2040, 4 ]
[ 2060, 43 ]
python
en
['en', 'en', 'en']
True
BasicTokenizer._tokenize_chinese_chars
(self, text)
Adds whitespace around any CJK character.
Adds whitespace around any CJK character.
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
[ "def", "_tokenize_chinese_chars", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "self", ".", "_is_chinese_char", "(", "cp", ")", ":", "output", ".", "append", ...
[ 2062, 4 ]
[ 2073, 30 ]
python
en
['en', 'en', 'en']
True
BasicTokenizer._is_chinese_char
(self, cp)
Checks whether CP is the codepoint of a CJK character.
Checks whether CP is the codepoint of a CJK character.
def _is_chinese_char(self, cp): """Checks whether CP is the codepoint of a CJK character.""" # This defines a "chinese character" as anything in the CJK Unicode block: # https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block) # # Note that the CJK Unicode block is ...
[ "def", "_is_chinese_char", "(", "self", ",", "cp", ")", ":", "# This defines a \"chinese character\" as anything in the CJK Unicode block:", "# https://en.wikipedia.org/wiki/CJK_Unified_Ideographs_(Unicode_block)", "#", "# Note that the CJK Unicode block is NOT all Japanese and Korean charac...
[ 2075, 4 ]
[ 2097, 20 ]
python
en
['en', 'en', 'en']
True
BasicTokenizer._clean_text
(self, text)
Performs invalid character removal and whitespace cleanup on text.
Performs invalid character removal and whitespace cleanup on text.
def _clean_text(self, text): """Performs invalid character removal and whitespace cleanup on text.""" output = [] for char in text: cp = ord(char) if cp == 0 or cp == 0xFFFD or _is_control(char): continue if _is_whitespace(char): ...
[ "def", "_clean_text", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "cp", "==", "0", "or", "cp", "==", "0xFFFD", "or", "_is_control", "(", "char", ")", "...
[ 2099, 4 ]
[ 2110, 30 ]
python
en
['en', 'en', 'en']
True
WordpieceTokenizer.tokenize
(self, text)
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example, :obj:`input = "unaffable"` wil return as output :obj:`["un", "##aff", "##able"]`. Args: text: A single token or w...
Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary.
def tokenize(self, text): """ Tokenizes a piece of text into its word pieces. This uses a greedy longest-match-first algorithm to perform tokenization using the given vocabulary. For example, :obj:`input = "unaffable"` wil return as output :obj:`["un", "##aff", "##able"]`. Args...
[ "def", "tokenize", "(", "self", ",", "text", ")", ":", "output_tokens", "=", "[", "]", "for", "token", "in", "whitespace_tokenize", "(", "text", ")", ":", "chars", "=", "list", "(", "token", ")", "if", "len", "(", "chars", ")", ">", "self", ".", "m...
[ 2122, 4 ]
[ 2168, 28 ]
python
en
['en', 'error', 'th']
False
get_available_envs
()
Get available built-in scenarios and their topologies. Returns: List[dict]: List of environment settings like [{"scenario": "cim", "topology": "toy.5p_ssddd_l0.1"}].
Get available built-in scenarios and their topologies.
def get_available_envs(): """Get available built-in scenarios and their topologies. Returns: List[dict]: List of environment settings like [{"scenario": "cim", "topology": "toy.5p_ssddd_l0.1"}]. """ envs = [] scenarios = get_scenarios() for scenario in scenarios: for topology ...
[ "def", "get_available_envs", "(", ")", ":", "envs", "=", "[", "]", "scenarios", "=", "get_scenarios", "(", ")", "for", "scenario", "in", "scenarios", ":", "for", "topology", "in", "get_topologies", "(", "scenario", ")", ":", "envs", ".", "append", "(", "...
[ 12, 0 ]
[ 26, 15 ]
python
en
['en', 'en', 'en']
True
get_scenarios
()
Get built-in scenario name list. Returns: List[str]: List of scenario name.
Get built-in scenario name list.
def get_scenarios() -> List[str]: """Get built-in scenario name list. Returns: List[str]: List of scenario name. """ try: _, scenarios, _ = next(os.walk(scenarios_root_folder)) scenarios = sorted([s for s in scenarios if not s.startswith("__")]) except StopIteration: ...
[ "def", "get_scenarios", "(", ")", "->", "List", "[", "str", "]", ":", "try", ":", "_", ",", "scenarios", ",", "_", "=", "next", "(", "os", ".", "walk", "(", "scenarios_root_folder", ")", ")", "scenarios", "=", "sorted", "(", "[", "s", "for", "s", ...
[ 29, 0 ]
[ 42, 20 ]
python
en
['it', 'nl', 'en']
False
get_topologies
(scenario: str)
Get topology list of specified built-in scenario name. Args: scenario(str): Built-in scenario name. Return: List[str]: List of topology name.
Get topology list of specified built-in scenario name.
def get_topologies(scenario: str) -> List[str]: """Get topology list of specified built-in scenario name. Args: scenario(str): Built-in scenario name. Return: List[str]: List of topology name. """ scenario_topology_root = f'{scenarios_root_folder}/{scenario}/{topologies_folder}' ...
[ "def", "get_topologies", "(", "scenario", ":", "str", ")", "->", "List", "[", "str", "]", ":", "scenario_topology_root", "=", "f'{scenarios_root_folder}/{scenario}/{topologies_folder}'", "if", "not", "os", ".", "path", ".", "exists", "(", "scenario_topology_root", "...
[ 45, 0 ]
[ 66, 21 ]
python
en
['en', 'en', 'en']
True
tick_to_frame_index
(start_tick: int, cur_tick: int, resolution: int)
Calculate frame index in snapshot list of specified configurations, usually is used when taking snapshot. Args: start_tick(int): Start tick of current simulation. cur_tick(int): Current tick in simulator. resolution(int): Snapshot resolution. Returns: int: Frame index in sn...
Calculate frame index in snapshot list of specified configurations, usually is used when taking snapshot.
def tick_to_frame_index(start_tick: int, cur_tick: int, resolution: int) -> int: """Calculate frame index in snapshot list of specified configurations, usually is used when taking snapshot. Args: start_tick(int): Start tick of current simulation. cur_tick(int): Current tick in simulator. ...
[ "def", "tick_to_frame_index", "(", "start_tick", ":", "int", ",", "cur_tick", ":", "int", ",", "resolution", ":", "int", ")", "->", "int", ":", "return", "floor", "(", "(", "cur_tick", "-", "start_tick", ")", "/", "resolution", ")" ]
[ 69, 0 ]
[ 81, 54 ]
python
en
['en', 'en', 'en']
True
frame_index_to_ticks
(start_tick: int, max_tick: int, resolution: int)
Calculate a dictionary that key is frame index, value is ticks. Args: start_tick (int): Start tick of current simulation. max_tick (int): Max tick of current simulation. resolution (int): Current snapshot resolution. Returns: dict: Key is the frame index in snapshot list, value...
Calculate a dictionary that key is frame index, value is ticks.
def frame_index_to_ticks(start_tick: int, max_tick: int, resolution: int) -> dict: """Calculate a dictionary that key is frame index, value is ticks. Args: start_tick (int): Start tick of current simulation. max_tick (int): Max tick of current simulation. resolution (int): Current snaps...
[ "def", "frame_index_to_ticks", "(", "start_tick", ":", "int", ",", "max_tick", ":", "int", ",", "resolution", ":", "int", ")", "->", "dict", ":", "mapping", "=", "{", "}", "max_snapshot_num", "=", "total_frames", "(", "start_tick", ",", "max_tick", ",", "r...
[ 84, 0 ]
[ 105, 18 ]
python
en
['en', 'en', 'en']
True
total_frames
(start_tick: int, max_tick: int, resolution: int)
Calculate total frame snapshot in snapshot list. NOTE: This method return the max snapshot number, but you can use small value to reduce memory using your own one. Args: start_tick(int): Start tick of current simulation. max_tick(int): Max tick of current simulation. re...
Calculate total frame snapshot in snapshot list.
def total_frames(start_tick: int, max_tick: int, resolution: int) -> int: """Calculate total frame snapshot in snapshot list. NOTE: This method return the max snapshot number, but you can use small value to reduce memory using your own one. Args: start_tick(int): Start tick of curr...
[ "def", "total_frames", "(", "start_tick", ":", "int", ",", "max_tick", ":", "int", ",", "resolution", ":", "int", ")", "->", "int", ":", "return", "ceil", "(", "(", "max_tick", "-", "start_tick", ")", "/", "resolution", ")" ]
[ 108, 0 ]
[ 123, 53 ]
python
en
['nl', 'en', 'en']
True
deeper_conv_block
(conv_layer, kernel_size, weighted=True)
deeper conv layer.
deeper conv layer.
def deeper_conv_block(conv_layer, kernel_size, weighted=True): '''deeper conv layer. ''' n_dim = get_n_dim(conv_layer) filter_shape = (kernel_size,) * 2 n_filters = conv_layer.filters weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filt...
[ "def", "deeper_conv_block", "(", "conv_layer", ",", "kernel_size", ",", "weighted", "=", "True", ")", ":", "n_dim", "=", "get_n_dim", "(", "conv_layer", ")", "filter_shape", "=", "(", "kernel_size", ",", ")", "*", "2", "n_filters", "=", "conv_layer", ".", ...
[ 16, 0 ]
[ 48, 43 ]
python
en
['it', 'kk', 'en']
False
dense_to_deeper_block
(dense_layer, weighted=True)
deeper dense layer.
deeper dense layer.
def dense_to_deeper_block(dense_layer, weighted=True): '''deeper dense layer. ''' units = dense_layer.units weight = np.eye(units) bias = np.zeros(units) new_dense_layer = StubDense(units, units) if weighted: new_dense_layer.set_weights( (add_noise(weight, np.array([0, 1]...
[ "def", "dense_to_deeper_block", "(", "dense_layer", ",", "weighted", "=", "True", ")", ":", "units", "=", "dense_layer", ".", "units", "weight", "=", "np", ".", "eye", "(", "units", ")", "bias", "=", "np", ".", "zeros", "(", "units", ")", "new_dense_laye...
[ 51, 0 ]
[ 63, 40 ]
python
da
['da', 'lb', 'en']
False
wider_pre_dense
(layer, n_add, weighted=True)
wider previous dense layer.
wider previous dense layer.
def wider_pre_dense(layer, n_add, weighted=True): '''wider previous dense layer. ''' if not weighted: return StubDense(layer.input_units, layer.units + n_add) n_units2 = layer.units teacher_w, teacher_b = layer.get_weights() rand = np.random.randint(n_units2, size=n_add) student_w ...
[ "def", "wider_pre_dense", "(", "layer", ",", "n_add", ",", "weighted", "=", "True", ")", ":", "if", "not", "weighted", ":", "return", "StubDense", "(", "layer", ".", "input_units", ",", "layer", ".", "units", "+", "n_add", ")", "n_units2", "=", "layer", ...
[ 66, 0 ]
[ 93, 24 ]
python
de
['fr', 'en', 'de']
False
wider_pre_conv
(layer, n_add_filters, weighted=True)
wider previous conv layer.
wider previous conv layer.
def wider_pre_conv(layer, n_add_filters, weighted=True): '''wider previous conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)( layer.input_channel, layer.filters + n_add_filters, kernel_size=layer.kernel_size, ) ...
[ "def", "wider_pre_conv", "(", "layer", ",", "n_add_filters", ",", "weighted", "=", "True", ")", ":", "n_dim", "=", "get_n_dim", "(", "layer", ")", "if", "not", "weighted", ":", "return", "get_conv_class", "(", "n_dim", ")", "(", "layer", ".", "input_channe...
[ 96, 0 ]
[ 126, 24 ]
python
en
['en', 'it', 'en']
True
wider_next_conv
(layer, start_dim, total_dim, n_add, weighted=True)
wider next conv layer.
wider next conv layer.
def wider_next_conv(layer, start_dim, total_dim, n_add, weighted=True): '''wider next conv layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_conv_class(n_dim)(layer.input_channel + n_add, layer.filters, kerne...
[ "def", "wider_next_conv", "(", "layer", ",", "start_dim", ",", "total_dim", ",", "n_add", ",", "weighted", "=", "True", ")", ":", "n_dim", "=", "get_n_dim", "(", "layer", ")", "if", "not", "weighted", ":", "return", "get_conv_class", "(", "n_dim", ")", "...
[ 129, 0 ]
[ 153, 20 ]
python
en
['en', 'de', 'en']
True
wider_bn
(layer, start_dim, total_dim, n_add, weighted=True)
wider batch norm layer.
wider batch norm layer.
def wider_bn(layer, start_dim, total_dim, n_add, weighted=True): '''wider batch norm layer. ''' n_dim = get_n_dim(layer) if not weighted: return get_batch_norm_class(n_dim)(layer.num_features + n_add) weights = layer.get_weights() new_weights = [ add_noise(np.ones(n_add, dtype=...
[ "def", "wider_bn", "(", "layer", ",", "start_dim", ",", "total_dim", ",", "n_add", ",", "weighted", "=", "True", ")", ":", "n_dim", "=", "get_n_dim", "(", "layer", ")", "if", "not", "weighted", ":", "return", "get_batch_norm_class", "(", "n_dim", ")", "(...
[ 156, 0 ]
[ 181, 20 ]
python
en
['en', 'de', 'en']
True
wider_next_dense
(layer, start_dim, total_dim, n_add, weighted=True)
wider next dense layer.
wider next dense layer.
def wider_next_dense(layer, start_dim, total_dim, n_add, weighted=True): '''wider next dense layer. ''' if not weighted: return StubDense(layer.input_units + n_add, layer.units) teacher_w, teacher_b = layer.get_weights() student_w = teacher_w.copy() n_units_each_channel = int(teacher_w.s...
[ "def", "wider_next_dense", "(", "layer", ",", "start_dim", ",", "total_dim", ",", "n_add", ",", "weighted", "=", "True", ")", ":", "if", "not", "weighted", ":", "return", "StubDense", "(", "layer", ".", "input_units", "+", "n_add", ",", "layer", ".", "un...
[ 184, 0 ]
[ 207, 20 ]
python
de
['fr', 'de', 'en']
False
add_noise
(weights, other_weights)
add noise to the layer.
add noise to the layer.
def add_noise(weights, other_weights): '''add noise to the layer. ''' w_range = np.ptp(other_weights.flatten()) noise_range = NOISE_RATIO * w_range noise = np.random.uniform(-noise_range / 2.0, noise_range / 2.0, weights.shape) return np.add(noise, weights)
[ "def", "add_noise", "(", "weights", ",", "other_weights", ")", ":", "w_range", "=", "np", ".", "ptp", "(", "other_weights", ".", "flatten", "(", ")", ")", "noise_range", "=", "NOISE_RATIO", "*", "w_range", "noise", "=", "np", ".", "random", ".", "uniform...
[ 210, 0 ]
[ 217, 33 ]
python
en
['en', 'en', 'en']
True
init_dense_weight
(layer)
initilize dense layer weight.
initilize dense layer weight.
def init_dense_weight(layer): '''initilize dense layer weight. ''' units = layer.units weight = np.eye(units) bias = np.zeros(units) layer.set_weights( (add_noise(weight, np.array([0, 1])), add_noise(bias, np.array([0, 1]))) )
[ "def", "init_dense_weight", "(", "layer", ")", ":", "units", "=", "layer", ".", "units", "weight", "=", "np", ".", "eye", "(", "units", ")", "bias", "=", "np", ".", "zeros", "(", "units", ")", "layer", ".", "set_weights", "(", "(", "add_noise", "(", ...
[ 220, 0 ]
[ 229, 5 ]
python
en
['ro', 'en', 'en']
True
init_conv_weight
(layer)
initilize conv layer weight.
initilize conv layer weight.
def init_conv_weight(layer): '''initilize conv layer weight. ''' n_filters = layer.filters filter_shape = (layer.kernel_size,) * get_n_dim(layer) weight = np.zeros((n_filters, n_filters) + filter_shape) center = tuple(map(lambda x: int((x - 1) / 2), filter_shape)) for i in range(n_filters):...
[ "def", "init_conv_weight", "(", "layer", ")", ":", "n_filters", "=", "layer", ".", "filters", "filter_shape", "=", "(", "layer", ".", "kernel_size", ",", ")", "*", "get_n_dim", "(", "layer", ")", "weight", "=", "np", ".", "zeros", "(", "(", "n_filters", ...
[ 232, 0 ]
[ 250, 5 ]
python
en
['es', 'en', 'en']
True
init_bn_weight
(layer)
initilize batch norm layer weight.
initilize batch norm layer weight.
def init_bn_weight(layer): '''initilize batch norm layer weight. ''' n_filters = layer.num_features new_weights = [ add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters,...
[ "def", "init_bn_weight", "(", "layer", ")", ":", "n_filters", "=", "layer", ".", "num_features", "new_weights", "=", "[", "add_noise", "(", "np", ".", "ones", "(", "n_filters", ",", "dtype", "=", "np", ".", "float32", ")", ",", "np", ".", "array", "(",...
[ 253, 0 ]
[ 263, 34 ]
python
en
['en', 'en', 'en']
True
ExampleLoginFlow.async_step_init
( self, user_input: Optional[Dict[str, str]] = None )
Handle the step of the form.
Handle the step of the form.
async def async_step_init( self, user_input: Optional[Dict[str, str]] = None ) -> Dict[str, Any]: """Handle the step of the form.""" errors = {} if user_input is not None: try: cast(ExampleAuthProvider, self._auth_provider).async_validate_login( ...
[ "async", "def", "async_step_init", "(", "self", ",", "user_input", ":", "Optional", "[", "Dict", "[", "str", ",", "str", "]", "]", "=", "None", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "errors", "=", "{", "}", "if", "user_input", "is", ...
[ 95, 4 ]
[ 119, 9 ]
python
en
['en', 'en', 'en']
True
get_logger
(file_path)
Make python logger
Make python logger
def get_logger(file_path): """ Make python logger """ log_format = '%(asctime)s | %(message)s' logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='%m/%d %I:%M:%S %p') logger = logging.getLogger('') formatter = logging.Formatter(log_format, ...
[ "def", "get_logger", "(", "file_path", ")", ":", "log_format", "=", "'%(asctime)s | %(message)s'", "logging", ".", "basicConfig", "(", "stream", "=", "sys", ".", "stdout", ",", "level", "=", "logging", ".", "INFO", ",", "format", "=", "log_format", ",", "dat...
[ 54, 0 ]
[ 67, 17 ]
python
en
['en', 'pt', 'en']
True