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
test_docs
()
Return HTML docs for root route.
Return HTML docs for root route.
def test_docs(): """Return HTML docs for root route.""" response = client.get('/') assert response.status_code == 200 assert response.headers['content-type'].startswith('text/html')
[ "def", "test_docs", "(", ")", ":", "response", "=", "client", ".", "get", "(", "'/'", ")", "assert", "response", ".", "status_code", "==", "200", "assert", "response", ".", "headers", "[", "'content-type'", "]", ".", "startswith", "(", "'text/html'", ")" ]
[ 7, 0 ]
[ 11, 67 ]
python
en
['en', 'en', 'en']
True
check_alter_settings_when_privilege_is_granted
(table, user, node)
Ensures ADD SETTINGS runs as expected when the privilege is granted to the specified user
Ensures ADD SETTINGS runs as expected when the privilege is granted to the specified user
def check_alter_settings_when_privilege_is_granted(table, user, node): """Ensures ADD SETTINGS runs as expected when the privilege is granted to the specified user """ with Given("I check that the modified setting is not already in the table"): output = json.loads(node.query(f"SHOW CREATE TABLE {tab...
[ "def", "check_alter_settings_when_privilege_is_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "Given", "(", "\"I check that the modified setting is not already in the table\"", ")", ":", "output", "=", "json", ".", "loads", "(", "node", ".", "quer...
[ 12, 0 ]
[ 25, 110 ]
python
en
['en', 'en', 'en']
True
check_alter_settings_when_privilege_is_not_granted
(table, user, node)
Ensures CLEAR SETTINGS runs as expected when the privilege is granted to the specified user
Ensures CLEAR SETTINGS runs as expected when the privilege is granted to the specified user
def check_alter_settings_when_privilege_is_not_granted(table, user, node): """Ensures CLEAR SETTINGS runs as expected when the privilege is granted to the specified user """ with When("I grant the user NONE privilege"): node.query(f"GRANT NONE TO {user}") with And("I grant the user USAGE privil...
[ "def", "check_alter_settings_when_privilege_is_not_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "When", "(", "\"I grant the user NONE privilege\"", ")", ":", "node", ".", "query", "(", "f\"GRANT NONE TO {user}\"", ")", "with", "And", "(", "\"I...
[ 27, 0 ]
[ 39, 74 ]
python
en
['en', 'en', 'en']
True
user_with_privileges
(self, privilege, table_type, node=None)
Check that user with ALTER SETTINGS privilege is able to alter the table
Check that user with ALTER SETTINGS privilege is able to alter the table
def user_with_privileges(self, privilege, table_type, node=None): """Check that user with ALTER SETTINGS privilege is able to alter the table """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" user_name = f"user_{getuid()}" with table(node, table_na...
[ "def", "user_with_privileges", "(", "self", ",", "privilege", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_nam...
[ 42, 0 ]
[ 57, 87 ]
python
en
['en', 'en', 'en']
True
user_with_revoked_privileges
(self, privilege, table_type, node=None)
Check that user is unable to alter settingss on table after ALTER SETTINGS privilege on that table has been revoked from the user.
Check that user is unable to alter settingss on table after ALTER SETTINGS privilege on that table has been revoked from the user.
def user_with_revoked_privileges(self, privilege, table_type, node=None): """Check that user is unable to alter settingss on table after ALTER SETTINGS privilege on that table has been revoked from the user. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}"...
[ "def", "user_with_revoked_privileges", "(", "self", ",", "privilege", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "...
[ 64, 0 ]
[ 82, 91 ]
python
en
['en', 'en', 'en']
True
role_with_some_privileges
(self, privilege, table_type, node=None)
Check that user can alter settings on a table after it is granted a role that has the alter settings privilege for that table.
Check that user can alter settings on a table after it is granted a role that has the alter settings privilege for that table.
def role_with_some_privileges(self, privilege, table_type, node=None): """Check that user can alter settings on a table after it is granted a role that has the alter settings privilege for that table. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" us...
[ "def", "role_with_some_privileges", "(", "self", ",", "privilege", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "use...
[ 88, 0 ]
[ 107, 87 ]
python
en
['en', 'en', 'en']
True
user_with_revoked_role
(self, privilege, table_type, node=None)
Check that user with a role that has alter settings privilege on a table is unable to alter settings from that table after the role with privilege has been revoked from the user.
Check that user with a role that has alter settings privilege on a table is unable to alter settings from that table after the role with privilege has been revoked from the user.
def user_with_revoked_role(self, privilege, table_type, node=None): """Check that user with a role that has alter settings privilege on a table is unable to alter settings from that table after the role with privilege has been revoked from the user. """ if node is None: node = self.context.node ...
[ "def", "user_with_revoked_role", "(", "self", ",", "privilege", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_n...
[ 110, 0 ]
[ 132, 91 ]
python
en
['en', 'en', 'en']
True
user_with_privileges_on_cluster
(self, privilege, table_type, node=None)
Check that user is able to alter settings on a table with privilege granted on a cluster.
Check that user is able to alter settings on a table with privilege granted on a cluster.
def user_with_privileges_on_cluster(self, privilege, table_type, node=None): """Check that user is able to alter settings on a table with privilege granted on a cluster. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" user_name = f"user_{getuid()}" ...
[ "def", "user_with_privileges_on_cluster", "(", "self", ",", "privilege", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", ...
[ 138, 0 ]
[ 167, 83 ]
python
en
['en', 'en', 'en']
True
scenario_parallelization
(self, table_type, privilege)
Runs all scenarios in parallel for a given privilege.
Runs all scenarios in parallel for a given privilege.
def scenario_parallelization(self, table_type, privilege): """Runs all scenarios in parallel for a given privilege. """ with Pool(4) as pool: tasks = [] try: for scenario in loads(current_module(), Scenario): run_scenario(pool, tasks, Scenario(test=scenario), {"ta...
[ "def", "scenario_parallelization", "(", "self", ",", "table_type", ",", "privilege", ")", ":", "with", "Pool", "(", "4", ")", "as", "pool", ":", "tasks", "=", "[", "]", "try", ":", "for", "scenario", "in", "loads", "(", "current_module", "(", ")", ",",...
[ 170, 0 ]
[ 179, 23 ]
python
en
['en', 'it', 'en']
True
feature
(self, node="clickhouse1", stress=None, parallel=None)
Runs test suites above which check correctness over scenarios and permutations
Runs test suites above which check correctness over scenarios and permutations
def feature(self, node="clickhouse1", stress=None, parallel=None): """Runs test suites above which check correctness over scenarios and permutations """ self.context.node = self.context.cluster.node(node) if parallel is not None: self.context.parallel = parallel if stress is not None: ...
[ "def", "feature", "(", "self", ",", "node", "=", "\"clickhouse1\"", ",", "stress", "=", "None", ",", "parallel", "=", "None", ")", ":", "self", ".", "context", ".", "node", "=", "self", ".", "context", ".", "cluster", ".", "node", "(", "node", ")", ...
[ 192, 0 ]
[ 217, 31 ]
python
en
['en', 'en', 'en']
True
permutations
()
Returns list of all permutations to run. Currently includes NONE, TTL, MATERIALIZE TTL, and both
Returns list of all permutations to run. Currently includes NONE, TTL, MATERIALIZE TTL, and both
def permutations(): """Returns list of all permutations to run. Currently includes NONE, TTL, MATERIALIZE TTL, and both """ return [*range(permutation_count)]
[ "def", "permutations", "(", ")", ":", "return", "[", "*", "range", "(", "permutation_count", ")", "]" ]
[ 23, 0 ]
[ 27, 38 ]
python
en
['en', 'en', 'en']
True
alter_ttl_privileges
(grants: int)
Takes in an integer, and returns the corresponding set of tests to grant and not grant using the binary string. Each integer corresponds to a unique permutation of grants.
Takes in an integer, and returns the corresponding set of tests to grant and not grant using the binary string. Each integer corresponds to a unique permutation of grants.
def alter_ttl_privileges(grants: int): """Takes in an integer, and returns the corresponding set of tests to grant and not grant using the binary string. Each integer corresponds to a unique permutation of grants. """ note(grants) privileges = [] if grants==0: # No privileges privil...
[ "def", "alter_ttl_privileges", "(", "grants", ":", "int", ")", ":", "note", "(", "grants", ")", "privileges", "=", "[", "]", "if", "grants", "==", "0", ":", "# No privileges", "privileges", ".", "append", "(", "\"NONE\"", ")", "else", ":", "if", "(", "...
[ 29, 0 ]
[ 46, 32 ]
python
en
['en', 'en', 'en']
True
alter_ttl_privilege_handler
(grants, table, user, node)
For all 2 subprivileges, if the privilege is granted: run test to ensure correct behavior, and if the privilege is not granted, run test to ensure correct behavior there as well
For all 2 subprivileges, if the privilege is granted: run test to ensure correct behavior, and if the privilege is not granted, run test to ensure correct behavior there as well
def alter_ttl_privilege_handler(grants, table, user, node): """For all 2 subprivileges, if the privilege is granted: run test to ensure correct behavior, and if the privilege is not granted, run test to ensure correct behavior there as well """ if (grants & subprivileges["TTL"]): with When("I c...
[ "def", "alter_ttl_privilege_handler", "(", "grants", ",", "table", ",", "user", ",", "node", ")", ":", "if", "(", "grants", "&", "subprivileges", "[", "\"TTL\"", "]", ")", ":", "with", "When", "(", "\"I check ttl when privilege is granted\"", ")", ":", "check_...
[ 48, 0 ]
[ 64, 82 ]
python
en
['en', 'en', 'en']
True
check_ttl_when_privilege_is_granted
(table, user, node)
Ensures ALTER TTL runs as expected when the privilege is granted to the specified user
Ensures ALTER TTL runs as expected when the privilege is granted to the specified user
def check_ttl_when_privilege_is_granted(table, user, node): """Ensures ALTER TTL runs as expected when the privilege is granted to the specified user """ with Given(f"I modify TTL"): node.query(f"ALTER TABLE {table} MODIFY TTL d + INTERVAL 1 DAY;", settings = [("user", user)]) with ...
[ "def", "check_ttl_when_privilege_is_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "Given", "(", "f\"I modify TTL\"", ")", ":", "node", ".", "query", "(", "f\"ALTER TABLE {table} MODIFY TTL d + INTERVAL 1 DAY;\"", ",", "settings", "=", "[", "(",...
[ 66, 0 ]
[ 75, 73 ]
python
en
['en', 'en', 'en']
True
check_materialize_ttl_when_privilege_is_granted
(table, user, node)
Ensures MATERIALIZE TTL runs as expected when the privilege is granted to the specified user
Ensures MATERIALIZE TTL runs as expected when the privilege is granted to the specified user
def check_materialize_ttl_when_privilege_is_granted(table, user, node): """Ensures MATERIALIZE TTL runs as expected when the privilege is granted to the specified user """ with Given("I modify TTL so it exists"): node.query(f"ALTER TABLE {table} MODIFY TTL d + INTERVAL 1 MONTH;") with Then("I m...
[ "def", "check_materialize_ttl_when_privilege_is_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "Given", "(", "\"I modify TTL so it exists\"", ")", ":", "node", ".", "query", "(", "f\"ALTER TABLE {table} MODIFY TTL d + INTERVAL 1 MONTH;\"", ")", "with"...
[ 77, 0 ]
[ 89, 75 ]
python
en
['en', 'en', 'en']
True
check_ttl_when_privilege_is_not_granted
(table, user, node)
Ensures ALTER TTL errors as expected without the required privilege for the specified user
Ensures ALTER TTL errors as expected without the required privilege for the specified user
def check_ttl_when_privilege_is_not_granted(table, user, node): """Ensures ALTER TTL errors as expected without the required privilege for the specified user """ with When("I try to use privilege that has not been granted"): exitcode, message = errors.not_enough_privileges(user) node.query(f...
[ "def", "check_ttl_when_privilege_is_not_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "When", "(", "\"I try to use privilege that has not been granted\"", ")", ":", "exitcode", ",", "message", "=", "errors", ".", "not_enough_privileges", "(", "us...
[ 91, 0 ]
[ 97, 84 ]
python
en
['en', 'en', 'en']
True
check_materialize_ttl_when_privilege_is_not_granted
(table, user, node)
Ensures MATERIALIZE TTL errors as expected without the required privilege for the specified user
Ensures MATERIALIZE TTL errors as expected without the required privilege for the specified user
def check_materialize_ttl_when_privilege_is_not_granted(table, user, node): """Ensures MATERIALIZE TTL errors as expected without the required privilege for the specified user """ with When("I try to use privilege that has not been granted"): exitcode, message = errors.not_enough_privileges(user) ...
[ "def", "check_materialize_ttl_when_privilege_is_not_granted", "(", "table", ",", "user", ",", "node", ")", ":", "with", "When", "(", "\"I try to use privilege that has not been granted\"", ")", ":", "exitcode", ",", "message", "=", "errors", ".", "not_enough_privileges", ...
[ 99, 0 ]
[ 105, 84 ]
python
en
['en', 'en', 'en']
True
user_with_some_privileges
(self, table_type, node=None)
Check that user with any permutation of ALTER TTL subprivileges is able to alter the table for privileges granted, and not for privileges not granted.
Check that user with any permutation of ALTER TTL subprivileges is able to alter the table for privileges granted, and not for privileges not granted.
def user_with_some_privileges(self, table_type, node=None): """Check that user with any permutation of ALTER TTL subprivileges is able to alter the table for privileges granted, and not for privileges not granted. """ if node is None: node = self.context.node table_name = f"merge_tree_{getu...
[ "def", "user_with_some_privileges", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_name", "=", "f\"...
[ 108, 0 ]
[ 127, 89 ]
python
en
['en', 'en', 'en']
True
user_with_revoked_privileges
(self, table_type, node=None)
Check that user is unable to ALTER TTLs on table after ALTER TTL privilege on that table has been revoked from the user.
Check that user is unable to ALTER TTLs on table after ALTER TTL privilege on that table has been revoked from the user.
def user_with_revoked_privileges(self, table_type, node=None): """Check that user is unable to ALTER TTLs on table after ALTER TTL privilege on that table has been revoked from the user. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" user_name = f"us...
[ "def", "user_with_revoked_privileges", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_name", "=", "...
[ 133, 0 ]
[ 156, 79 ]
python
en
['en', 'en', 'en']
True
role_with_some_privileges
(self, table_type, node=None)
Check that user can ALTER TTL on a table after it is granted a role that has the ALTER TTL privilege for that table.
Check that user can ALTER TTL on a table after it is granted a role that has the ALTER TTL privilege for that table.
def role_with_some_privileges(self, table_type, node=None): """Check that user can ALTER TTL on a table after it is granted a role that has the ALTER TTL privilege for that table. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" user_name = f"user_{get...
[ "def", "role_with_some_privileges", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_name", "=", "f\"...
[ 162, 0 ]
[ 185, 89 ]
python
en
['en', 'en', 'en']
True
user_with_revoked_role
(self, table_type, node=None)
Check that user with a role that has ALTER TTL privilege on a table is unable to ALTER TTL from that table after the role with privilege has been revoked from the user.
Check that user with a role that has ALTER TTL privilege on a table is unable to ALTER TTL from that table after the role with privilege has been revoked from the user.
def user_with_revoked_role(self, table_type, node=None): """Check that user with a role that has ALTER TTL privilege on a table is unable to ALTER TTL from that table after the role with privilege has been revoked from the user. """ if node is None: node = self.context.node table_name = f"m...
[ "def", "user_with_revoked_role", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_name", "=", "f\"use...
[ 188, 0 ]
[ 215, 79 ]
python
en
['en', 'en', 'en']
True
user_with_privileges_on_cluster
(self, table_type, node=None)
Check that user is able to ALTER TTL on a table with privilege granted on a cluster.
Check that user is able to ALTER TTL on a table with privilege granted on a cluster.
def user_with_privileges_on_cluster(self, table_type, node=None): """Check that user is able to ALTER TTL on a table with privilege granted on a cluster. """ if node is None: node = self.context.node table_name = f"merge_tree_{getuid()}" user_name = f"user_{getuid()}" for permutati...
[ "def", "user_with_privileges_on_cluster", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "table_name", "=", "f\"merge_tree_{getuid()}\"", "user_name", "=", ...
[ 221, 0 ]
[ 247, 87 ]
python
en
['en', 'en', 'en']
True
privileges_granted_directly
(self, node=None)
Check that a user is able to execute `CREATE QUOTA` with privileges are granted directly.
Check that a user is able to execute `CREATE QUOTA` with privileges are granted directly.
def privileges_granted_directly(self, node=None): """Check that a user is able to execute `CREATE QUOTA` with privileges are granted directly. """ user_name = f"user_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name}"): Suite(run=create_quota, ...
[ "def", "privileges_granted_directly", "(", "self", ",", "node", "=", "None", ")", ":", "user_name", "=", "f\"user_{getuid()}\"", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "with", "user", "(", "node", ",", "f\"{user_...
[ 8, 0 ]
[ 22, 74 ]
python
en
['en', 'en', 'en']
True
privileges_granted_via_role
(self, node=None)
Check that a user is able to execute `CREATE QUOTA` with privileges are granted through a role.
Check that a user is able to execute `CREATE QUOTA` with privileges are granted through a role.
def privileges_granted_via_role(self, node=None): """Check that a user is able to execute `CREATE QUOTA` with privileges are granted through a role. """ user_name = f"user_{getuid()}" role_name = f"role_{getuid()}" if node is None: node = self.context.node with user(node, f"{user_name...
[ "def", "privileges_granted_via_role", "(", "self", ",", "node", "=", "None", ")", ":", "user_name", "=", "f\"user_{getuid()}\"", "role_name", "=", "f\"role_{getuid()}\"", "if", "node", "is", "None", ":", "node", "=", "self", ".", "context", ".", "node", "with"...
[ 25, 0 ]
[ 43, 74 ]
python
en
['en', 'en', 'en']
True
create_quota
(self, privilege, grant_target_name, user_name, node=None)
Check that user is only able to execute `CREATE QUOTA` when they have the necessary privilege.
Check that user is only able to execute `CREATE QUOTA` when they have the necessary privilege.
def create_quota(self, privilege, grant_target_name, user_name, node=None): """Check that user is only able to execute `CREATE QUOTA` when they have the necessary privilege. """ exitcode, message = errors.not_enough_privileges(name=user_name) if node is None: node = self.context.node with ...
[ "def", "create_quota", "(", "self", ",", "privilege", ",", "grant_target_name", ",", "user_name", ",", "node", "=", "None", ")", ":", "exitcode", ",", "message", "=", "errors", ".", "not_enough_privileges", "(", "name", "=", "user_name", ")", "if", "node", ...
[ 51, 0 ]
[ 121, 71 ]
python
en
['en', 'en', 'en']
True
feature
(self, node="clickhouse1")
Check the RBAC functionality of CREATE QUOTA.
Check the RBAC functionality of CREATE QUOTA.
def feature(self, node="clickhouse1"): """Check the RBAC functionality of CREATE QUOTA. """ self.context.node = self.context.cluster.node(node) Suite(run=privileges_granted_directly, setup=instrument_clickhouse_server_log) Suite(run=privileges_granted_via_role, setup=instrument_clickhouse_server_lo...
[ "def", "feature", "(", "self", ",", "node", "=", "\"clickhouse1\"", ")", ":", "self", ".", "context", ".", "node", "=", "self", ".", "context", ".", "cluster", ".", "node", "(", "node", ")", "Suite", "(", "run", "=", "privileges_granted_directly", ",", ...
[ 130, 0 ]
[ 136, 82 ]
python
en
['en', 'en', 'en']
True
send_log
(path)
Log access via web
Log access via web
def send_log(path): """ Log access via web """ logfile = os.path.join(LOG_DIR, path) if not logfile.startswith(os.path.abspath(LOG_DIR) + os.sep): return 'Wrong path' file = io.open(logfile, mode='r', encoding='utf-8', errors='ignore').read() out = file[-1024 * 100:] # read last 100 kB ...
[ "def", "send_log", "(", "path", ")", ":", "logfile", "=", "os", ".", "path", ".", "join", "(", "LOG_DIR", ",", "path", ")", "if", "not", "logfile", ".", "startswith", "(", "os", ".", "path", ".", "abspath", "(", "LOG_DIR", ")", "+", "os", ".", "s...
[ 159, 0 ]
[ 170, 35 ]
python
en
['en', 'st', 'it']
False
Transform
(lines)
Converts the contents of a file into javascript that uses goog.scope. Arguments: lines: A list of strings, corresponding to each line of the file. Returns: A new list of strings, or None if the file was not modified.
Converts the contents of a file into javascript that uses goog.scope.
def Transform(lines): """Converts the contents of a file into javascript that uses goog.scope. Arguments: lines: A list of strings, corresponding to each line of the file. Returns: A new list of strings, or None if the file was not modified. """ requires = [] # Do an initial scan to be sure that t...
[ "def", "Transform", "(", "lines", ")", ":", "requires", "=", "[", "]", "# Do an initial scan to be sure that this file can be processed.", "for", "line", "in", "lines", ":", "# Skip this file if it has already been scopified.", "if", "line", ".", "find", "(", "'goog.scope...
[ 58, 0 ]
[ 189, 15 ]
python
en
['en', 'en', 'en']
True
TransformFileAt
(path)
Converts a file into javascript that uses goog.scope. Arguments: path: A path to a file.
Converts a file into javascript that uses goog.scope.
def TransformFileAt(path): """Converts a file into javascript that uses goog.scope. Arguments: path: A path to a file. """ f = open(path) lines = Transform(f.readlines()) if lines: f = open(path, 'w') for l in lines: f.write(l) f.close()
[ "def", "TransformFileAt", "(", "path", ")", ":", "f", "=", "open", "(", "path", ")", "lines", "=", "Transform", "(", "f", ".", "readlines", "(", ")", ")", "if", "lines", ":", "f", "=", "open", "(", "path", ",", "'w'", ")", "for", "l", "in", "li...
[ 191, 0 ]
[ 203, 13 ]
python
en
['en', 'en', 'en']
True
Response.get
(self, request: Request)
Return a single form response by ID.
Return a single form response by ID.
async def get(self, request: Request) -> JSONResponse: """Return a single form response by ID.""" if raw_response := await request.state.db.responses.find_one( { "_id": request.path_params["response_id"], "form_id": request.path_params["form_id"] }...
[ "async", "def", "get", "(", "self", ",", "request", ":", "Request", ")", "->", "JSONResponse", ":", "if", "raw_response", ":=", "await", "request", ".", "state", ".", "db", ".", "responses", ".", "find_one", "(", "{", "\"_id\"", ":", "request", ".", "p...
[ 24, 4 ]
[ 35, 72 ]
python
en
['en', 'en', 'en']
True
Response.delete
(self, request: Request)
Delete a form response by ID.
Delete a form response by ID.
async def delete(self, request: Request) -> JSONResponse: """Delete a form response by ID.""" if not await request.state.db.responses.find_one( { "_id": request.path_params["response_id"], "form_id": request.path_params["form_id"] } ): ...
[ "async", "def", "delete", "(", "self", ",", "request", ":", "Request", ")", "->", "JSONResponse", ":", "if", "not", "await", "request", ".", "state", ".", "db", ".", "responses", ".", "find_one", "(", "{", "\"_id\"", ":", "request", ".", "path_params", ...
[ 42, 4 ]
[ 55, 45 ]
python
en
['en', 'en', 'en']
True
SubmitForm.post
(self, request: Request)
Submit a response to the form.
Submit a response to the form.
async def post(self, request: Request) -> JSONResponse: """Submit a response to the form.""" data = await request.json() data["timestamp"] = None if form := await request.state.db.forms.find_one( {"_id": request.path_params["form_id"], "features": "OPEN"} ): ...
[ "async", "def", "post", "(", "self", ",", "request", ":", "Request", ")", "->", "JSONResponse", ":", "data", "=", "await", "request", ".", "json", "(", ")", "data", "[", "\"timestamp\"", "]", "=", "None", "if", "form", ":=", "await", "request", ".", ...
[ 56, 4 ]
[ 150, 31 ]
python
en
['en', 'en', 'en']
True
SubmitForm.send_submission_webhook
( form: Form, response: FormResponse, request_user: Request.user )
Helper to send a submission message to a discord webhook.
Helper to send a submission message to a discord webhook.
async def send_submission_webhook( form: Form, response: FormResponse, request_user: Request.user ) -> None: """Helper to send a submission message to a discord webhook.""" # Stop if webhook is not available if form.webhook is None: raise Value...
[ "async", "def", "send_submission_webhook", "(", "form", ":", "Form", ",", "response", ":", "FormResponse", ",", "request_user", ":", "Request", ".", "user", ")", "->", "None", ":", "# Stop if webhook is not available", "if", "form", ".", "webhook", "is", "None",...
[ 153, 4 ]
[ 214, 32 ]
python
en
['en', 'en', 'en']
True
DemoImprintingEngine.__init__
(self, model_path, output_path, keep_classes, batch_size)
Creates a ImprintingEngine with given model and labels. Args: model_path: String, path to TF-Lite Flatbuffer file. output_path: String, path to output tflite file. keep_classes: Bool, whether to keep base model classes. batch_size: Int, batch size for engine to train once. Raises: ...
Creates a ImprintingEngine with given model and labels.
def __init__(self, model_path, output_path, keep_classes, batch_size): """Creates a ImprintingEngine with given model and labels. Args: model_path: String, path to TF-Lite Flatbuffer file. output_path: String, path to output tflite file. keep_classes: Bool, whether to keep base model classes....
[ "def", "__init__", "(", "self", ",", "model_path", ",", "output_path", ",", "keep_classes", ",", "batch_size", ")", ":", "self", ".", "_model_path", "=", "model_path", "self", ".", "_keep_classes", "=", "keep_classes", "self", ".", "_output_path", "=", "output...
[ 31, 2 ]
[ 50, 16 ]
python
en
['en', 'en', 'en']
True
DemoImprintingEngine.getRequiredInputShape
(self)
Get the required input shape for the model.
Get the required input shape for the model.
def getRequiredInputShape(self): """ Get the required input shape for the model. """ basic_engine = BasicEngine(self._model_path) input_tensor_shape = basic_engine.get_input_tensor_shape() if (input_tensor_shape.size != 4 or input_tensor_shape[3] != 3 or input_tensor_shape[0] != 1): ...
[ "def", "getRequiredInputShape", "(", "self", ")", ":", "basic_engine", "=", "BasicEngine", "(", "self", ".", "_model_path", ")", "input_tensor_shape", "=", "basic_engine", ".", "get_input_tensor_shape", "(", ")", "if", "(", "input_tensor_shape", ".", "size", "!=",...
[ 52, 2 ]
[ 62, 57 ]
python
en
['en', 'error', 'th']
False
DemoImprintingEngine.clear
(self)
Save the trained model. Clear the store: forgets all stored images.
Save the trained model. Clear the store: forgets all stored images.
def clear(self): """ Save the trained model. Clear the store: forgets all stored images. """ # Save the trained model. if self._example_count > 0: self._imprinting_engine.SaveModel(self._output_path) # The size of all the image store. self._example_count = 0 # The ImprintingEn...
[ "def", "clear", "(", "self", ")", ":", "# Save the trained model.", "if", "self", ".", "_example_count", ">", "0", ":", "self", ".", "_imprinting_engine", ".", "SaveModel", "(", "self", ".", "_output_path", ")", "# The size of all the image store.", "self", ".", ...
[ 64, 2 ]
[ 86, 39 ]
python
en
['en', 'error', 'th']
False
DemoImprintingEngine.trainAndUpdateModel
(self)
Train a batch of images and update the engines.
Train a batch of images and update the engines.
def trainAndUpdateModel(self): """Train a batch of images and update the engines.""" for label_real in range(0, self._max_real_label): if label_real in self._image_map: self._imprinting_engine.Train(np.array(self._image_map[label_real]), label_real) self._image_map = defaultdict(list)
[ "def", "trainAndUpdateModel", "(", "self", ")", ":", "for", "label_real", "in", "range", "(", "0", ",", "self", ".", "_max_real_label", ")", ":", "if", "label_real", "in", "self", ".", "_image_map", ":", "self", ".", "_imprinting_engine", ".", "Train", "("...
[ 88, 2 ]
[ 93, 39 ]
python
en
['en', 'en', 'en']
True
DemoImprintingEngine.addImage
(self, img, label_button)
Add an image to the store.
Add an image to the store.
def addImage(self, img, label_button): """Add an image to the store.""" # Update the label map. if label_button not in self._label_map_button2real: self._label_map_button2real[label_button] = self._max_real_label self._label_map_real2button[self._max_real_label] = label_button self._max_re...
[ "def", "addImage", "(", "self", ",", "img", ",", "label_button", ")", ":", "# Update the label map.", "if", "label_button", "not", "in", "self", ".", "_label_map_button2real", ":", "self", ".", "_label_map_button2real", "[", "label_button", "]", "=", "self", "."...
[ 95, 2 ]
[ 109, 32 ]
python
en
['en', 'en', 'en']
True
DemoImprintingEngine.exampleCount
(self)
Just returns the size of the image store.
Just returns the size of the image store.
def exampleCount(self): """Just returns the size of the image store.""" return self._example_count
[ "def", "exampleCount", "(", "self", ")", ":", "return", "self", ".", "_example_count" ]
[ 119, 2 ]
[ 121, 30 ]
python
en
['en', 'en', 'en']
True
IsValidFile
(ref)
Returns true if the provided reference is a file and exists.
Returns true if the provided reference is a file and exists.
def IsValidFile(ref): """Returns true if the provided reference is a file and exists.""" return os.path.isfile(ref)
[ "def", "IsValidFile", "(", "ref", ")", ":", "return", "os", ".", "path", ".", "isfile", "(", "ref", ")" ]
[ 52, 0 ]
[ 54, 28 ]
python
en
['en', 'en', 'en']
True
IsJsFile
(ref)
Returns true if the provided reference is a JavaScript file.
Returns true if the provided reference is a JavaScript file.
def IsJsFile(ref): """Returns true if the provided reference is a JavaScript file.""" return ref.endswith('.js')
[ "def", "IsJsFile", "(", "ref", ")", ":", "return", "ref", ".", "endswith", "(", "'.js'", ")" ]
[ 57, 0 ]
[ 59, 28 ]
python
en
['en', 'en', 'en']
True
IsNamespace
(ref)
Returns true if the provided reference is a namespace.
Returns true if the provided reference is a namespace.
def IsNamespace(ref): """Returns true if the provided reference is a namespace.""" return re.match(ns_regex, ref) is not None
[ "def", "IsNamespace", "(", "ref", ")", ":", "return", "re", ".", "match", "(", "ns_regex", ",", "ref", ")", "is", "not", "None" ]
[ 62, 0 ]
[ 64, 44 ]
python
en
['en', 'en', 'en']
True
IsDirectory
(ref)
Returns true if the provided reference is a directory.
Returns true if the provided reference is a directory.
def IsDirectory(ref): """Returns true if the provided reference is a directory.""" return os.path.isdir(ref)
[ "def", "IsDirectory", "(", "ref", ")", ":", "return", "os", ".", "path", ".", "isdir", "(", "ref", ")" ]
[ 67, 0 ]
[ 69, 27 ]
python
en
['en', 'en', 'en']
True
ExpandDirectories
(refs)
Expands any directory references into inputs. Description: Looks for any directories in the provided references. Found directories are recursively searched for .js files, which are then added to the result list. Args: refs: a list of references such as files, directories, and namespaces Return...
Expands any directory references into inputs.
def ExpandDirectories(refs): """Expands any directory references into inputs. Description: Looks for any directories in the provided references. Found directories are recursively searched for .js files, which are then added to the result list. Args: refs: a list of references such as files, dir...
[ "def", "ExpandDirectories", "(", "refs", ")", ":", "result", "=", "[", "]", "for", "ref", "in", "refs", ":", "if", "IsDirectory", "(", "ref", ")", ":", "# Disable 'Unused variable' for subdirs", "# pylint: disable=unused-variable", "for", "(", "directory", ",", ...
[ 72, 0 ]
[ 98, 38 ]
python
en
['en', 'en', 'en']
True
BuildDependenciesFromFiles
(files)
Build a list of dependencies from a list of files. Description: Takes a list of files, extracts their provides and requires, and builds out a list of dependency objects. Args: files: a list of files to be parsed for goog.provides and goog.requires. Returns: A list of dependency objects, one for...
Build a list of dependencies from a list of files.
def BuildDependenciesFromFiles(files): """Build a list of dependencies from a list of files. Description: Takes a list of files, extracts their provides and requires, and builds out a list of dependency objects. Args: files: a list of files to be parsed for goog.provides and goog.requires. Return...
[ "def", "BuildDependenciesFromFiles", "(", "files", ")", ":", "result", "=", "[", "]", "filenames", "=", "set", "(", ")", "for", "filename", "in", "files", ":", "if", "filename", "in", "filenames", ":", "continue", "# Python 3 requires the file encoding to be speci...
[ 115, 0 ]
[ 148, 15 ]
python
en
['en', 'en', 'en']
True
CreateDependencyInfo
(filename, source)
Create dependency info. Args: filename: Filename for source. source: File-like object containing source. Returns: A DependencyInfo object with provides and requires filled.
Create dependency info.
def CreateDependencyInfo(filename, source): """Create dependency info. Args: filename: Filename for source. source: File-like object containing source. Returns: A DependencyInfo object with provides and requires filled. """ dep = DependencyInfo(filename) for line in source: if re.match(req...
[ "def", "CreateDependencyInfo", "(", "filename", ",", "source", ")", ":", "dep", "=", "DependencyInfo", "(", "filename", ")", "for", "line", "in", "source", ":", "if", "re", ".", "match", "(", "req_regex", ",", "line", ")", ":", "dep", ".", "requires", ...
[ 151, 0 ]
[ 167, 12 ]
python
en
['it', 'en', 'en']
True
BuildDependencyHashFromDependencies
(deps)
Builds a hash for searching dependencies by the namespaces they provide. Description: Dependency objects can provide multiple namespaces. This method enumerates the provides of each dependency and adds them to a hash that can be used to easily resolve a given dependency by a namespace it provides. Ar...
Builds a hash for searching dependencies by the namespaces they provide.
def BuildDependencyHashFromDependencies(deps): """Builds a hash for searching dependencies by the namespaces they provide. Description: Dependency objects can provide multiple namespaces. This method enumerates the provides of each dependency and adds them to a hash that can be used to easily resolve ...
[ "def", "BuildDependencyHashFromDependencies", "(", "deps", ")", ":", "dep_hash", "=", "{", "}", "for", "dep", "in", "deps", ":", "for", "provide", "in", "dep", ".", "provides", ":", "if", "provide", "in", "dep_hash", ":", "raise", "Exception", "(", "'Dupli...
[ 170, 0 ]
[ 197, 17 ]
python
en
['en', 'en', 'en']
True
CalculateDependencies
(paths, inputs)
Calculates the dependencies for given inputs. Description: This method takes a list of paths (files, directories) and builds a searchable data structure based on the namespaces that each .js file provides. It then parses through each input, resolving dependencies against this data structure. The fi...
Calculates the dependencies for given inputs.
def CalculateDependencies(paths, inputs): """Calculates the dependencies for given inputs. Description: This method takes a list of paths (files, directories) and builds a searchable data structure based on the namespaces that each .js file provides. It then parses through each input, resolving depend...
[ "def", "CalculateDependencies", "(", "paths", ",", "inputs", ")", ":", "deps", "=", "BuildDependenciesFromFiles", "(", "paths", "+", "inputs", ")", "search_hash", "=", "BuildDependencyHashFromDependencies", "(", "deps", ")", "result_list", "=", "[", "]", "seen_lis...
[ 200, 0 ]
[ 254, 20 ]
python
en
['en', 'en', 'en']
True
FindClosureBasePath
(paths)
Given a list of file paths, return Closure base.js path, if any. Args: paths: A list of paths. Returns: The path to Closure's base.js file including filename, if found.
Given a list of file paths, return Closure base.js path, if any.
def FindClosureBasePath(paths): """Given a list of file paths, return Closure base.js path, if any. Args: paths: A list of paths. Returns: The path to Closure's base.js file including filename, if found. """ for path in paths: pathname, filename = os.path.split(path) if filename == 'base.j...
[ "def", "FindClosureBasePath", "(", "paths", ")", ":", "for", "path", "in", "paths", ":", "pathname", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "if", "filename", "==", "'base.js'", ":", "f", "=", "open", "(", "path", ")"...
[ 257, 0 ]
[ 286, 19 ]
python
en
['en', 'en', 'en']
True
ResolveDependencies
(require, search_hash, result_list, seen_list)
Takes a given requirement and resolves all of the dependencies for it. Description: A given requirement may require other dependencies. This method recursively resolves all dependencies for the given requirement. Raises: Exception: when require does not exist in the search_hash. Args: require:...
Takes a given requirement and resolves all of the dependencies for it.
def ResolveDependencies(require, search_hash, result_list, seen_list): """Takes a given requirement and resolves all of the dependencies for it. Description: A given requirement may require other dependencies. This method recursively resolves all dependencies for the given requirement. Raises: Exce...
[ "def", "ResolveDependencies", "(", "require", ",", "search_hash", ",", "result_list", ",", "seen_list", ")", ":", "if", "require", "not", "in", "search_hash", ":", "raise", "Exception", "(", "'Missing provider for (%s)'", "%", "require", ")", "dep", "=", "search...
[ 288, 0 ]
[ 314, 36 ]
python
en
['en', 'en', 'en']
True
GetDepsLine
(dep, base_path)
Returns a JS string for a dependency statement in the deps.js file. Args: dep: The dependency that we're printing. base_path: The path to Closure's base.js including filename.
Returns a JS string for a dependency statement in the deps.js file.
def GetDepsLine(dep, base_path): """Returns a JS string for a dependency statement in the deps.js file. Args: dep: The dependency that we're printing. base_path: The path to Closure's base.js including filename. """ return 'goog.addDependency("%s", %s, %s);' % ( GetRelpath(dep.filename, base_path...
[ "def", "GetDepsLine", "(", "dep", ",", "base_path", ")", ":", "return", "'goog.addDependency(\"%s\", %s, %s);'", "%", "(", "GetRelpath", "(", "dep", ".", "filename", ",", "base_path", ")", ",", "dep", ".", "provides", ",", "dep", ".", "requires", ")" ]
[ 317, 0 ]
[ 325, 70 ]
python
en
['en', 'en', 'en']
True
GetRelpath
(path, start)
Return a relative path to |path| from |start|.
Return a relative path to |path| from |start|.
def GetRelpath(path, start): """Return a relative path to |path| from |start|.""" # NOTE: Python 2.6 provides os.path.relpath, which has almost the same # functionality as this function. Since we want to support 2.4, we have # to implement it manually. :( path_list = os.path.abspath(os.path.normpath(path)).sp...
[ "def", "GetRelpath", "(", "path", ",", "start", ")", ":", "# NOTE: Python 2.6 provides os.path.relpath, which has almost the same", "# functionality as this function. Since we want to support 2.4, we have", "# to implement it manually. :(", "path_list", "=", "os", ".", "path", ".", ...
[ 328, 0 ]
[ 346, 50 ]
python
en
['en', 'en', 'en']
True
PrintDeps
(source_paths, deps, out)
Print out a deps.js file from a list of source paths. Args: source_paths: Paths that we should generate dependency info for. deps: Paths that provide dependency info. Their dependency info should not appear in the deps file. out: The output file. Returns: True on success, false if it was u...
Print out a deps.js file from a list of source paths.
def PrintDeps(source_paths, deps, out): """Print out a deps.js file from a list of source paths. Args: source_paths: Paths that we should generate dependency info for. deps: Paths that provide dependency info. Their dependency info should not appear in the deps file. out: The output file. Re...
[ "def", "PrintDeps", "(", "source_paths", ",", "deps", ",", "out", ")", ":", "base_path", "=", "FindClosureBasePath", "(", "source_paths", "+", "deps", ")", "if", "not", "base_path", ":", "return", "False", "PrintLine", "(", "'// This file was autogenerated by calc...
[ 354, 0 ]
[ 378, 13 ]
python
en
['en', 'en', 'en']
True
GetJavaVersion
()
Returns the string for the current version of Java installed.
Returns the string for the current version of Java installed.
def GetJavaVersion(): """Returns the string for the current version of Java installed.""" proc = subprocess.Popen(['java', '-version'], stderr=subprocess.PIPE) proc.wait() version_line = proc.stderr.read().splitlines()[0] return version_regex.search(version_line.decode('utf-8')).group()
[ "def", "GetJavaVersion", "(", ")", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "'java'", ",", "'-version'", "]", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "proc", ".", "wait", "(", ")", "version_line", "=", "proc", ".", "stderr", ...
[ 389, 0 ]
[ 394, 67 ]
python
en
['en', 'en', 'en']
True
FilterByExcludes
(options, files)
Filters the given files by the exlusions specified at the command line. Args: options: The flags to calcdeps. files: The files to filter. Returns: A list of files.
Filters the given files by the exlusions specified at the command line.
def FilterByExcludes(options, files): """Filters the given files by the exlusions specified at the command line. Args: options: The flags to calcdeps. files: The files to filter. Returns: A list of files. """ excludes = [] if options.excludes: excludes = ExpandDirectories(options.excludes) ...
[ "def", "FilterByExcludes", "(", "options", ",", "files", ")", ":", "excludes", "=", "[", "]", "if", "options", ".", "excludes", ":", "excludes", "=", "ExpandDirectories", "(", "options", ".", "excludes", ")", "excludesSet", "=", "set", "(", "excludes", ")"...
[ 397, 0 ]
[ 411, 51 ]
python
en
['en', 'en', 'en']
True
GetPathsFromOptions
(options)
Generates the path files from flag options. Args: options: The flags to calcdeps. Returns: A list of files in the specified paths. (strings).
Generates the path files from flag options.
def GetPathsFromOptions(options): """Generates the path files from flag options. Args: options: The flags to calcdeps. Returns: A list of files in the specified paths. (strings). """ search_paths = options.paths if not search_paths: search_paths = ['.'] # Add default folder if no path is spec...
[ "def", "GetPathsFromOptions", "(", "options", ")", ":", "search_paths", "=", "options", ".", "paths", "if", "not", "search_paths", ":", "search_paths", "=", "[", "'.'", "]", "# Add default folder if no path is specified.", "search_paths", "=", "ExpandDirectories", "("...
[ 414, 0 ]
[ 428, 48 ]
python
en
['en', 'en', 'en']
True
GetInputsFromOptions
(options)
Generates the inputs from flag options. Args: options: The flags to calcdeps. Returns: A list of inputs (strings).
Generates the inputs from flag options.
def GetInputsFromOptions(options): """Generates the inputs from flag options. Args: options: The flags to calcdeps. Returns: A list of inputs (strings). """ inputs = options.inputs if not inputs: # Parse stdin logging.info('No inputs specified. Reading from stdin...') inputs = filter(None,...
[ "def", "GetInputsFromOptions", "(", "options", ")", ":", "inputs", "=", "options", ".", "inputs", "if", "not", "inputs", ":", "# Parse stdin", "logging", ".", "info", "(", "'No inputs specified. Reading from stdin...'", ")", "inputs", "=", "filter", "(", "None", ...
[ 431, 0 ]
[ 447, 42 ]
python
en
['en', 'en', 'en']
True
Compile
(compiler_jar_path, source_paths, out, flags=None)
Prepares command-line call to Closure compiler. Args: compiler_jar_path: Path to the Closure compiler .jar file. source_paths: Source paths to build, in order. flags: A list of additional flags to pass on to Closure compiler.
Prepares command-line call to Closure compiler.
def Compile(compiler_jar_path, source_paths, out, flags=None): """Prepares command-line call to Closure compiler. Args: compiler_jar_path: Path to the Closure compiler .jar file. source_paths: Source paths to build, in order. flags: A list of additional flags to pass on to Closure compiler. """ arg...
[ "def", "Compile", "(", "compiler_jar_path", ",", "source_paths", ",", "out", ",", "flags", "=", "None", ")", ":", "args", "=", "[", "'java'", ",", "'-jar'", ",", "compiler_jar_path", "]", "for", "path", "in", "source_paths", ":", "args", "+=", "[", "'--j...
[ 450, 0 ]
[ 472, 41 ]
python
en
['en', 'pt', 'en']
True
main
()
The entrypoint for this script.
The entrypoint for this script.
def main(): """The entrypoint for this script.""" logging.basicConfig(format='calcdeps.py: %(message)s', level=logging.INFO) usage = 'usage: %prog [options] arg' parser = optparse.OptionParser(usage) parser.add_option('-i', '--input', dest='inputs', ...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "'calcdeps.py: %(message)s'", ",", "level", "=", "logging", ".", "INFO", ")", "usage", "=", "'usage: %prog [options] arg'", "parser", "=", "optparse", ".", "OptionParser", "(", "u...
[ 475, 0 ]
[ 586, 15 ]
python
en
['en', 'en', 'en']
True
TestSQFlavors.subtest_add2col
(self, xb, xq, index, qname)
Test with 2 additional dimensions to take also the non-SIMD codepath. We don't retrain anything but add 2 dims to the queries, the centroids and the trained ScalarQuantizer.
Test with 2 additional dimensions to take also the non-SIMD codepath. We don't retrain anything but add 2 dims to the queries, the centroids and the trained ScalarQuantizer.
def subtest_add2col(self, xb, xq, index, qname): """Test with 2 additional dimensions to take also the non-SIMD codepath. We don't retrain anything but add 2 dims to the queries, the centroids and the trained ScalarQuantizer. """ nb, d = xb.shape d2 = d + 2 xb2 =...
[ "def", "subtest_add2col", "(", "self", ",", "xb", ",", "xq", ",", "index", ",", "qname", ")", ":", "nb", ",", "d", "=", "xb", ".", "shape", "d2", "=", "d", "+", "2", "xb2", "=", "self", ".", "add2columns", "(", "xb", ")", "xq2", "=", "self", ...
[ 170, 4 ]
[ 207, 37 ]
python
en
['en', 'en', 'en']
True
load_constants
(filename)
Read in constants file, which must be output in every language.
Read in constants file, which must be output in every language.
def load_constants(filename): """Read in constants file, which must be output in every language.""" constant_defs = read_json_file(filename); constants_text = '\n' for key in constant_defs: value = constant_defs[key] value = value.replace('"', '\\"') constants_text += '\nBlockly.Msg["{0}"] = "{1}";'...
[ "def", "load_constants", "(", "filename", ")", ":", "constant_defs", "=", "read_json_file", "(", "filename", ")", "constants_text", "=", "'\\n'", "for", "key", "in", "constant_defs", ":", "value", "=", "constant_defs", "[", "key", "]", "value", "=", "value", ...
[ 37, 0 ]
[ 45, 23 ]
python
en
['en', 'en', 'en']
True
main
()
Generate .js files defining Blockly core and language messages.
Generate .js files defining Blockly core and language messages.
def main(): """Generate .js files defining Blockly core and language messages.""" # Process command-line arguments. parser = argparse.ArgumentParser(description='Convert JSON files to JS.') parser.add_argument('--source_lang', default='en', help='ISO 639-1 source language code') parser....
[ "def", "main", "(", ")", ":", "# Process command-line arguments.", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Convert JSON files to JS.'", ")", "parser", ".", "add_argument", "(", "'--source_lang'", ",", "default", "=", "'en'", ",",...
[ 47, 0 ]
[ 160, 45 ]
python
en
['en', 'en', 'en']
True
MakeDepsFile
(source_map)
Make a generated deps file. Args: source_map: A dict map of the source path to source.Source object. Returns: str, A generated deps file source.
Make a generated deps file.
def MakeDepsFile(source_map): """Make a generated deps file. Args: source_map: A dict map of the source path to source.Source object. Returns: str, A generated deps file source. """ # Write in path alphabetical order paths = sorted(source_map.keys()) lines = [] for path in paths: js_sou...
[ "def", "MakeDepsFile", "(", "source_map", ")", ":", "# Write in path alphabetical order", "paths", "=", "sorted", "(", "source_map", ".", "keys", "(", ")", ")", "lines", "=", "[", "]", "for", "path", "in", "paths", ":", "js_source", "=", "source_map", "[", ...
[ 40, 0 ]
[ 62, 23 ]
python
en
['en', 'en', 'en']
True
_GetDepsLine
(path, js_source)
Get a deps.js file string for a source.
Get a deps.js file string for a source.
def _GetDepsLine(path, js_source): """Get a deps.js file string for a source.""" provides = _ToJsSrc(sorted(js_source.provides)) requires = _ToJsSrc(sorted(js_source.requires)) module = "{'module': 'goog'}" if js_source.is_goog_module else '{}' return 'goog.addDependency(\'%s\', %s, %s, %s);\n' % ( pa...
[ "def", "_GetDepsLine", "(", "path", ",", "js_source", ")", ":", "provides", "=", "_ToJsSrc", "(", "sorted", "(", "js_source", ".", "provides", ")", ")", "requires", "=", "_ToJsSrc", "(", "sorted", "(", "js_source", ".", "requires", ")", ")", "module", "=...
[ 65, 0 ]
[ 73, 39 ]
python
en
['en', 'da', 'en']
True
_ToJsSrc
(arr)
Convert a python arr to a js source string.
Convert a python arr to a js source string.
def _ToJsSrc(arr): """Convert a python arr to a js source string.""" return json.dumps(arr).replace('"', '\'')
[ "def", "_ToJsSrc", "(", "arr", ")", ":", "return", "json", ".", "dumps", "(", "arr", ")", ".", "replace", "(", "'\"'", ",", "'\\''", ")" ]
[ 76, 0 ]
[ 79, 43 ]
python
en
['en', 'lb', 'en']
True
_GetOptionsParser
()
Get the options parser.
Get the options parser.
def _GetOptionsParser(): """Get the options parser.""" parser = optparse.OptionParser(__doc__) parser.add_option('--output_file', dest='output_file', action='store', help=('If specified, write output to this path instead of ' ...
[ "def", "_GetOptionsParser", "(", ")", ":", "parser", "=", "optparse", ".", "OptionParser", "(", "__doc__", ")", "parser", ".", "add_option", "(", "'--output_file'", ",", "dest", "=", "'output_file'", ",", "action", "=", "'store'", ",", "help", "=", "(", "'...
[ 82, 0 ]
[ 117, 15 ]
python
en
['en', 'en', 'en']
True
_NormalizePathSeparators
(path)
Replaces OS-specific path separators with POSIX-style slashes. Args: path: str, A file path. Returns: str, The path with any OS-specific path separators (such as backslash on Windows) replaced with URL-compatible forward slashes. A no-op on systems that use POSIX paths.
Replaces OS-specific path separators with POSIX-style slashes.
def _NormalizePathSeparators(path): """Replaces OS-specific path separators with POSIX-style slashes. Args: path: str, A file path. Returns: str, The path with any OS-specific path separators (such as backslash on Windows) replaced with URL-compatible forward slashes. A no-op on systems that...
[ "def", "_NormalizePathSeparators", "(", "path", ")", ":", "return", "path", ".", "replace", "(", "os", ".", "sep", ",", "posixpath", ".", "sep", ")" ]
[ 120, 0 ]
[ 131, 44 ]
python
en
['en', 'en', 'en']
True
_GetRelativePathToSourceDict
(root, prefix='')
Scans a top root directory for .js sources. Args: root: str, Root directory. prefix: str, Prefix for returned paths. Returns: dict, A map of relative paths (with prefix, if given), to source.Source objects.
Scans a top root directory for .js sources.
def _GetRelativePathToSourceDict(root, prefix=''): """Scans a top root directory for .js sources. Args: root: str, Root directory. prefix: str, Prefix for returned paths. Returns: dict, A map of relative paths (with prefix, if given), to source.Source objects. """ # Remember and restore th...
[ "def", "_GetRelativePathToSourceDict", "(", "root", ",", "prefix", "=", "''", ")", ":", "# Remember and restore the cwd when we're done. We work from the root so", "# that paths are relative from the root.", "start_wd", "=", "os", ".", "getcwd", "(", ")", "os", ".", "chdir"...
[ 134, 0 ]
[ 157, 23 ]
python
en
['en', 'en', 'en']
True
_GetPair
(s)
Return a string as a shell-parsed tuple. Two values expected.
Return a string as a shell-parsed tuple. Two values expected.
def _GetPair(s): """Return a string as a shell-parsed tuple. Two values expected.""" try: # shlex uses '\' as an escape character, so they must be escaped. s = s.replace('\\', '\\\\') first, second = shlex.split(s) return (first, second) except: raise Exception('Unable to parse input line as ...
[ "def", "_GetPair", "(", "s", ")", ":", "try", ":", "# shlex uses '\\' as an escape character, so they must be escaped.", "s", "=", "s", ".", "replace", "(", "'\\\\'", ",", "'\\\\\\\\'", ")", "first", ",", "second", "=", "shlex", ".", "split", "(", "s", ")", ...
[ 160, 0 ]
[ 168, 67 ]
python
en
['en', 'en', 'en']
True
main
()
CLI frontend to MakeDepsFile.
CLI frontend to MakeDepsFile.
def main(): """CLI frontend to MakeDepsFile.""" logging.basicConfig(format=(sys.argv[0] + ': %(message)s'), level=logging.INFO) options, args = _GetOptionsParser().parse_args() path_to_source = {} # Roots without prefixes for root in options.roots: path_to_source.update(_GetRelat...
[ "def", "main", "(", ")", ":", "logging", ".", "basicConfig", "(", "format", "=", "(", "sys", ".", "argv", "[", "0", "]", "+", "': %(message)s'", ")", ",", "level", "=", "logging", ".", "INFO", ")", "options", ",", "args", "=", "_GetOptionsParser", "(...
[ 171, 0 ]
[ 207, 41 ]
python
en
['en', 'en', 'en']
True
Book.__init__
(self)
list to hold books a user creates
list to hold books a user creates
def __init__(self): """ list to hold books a user creates """ pass
[ "def", "__init__", "(", "self", ")", ":", "pass" ]
[ 21, 4 ]
[ 23, 12 ]
python
en
['en', 'en', 'en']
True
User.register
(self, email, password, confirm_password, role)
Create user accounts by user info to empty dictonary
Create user accounts by user info to empty dictonary
def register(self, email, password, confirm_password, role): """ Create user accounts by user info to empty dictonary """ user_dict = {} for user in self.user_list: if email == user['email'] and password == user['password']: response = {"message":"Account already exi...
[ "def", "register", "(", "self", ",", "email", ",", "password", ",", "confirm_password", ",", "role", ")", ":", "user_dict", "=", "{", "}", "for", "user", "in", "self", ".", "user_list", ":", "if", "email", "==", "user", "[", "'email'", "]", "and", "p...
[ 118, 4 ]
[ 144, 23 ]
python
en
['en', 'en', 'en']
True
User.login
(self, email, password)
Login user by checking if user exists in users_list
Login user by checking if user exists in users_list
def login(self, email, password): """ Login user by checking if user exists in users_list """ for user in self.user_list: if email == user['email']: if password == user['password']: response = {"message":"You have successfully logged in...
[ "def", "login", "(", "self", ",", "email", ",", "password", ")", ":", "for", "user", "in", "self", ".", "user_list", ":", "if", "email", "==", "user", "[", "'email'", "]", ":", "if", "password", "==", "user", "[", "'password'", "]", ":", "response", ...
[ 146, 4 ]
[ 160, 23 ]
python
en
['en', 'en', 'en']
True
User.check_email_exists
(self, email)
validates email to avoid two accounts with same user email
validates email to avoid two accounts with same user email
def check_email_exists(self, email): """validates email to avoid two accounts with same user email""" for user in self.user_list: if user.get("email") == email: return True return False
[ "def", "check_email_exists", "(", "self", ",", "email", ")", ":", "for", "user", "in", "self", ".", "user_list", ":", "if", "user", ".", "get", "(", "\"email\"", ")", "==", "email", ":", "return", "True", "return", "False" ]
[ 173, 4 ]
[ 179, 24 ]
python
en
['en', 'en', 'en']
True
encrypt
(self, plaintext=None, key=None, mode=None, iv=None, aad=None, exitcode=0, message=None, step=When)
Execute `encrypt` function with the specified parameters.
Execute `encrypt` function with the specified parameters.
def encrypt(self, plaintext=None, key=None, mode=None, iv=None, aad=None, exitcode=0, message=None, step=When): """Execute `encrypt` function with the specified parameters. """ params = [] if mode is not None: params.append(mode) if plaintext is not None: params.append(plaintext) ...
[ "def", "encrypt", "(", "self", ",", "plaintext", "=", "None", ",", "key", "=", "None", ",", "mode", "=", "None", ",", "iv", "=", "None", ",", "aad", "=", "None", ",", "exitcode", "=", "0", ",", "message", "=", "None", ",", "step", "=", "When", ...
[ 9, 0 ]
[ 26, 91 ]
python
en
['en', 'en', 'en']
True
invalid_parameters
(self)
Check that `encrypt` function returns an error when we call it with invalid parameters.
Check that `encrypt` function returns an error when we call it with invalid parameters.
def invalid_parameters(self): """Check that `encrypt` function returns an error when we call it with invalid parameters. """ with Example("no parameters"): encrypt(exitcode=42, message="DB::Exception: Incorrect number of arguments for function encrypt provided 0, expected 3 to 5") with Exam...
[ "def", "invalid_parameters", "(", "self", ")", ":", "with", "Example", "(", "\"no parameters\"", ")", ":", "encrypt", "(", "exitcode", "=", "42", ",", "message", "=", "\"DB::Exception: Incorrect number of arguments for function encrypt provided 0, expected 3 to 5\"", ")", ...
[ 32, 0 ]
[ 108, 67 ]
python
en
['en', 'en', 'en']
True
invalid_plaintext_data_type
(self, data_type, value)
Check that encrypt function returns an error if the plaintext parameter has invalid data type.
Check that encrypt function returns an error if the plaintext parameter has invalid data type.
def invalid_plaintext_data_type(self, data_type, value): """Check that encrypt function returns an error if the plaintext parameter has invalid data type. """ with When("I try to encrypt plaintext with invalid data type", description=f"{data_type} with value {value}"): encrypt(plaintext=value, k...
[ "def", "invalid_plaintext_data_type", "(", "self", ",", "data_type", ",", "value", ")", ":", "with", "When", "(", "\"I try to encrypt plaintext with invalid data type\"", ",", "description", "=", "f\"{data_type} with value {value}\"", ")", ":", "encrypt", "(", "plaintext"...
[ 139, 0 ]
[ 145, 75 ]
python
en
['en', 'en', 'en']
True
invalid_key_or_iv_length_for_mode_non_gcm
(self, mode, key_len, iv_len, aad)
Check that an error is returned when key or iv length does not match the expected value for the mode.
Check that an error is returned when key or iv length does not match the expected value for the mode.
def invalid_key_or_iv_length_for_mode_non_gcm(self, mode, key_len, iv_len, aad): """Check that an error is returned when key or iv length does not match the expected value for the mode. """ plaintext = "'hello there'" key = "0123456789" * 4 iv = "0123456789" * 4 with When("key is too short"...
[ "def", "invalid_key_or_iv_length_for_mode_non_gcm", "(", "self", ",", "mode", ",", "key_len", ",", "iv_len", ",", "aad", ")", ":", "plaintext", "=", "\"'hello there'\"", "key", "=", "\"0123456789\"", "*", "4", "iv", "=", "\"0123456789\"", "*", "4", "with", "Wh...
[ 176, 0 ]
[ 203, 177 ]
python
en
['en', 'en', 'en']
True
invalid_key_or_iv_length_for_gcm
(self, mode, key_len, iv_len, aad)
Check that an error is returned when key or iv length does not match the expected value for the GCM mode.
Check that an error is returned when key or iv length does not match the expected value for the GCM mode.
def invalid_key_or_iv_length_for_gcm(self, mode, key_len, iv_len, aad): """Check that an error is returned when key or iv length does not match the expected value for the GCM mode. """ plaintext = "'hello there'" key = "0123456789" * 4 iv = "0123456789" * 4 with When("key is too short"): ...
[ "def", "invalid_key_or_iv_length_for_gcm", "(", "self", ",", "mode", ",", "key_len", ",", "iv_len", ",", "aad", ")", ":", "plaintext", "=", "\"'hello there'\"", "key", "=", "\"0123456789\"", "*", "4", "iv", "=", "\"0123456789\"", "*", "4", "with", "When", "(...
[ 218, 0 ]
[ 241, 114 ]
python
en
['en', 'en', 'en']
True
aad_parameter_types_and_length
(self)
Check that `encrypt` function accepts `aad` parameter as the fifth argument of either `String` or `FixedString` types and that the length is not limited.
Check that `encrypt` function accepts `aad` parameter as the fifth argument of either `String` or `FixedString` types and that the length is not limited.
def aad_parameter_types_and_length(self): """Check that `encrypt` function accepts `aad` parameter as the fifth argument of either `String` or `FixedString` types and that the length is not limited. """ plaintext = "'hello there'" iv = "'012345678912'" mode = "'aes-128-gcm'" key = "'01234567...
[ "def", "aad_parameter_types_and_length", "(", "self", ")", ":", "plaintext", "=", "\"'hello there'\"", "iv", "=", "\"'012345678912'\"", "mode", "=", "\"'aes-128-gcm'\"", "key", "=", "\"'0123456789123456'\"", "with", "When", "(", "\"aad is specified using String type\"", "...
[ 248, 0 ]
[ 276, 151 ]
python
en
['en', 'en', 'en']
True
iv_parameter_types
(self)
Check that `encrypt` function accepts `iv` parameter as the fourth argument of either `String` or `FixedString` types.
Check that `encrypt` function accepts `iv` parameter as the fourth argument of either `String` or `FixedString` types.
def iv_parameter_types(self): """Check that `encrypt` function accepts `iv` parameter as the fourth argument of either `String` or `FixedString` types. """ plaintext = "'hello there'" iv = "'0123456789123456'" mode = "'aes-128-cbc'" key = "'0123456789123456'" with When("iv is specified ...
[ "def", "iv_parameter_types", "(", "self", ")", ":", "plaintext", "=", "\"'hello there'\"", "iv", "=", "\"'0123456789123456'\"", "mode", "=", "\"'aes-128-cbc'\"", "key", "=", "\"'0123456789123456'\"", "with", "When", "(", "\"iv is specified using String type\"", ")", ":"...
[ 282, 0 ]
[ 301, 144 ]
python
en
['en', 'en', 'en']
True
key_parameter_types
(self)
Check that `encrypt` function accepts `key` parameter as the second argument of either `String` or `FixedString` types.
Check that `encrypt` function accepts `key` parameter as the second argument of either `String` or `FixedString` types.
def key_parameter_types(self): """Check that `encrypt` function accepts `key` parameter as the second argument of either `String` or `FixedString` types. """ plaintext = "'hello there'" iv = "'0123456789123456'" mode = "'aes-128-cbc'" key = "'0123456789123456'" with When("key is specifi...
[ "def", "key_parameter_types", "(", "self", ")", ":", "plaintext", "=", "\"'hello there'\"", "iv", "=", "\"'0123456789123456'\"", "mode", "=", "\"'aes-128-cbc'\"", "key", "=", "\"'0123456789123456'\"", "with", "When", "(", "\"key is specified using String type\"", ")", "...
[ 307, 0 ]
[ 326, 136 ]
python
en
['en', 'en', 'en']
True
mode_parameter_types
(self)
Check that `encrypt` function accepts `mode` parameter as the third argument of either `String` or `FixedString` types.
Check that `encrypt` function accepts `mode` parameter as the third argument of either `String` or `FixedString` types.
def mode_parameter_types(self): """Check that `encrypt` function accepts `mode` parameter as the third argument of either `String` or `FixedString` types. """ plaintext = "'hello there'" mode = "'aes-128-cbc'" key = "'0123456789123456'" with When("mode is specified using String type"): ...
[ "def", "mode_parameter_types", "(", "self", ")", ":", "plaintext", "=", "\"'hello there'\"", "mode", "=", "\"'aes-128-cbc'\"", "key", "=", "\"'0123456789123456'\"", "with", "When", "(", "\"mode is specified using String type\"", ")", ":", "encrypt", "(", "plaintext", ...
[ 332, 0 ]
[ 344, 124 ]
python
en
['en', 'en', 'en']
True
encryption
(self)
Check that `encrypt` functions accepts `plaintext` as the second parameter with any data type and `mode` as the first parameter.
Check that `encrypt` functions accepts `plaintext` as the second parameter with any data type and `mode` as the first parameter.
def encryption(self): """Check that `encrypt` functions accepts `plaintext` as the second parameter with any data type and `mode` as the first parameter. """ key = f"{'1' * 36}" iv = f"{'2' * 16}" aad = "some random aad" for mode, key_len, iv_len, aad_len in modes: for datatype, pla...
[ "def", "encryption", "(", "self", ")", ":", "key", "=", "f\"{'1' * 36}\"", "iv", "=", "f\"{'2' * 16}\"", "aad", "=", "\"some random aad\"", "for", "mode", ",", "key_len", ",", "iv_len", ",", "aad_len", "in", "modes", ":", "for", "datatype", ",", "plaintext",...
[ 353, 0 ]
[ 371, 133 ]
python
en
['en', 'en', 'en']
True
return_value
(self)
Check that `encrypt` functions returns String data type.
Check that `encrypt` functions returns String data type.
def return_value(self): """Check that `encrypt` functions returns String data type. """ plaintext = "'hello there'" iv = "'0123456789123456'" mode = "'aes-128-cbc'" key = "'0123456789123456'" with When("I get type of the return value"): sql = "SELECT toTypeName(encrypt(" + mode + ",...
[ "def", "return_value", "(", "self", ")", ":", "plaintext", "=", "\"'hello there'\"", "iv", "=", "\"'0123456789123456'\"", "mode", "=", "\"'aes-128-cbc'\"", "key", "=", "\"'0123456789123456'\"", "with", "When", "(", "\"I get type of the return value\"", ")", ":", "sql"...
[ 377, 0 ]
[ 393, 107 ]
python
en
['en', 'en', 'en']
True
syntax
(self)
Check that `encrypt` function supports syntax ```sql encrypt(plaintext, key, mode, [iv, aad]) ```
Check that `encrypt` function supports syntax
def syntax(self): """Check that `encrypt` function supports syntax ```sql encrypt(plaintext, key, mode, [iv, aad]) ``` """ sql = "SELECT hex(encrypt('aes-128-gcm', 'hello there', '0123456789123456', '012345678912', 'AAD'))" self.context.node.query(sql, step=When, message="19A1183335B374C626...
[ "def", "syntax", "(", "self", ")", ":", "sql", "=", "\"SELECT hex(encrypt('aes-128-gcm', 'hello there', '0123456789123456', '012345678912', 'AAD'))\"", "self", ".", "context", ".", "node", ".", "query", "(", "sql", ",", "step", "=", "When", ",", "message", "=", "\"1...
[ 399, 0 ]
[ 407, 109 ]
python
en
['en', 'en', 'en']
True
feature
(self, node="clickhouse1")
Check the behavior of the `encrypt` function.
Check the behavior of the `encrypt` function.
def feature(self, node="clickhouse1"): """Check the behavior of the `encrypt` function. """ self.context.node = self.context.cluster.node(node) for scenario in loads(current_module(), Scenario): Scenario(run=scenario, flags=TE)
[ "def", "feature", "(", "self", ",", "node", "=", "\"clickhouse1\"", ")", ":", "self", ".", "context", ".", "node", "=", "self", ".", "context", ".", "cluster", ".", "node", "(", "node", ")", "for", "scenario", "in", "loads", "(", "current_module", "(",...
[ 414, 0 ]
[ 420, 40 ]
python
en
['en', 'en', 'en']
True
fastai_image_classifier
(image_dir, filenames, labels, output_dir)
This script provides FastAI-compatible training for the input labeled images :param image_dir: directory with images :param filenames: image filenames :param labels: image labels :param output_dir: output directory where results will be exported :return: fastai.basic_train.Learner object
This script provides FastAI-compatible training for the input labeled images :param image_dir: directory with images :param filenames: image filenames :param labels: image labels :param output_dir: output directory where results will be exported :return: fastai.basic_train.Learner object
def fastai_image_classifier(image_dir, filenames, labels, output_dir): """ This script provides FastAI-compatible training for the input labeled images :param image_dir: directory with images :param filenames: image filenames :param labels: image labels :param output_dir: output directory where ...
[ "def", "fastai_image_classifier", "(", "image_dir", ",", "filenames", ",", "labels", ",", "output_dir", ")", ":", "tfms", "=", "get_transforms", "(", ")", "data", "=", "ImageDataBunch", ".", "from_lists", "(", "Path", "(", "image_dir", ")", ",", "filenames", ...
[ 7, 0 ]
[ 27, 16 ]
python
en
['en', 'error', 'th']
False
read_glove_vecs
(glove_file)
read gloveVec file, initial encoding
read gloveVec file, initial encoding
def read_glove_vecs(glove_file): """ read gloveVec file, initial encoding """ with open(glove_file, 'r', encoding='UTF-8') as f: words = set() word_to_vec_map = {} for line in f: line = line.strip().split() curr_word = line[0] words.add(curr_wo...
[ "def", "read_glove_vecs", "(", "glove_file", ")", ":", "with", "open", "(", "glove_file", ",", "'r'", ",", "encoding", "=", "'UTF-8'", ")", "as", "f", ":", "words", "=", "set", "(", ")", "word_to_vec_map", "=", "{", "}", "for", "line", "in", "f", ":"...
[ 17, 0 ]
[ 37, 58 ]
python
en
['en', 'error', 'th']
False
softmax
(x)
Compute softmax values for each sets of scores in x.
Compute softmax values for each sets of scores in x.
def softmax(x): """Compute softmax values for each sets of scores in x.""" e_x = np.exp(x - np.max(x)) return e_x / e_x.sum()
[ "def", "softmax", "(", "x", ")", ":", "e_x", "=", "np", ".", "exp", "(", "x", "-", "np", ".", "max", "(", "x", ")", ")", "return", "e_x", "/", "e_x", ".", "sum", "(", ")" ]
[ 40, 0 ]
[ 43, 26 ]
python
en
['en', 'en', 'en']
True
label_to_emoji
(label)
Converts a label (int or string) into the corresponding emoji code (string) ready to be printed
Converts a label (int or string) into the corresponding emoji code (string) ready to be printed
def label_to_emoji(label): """ Converts a label (int or string) into the corresponding emoji code (string) ready to be printed """ return emoji.emojize(emoji_dictionary[str(label)], use_aliases=True)
[ "def", "label_to_emoji", "(", "label", ")", ":", "return", "emoji", ".", "emojize", "(", "emoji_dictionary", "[", "str", "(", "label", ")", "]", ",", "use_aliases", "=", "True", ")" ]
[ 75, 0 ]
[ 80, 72 ]
python
en
['en', 'error', 'th']
False
plot_confusion_matrix
(y_actu, y_pred, title='Confusion matrix', cmap=plt.cm.gray_r)
plot the confusion matrix
plot the confusion matrix
def plot_confusion_matrix(y_actu, y_pred, title='Confusion matrix', cmap=plt.cm.gray_r): """ plot the confusion matrix """
[ "def", "plot_confusion_matrix", "(", "y_actu", ",", "y_pred", ",", "title", "=", "'Confusion matrix'", ",", "cmap", "=", "plt", ".", "cm", ".", "gray_r", ")", ":" ]
[ 89, 0 ]
[ 92, 3 ]
python
en
['en', 'error', 'th']
False
predict
(X, Y, W, b, word_to_vec_map)
Given X (sentences) and Y (emoji indices), predict emojis and compute the accuracy of your model over the given set. Arguments: X -- input data containing sentences, numpy array of shape (m, None) Y -- labels, containing index of the label emoji, numpy array of shape (m, 1) Returns: pred ...
Given X (sentences) and Y (emoji indices), predict emojis and compute the accuracy of your model over the given set.
def predict(X, Y, W, b, word_to_vec_map): """ Given X (sentences) and Y (emoji indices), predict emojis and compute the accuracy of your model over the given set. Arguments: X -- input data containing sentences, numpy array of shape (m, None) Y -- labels, containing index of the label emoji, nu...
[ "def", "predict", "(", "X", ",", "Y", ",", "W", ",", "b", ",", "word_to_vec_map", ")", ":", "m", "=", "X", ".", "shape", "[", "0", "]", "pred", "=", "np", ".", "zeros", "(", "(", "m", ",", "1", ")", ")", "for", "j", "in", "range", "(", "m...
[ 108, 0 ]
[ 141, 15 ]
python
en
['en', 'error', 'th']
False
sentence_to_avg
(sentence, word_to_vec_map)
Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: sentence -- string, one training example from X word_to_vec_map -- dictionary mapping every w...
Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence.
def sentence_to_avg(sentence, word_to_vec_map): """ Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence. Arguments: sentence -- string, one training example f...
[ "def", "sentence_to_avg", "(", "sentence", ",", "word_to_vec_map", ")", ":", "# Step 1: Split sentence into list of lower case words (≈ 1 line)", "words", "=", "(", "sentence", ".", "lower", "(", ")", ")", ".", "split", "(", ")", "# Initialize the average word vector, sho...
[ 166, 0 ]
[ 193, 14 ]
python
en
['en', 'error', 'th']
False
model
(X, Y, word_to_vec_map, learning_rate=0.01, num_iterations=400)
Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-d...
Model to train word vector representations in numpy.
def model(X, Y, word_to_vec_map, learning_rate=0.01, num_iterations=400): """ Model to train word vector representations in numpy. Arguments: X -- input data, numpy array of sentences as strings, of shape (m, 1) Y -- labels, numpy array of integers between 0 and 7, numpy-array of shape (m, 1) w...
[ "def", "model", "(", "X", ",", "Y", ",", "word_to_vec_map", ",", "learning_rate", "=", "0.01", ",", "num_iterations", "=", "400", ")", ":", "np", ".", "random", ".", "seed", "(", "1", ")", "# Define number of training examples", "m", "=", "Y", ".", "shap...
[ 200, 0 ]
[ 259, 21 ]
python
en
['en', 'error', 'th']
False
sentences_to_indices
(X, word_to_index, max_len)
Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). Arguments: X -- array of sentences (strings), of shape (m, 1) word_to_index -- a dictionary cont...
Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4).
def sentences_to_indices(X, word_to_index, max_len): """ Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4). Arguments: X -- array of sentences (stri...
[ "def", "sentences_to_indices", "(", "X", ",", "word_to_index", ",", "max_len", ")", ":", "m", "=", "X", ".", "shape", "[", "0", "]", "# number of training examples", "# Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line)", "X_indices", "=", "n...
[ 317, 0 ]
[ 352, 20 ]
python
en
['en', 'error', 'th']
False
pretrained_embedding_layer
(word_to_vec_map, word_to_index)
Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to their indices in the vocabulary (400,001 words) Returns: embe...
Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors.
def pretrained_embedding_layer(word_to_vec_map, word_to_index): """ Creates a Keras Embedding() layer and loads in pre-trained GloVe 50-dimensional vectors. Arguments: word_to_vec_map -- dictionary mapping words to their GloVe vector representation. word_to_index -- dictionary mapping from words to...
[ "def", "pretrained_embedding_layer", "(", "word_to_vec_map", ",", "word_to_index", ")", ":", "vocab_len", "=", "len", "(", "word_to_index", ")", "+", "1", "# adding 1 to fit Keras embedding (requirement)", "emb_dim", "=", "word_to_vec_map", "[", "\"cucumber\"", "]", "."...
[ 355, 0 ]
[ 391, 26 ]
python
en
['en', 'error', 'th']
False
Emojify_V2
(input_shape, word_to_vec_map, word_to_index)
Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_to_index -- dictionary mapping from words to their indices in the...
Function creating the Emojify-v2 model's graph.
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_t...
[ "def", "Emojify_V2", "(", "input_shape", ",", "word_to_vec_map", ",", "word_to_index", ")", ":", "# Define sentence_indices as the input of the graph,", "# it should be of shape input_shape and dtype 'int32' (as it contains indices).", "sentence_indices", "=", "Input", "(", "shape", ...
[ 398, 0 ]
[ 440, 16 ]
python
en
['en', 'error', 'th']
False
privilege_granted_directly_or_via_role
(self, table_type, node=None)
Check that user is only able to execute TRUNCATE when they have required privilege, either directly or via role.
Check that user is only able to execute TRUNCATE when they have required privilege, either directly or via role.
def privilege_granted_directly_or_via_role(self, table_type, node=None): """Check that user is only able to execute TRUNCATE when they have required privilege, either directly or via role. """ role_name = f"role_{getuid()}" user_name = f"user_{getuid()}" if node is None: node = self.context...
[ "def", "privilege_granted_directly_or_via_role", "(", "self", ",", "table_type", ",", "node", "=", "None", ")", ":", "role_name", "=", "f\"role_{getuid()}\"", "user_name", "=", "f\"user_{getuid()}\"", "if", "node", "is", "None", ":", "node", "=", "self", ".", "c...
[ 5, 0 ]
[ 27, 115 ]
python
en
['en', 'en', 'en']
True
privilege_check
(grant_target_name, user_name, table_type, node=None)
Run scenarios to check the user's access with different privileges.
Run scenarios to check the user's access with different privileges.
def privilege_check(grant_target_name, user_name, table_type, node=None): """Run scenarios to check the user's access with different privileges. """ exitcode, message = errors.not_enough_privileges(name=f"{user_name}") with Scenario("user without privilege"): table_name = f"merge_tree_{getuid()...
[ "def", "privilege_check", "(", "grant_target_name", ",", "user_name", ",", "table_type", ",", "node", "=", "None", ")", ":", "exitcode", ",", "message", "=", "errors", ".", "not_enough_privileges", "(", "name", "=", "f\"{user_name}\"", ")", "with", "Scenario", ...
[ 29, 0 ]
[ 113, 92 ]
python
en
['en', 'en', 'en']
True