partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
train
Superset.sync_druid_source
Syncs the druid datasource in main db with the provided config. The endpoint takes 3 arguments: user - user name to perform the operation as cluster - name of the druid cluster config - configuration stored in json that contains: name: druid datasource name ...
superset/views/core.py
def sync_druid_source(self): """Syncs the druid datasource in main db with the provided config. The endpoint takes 3 arguments: user - user name to perform the operation as cluster - name of the druid cluster config - configuration stored in json that contains: ...
def sync_druid_source(self): """Syncs the druid datasource in main db with the provided config. The endpoint takes 3 arguments: user - user name to perform the operation as cluster - name of the druid cluster config - configuration stored in json that contains: ...
[ "Syncs", "the", "druid", "datasource", "in", "main", "db", "with", "the", "provided", "config", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2257-L2304
[ "def", "sync_druid_source", "(", "self", ")", ":", "payload", "=", "request", ".", "get_json", "(", "force", "=", "True", ")", "druid_config", "=", "payload", "[", "'config'", "]", "user_name", "=", "payload", "[", "'user'", "]", "cluster_name", "=", "payl...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.cache_key_exist
Returns if a key from cache exist
superset/views/core.py
def cache_key_exist(self, key): """Returns if a key from cache exist""" key_exist = True if cache.get(key) else False status = 200 if key_exist else 404 return json_success(json.dumps({'key_exist': key_exist}), status=status)
def cache_key_exist(self, key): """Returns if a key from cache exist""" key_exist = True if cache.get(key) else False status = 200 if key_exist else 404 return json_success(json.dumps({'key_exist': key_exist}), status=status)
[ "Returns", "if", "a", "key", "from", "cache", "exist" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2455-L2460
[ "def", "cache_key_exist", "(", "self", ",", "key", ")", ":", "key_exist", "=", "True", "if", "cache", ".", "get", "(", "key", ")", "else", "False", "status", "=", "200", "if", "key_exist", "else", "404", "return", "json_success", "(", "json", ".", "dum...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.results
Serves a key off of the results backend
superset/views/core.py
def results(self, key): """Serves a key off of the results backend""" if not results_backend: return json_error_response("Results backend isn't configured") read_from_results_backend_start = now_as_float() blob = results_backend.get(key) stats_logger.timing( ...
def results(self, key): """Serves a key off of the results backend""" if not results_backend: return json_error_response("Results backend isn't configured") read_from_results_backend_start = now_as_float() blob = results_backend.get(key) stats_logger.timing( ...
[ "Serves", "a", "key", "off", "of", "the", "results", "backend" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2465-L2501
[ "def", "results", "(", "self", ",", "key", ")", ":", "if", "not", "results_backend", ":", "return", "json_error_response", "(", "\"Results backend isn't configured\"", ")", "read_from_results_backend_start", "=", "now_as_float", "(", ")", "blob", "=", "results_backend...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.sql_json
Runs arbitrary sql and returns and json
superset/views/core.py
def sql_json(self): """Runs arbitrary sql and returns and json""" async_ = request.form.get('runAsync') == 'true' sql = request.form.get('sql') database_id = request.form.get('database_id') schema = request.form.get('schema') or None template_params = json.loads( ...
def sql_json(self): """Runs arbitrary sql and returns and json""" async_ = request.form.get('runAsync') == 'true' sql = request.form.get('sql') database_id = request.form.get('database_id') schema = request.form.get('schema') or None template_params = json.loads( ...
[ "Runs", "arbitrary", "sql", "and", "returns", "and", "json" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2522-L2649
[ "def", "sql_json", "(", "self", ")", ":", "async_", "=", "request", ".", "form", ".", "get", "(", "'runAsync'", ")", "==", "'true'", "sql", "=", "request", ".", "form", ".", "get", "(", "'sql'", ")", "database_id", "=", "request", ".", "form", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.csv
Download the query results as csv.
superset/views/core.py
def csv(self, client_id): """Download the query results as csv.""" logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rejected...
def csv(self, client_id): """Download the query results as csv.""" logging.info('Exporting CSV file [{}]'.format(client_id)) query = ( db.session.query(Query) .filter_by(client_id=client_id) .one() ) rejected_tables = security_manager.rejected...
[ "Download", "the", "query", "results", "as", "csv", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2654-L2692
[ "def", "csv", "(", "self", ",", "client_id", ")", ":", "logging", ".", "info", "(", "'Exporting CSV file [{}]'", ".", "format", "(", "client_id", ")", ")", "query", "=", "(", "db", ".", "session", ".", "query", "(", "Query", ")", ".", "filter_by", "(",...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.queries
Get the updated queries.
superset/views/core.py
def queries(self, last_updated_ms): """Get the updated queries.""" stats_logger.incr('queries') if not g.user.get_id(): return json_error_response( 'Please login to access the queries.', status=403) # Unix time, milliseconds. last_updated_ms_int = int...
def queries(self, last_updated_ms): """Get the updated queries.""" stats_logger.incr('queries') if not g.user.get_id(): return json_error_response( 'Please login to access the queries.', status=403) # Unix time, milliseconds. last_updated_ms_int = int...
[ "Get", "the", "updated", "queries", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2714-L2766
[ "def", "queries", "(", "self", ",", "last_updated_ms", ")", ":", "stats_logger", ".", "incr", "(", "'queries'", ")", "if", "not", "g", ".", "user", ".", "get_id", "(", ")", ":", "return", "json_error_response", "(", "'Please login to access the queries.'", ","...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.search_queries
Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with list of sql query dicts
superset/views/core.py
def search_queries(self) -> Response: """ Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with ...
def search_queries(self) -> Response: """ Search for previously run sqllab queries. Used for Sqllab Query Search page /superset/sqllab#search. Custom permission can_only_search_queries_owned restricts queries to only queries run by current user. :returns: Response with ...
[ "Search", "for", "previously", "run", "sqllab", "queries", ".", "Used", "for", "Sqllab", "Query", "Search", "page", "/", "superset", "/", "sqllab#search", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2771-L2828
[ "def", "search_queries", "(", "self", ")", "->", "Response", ":", "query", "=", "db", ".", "session", ".", "query", "(", "Query", ")", "if", "security_manager", ".", "can_only_access_owned_queries", "(", ")", ":", "search_user_id", "=", "g", ".", "user", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.welcome
Personalized welcome page
superset/views/core.py
def welcome(self): """Personalized welcome page""" if not g.user or not g.user.get_id(): return redirect(appbuilder.get_url_for_login) welcome_dashboard_id = ( db.session .query(UserAttribute.welcome_dashboard_id) .filter_by(user_id=g.user.get_id(...
def welcome(self): """Personalized welcome page""" if not g.user or not g.user.get_id(): return redirect(appbuilder.get_url_for_login) welcome_dashboard_id = ( db.session .query(UserAttribute.welcome_dashboard_id) .filter_by(user_id=g.user.get_id(...
[ "Personalized", "welcome", "page" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2838-L2862
[ "def", "welcome", "(", "self", ")", ":", "if", "not", "g", ".", "user", "or", "not", "g", ".", "user", ".", "get_id", "(", ")", ":", "return", "redirect", "(", "appbuilder", ".", "get_url_for_login", ")", "welcome_dashboard_id", "=", "(", "db", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.profile
User profile page
superset/views/core.py
def profile(self, username): """User profile page""" if not username and g.user: username = g.user.username payload = { 'user': bootstrap_user_data(username, include_perms=True), 'common': self.common_bootsrap_payload(), } return self.render_...
def profile(self, username): """User profile page""" if not username and g.user: username = g.user.username payload = { 'user': bootstrap_user_data(username, include_perms=True), 'common': self.common_bootsrap_payload(), } return self.render_...
[ "User", "profile", "page" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2866-L2881
[ "def", "profile", "(", "self", ",", "username", ")", ":", "if", "not", "username", "and", "g", ".", "user", ":", "username", "=", "g", ".", "user", ".", "username", "payload", "=", "{", "'user'", ":", "bootstrap_user_data", "(", "username", ",", "inclu...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.sqllab
SQL Editor
superset/views/core.py
def sqllab(self): """SQL Editor""" d = { 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'), 'common': self.common_bootsrap_payload(), } return self.render_template( 'superset/basic.html', entry='sqllab', bootstrap_data=json.dumps...
def sqllab(self): """SQL Editor""" d = { 'defaultDbId': config.get('SQLLAB_DEFAULT_DBID'), 'common': self.common_bootsrap_payload(), } return self.render_template( 'superset/basic.html', entry='sqllab', bootstrap_data=json.dumps...
[ "SQL", "Editor" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2885-L2895
[ "def", "sqllab", "(", "self", ")", ":", "d", "=", "{", "'defaultDbId'", ":", "config", ".", "get", "(", "'SQLLAB_DEFAULT_DBID'", ")", ",", "'common'", ":", "self", ".", "common_bootsrap_payload", "(", ")", ",", "}", "return", "self", ".", "render_template"...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.slice_query
This method exposes an API endpoint to get the database query string for this slice
superset/views/core.py
def slice_query(self, slice_id): """ This method exposes an API endpoint to get the database query string for this slice """ viz_obj = get_viz(slice_id) security_manager.assert_datasource_permission(viz_obj.datasource) return self.get_query_string_response(viz_obj...
def slice_query(self, slice_id): """ This method exposes an API endpoint to get the database query string for this slice """ viz_obj = get_viz(slice_id) security_manager.assert_datasource_permission(viz_obj.datasource) return self.get_query_string_response(viz_obj...
[ "This", "method", "exposes", "an", "API", "endpoint", "to", "get", "the", "database", "query", "string", "for", "this", "slice" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2901-L2908
[ "def", "slice_query", "(", "self", ",", "slice_id", ")", ":", "viz_obj", "=", "get_viz", "(", "slice_id", ")", "security_manager", ".", "assert_datasource_permission", "(", "viz_obj", ".", "datasource", ")", "return", "self", ".", "get_query_string_response", "(",...
ca2996c78f679260eb79c6008e276733df5fb653
train
Superset.schemas_access_for_csv_upload
This method exposes an API endpoint to get the schema access control settings for csv upload in this database
superset/views/core.py
def schemas_access_for_csv_upload(self): """ This method exposes an API endpoint to get the schema access control settings for csv upload in this database """ if not request.args.get('db_id'): return json_error_response( 'No database is allowed for you...
def schemas_access_for_csv_upload(self): """ This method exposes an API endpoint to get the schema access control settings for csv upload in this database """ if not request.args.get('db_id'): return json_error_response( 'No database is allowed for you...
[ "This", "method", "exposes", "an", "API", "endpoint", "to", "get", "the", "schema", "access", "control", "settings", "for", "csv", "upload", "in", "this", "database" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/core.py#L2913-L2946
[ "def", "schemas_access_for_csv_upload", "(", "self", ")", ":", "if", "not", "request", ".", "args", ".", "get", "(", "'db_id'", ")", ":", "return", "json_error_response", "(", "'No database is allowed for your csv upload'", ")", "db_id", "=", "int", "(", "request"...
ca2996c78f679260eb79c6008e276733df5fb653
train
stats_timing
Provide a transactional scope around a series of operations.
superset/utils/decorators.py
def stats_timing(stats_key, stats_logger): """Provide a transactional scope around a series of operations.""" start_ts = now_as_float() try: yield start_ts except Exception as e: raise e finally: stats_logger.timing(stats_key, now_as_float() - start_ts)
def stats_timing(stats_key, stats_logger): """Provide a transactional scope around a series of operations.""" start_ts = now_as_float() try: yield start_ts except Exception as e: raise e finally: stats_logger.timing(stats_key, now_as_float() - start_ts)
[ "Provide", "a", "transactional", "scope", "around", "a", "series", "of", "operations", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/decorators.py#L35-L43
[ "def", "stats_timing", "(", "stats_key", ",", "stats_logger", ")", ":", "start_ts", "=", "now_as_float", "(", ")", "try", ":", "yield", "start_ts", "except", "Exception", "as", "e", ":", "raise", "e", "finally", ":", "stats_logger", ".", "timing", "(", "st...
ca2996c78f679260eb79c6008e276733df5fb653
train
etag_cache
A decorator for caching views and handling etag conditional requests. The decorator adds headers to GET requests that help with caching: Last- Modified, Expires and ETag. It also handles conditional requests, when the client send an If-Matches header. If a cache is set, the decorator will cache GET re...
superset/utils/decorators.py
def etag_cache(max_age, check_perms=bool): """ A decorator for caching views and handling etag conditional requests. The decorator adds headers to GET requests that help with caching: Last- Modified, Expires and ETag. It also handles conditional requests, when the client send an If-Matches header. ...
def etag_cache(max_age, check_perms=bool): """ A decorator for caching views and handling etag conditional requests. The decorator adds headers to GET requests that help with caching: Last- Modified, Expires and ETag. It also handles conditional requests, when the client send an If-Matches header. ...
[ "A", "decorator", "for", "caching", "views", "and", "handling", "etag", "conditional", "requests", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/decorators.py#L46-L118
[ "def", "etag_cache", "(", "max_age", ",", "check_perms", "=", "bool", ")", ":", "def", "decorator", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# check if the user can access ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseEngineSpec.apply_limit_to_sql
Alters the SQL statement to apply a LIMIT clause
superset/db_engine_specs.py
def apply_limit_to_sql(cls, sql, limit, database): """Alters the SQL statement to apply a LIMIT clause""" if cls.limit_method == LimitMethod.WRAP_SQL: sql = sql.strip('\t\n ;') qry = ( select('*') .select_from( TextAsFrom(text(s...
def apply_limit_to_sql(cls, sql, limit, database): """Alters the SQL statement to apply a LIMIT clause""" if cls.limit_method == LimitMethod.WRAP_SQL: sql = sql.strip('\t\n ;') qry = ( select('*') .select_from( TextAsFrom(text(s...
[ "Alters", "the", "SQL", "statement", "to", "apply", "a", "LIMIT", "clause" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L183-L198
[ "def", "apply_limit_to_sql", "(", "cls", ",", "sql", ",", "limit", ",", "database", ")", ":", "if", "cls", ".", "limit_method", "==", "LimitMethod", ".", "WRAP_SQL", ":", "sql", "=", "sql", ".", "strip", "(", "'\\t\\n ;'", ")", "qry", "=", "(", "select...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseEngineSpec.modify_url_for_impersonation
Modify the SQL Alchemy URL object with the user to impersonate if applicable. :param url: SQLAlchemy URL object :param impersonate_user: Bool indicating if impersonation is enabled :param username: Effective username
superset/db_engine_specs.py
def modify_url_for_impersonation(cls, url, impersonate_user, username): """ Modify the SQL Alchemy URL object with the user to impersonate if applicable. :param url: SQLAlchemy URL object :param impersonate_user: Bool indicating if impersonation is enabled :param username: Effect...
def modify_url_for_impersonation(cls, url, impersonate_user, username): """ Modify the SQL Alchemy URL object with the user to impersonate if applicable. :param url: SQLAlchemy URL object :param impersonate_user: Bool indicating if impersonation is enabled :param username: Effect...
[ "Modify", "the", "SQL", "Alchemy", "URL", "object", "with", "the", "user", "to", "impersonate", "if", "applicable", ".", ":", "param", "url", ":", "SQLAlchemy", "URL", "object", ":", "param", "impersonate_user", ":", "Bool", "indicating", "if", "impersonation"...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L395-L403
[ "def", "modify_url_for_impersonation", "(", "cls", ",", "url", ",", "impersonate_user", ",", "username", ")", ":", "if", "impersonate_user", "is", "not", "None", "and", "username", "is", "not", "None", ":", "url", ".", "username", "=", "username" ]
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseEngineSpec.make_label_compatible
Conditionally mutate and/or quote a sql column/expression label. If force_column_alias_quotes is set to True, return the label as a sqlalchemy.sql.elements.quoted_name object to ensure that the select query and query results have same case. Otherwise return the mutated label as a regular...
superset/db_engine_specs.py
def make_label_compatible(cls, label): """ Conditionally mutate and/or quote a sql column/expression label. If force_column_alias_quotes is set to True, return the label as a sqlalchemy.sql.elements.quoted_name object to ensure that the select query and query results have same ca...
def make_label_compatible(cls, label): """ Conditionally mutate and/or quote a sql column/expression label. If force_column_alias_quotes is set to True, return the label as a sqlalchemy.sql.elements.quoted_name object to ensure that the select query and query results have same ca...
[ "Conditionally", "mutate", "and", "/", "or", "quote", "a", "sql", "column", "/", "expression", "label", ".", "If", "force_column_alias_quotes", "is", "set", "to", "True", "return", "the", "label", "as", "a", "sqlalchemy", ".", "sql", ".", "elements", ".", ...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L424-L438
[ "def", "make_label_compatible", "(", "cls", ",", "label", ")", ":", "label_mutated", "=", "cls", ".", "mutate_label", "(", "label", ")", "if", "cls", ".", "max_column_name_length", "and", "len", "(", "label_mutated", ")", ">", "cls", ".", "max_column_name_leng...
ca2996c78f679260eb79c6008e276733df5fb653
train
BaseEngineSpec.truncate_label
In the case that a label exceeds the max length supported by the engine, this method is used to construct a deterministic and unique label based on an md5 hash.
superset/db_engine_specs.py
def truncate_label(cls, label): """ In the case that a label exceeds the max length supported by the engine, this method is used to construct a deterministic and unique label based on an md5 hash. """ label = hashlib.md5(label.encode('utf-8')).hexdigest() # trunca...
def truncate_label(cls, label): """ In the case that a label exceeds the max length supported by the engine, this method is used to construct a deterministic and unique label based on an md5 hash. """ label = hashlib.md5(label.encode('utf-8')).hexdigest() # trunca...
[ "In", "the", "case", "that", "a", "label", "exceeds", "the", "max", "length", "supported", "by", "the", "engine", "this", "method", "is", "used", "to", "construct", "a", "deterministic", "and", "unique", "label", "based", "on", "an", "md5", "hash", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L463-L473
[ "def", "truncate_label", "(", "cls", ",", "label", ")", ":", "label", "=", "hashlib", ".", "md5", "(", "label", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "# truncate hash if it exceeds max length", "if", "cls", ".", "max_column_nam...
ca2996c78f679260eb79c6008e276733df5fb653
train
PostgresEngineSpec.get_table_names
Need to consider foreign tables for PostgreSQL
superset/db_engine_specs.py
def get_table_names(cls, inspector, schema): """Need to consider foreign tables for PostgreSQL""" tables = inspector.get_table_names(schema) tables.extend(inspector.get_foreign_table_names(schema)) return sorted(tables)
def get_table_names(cls, inspector, schema): """Need to consider foreign tables for PostgreSQL""" tables = inspector.get_table_names(schema) tables.extend(inspector.get_foreign_table_names(schema)) return sorted(tables)
[ "Need", "to", "consider", "foreign", "tables", "for", "PostgreSQL" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L522-L526
[ "def", "get_table_names", "(", "cls", ",", "inspector", ",", "schema", ")", ":", "tables", "=", "inspector", ".", "get_table_names", "(", "schema", ")", "tables", ".", "extend", "(", "inspector", ".", "get_foreign_table_names", "(", "schema", ")", ")", "retu...
ca2996c78f679260eb79c6008e276733df5fb653
train
PostgresEngineSpec.get_timestamp_column
Postgres is unable to identify mixed case column names unless they are quoted.
superset/db_engine_specs.py
def get_timestamp_column(expression, column_name): """Postgres is unable to identify mixed case column names unless they are quoted.""" if expression: return expression elif column_name.lower() != column_name: return f'"{column_name}"' return column_name
def get_timestamp_column(expression, column_name): """Postgres is unable to identify mixed case column names unless they are quoted.""" if expression: return expression elif column_name.lower() != column_name: return f'"{column_name}"' return column_name
[ "Postgres", "is", "unable", "to", "identify", "mixed", "case", "column", "names", "unless", "they", "are", "quoted", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L529-L536
[ "def", "get_timestamp_column", "(", "expression", ",", "column_name", ")", ":", "if", "expression", ":", "return", "expression", "elif", "column_name", ".", "lower", "(", ")", "!=", "column_name", ":", "return", "f'\"{column_name}\"'", "return", "column_name" ]
ca2996c78f679260eb79c6008e276733df5fb653
train
MySQLEngineSpec.extract_error_message
Extract error message for queries
superset/db_engine_specs.py
def extract_error_message(cls, e): """Extract error message for queries""" message = str(e) try: if isinstance(e.args, tuple) and len(e.args) > 1: message = e.args[1] except Exception: pass return message
def extract_error_message(cls, e): """Extract error message for queries""" message = str(e) try: if isinstance(e.args, tuple) and len(e.args) > 1: message = e.args[1] except Exception: pass return message
[ "Extract", "error", "message", "for", "queries" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L775-L783
[ "def", "extract_error_message", "(", "cls", ",", "e", ")", ":", "message", "=", "str", "(", "e", ")", "try", ":", "if", "isinstance", "(", "e", ".", "args", ",", "tuple", ")", "and", "len", "(", "e", ".", "args", ")", ">", "1", ":", "message", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
PrestoEngineSpec.fetch_result_sets
Returns a list of tables [schema1.table1, schema2.table2, ...] Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>.
superset/db_engine_specs.py
def fetch_result_sets(cls, db, datasource_type): """Returns a list of tables [schema1.table1, schema2.table2, ...] Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ res...
def fetch_result_sets(cls, db, datasource_type): """Returns a list of tables [schema1.table1, schema2.table2, ...] Datasource_type can be 'table' or 'view'. Empty schema corresponds to the list of full names of the all tables or views: <schema>.<result_set_name>. """ res...
[ "Returns", "a", "list", "of", "tables", "[", "schema1", ".", "table1", "schema2", ".", "table2", "...", "]" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L844-L861
[ "def", "fetch_result_sets", "(", "cls", ",", "db", ",", "datasource_type", ")", ":", "result_set_df", "=", "db", ".", "get_df", "(", "\"\"\"SELECT table_schema, table_name FROM INFORMATION_SCHEMA.{}S\n ORDER BY concat(table_schema, '.', table_name)\"\"\"", ".", "for...
ca2996c78f679260eb79c6008e276733df5fb653
train
PrestoEngineSpec.handle_cursor
Updates progress information
superset/db_engine_specs.py
def handle_cursor(cls, cursor, query, session): """Updates progress information""" logging.info('Polling the cursor for progress') polled = cursor.poll() # poll returns dict -- JSON status information or ``None`` # if the query is done # https://github.com/dropbox/PyHive/...
def handle_cursor(cls, cursor, query, session): """Updates progress information""" logging.info('Polling the cursor for progress') polled = cursor.poll() # poll returns dict -- JSON status information or ``None`` # if the query is done # https://github.com/dropbox/PyHive/...
[ "Updates", "progress", "information" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L884-L920
[ "def", "handle_cursor", "(", "cls", ",", "cursor", ",", "query", ",", "session", ")", ":", "logging", ".", "info", "(", "'Polling the cursor for progress'", ")", "polled", "=", "cursor", ".", "poll", "(", ")", "# poll returns dict -- JSON status information or ``Non...
ca2996c78f679260eb79c6008e276733df5fb653
train
PrestoEngineSpec._partition_query
Returns a partition query :param table_name: the name of the table to get partitions from :type table_name: str :param limit: the number of partitions to be returned :type limit: int :param order_by: a list of tuples of field name and a boolean that determines if tha...
superset/db_engine_specs.py
def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): """Returns a partition query :param table_name: the name of the table to get partitions from :type table_name: str :param limit: the number of partitions to be returned :type limit: int ...
def _partition_query( cls, table_name, limit=0, order_by=None, filters=None): """Returns a partition query :param table_name: the name of the table to get partitions from :type table_name: str :param limit: the number of partitions to be returned :type limit: int ...
[ "Returns", "a", "partition", "query" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L944-L980
[ "def", "_partition_query", "(", "cls", ",", "table_name", ",", "limit", "=", "0", ",", "order_by", "=", "None", ",", "filters", "=", "None", ")", ":", "limit_clause", "=", "'LIMIT {}'", ".", "format", "(", "limit", ")", "if", "limit", "else", "''", "or...
ca2996c78f679260eb79c6008e276733df5fb653
train
HiveEngineSpec.create_table_from_csv
Uploads a csv file and creates a superset datasource in Hive.
superset/db_engine_specs.py
def create_table_from_csv(form, table): """Uploads a csv file and creates a superset datasource in Hive.""" def convert_to_hive_type(col_type): """maps tableschema's types to hive types""" tableschema_to_hive_types = { 'boolean': 'BOOLEAN', 'intege...
def create_table_from_csv(form, table): """Uploads a csv file and creates a superset datasource in Hive.""" def convert_to_hive_type(col_type): """maps tableschema's types to hive types""" tableschema_to_hive_types = { 'boolean': 'BOOLEAN', 'intege...
[ "Uploads", "a", "csv", "file", "and", "creates", "a", "superset", "datasource", "in", "Hive", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L1139-L1209
[ "def", "create_table_from_csv", "(", "form", ",", "table", ")", ":", "def", "convert_to_hive_type", "(", "col_type", ")", ":", "\"\"\"maps tableschema's types to hive types\"\"\"", "tableschema_to_hive_types", "=", "{", "'boolean'", ":", "'BOOLEAN'", ",", "'integer'", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
HiveEngineSpec.handle_cursor
Updates progress information
superset/db_engine_specs.py
def handle_cursor(cls, cursor, query, session): """Updates progress information""" from pyhive import hive # pylint: disable=no-name-in-module unfinished_states = ( hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE, ) ...
def handle_cursor(cls, cursor, query, session): """Updates progress information""" from pyhive import hive # pylint: disable=no-name-in-module unfinished_states = ( hive.ttypes.TOperationState.INITIALIZED_STATE, hive.ttypes.TOperationState.RUNNING_STATE, ) ...
[ "Updates", "progress", "information" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L1276-L1324
[ "def", "handle_cursor", "(", "cls", ",", "cursor", ",", "query", ",", "session", ")", ":", "from", "pyhive", "import", "hive", "# pylint: disable=no-name-in-module", "unfinished_states", "=", "(", "hive", ".", "ttypes", ".", "TOperationState", ".", "INITIALIZED_ST...
ca2996c78f679260eb79c6008e276733df5fb653
train
HiveEngineSpec.get_configuration_for_impersonation
Return a configuration dictionary that can be merged with other configs that can set the correct properties for impersonating users :param uri: URI string :param impersonate_user: Bool indicating if impersonation is enabled :param username: Effective username :return: Dictionary ...
superset/db_engine_specs.py
def get_configuration_for_impersonation(cls, uri, impersonate_user, username): """ Return a configuration dictionary that can be merged with other configs that can set the correct properties for impersonating users :param uri: URI string :param impersonate_user: Bool indicating i...
def get_configuration_for_impersonation(cls, uri, impersonate_user, username): """ Return a configuration dictionary that can be merged with other configs that can set the correct properties for impersonating users :param uri: URI string :param impersonate_user: Bool indicating i...
[ "Return", "a", "configuration", "dictionary", "that", "can", "be", "merged", "with", "other", "configs", "that", "can", "set", "the", "correct", "properties", "for", "impersonating", "users", ":", "param", "uri", ":", "URI", "string", ":", "param", "impersonat...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L1370-L1387
[ "def", "get_configuration_for_impersonation", "(", "cls", ",", "uri", ",", "impersonate_user", ",", "username", ")", ":", "configuration", "=", "{", "}", "url", "=", "make_url", "(", "uri", ")", "backend_name", "=", "url", ".", "get_backend_name", "(", ")", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
BQEngineSpec.mutate_label
BigQuery field_name should start with a letter or underscore and contain only alphanumeric characters. Labels that start with a number are prefixed with an underscore. Any unsupported characters are replaced with underscores and an md5 hash is added to the end of the label to avoid possible coll...
superset/db_engine_specs.py
def mutate_label(label): """ BigQuery field_name should start with a letter or underscore and contain only alphanumeric characters. Labels that start with a number are prefixed with an underscore. Any unsupported characters are replaced with underscores and an md5 hash is added t...
def mutate_label(label): """ BigQuery field_name should start with a letter or underscore and contain only alphanumeric characters. Labels that start with a number are prefixed with an underscore. Any unsupported characters are replaced with underscores and an md5 hash is added t...
[ "BigQuery", "field_name", "should", "start", "with", "a", "letter", "or", "underscore", "and", "contain", "only", "alphanumeric", "characters", ".", "Labels", "that", "start", "with", "a", "number", "are", "prefixed", "with", "an", "underscore", ".", "Any", "u...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L1612-L1632
[ "def", "mutate_label", "(", "label", ")", ":", "label_hashed", "=", "'_'", "+", "hashlib", ".", "md5", "(", "label", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "# if label starts with number, add underscore as first character", "label_mut...
ca2996c78f679260eb79c6008e276733df5fb653
train
BQEngineSpec._get_fields
BigQuery dialect requires us to not use backtick in the fieldname which are nested. Using literal_column handles that issue. https://docs.sqlalchemy.org/en/latest/core/tutorial.html#using-more-specific-text-with-table-literal-column-and-column Also explicility specifying column names so ...
superset/db_engine_specs.py
def _get_fields(cls, cols): """ BigQuery dialect requires us to not use backtick in the fieldname which are nested. Using literal_column handles that issue. https://docs.sqlalchemy.org/en/latest/core/tutorial.html#using-more-specific-text-with-table-literal-column-and-column ...
def _get_fields(cls, cols): """ BigQuery dialect requires us to not use backtick in the fieldname which are nested. Using literal_column handles that issue. https://docs.sqlalchemy.org/en/latest/core/tutorial.html#using-more-specific-text-with-table-literal-column-and-column ...
[ "BigQuery", "dialect", "requires", "us", "to", "not", "use", "backtick", "in", "the", "fieldname", "which", "are", "nested", ".", "Using", "literal_column", "handles", "that", "issue", ".", "https", ":", "//", "docs", ".", "sqlalchemy", ".", "org", "/", "e...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engine_specs.py#L1665-L1675
[ "def", "_get_fields", "(", "cls", ",", "cols", ")", ":", "return", "[", "sqla", ".", "literal_column", "(", "c", ".", "get", "(", "'name'", ")", ")", ".", "label", "(", "c", ".", "get", "(", "'name'", ")", ".", "replace", "(", "'.'", ",", "'__'",...
ca2996c78f679260eb79c6008e276733df5fb653
train
load_multiformat_time_series
Loading time series data from a zip file in the repo
superset/data/multiformat_time_series.py
def load_multiformat_time_series(): """Loading time series data from a zip file in the repo""" data = get_example_data('multiformat_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.ds2 = pd.to_datetime(pdf.ds2, unit='s') pdf.to_sql( 'multiform...
def load_multiformat_time_series(): """Loading time series data from a zip file in the repo""" data = get_example_data('multiformat_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.ds2 = pd.to_datetime(pdf.ds2, unit='s') pdf.to_sql( 'multiform...
[ "Loading", "time", "series", "data", "from", "a", "zip", "file", "in", "the", "repo" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/multiformat_time_series.py#L34-L107
[ "def", "load_multiformat_time_series", "(", ")", ":", "data", "=", "get_example_data", "(", "'multiformat_time_series.json.gz'", ")", "pdf", "=", "pd", ".", "read_json", "(", "data", ")", "pdf", ".", "ds", "=", "pd", ".", "to_datetime", "(", "pdf", ".", "ds"...
ca2996c78f679260eb79c6008e276733df5fb653
train
import_dashboards
Imports dashboards from a stream to databases
superset/utils/dashboard_import_export.py
def import_dashboards(session, data_stream, import_time=None): """Imports dashboards from a stream to databases""" current_tt = int(time.time()) import_time = current_tt if import_time is None else import_time data = json.loads(data_stream.read(), object_hook=decode_dashboards) # TODO: import DRUID ...
def import_dashboards(session, data_stream, import_time=None): """Imports dashboards from a stream to databases""" current_tt = int(time.time()) import_time = current_tt if import_time is None else import_time data = json.loads(data_stream.read(), object_hook=decode_dashboards) # TODO: import DRUID ...
[ "Imports", "dashboards", "from", "a", "stream", "to", "databases" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/dashboard_import_export.py#L26-L38
[ "def", "import_dashboards", "(", "session", ",", "data_stream", ",", "import_time", "=", "None", ")", ":", "current_tt", "=", "int", "(", "time", ".", "time", "(", ")", ")", "import_time", "=", "current_tt", "if", "import_time", "is", "None", "else", "impo...
ca2996c78f679260eb79c6008e276733df5fb653
train
export_dashboards
Returns all dashboards metadata as a json dump
superset/utils/dashboard_import_export.py
def export_dashboards(session): """Returns all dashboards metadata as a json dump""" logging.info('Starting export') dashboards = session.query(Dashboard) dashboard_ids = [] for dashboard in dashboards: dashboard_ids.append(dashboard.id) data = Dashboard.export_dashboards(dashboard_ids) ...
def export_dashboards(session): """Returns all dashboards metadata as a json dump""" logging.info('Starting export') dashboards = session.query(Dashboard) dashboard_ids = [] for dashboard in dashboards: dashboard_ids.append(dashboard.id) data = Dashboard.export_dashboards(dashboard_ids) ...
[ "Returns", "all", "dashboards", "metadata", "as", "a", "json", "dump" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/dashboard_import_export.py#L41-L49
[ "def", "export_dashboards", "(", "session", ")", ":", "logging", ".", "info", "(", "'Starting export'", ")", "dashboards", "=", "session", ".", "query", "(", "Dashboard", ")", "dashboard_ids", "=", "[", "]", "for", "dashboard", "in", "dashboards", ":", "dash...
ca2996c78f679260eb79c6008e276733df5fb653
train
QueryObject.cache_key
The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra` We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5 days ago" or "now").
superset/common/query_object.py
def cache_key(self, **extra): """ The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra` We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5...
def cache_key(self, **extra): """ The cache key is made out of the key/values in `query_obj`, plus any other key/values in `extra` We remove datetime bounds that are hard values, and replace them with the use-provided inputs to bounds, which may be time-relative (as in "5...
[ "The", "cache", "key", "is", "made", "out", "of", "the", "key", "/", "values", "in", "query_obj", "plus", "any", "other", "key", "/", "values", "in", "extra", "We", "remove", "datetime", "bounds", "that", "are", "hard", "values", "and", "replace", "them"...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_object.py#L100-L116
[ "def", "cache_key", "(", "self", ",", "*", "*", "extra", ")", ":", "cache_dict", "=", "self", ".", "to_dict", "(", ")", "cache_dict", ".", "update", "(", "extra", ")", "for", "k", "in", "[", "'from_dttm'", ",", "'to_dttm'", "]", ":", "del", "cache_di...
ca2996c78f679260eb79c6008e276733df5fb653
train
handle_query_error
Local method handling error while processing the SQL
superset/sql_lab.py
def handle_query_error(msg, query, session, payload=None): """Local method handling error while processing the SQL""" payload = payload or {} troubleshooting_link = config['TROUBLESHOOTING_LINK'] query.error_message = msg query.status = QueryStatus.FAILED query.tmp_table_name = None session....
def handle_query_error(msg, query, session, payload=None): """Local method handling error while processing the SQL""" payload = payload or {} troubleshooting_link = config['TROUBLESHOOTING_LINK'] query.error_message = msg query.status = QueryStatus.FAILED query.tmp_table_name = None session....
[ "Local", "method", "handling", "error", "while", "processing", "the", "SQL" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L63-L77
[ "def", "handle_query_error", "(", "msg", ",", "query", ",", "session", ",", "payload", "=", "None", ")", ":", "payload", "=", "payload", "or", "{", "}", "troubleshooting_link", "=", "config", "[", "'TROUBLESHOOTING_LINK'", "]", "query", ".", "error_message", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
get_query
attemps to get the query and retry if it cannot
superset/sql_lab.py
def get_query(query_id, session, retry_count=5): """attemps to get the query and retry if it cannot""" query = None attempt = 0 while not query and attempt < retry_count: try: query = session.query(Query).filter_by(id=query_id).one() except Exception: attempt += 1...
def get_query(query_id, session, retry_count=5): """attemps to get the query and retry if it cannot""" query = None attempt = 0 while not query and attempt < retry_count: try: query = session.query(Query).filter_by(id=query_id).one() except Exception: attempt += 1...
[ "attemps", "to", "get", "the", "query", "and", "retry", "if", "it", "cannot" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L80-L97
[ "def", "get_query", "(", "query_id", ",", "session", ",", "retry_count", "=", "5", ")", ":", "query", "=", "None", "attempt", "=", "0", "while", "not", "query", "and", "attempt", "<", "retry_count", ":", "try", ":", "query", "=", "session", ".", "query...
ca2996c78f679260eb79c6008e276733df5fb653
train
session_scope
Provide a transactional scope around a series of operations.
superset/sql_lab.py
def session_scope(nullpool): """Provide a transactional scope around a series of operations.""" if nullpool: engine = sqlalchemy.create_engine( app.config.get('SQLALCHEMY_DATABASE_URI'), poolclass=NullPool) session_class = sessionmaker() session_class.configure(bind=engine) ...
def session_scope(nullpool): """Provide a transactional scope around a series of operations.""" if nullpool: engine = sqlalchemy.create_engine( app.config.get('SQLALCHEMY_DATABASE_URI'), poolclass=NullPool) session_class = sessionmaker() session_class.configure(bind=engine) ...
[ "Provide", "a", "transactional", "scope", "around", "a", "series", "of", "operations", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L101-L121
[ "def", "session_scope", "(", "nullpool", ")", ":", "if", "nullpool", ":", "engine", "=", "sqlalchemy", ".", "create_engine", "(", "app", ".", "config", ".", "get", "(", "'SQLALCHEMY_DATABASE_URI'", ")", ",", "poolclass", "=", "NullPool", ")", "session_class", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
get_sql_results
Executes the sql query returns the results.
superset/sql_lab.py
def get_sql_results( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, start_time=None): """Executes the sql query returns the results.""" with session_scope(not ctask.request.called_directly) as session: try: return execute_sql_statement...
def get_sql_results( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, start_time=None): """Executes the sql query returns the results.""" with session_scope(not ctask.request.called_directly) as session: try: return execute_sql_statement...
[ "Executes", "the", "sql", "query", "returns", "the", "results", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L127-L141
[ "def", "get_sql_results", "(", "ctask", ",", "query_id", ",", "rendered_query", ",", "return_results", "=", "True", ",", "store_results", "=", "False", ",", "user_name", "=", "None", ",", "start_time", "=", "None", ")", ":", "with", "session_scope", "(", "no...
ca2996c78f679260eb79c6008e276733df5fb653
train
execute_sql_statement
Executes a single SQL statement
superset/sql_lab.py
def execute_sql_statement(sql_statement, query, user_name, session, cursor): """Executes a single SQL statement""" database = query.database db_engine_spec = database.db_engine_spec parsed_query = ParsedQuery(sql_statement) sql = parsed_query.stripped() SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW...
def execute_sql_statement(sql_statement, query, user_name, session, cursor): """Executes a single SQL statement""" database = query.database db_engine_spec = database.db_engine_spec parsed_query = ParsedQuery(sql_statement) sql = parsed_query.stripped() SQL_MAX_ROWS = app.config.get('SQL_MAX_ROW...
[ "Executes", "a", "single", "SQL", "statement" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L144-L209
[ "def", "execute_sql_statement", "(", "sql_statement", ",", "query", ",", "user_name", ",", "session", ",", "cursor", ")", ":", "database", "=", "query", ".", "database", "db_engine_spec", "=", "database", ".", "db_engine_spec", "parsed_query", "=", "ParsedQuery", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
execute_sql_statements
Executes the sql query returns the results.
superset/sql_lab.py
def execute_sql_statements( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, session=None, start_time=None, ): """Executes the sql query returns the results.""" if store_results and start_time: # only asynchronous queries stats_logger.timing( ...
def execute_sql_statements( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, session=None, start_time=None, ): """Executes the sql query returns the results.""" if store_results and start_time: # only asynchronous queries stats_logger.timing( ...
[ "Executes", "the", "sql", "query", "returns", "the", "results", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_lab.py#L212-L303
[ "def", "execute_sql_statements", "(", "ctask", ",", "query_id", ",", "rendered_query", ",", "return_results", "=", "True", ",", "store_results", "=", "False", ",", "user_name", "=", "None", ",", "session", "=", "None", ",", "start_time", "=", "None", ",", ")...
ca2996c78f679260eb79c6008e276733df5fb653
train
flasher
Flask's flash if available, logging call if not
superset/utils/core.py
def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg)
def flasher(msg, severity=None): """Flask's flash if available, logging call if not""" try: flash(msg, severity) except RuntimeError: if severity == 'danger': logging.error(msg) else: logging.info(msg)
[ "Flask", "s", "flash", "if", "available", "logging", "call", "if", "not" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L81-L89
[ "def", "flasher", "(", "msg", ",", "severity", "=", "None", ")", ":", "try", ":", "flash", "(", "msg", ",", "severity", ")", "except", "RuntimeError", ":", "if", "severity", "==", "'danger'", ":", "logging", ".", "error", "(", "msg", ")", "else", ":"...
ca2996c78f679260eb79c6008e276733df5fb653
train
string_to_num
Converts a string to an int/float Returns ``None`` if it can't be converted >>> string_to_num('5') 5 >>> string_to_num('5.2') 5.2 >>> string_to_num(10) 10 >>> string_to_num(10.1) 10.1 >>> string_to_num('this is not a string') is None True
superset/utils/core.py
def string_to_num(s: str): """Converts a string to an int/float Returns ``None`` if it can't be converted >>> string_to_num('5') 5 >>> string_to_num('5.2') 5.2 >>> string_to_num(10) 10 >>> string_to_num(10.1) 10.1 >>> string_to_num('this is not a string') is None True ...
def string_to_num(s: str): """Converts a string to an int/float Returns ``None`` if it can't be converted >>> string_to_num('5') 5 >>> string_to_num('5.2') 5.2 >>> string_to_num(10) 10 >>> string_to_num(10.1) 10.1 >>> string_to_num('this is not a string') is None True ...
[ "Converts", "a", "string", "to", "an", "int", "/", "float" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L148-L171
[ "def", "string_to_num", "(", "s", ":", "str", ")", ":", "if", "isinstance", "(", "s", ",", "(", "int", ",", "float", ")", ")", ":", "return", "s", "if", "s", ".", "isdigit", "(", ")", ":", "return", "int", "(", "s", ")", "try", ":", "return", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
list_minus
Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3]
superset/utils/core.py
def list_minus(l: List, minus: List) -> List: """Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3] """ return [o for o in l if o not in minus]
def list_minus(l: List, minus: List) -> List: """Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3] """ return [o for o in l if o not in minus]
[ "Returns", "l", "without", "what", "is", "in", "minus" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L188-L194
[ "def", "list_minus", "(", "l", ":", "List", ",", "minus", ":", "List", ")", "->", "List", ":", "return", "[", "o", "for", "o", "in", "l", "if", "o", "not", "in", "minus", "]" ]
ca2996c78f679260eb79c6008e276733df5fb653
train
parse_human_datetime
Returns ``datetime.datetime`` from human readable strings >>> from datetime import date, timedelta >>> from dateutil.relativedelta import relativedelta >>> parse_human_datetime('2015-04-03') datetime.datetime(2015, 4, 3, 0, 0) >>> parse_human_datetime('2/3/1969') datetime.datetime(1969, 2, 3, 0...
superset/utils/core.py
def parse_human_datetime(s): """ Returns ``datetime.datetime`` from human readable strings >>> from datetime import date, timedelta >>> from dateutil.relativedelta import relativedelta >>> parse_human_datetime('2015-04-03') datetime.datetime(2015, 4, 3, 0, 0) >>> parse_human_datetime('2/3/1...
def parse_human_datetime(s): """ Returns ``datetime.datetime`` from human readable strings >>> from datetime import date, timedelta >>> from dateutil.relativedelta import relativedelta >>> parse_human_datetime('2015-04-03') datetime.datetime(2015, 4, 3, 0, 0) >>> parse_human_datetime('2/3/1...
[ "Returns", "datetime", ".", "datetime", "from", "human", "readable", "strings" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L197-L233
[ "def", "parse_human_datetime", "(", "s", ")", ":", "if", "not", "s", ":", "return", "None", "try", ":", "dttm", "=", "parse", "(", "s", ")", "except", "Exception", ":", "try", ":", "cal", "=", "parsedatetime", ".", "Calendar", "(", ")", "parsed_dttm", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
decode_dashboards
Function to be passed into json.loads obj_hook parameter Recreates the dashboard object from a json representation.
superset/utils/core.py
def decode_dashboards(o): """ Function to be passed into json.loads obj_hook parameter Recreates the dashboard object from a json representation. """ import superset.models.core as models from superset.connectors.sqla.models import ( SqlaTable, SqlMetric, TableColumn, ) if '__Da...
def decode_dashboards(o): """ Function to be passed into json.loads obj_hook parameter Recreates the dashboard object from a json representation. """ import superset.models.core as models from superset.connectors.sqla.models import ( SqlaTable, SqlMetric, TableColumn, ) if '__Da...
[ "Function", "to", "be", "passed", "into", "json", ".", "loads", "obj_hook", "parameter", "Recreates", "the", "dashboard", "object", "from", "a", "json", "representation", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L241-L274
[ "def", "decode_dashboards", "(", "o", ")", ":", "import", "superset", ".", "models", ".", "core", "as", "models", "from", "superset", ".", "connectors", ".", "sqla", ".", "models", "import", "(", "SqlaTable", ",", "SqlMetric", ",", "TableColumn", ",", ")",...
ca2996c78f679260eb79c6008e276733df5fb653
train
parse_human_timedelta
Returns ``datetime.datetime`` from natural language time deltas >>> parse_human_datetime('now') <= datetime.now() True
superset/utils/core.py
def parse_human_timedelta(s: str): """ Returns ``datetime.datetime`` from natural language time deltas >>> parse_human_datetime('now') <= datetime.now() True """ cal = parsedatetime.Calendar() dttm = dttm_from_timtuple(datetime.now().timetuple()) d = cal.parse(s or '', dttm)[0] d = ...
def parse_human_timedelta(s: str): """ Returns ``datetime.datetime`` from natural language time deltas >>> parse_human_datetime('now') <= datetime.now() True """ cal = parsedatetime.Calendar() dttm = dttm_from_timtuple(datetime.now().timetuple()) d = cal.parse(s or '', dttm)[0] d = ...
[ "Returns", "datetime", ".", "datetime", "from", "natural", "language", "time", "deltas" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L290-L301
[ "def", "parse_human_timedelta", "(", "s", ":", "str", ")", ":", "cal", "=", "parsedatetime", ".", "Calendar", "(", ")", "dttm", "=", "dttm_from_timtuple", "(", "datetime", ".", "now", "(", ")", ".", "timetuple", "(", ")", ")", "d", "=", "cal", ".", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
datetime_f
Formats datetime to take less room when it is recent
superset/utils/core.py
def datetime_f(dttm): """Formats datetime to take less room when it is recent""" if dttm: dttm = dttm.isoformat() now_iso = datetime.now().isoformat() if now_iso[:10] == dttm[:10]: dttm = dttm[11:] elif now_iso[:4] == dttm[:4]: dttm = dttm[5:] return '...
def datetime_f(dttm): """Formats datetime to take less room when it is recent""" if dttm: dttm = dttm.isoformat() now_iso = datetime.now().isoformat() if now_iso[:10] == dttm[:10]: dttm = dttm[11:] elif now_iso[:4] == dttm[:4]: dttm = dttm[5:] return '...
[ "Formats", "datetime", "to", "take", "less", "room", "when", "it", "is", "recent" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L321-L330
[ "def", "datetime_f", "(", "dttm", ")", ":", "if", "dttm", ":", "dttm", "=", "dttm", ".", "isoformat", "(", ")", "now_iso", "=", "datetime", ".", "now", "(", ")", ".", "isoformat", "(", ")", "if", "now_iso", "[", ":", "10", "]", "==", "dttm", "[",...
ca2996c78f679260eb79c6008e276733df5fb653
train
json_iso_dttm_ser
json serializer that deals with dates >>> dttm = datetime(1970, 1, 1) >>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser) '{"dttm": "1970-01-01T00:00:00"}'
superset/utils/core.py
def json_iso_dttm_ser(obj, pessimistic: Optional[bool] = False): """ json serializer that deals with dates >>> dttm = datetime(1970, 1, 1) >>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser) '{"dttm": "1970-01-01T00:00:00"}' """ val = base_json_conv(obj) if val is not None: ...
def json_iso_dttm_ser(obj, pessimistic: Optional[bool] = False): """ json serializer that deals with dates >>> dttm = datetime(1970, 1, 1) >>> json.dumps({'dttm': dttm}, default=json_iso_dttm_ser) '{"dttm": "1970-01-01T00:00:00"}' """ val = base_json_conv(obj) if val is not None: ...
[ "json", "serializer", "that", "deals", "with", "dates" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L355-L374
[ "def", "json_iso_dttm_ser", "(", "obj", ",", "pessimistic", ":", "Optional", "[", "bool", "]", "=", "False", ")", ":", "val", "=", "base_json_conv", "(", "obj", ")", "if", "val", "is", "not", "None", ":", "return", "val", "if", "isinstance", "(", "obj"...
ca2996c78f679260eb79c6008e276733df5fb653
train
json_int_dttm_ser
json serializer that deals with dates
superset/utils/core.py
def json_int_dttm_ser(obj): """json serializer that deals with dates""" val = base_json_conv(obj) if val is not None: return val if isinstance(obj, (datetime, pd.Timestamp)): obj = datetime_to_epoch(obj) elif isinstance(obj, date): obj = (obj - EPOCH.date()).total_seconds() *...
def json_int_dttm_ser(obj): """json serializer that deals with dates""" val = base_json_conv(obj) if val is not None: return val if isinstance(obj, (datetime, pd.Timestamp)): obj = datetime_to_epoch(obj) elif isinstance(obj, date): obj = (obj - EPOCH.date()).total_seconds() *...
[ "json", "serializer", "that", "deals", "with", "dates" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L384-L396
[ "def", "json_int_dttm_ser", "(", "obj", ")", ":", "val", "=", "base_json_conv", "(", "obj", ")", "if", "val", "is", "not", "None", ":", "return", "val", "if", "isinstance", "(", "obj", ",", "(", "datetime", ",", "pd", ".", "Timestamp", ")", ")", ":",...
ca2996c78f679260eb79c6008e276733df5fb653
train
error_msg_from_exception
Translate exception into error message Database have different ways to handle exception. This function attempts to make sense of the exception object and construct a human readable sentence. TODO(bkyryliuk): parse the Presto error message from the connection created via create_eng...
superset/utils/core.py
def error_msg_from_exception(e): """Translate exception into error message Database have different ways to handle exception. This function attempts to make sense of the exception object and construct a human readable sentence. TODO(bkyryliuk): parse the Presto error message from the connection ...
def error_msg_from_exception(e): """Translate exception into error message Database have different ways to handle exception. This function attempts to make sense of the exception object and construct a human readable sentence. TODO(bkyryliuk): parse the Presto error message from the connection ...
[ "Translate", "exception", "into", "error", "message" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L403-L423
[ "def", "error_msg_from_exception", "(", "e", ")", ":", "msg", "=", "''", "if", "hasattr", "(", "e", ",", "'message'", ")", ":", "if", "isinstance", "(", "e", ".", "message", ",", "dict", ")", ":", "msg", "=", "e", ".", "message", ".", "get", "(", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
generic_find_constraint_name
Utility to find a constraint name in alembic migrations
superset/utils/core.py
def generic_find_constraint_name(table, columns, referenced, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for fk in t.foreign_key_constraints: if fk.referred_table.name == referenced and set(fk.column_key...
def generic_find_constraint_name(table, columns, referenced, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for fk in t.foreign_key_constraints: if fk.referred_table.name == referenced and set(fk.column_key...
[ "Utility", "to", "find", "a", "constraint", "name", "in", "alembic", "migrations" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L450-L456
[ "def", "generic_find_constraint_name", "(", "table", ",", "columns", ",", "referenced", ",", "db", ")", ":", "t", "=", "sa", ".", "Table", "(", "table", ",", "db", ".", "metadata", ",", "autoload", "=", "True", ",", "autoload_with", "=", "db", ".", "en...
ca2996c78f679260eb79c6008e276733df5fb653
train
generic_find_fk_constraint_name
Utility to find a foreign-key constraint name in alembic migrations
superset/utils/core.py
def generic_find_fk_constraint_name(table, columns, referenced, insp): """Utility to find a foreign-key constraint name in alembic migrations""" for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: return fk['name']
def generic_find_fk_constraint_name(table, columns, referenced, insp): """Utility to find a foreign-key constraint name in alembic migrations""" for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: return fk['name']
[ "Utility", "to", "find", "a", "foreign", "-", "key", "constraint", "name", "in", "alembic", "migrations" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L459-L463
[ "def", "generic_find_fk_constraint_name", "(", "table", ",", "columns", ",", "referenced", ",", "insp", ")", ":", "for", "fk", "in", "insp", ".", "get_foreign_keys", "(", "table", ")", ":", "if", "fk", "[", "'referred_table'", "]", "==", "referenced", "and",...
ca2996c78f679260eb79c6008e276733df5fb653
train
generic_find_fk_constraint_names
Utility to find foreign-key constraint names in alembic migrations
superset/utils/core.py
def generic_find_fk_constraint_names(table, columns, referenced, insp): """Utility to find foreign-key constraint names in alembic migrations""" names = set() for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: names....
def generic_find_fk_constraint_names(table, columns, referenced, insp): """Utility to find foreign-key constraint names in alembic migrations""" names = set() for fk in insp.get_foreign_keys(table): if fk['referred_table'] == referenced and set(fk['referred_columns']) == columns: names....
[ "Utility", "to", "find", "foreign", "-", "key", "constraint", "names", "in", "alembic", "migrations" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L466-L474
[ "def", "generic_find_fk_constraint_names", "(", "table", ",", "columns", ",", "referenced", ",", "insp", ")", ":", "names", "=", "set", "(", ")", "for", "fk", "in", "insp", ".", "get_foreign_keys", "(", "table", ")", ":", "if", "fk", "[", "'referred_table'...
ca2996c78f679260eb79c6008e276733df5fb653
train
generic_find_uq_constraint_name
Utility to find a unique constraint name in alembic migrations
superset/utils/core.py
def generic_find_uq_constraint_name(table, columns, insp): """Utility to find a unique constraint name in alembic migrations""" for uq in insp.get_unique_constraints(table): if columns == set(uq['column_names']): return uq['name']
def generic_find_uq_constraint_name(table, columns, insp): """Utility to find a unique constraint name in alembic migrations""" for uq in insp.get_unique_constraints(table): if columns == set(uq['column_names']): return uq['name']
[ "Utility", "to", "find", "a", "unique", "constraint", "name", "in", "alembic", "migrations" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L477-L482
[ "def", "generic_find_uq_constraint_name", "(", "table", ",", "columns", ",", "insp", ")", ":", "for", "uq", "in", "insp", ".", "get_unique_constraints", "(", "table", ")", ":", "if", "columns", "==", "set", "(", "uq", "[", "'column_names'", "]", ")", ":", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
table_has_constraint
Utility to find a constraint name in alembic migrations
superset/utils/core.py
def table_has_constraint(table, name, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for c in t.constraints: if c.name == name: return True return False
def table_has_constraint(table, name, db): """Utility to find a constraint name in alembic migrations""" t = sa.Table(table, db.metadata, autoload=True, autoload_with=db.engine) for c in t.constraints: if c.name == name: return True return False
[ "Utility", "to", "find", "a", "constraint", "name", "in", "alembic", "migrations" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L499-L506
[ "def", "table_has_constraint", "(", "table", ",", "name", ",", "db", ")", ":", "t", "=", "sa", ".", "Table", "(", "table", ",", "db", ".", "metadata", ",", "autoload", "=", "True", ",", "autoload_with", "=", "db", ".", "engine", ")", "for", "c", "i...
ca2996c78f679260eb79c6008e276733df5fb653
train
send_email_smtp
Send an email with html content, eg: send_email_smtp( 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
superset/utils/core.py
def send_email_smtp(to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send an email with html content, eg: send_email_smtp( 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null...
def send_email_smtp(to, subject, html_content, config, files=None, data=None, images=None, dryrun=False, cc=None, bcc=None, mime_subtype='mixed'): """ Send an email with html content, eg: send_email_smtp( 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null...
[ "Send", "an", "email", "with", "html", "content", "eg", ":", "send_email_smtp", "(", "test" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L598-L657
[ "def", "send_email_smtp", "(", "to", ",", "subject", ",", "html_content", ",", "config", ",", "files", "=", "None", ",", "data", "=", "None", ",", "images", "=", "None", ",", "dryrun", "=", "False", ",", "cc", "=", "None", ",", "bcc", "=", "None", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
setup_cache
Setup the flask-cache on a flask app
superset/utils/core.py
def setup_cache(app: Flask, cache_config) -> Optional[Cache]: """Setup the flask-cache on a flask app""" if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
def setup_cache(app: Flask, cache_config) -> Optional[Cache]: """Setup the flask-cache on a flask app""" if cache_config and cache_config.get('CACHE_TYPE') != 'null': return Cache(app, config=cache_config) return None
[ "Setup", "the", "flask", "-", "cache", "on", "a", "flask", "app" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L702-L707
[ "def", "setup_cache", "(", "app", ":", "Flask", ",", "cache_config", ")", "->", "Optional", "[", "Cache", "]", ":", "if", "cache_config", "and", "cache_config", ".", "get", "(", "'CACHE_TYPE'", ")", "!=", "'null'", ":", "return", "Cache", "(", "app", ","...
ca2996c78f679260eb79c6008e276733df5fb653
train
zlib_compress
Compress things in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str)
superset/utils/core.py
def zlib_compress(data): """ Compress things in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) """ if PY3K: if isinstance(data, str): return zlib.compress(bytes(data, 'utf-8')) return zlib.compress(data) return zlib.compress(d...
def zlib_compress(data): """ Compress things in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) """ if PY3K: if isinstance(data, str): return zlib.compress(bytes(data, 'utf-8')) return zlib.compress(data) return zlib.compress(d...
[ "Compress", "things", "in", "a", "py2", "/", "3", "safe", "fashion", ">>>", "json_str", "=", "{", "test", ":", "1", "}", ">>>", "blob", "=", "zlib_compress", "(", "json_str", ")" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L710-L720
[ "def", "zlib_compress", "(", "data", ")", ":", "if", "PY3K", ":", "if", "isinstance", "(", "data", ",", "str", ")", ":", "return", "zlib", ".", "compress", "(", "bytes", "(", "data", ",", "'utf-8'", ")", ")", "return", "zlib", ".", "compress", "(", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
zlib_decompress_to_string
Decompress things to a string in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) >>> got_str = zlib_decompress_to_string(blob) >>> got_str == json_str True
superset/utils/core.py
def zlib_decompress_to_string(blob): """ Decompress things to a string in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) >>> got_str = zlib_decompress_to_string(blob) >>> got_str == json_str True """ if PY3K: if isinstance(blob, bytes): ...
def zlib_decompress_to_string(blob): """ Decompress things to a string in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str) >>> got_str = zlib_decompress_to_string(blob) >>> got_str == json_str True """ if PY3K: if isinstance(blob, bytes): ...
[ "Decompress", "things", "to", "a", "string", "in", "a", "py2", "/", "3", "safe", "fashion", ">>>", "json_str", "=", "{", "test", ":", "1", "}", ">>>", "blob", "=", "zlib_compress", "(", "json_str", ")", ">>>", "got_str", "=", "zlib_decompress_to_string", ...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L723-L738
[ "def", "zlib_decompress_to_string", "(", "blob", ")", ":", "if", "PY3K", ":", "if", "isinstance", "(", "blob", ",", "bytes", ")", ":", "decompressed", "=", "zlib", ".", "decompress", "(", "blob", ")", "else", ":", "decompressed", "=", "zlib", ".", "decom...
ca2996c78f679260eb79c6008e276733df5fb653
train
user_label
Given a user ORM FAB object, returns a label
superset/utils/core.py
def user_label(user: User) -> Optional[str]: """Given a user ORM FAB object, returns a label""" if user: if user.first_name and user.last_name: return user.first_name + ' ' + user.last_name else: return user.username return None
def user_label(user: User) -> Optional[str]: """Given a user ORM FAB object, returns a label""" if user: if user.first_name and user.last_name: return user.first_name + ' ' + user.last_name else: return user.username return None
[ "Given", "a", "user", "ORM", "FAB", "object", "returns", "a", "label" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L860-L868
[ "def", "user_label", "(", "user", ":", "User", ")", "->", "Optional", "[", "str", "]", ":", "if", "user", ":", "if", "user", ".", "first_name", "and", "user", ".", "last_name", ":", "return", "user", ".", "first_name", "+", "' '", "+", "user", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
get_since_until
Return `since` and `until` date time tuple from string representations of time_range, since, until and time_shift. This functiom supports both reading the keys separately (from `since` and `until`), as well as the new `time_range` key. Valid formats are: - ISO 8601 - X days/years/hours/day...
superset/utils/core.py
def get_since_until(time_range: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None, time_shift: Optional[str] = None, relative_end: Optional[str] = None) -> Tuple[datetime, datetime]: """Return `since` and `u...
def get_since_until(time_range: Optional[str] = None, since: Optional[str] = None, until: Optional[str] = None, time_shift: Optional[str] = None, relative_end: Optional[str] = None) -> Tuple[datetime, datetime]: """Return `since` and `u...
[ "Return", "since", "and", "until", "date", "time", "tuple", "from", "string", "representations", "of", "time_range", "since", "until", "and", "time_shift", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L932-L1005
[ "def", "get_since_until", "(", "time_range", ":", "Optional", "[", "str", "]", "=", "None", ",", "since", ":", "Optional", "[", "str", "]", "=", "None", ",", "until", ":", "Optional", "[", "str", "]", "=", "None", ",", "time_shift", ":", "Optional", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
add_ago_to_since
Backwards compatibility hack. Without this slices with since: 7 days will be treated as 7 days in the future. :param str since: :returns: Since with ago added if necessary :rtype: str
superset/utils/core.py
def add_ago_to_since(since: str) -> str: """ Backwards compatibility hack. Without this slices with since: 7 days will be treated as 7 days in the future. :param str since: :returns: Since with ago added if necessary :rtype: str """ since_words = since.split(' ') grains = ['days', '...
def add_ago_to_since(since: str) -> str: """ Backwards compatibility hack. Without this slices with since: 7 days will be treated as 7 days in the future. :param str since: :returns: Since with ago added if necessary :rtype: str """ since_words = since.split(' ') grains = ['days', '...
[ "Backwards", "compatibility", "hack", ".", "Without", "this", "slices", "with", "since", ":", "7", "days", "will", "be", "treated", "as", "7", "days", "in", "the", "future", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L1008-L1021
[ "def", "add_ago_to_since", "(", "since", ":", "str", ")", "->", "str", ":", "since_words", "=", "since", ".", "split", "(", "' '", ")", "grains", "=", "[", "'days'", ",", "'years'", ",", "'hours'", ",", "'day'", ",", "'year'", ",", "'weeks'", "]", "i...
ca2996c78f679260eb79c6008e276733df5fb653
train
split_adhoc_filters_into_base_filters
Mutates form data to restructure the adhoc filters in the form of the four base filters, `where`, `having`, `filters`, and `having_filters` which represent free form where sql, free form having sql, structured where clauses and structured having clauses.
superset/utils/core.py
def split_adhoc_filters_into_base_filters(fd): """ Mutates form data to restructure the adhoc filters in the form of the four base filters, `where`, `having`, `filters`, and `having_filters` which represent free form where sql, free form having sql, structured where clauses and structured having cla...
def split_adhoc_filters_into_base_filters(fd): """ Mutates form data to restructure the adhoc filters in the form of the four base filters, `where`, `having`, `filters`, and `having_filters` which represent free form where sql, free form having sql, structured where clauses and structured having cla...
[ "Mutates", "form", "data", "to", "restructure", "the", "adhoc", "filters", "in", "the", "form", "of", "the", "four", "base", "filters", "where", "having", "filters", "and", "having_filters", "which", "represent", "free", "form", "where", "sql", "free", "form",...
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/core.py#L1043-L1080
[ "def", "split_adhoc_filters_into_base_filters", "(", "fd", ")", ":", "adhoc_filters", "=", "fd", ".", "get", "(", "'adhoc_filters'", ")", "if", "isinstance", "(", "adhoc_filters", ",", "list", ")", ":", "simple_where_filters", "=", "[", "]", "simple_having_filters...
ca2996c78f679260eb79c6008e276733df5fb653
train
load_energy
Loads an energy related dataset to use with sankey and graphs
superset/data/energy.py
def load_energy(): """Loads an energy related dataset to use with sankey and graphs""" tbl_name = 'energy_usage' data = get_example_data('energy.json.gz') pdf = pd.read_json(data) pdf.to_sql( tbl_name, db.engine, if_exists='replace', chunksize=500, dtype={ ...
def load_energy(): """Loads an energy related dataset to use with sankey and graphs""" tbl_name = 'energy_usage' data = get_example_data('energy.json.gz') pdf = pd.read_json(data) pdf.to_sql( tbl_name, db.engine, if_exists='replace', chunksize=500, dtype={ ...
[ "Loads", "an", "energy", "related", "dataset", "to", "use", "with", "sankey", "and", "graphs" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/energy.py#L32-L140
[ "def", "load_energy", "(", ")", ":", "tbl_name", "=", "'energy_usage'", "data", "=", "get_example_data", "(", "'energy.json.gz'", ")", "pdf", "=", "pd", ".", "read_json", "(", "data", ")", "pdf", ".", "to_sql", "(", "tbl_name", ",", "db", ".", "engine", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
load_random_time_series_data
Loading random time series data from a zip file in the repo
superset/data/random_time_series.py
def load_random_time_series_data(): """Loading random time series data from a zip file in the repo""" data = get_example_data('random_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.to_sql( 'random_time_series', db.engine, if_exist...
def load_random_time_series_data(): """Loading random time series data from a zip file in the repo""" data = get_example_data('random_time_series.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='s') pdf.to_sql( 'random_time_series', db.engine, if_exist...
[ "Loading", "random", "time", "series", "data", "from", "a", "zip", "file", "in", "the", "repo" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/random_time_series.py#L33-L81
[ "def", "load_random_time_series_data", "(", ")", ":", "data", "=", "get_example_data", "(", "'random_time_series.json.gz'", ")", "pdf", "=", "pd", ".", "read_json", "(", "data", ")", "pdf", ".", "ds", "=", "pd", ".", "to_datetime", "(", "pdf", ".", "ds", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
runserver
Starts a Superset web server.
superset/cli.py
def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket): """Starts a Superset web server.""" debug = debug or config.get('DEBUG') or console_log if debug: print(Fore.BLUE + '-=' * 20) print( Fore.YELLOW + 'Starting Superset server in ' + ...
def runserver(debug, console_log, use_reloader, address, port, timeout, workers, socket): """Starts a Superset web server.""" debug = debug or config.get('DEBUG') or console_log if debug: print(Fore.BLUE + '-=' * 20) print( Fore.YELLOW + 'Starting Superset server in ' + ...
[ "Starts", "a", "Superset", "web", "server", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L112-L144
[ "def", "runserver", "(", "debug", ",", "console_log", ",", "use_reloader", ",", "address", ",", "port", ",", "timeout", ",", "workers", ",", "socket", ")", ":", "debug", "=", "debug", "or", "config", ".", "get", "(", "'DEBUG'", ")", "or", "console_log", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
version
Prints the current version number
superset/cli.py
def version(verbose): """Prints the current version number""" print(Fore.BLUE + '-=' * 15) print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format( version=config.get('VERSION_STRING'))) print(Fore.BLUE + '-=' * 15) if verbose: print('[DB] : ' + '{}'.format(db.engine)) p...
def version(verbose): """Prints the current version number""" print(Fore.BLUE + '-=' * 15) print(Fore.YELLOW + 'Superset ' + Fore.CYAN + '{version}'.format( version=config.get('VERSION_STRING'))) print(Fore.BLUE + '-=' * 15) if verbose: print('[DB] : ' + '{}'.format(db.engine)) p...
[ "Prints", "the", "current", "version", "number" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L149-L157
[ "def", "version", "(", "verbose", ")", ":", "print", "(", "Fore", ".", "BLUE", "+", "'-='", "*", "15", ")", "print", "(", "Fore", ".", "YELLOW", "+", "'Superset '", "+", "Fore", ".", "CYAN", "+", "'{version}'", ".", "format", "(", "version", "=", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
refresh_druid
Refresh druid datasources
superset/cli.py
def refresh_druid(datasource, merge): """Refresh druid datasources""" session = db.session() from superset.connectors.druid.models import DruidCluster for cluster in session.query(DruidCluster).all(): try: cluster.refresh_datasources(datasource_name=datasource, ...
def refresh_druid(datasource, merge): """Refresh druid datasources""" session = db.session() from superset.connectors.druid.models import DruidCluster for cluster in session.query(DruidCluster).all(): try: cluster.refresh_datasources(datasource_name=datasource, ...
[ "Refresh", "druid", "datasources" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L225-L242
[ "def", "refresh_druid", "(", "datasource", ",", "merge", ")", ":", "session", "=", "db", ".", "session", "(", ")", "from", "superset", ".", "connectors", ".", "druid", ".", "models", "import", "DruidCluster", "for", "cluster", "in", "session", ".", "query"...
ca2996c78f679260eb79c6008e276733df5fb653
train
import_dashboards
Import dashboards from JSON
superset/cli.py
def import_dashboards(path, recursive): """Import dashboards from JSON""" p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.json')) elif p.exists() and recursive: files.extend(p.rglob('*.json')) for f i...
def import_dashboards(path, recursive): """Import dashboards from JSON""" p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.json')) elif p.exists() and recursive: files.extend(p.rglob('*.json')) for f i...
[ "Import", "dashboards", "from", "JSON" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L253-L271
[ "def", "import_dashboards", "(", "path", ",", "recursive", ")", ":", "p", "=", "Path", "(", "path", ")", "files", "=", "[", "]", "if", "p", ".", "is_file", "(", ")", ":", "files", ".", "append", "(", "p", ")", "elif", "p", ".", "exists", "(", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
export_dashboards
Export dashboards to JSON
superset/cli.py
def export_dashboards(print_stdout, dashboard_file): """Export dashboards to JSON""" data = dashboard_import_export.export_dashboards(db.session) if print_stdout or not dashboard_file: print(data) if dashboard_file: logging.info('Exporting dashboards to %s', dashboard_file) with ...
def export_dashboards(print_stdout, dashboard_file): """Export dashboards to JSON""" data = dashboard_import_export.export_dashboards(db.session) if print_stdout or not dashboard_file: print(data) if dashboard_file: logging.info('Exporting dashboards to %s', dashboard_file) with ...
[ "Export", "dashboards", "to", "JSON" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L281-L289
[ "def", "export_dashboards", "(", "print_stdout", ",", "dashboard_file", ")", ":", "data", "=", "dashboard_import_export", ".", "export_dashboards", "(", "db", ".", "session", ")", "if", "print_stdout", "or", "not", "dashboard_file", ":", "print", "(", "data", ")...
ca2996c78f679260eb79c6008e276733df5fb653
train
import_datasources
Import datasources from YAML
superset/cli.py
def import_datasources(path, sync, recursive): """Import datasources from YAML""" sync_array = sync.split(',') p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.yaml')) files.extend(p.glob('*.yml')) eli...
def import_datasources(path, sync, recursive): """Import datasources from YAML""" sync_array = sync.split(',') p = Path(path) files = [] if p.is_file(): files.append(p) elif p.exists() and not recursive: files.extend(p.glob('*.yaml')) files.extend(p.glob('*.yml')) eli...
[ "Import", "datasources", "from", "YAML" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L305-L328
[ "def", "import_datasources", "(", "path", ",", "sync", ",", "recursive", ")", ":", "sync_array", "=", "sync", ".", "split", "(", "','", ")", "p", "=", "Path", "(", "path", ")", "files", "=", "[", "]", "if", "p", ".", "is_file", "(", ")", ":", "fi...
ca2996c78f679260eb79c6008e276733df5fb653
train
export_datasources
Export datasources to YAML
superset/cli.py
def export_datasources(print_stdout, datasource_file, back_references, include_defaults): """Export datasources to YAML""" data = dict_import_export.export_to_dict( session=db.session, recursive=True, back_references=back_references, include_defaults=includ...
def export_datasources(print_stdout, datasource_file, back_references, include_defaults): """Export datasources to YAML""" data = dict_import_export.export_to_dict( session=db.session, recursive=True, back_references=back_references, include_defaults=includ...
[ "Export", "datasources", "to", "YAML" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L344-L357
[ "def", "export_datasources", "(", "print_stdout", ",", "datasource_file", ",", "back_references", ",", "include_defaults", ")", ":", "data", "=", "dict_import_export", ".", "export_to_dict", "(", "session", "=", "db", ".", "session", ",", "recursive", "=", "True",...
ca2996c78f679260eb79c6008e276733df5fb653
train
export_datasource_schema
Export datasource YAML schema to stdout
superset/cli.py
def export_datasource_schema(back_references): """Export datasource YAML schema to stdout""" data = dict_import_export.export_schema_to_dict( back_references=back_references) yaml.safe_dump(data, stdout, default_flow_style=False)
def export_datasource_schema(back_references): """Export datasource YAML schema to stdout""" data = dict_import_export.export_schema_to_dict( back_references=back_references) yaml.safe_dump(data, stdout, default_flow_style=False)
[ "Export", "datasource", "YAML", "schema", "to", "stdout" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L364-L368
[ "def", "export_datasource_schema", "(", "back_references", ")", ":", "data", "=", "dict_import_export", ".", "export_schema_to_dict", "(", "back_references", "=", "back_references", ")", "yaml", ".", "safe_dump", "(", "data", ",", "stdout", ",", "default_flow_style", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
update_datasources_cache
Refresh sqllab datasources cache
superset/cli.py
def update_datasources_cache(): """Refresh sqllab datasources cache""" from superset.models.core import Database for database in db.session.query(Database).all(): if database.allow_multi_schema_metadata_fetch: print('Fetching {} datasources ...'.format(database.name)) try: ...
def update_datasources_cache(): """Refresh sqllab datasources cache""" from superset.models.core import Database for database in db.session.query(Database).all(): if database.allow_multi_schema_metadata_fetch: print('Fetching {} datasources ...'.format(database.name)) try: ...
[ "Refresh", "sqllab", "datasources", "cache" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L372-L384
[ "def", "update_datasources_cache", "(", ")", ":", "from", "superset", ".", "models", ".", "core", "import", "Database", "for", "database", "in", "db", ".", "session", ".", "query", "(", "Database", ")", ".", "all", "(", ")", ":", "if", "database", ".", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
worker
Starts a Superset worker for async SQL query execution.
superset/cli.py
def worker(workers): """Starts a Superset worker for async SQL query execution.""" logging.info( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead.") if workers: celery_app.conf.update(CELERYD_CONCURRENCY=workers) elif config.get('SUP...
def worker(workers): """Starts a Superset worker for async SQL query execution.""" logging.info( "The 'superset worker' command is deprecated. Please use the 'celery " "worker' command instead.") if workers: celery_app.conf.update(CELERYD_CONCURRENCY=workers) elif config.get('SUP...
[ "Starts", "a", "Superset", "worker", "for", "async", "SQL", "query", "execution", "." ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L392-L404
[ "def", "worker", "(", "workers", ")", ":", "logging", ".", "info", "(", "\"The 'superset worker' command is deprecated. Please use the 'celery \"", "\"worker' command instead.\"", ")", "if", "workers", ":", "celery_app", ".", "conf", ".", "update", "(", "CELERYD_CONCURREN...
ca2996c78f679260eb79c6008e276733df5fb653
train
flower
Runs a Celery Flower web server Celery Flower is a UI to monitor the Celery operation on a given broker
superset/cli.py
def flower(port, address): """Runs a Celery Flower web server Celery Flower is a UI to monitor the Celery operation on a given broker""" BROKER_URL = celery_app.conf.BROKER_URL cmd = ( 'celery flower ' f'--broker={BROKER_URL} ' f'--port={port} ' f'--address={address}...
def flower(port, address): """Runs a Celery Flower web server Celery Flower is a UI to monitor the Celery operation on a given broker""" BROKER_URL = celery_app.conf.BROKER_URL cmd = ( 'celery flower ' f'--broker={BROKER_URL} ' f'--port={port} ' f'--address={address}...
[ "Runs", "a", "Celery", "Flower", "web", "server" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/cli.py#L416-L435
[ "def", "flower", "(", "port", ",", "address", ")", ":", "BROKER_URL", "=", "celery_app", ".", "conf", ".", "BROKER_URL", "cmd", "=", "(", "'celery flower '", "f'--broker={BROKER_URL} '", "f'--port={port} '", "f'--address={address} '", ")", "logging", ".", "info", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
load_flights
Loading random time series data from a zip file in the repo
superset/data/flights.py
def load_flights(): """Loading random time series data from a zip file in the repo""" tbl_name = 'flights' data = get_example_data('flight_data.csv.gz', make_bytes=True) pdf = pd.read_csv(data, encoding='latin-1') # Loading airports info to join and get lat/long airports_bytes = get_example_dat...
def load_flights(): """Loading random time series data from a zip file in the repo""" tbl_name = 'flights' data = get_example_data('flight_data.csv.gz', make_bytes=True) pdf = pd.read_csv(data, encoding='latin-1') # Loading airports info to join and get lat/long airports_bytes = get_example_dat...
[ "Loading", "random", "time", "series", "data", "from", "a", "zip", "file", "in", "the", "repo" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/flights.py#L25-L61
[ "def", "load_flights", "(", ")", ":", "tbl_name", "=", "'flights'", "data", "=", "get_example_data", "(", "'flight_data.csv.gz'", ",", "make_bytes", "=", "True", ")", "pdf", "=", "pd", ".", "read_csv", "(", "data", ",", "encoding", "=", "'latin-1'", ")", "...
ca2996c78f679260eb79c6008e276733df5fb653
train
load_birth_names
Loading birth name dataset from a zip file in the repo
superset/data/birth_names.py
def load_birth_names(): """Loading birth name dataset from a zip file in the repo""" data = get_example_data('birth_names.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='ms') pdf.to_sql( 'birth_names', db.engine, if_exists='replace', chunksize...
def load_birth_names(): """Loading birth name dataset from a zip file in the repo""" data = get_example_data('birth_names.json.gz') pdf = pd.read_json(data) pdf.ds = pd.to_datetime(pdf.ds, unit='ms') pdf.to_sql( 'birth_names', db.engine, if_exists='replace', chunksize...
[ "Loading", "birth", "name", "dataset", "from", "a", "zip", "file", "in", "the", "repo" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/birth_names.py#L38-L622
[ "def", "load_birth_names", "(", ")", ":", "data", "=", "get_example_data", "(", "'birth_names.json.gz'", ")", "pdf", "=", "pd", ".", "read_json", "(", "data", ")", "pdf", ".", "ds", "=", "pd", ".", "to_datetime", "(", "pdf", ".", "ds", ",", "unit", "="...
ca2996c78f679260eb79c6008e276733df5fb653
train
Druid.refresh_datasources
endpoint that refreshes druid datasources metadata
superset/connectors/druid/views.py
def refresh_datasources(self, refreshAll=True): """endpoint that refreshes druid datasources metadata""" session = db.session() DruidCluster = ConnectorRegistry.sources['druid'].cluster_class for cluster in session.query(DruidCluster).all(): cluster_name = cluster.cluster_nam...
def refresh_datasources(self, refreshAll=True): """endpoint that refreshes druid datasources metadata""" session = db.session() DruidCluster = ConnectorRegistry.sources['druid'].cluster_class for cluster in session.query(DruidCluster).all(): cluster_name = cluster.cluster_nam...
[ "endpoint", "that", "refreshes", "druid", "datasources", "metadata" ]
apache/incubator-superset
python
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/views.py#L339-L363
[ "def", "refresh_datasources", "(", "self", ",", "refreshAll", "=", "True", ")", ":", "session", "=", "db", ".", "session", "(", ")", "DruidCluster", "=", "ConnectorRegistry", ".", "sources", "[", "'druid'", "]", ".", "cluster_class", "for", "cluster", "in", ...
ca2996c78f679260eb79c6008e276733df5fb653
train
convert_to_list
converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1
algorithms/linkedlist/add_two_numbers.py
def convert_to_list(number: int) -> Node: """ converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1 """ if number >= 0: head = Node(0) current = head remainder = number % 10 quotient = number // 10 ...
def convert_to_list(number: int) -> Node: """ converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1 """ if number >= 0: head = Node(0) current = head remainder = number % 10 quotient = number // 10 ...
[ "converts", "a", "positive", "integer", "into", "a", "(", "reversed", ")", "linked", "list", ".", "for", "example", ":", "give", "112", "result", "2", "-", ">", "1", "-", ">", "1" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L43-L63
[ "def", "convert_to_list", "(", "number", ":", "int", ")", "->", "Node", ":", "if", "number", ">=", "0", ":", "head", "=", "Node", "(", "0", ")", "current", "=", "head", "remainder", "=", "number", "%", "10", "quotient", "=", "number", "//", "10", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
convert_to_str
converts the non-negative number list into a string.
algorithms/linkedlist/add_two_numbers.py
def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result
def convert_to_str(l: Node) -> str: """ converts the non-negative number list into a string. """ result = "" while l: result += str(l.val) l = l.next return result
[ "converts", "the", "non", "-", "negative", "number", "list", "into", "a", "string", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L66-L74
[ "def", "convert_to_str", "(", "l", ":", "Node", ")", "->", "str", ":", "result", "=", "\"\"", "while", "l", ":", "result", "+=", "str", "(", "l", ".", "val", ")", "l", "=", "l", ".", "next", "return", "result" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
longest_consecutive
:type root: TreeNode :rtype: int
algorithms/tree/longest_consecutive.py
def longest_consecutive(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 max_len = 0 dfs(root, 0, root.val, max_len) return max_len
def longest_consecutive(root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 max_len = 0 dfs(root, 0, root.val, max_len) return max_len
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/longest_consecutive.py#L28-L37
[ "def", "longest_consecutive", "(", "root", ")", ":", "if", "root", "is", "None", ":", "return", "0", "max_len", "=", "0", "dfs", "(", "root", ",", "0", ",", "root", ".", "val", ",", "max_len", ")", "return", "max_len" ]
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
three_sum
:param array: List[int] :return: Set[ Tuple[int, int, int] ]
algorithms/arrays/three_sum.py
def three_sum(array): """ :param array: List[int] :return: Set[ Tuple[int, int, int] ] """ res = set() array.sort() for i in range(len(array) - 2): if i > 0 and array[i] == array[i - 1]: continue l, r = i + 1, len(array) - 1 while l < r: s = ar...
def three_sum(array): """ :param array: List[int] :return: Set[ Tuple[int, int, int] ] """ res = set() array.sort() for i in range(len(array) - 2): if i > 0 and array[i] == array[i - 1]: continue l, r = i + 1, len(array) - 1 while l < r: s = ar...
[ ":", "param", "array", ":", "List", "[", "int", "]", ":", "return", ":", "Set", "[", "Tuple", "[", "int", "int", "int", "]", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/three_sum.py#L18-L48
[ "def", "three_sum", "(", "array", ")", ":", "res", "=", "set", "(", ")", "array", ".", "sort", "(", ")", "for", "i", "in", "range", "(", "len", "(", "array", ")", "-", "2", ")", ":", "if", "i", ">", "0", "and", "array", "[", "i", "]", "==",...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
top_sort_recursive
Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V)
algorithms/sort/top_sort.py
def top_sort_recursive(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY #print(node) for k in graph.get(node, ()): sk = state.get(k, Non...
def top_sort_recursive(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def dfs(node): state[node] = GRAY #print(node) for k in graph.get(node, ()): sk = state.get(k, Non...
[ "Time", "complexity", "is", "the", "same", "as", "DFS", "which", "is", "O", "(", "V", "+", "E", ")", "Space", "complexity", ":", "O", "(", "V", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/top_sort.py#L3-L24
[ "def", "top_sort_recursive", "(", "graph", ")", ":", "order", ",", "enter", ",", "state", "=", "[", "]", ",", "set", "(", "graph", ")", ",", "{", "}", "def", "dfs", "(", "node", ")", ":", "state", "[", "node", "]", "=", "GRAY", "#print(node)", "f...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
top_sort
Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V)
algorithms/sort/top_sort.py
def top_sort(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) if len(lst) == 0: return True for k in lst: sk = s...
def top_sort(graph): """ Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V) """ order, enter, state = [], set(graph), {} def is_ready(node): lst = graph.get(node, ()) if len(lst) == 0: return True for k in lst: sk = s...
[ "Time", "complexity", "is", "the", "same", "as", "DFS", "which", "is", "O", "(", "V", "+", "E", ")", "Space", "complexity", ":", "O", "(", "V", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/top_sort.py#L26-L66
[ "def", "top_sort", "(", "graph", ")", ":", "order", ",", "enter", ",", "state", "=", "[", "]", ",", "set", "(", "graph", ")", ",", "{", "}", "def", "is_ready", "(", "node", ")", ":", "lst", "=", "graph", ".", "get", "(", "node", ",", "(", ")"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
max_product
:type nums: List[int] :rtype: int
algorithms/dp/max_product_subarray.py
def max_product(nums): """ :type nums: List[int] :rtype: int """ lmin = lmax = gmax = nums[0] for i in range(len(nums)): t1 = nums[i] * lmax t2 = nums[i] * lmin lmax = max(max(t1, t2), nums[i]) lmin = min(min(t1, t2), nums[i]) gmax = max(gmax, lmax)
def max_product(nums): """ :type nums: List[int] :rtype: int """ lmin = lmax = gmax = nums[0] for i in range(len(nums)): t1 = nums[i] * lmax t2 = nums[i] * lmin lmax = max(max(t1, t2), nums[i]) lmin = min(min(t1, t2), nums[i]) gmax = max(gmax, lmax)
[ ":", "type", "nums", ":", "List", "[", "int", "]", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/max_product_subarray.py#L11-L22
[ "def", "max_product", "(", "nums", ")", ":", "lmin", "=", "lmax", "=", "gmax", "=", "nums", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "nums", ")", ")", ":", "t1", "=", "nums", "[", "i", "]", "*", "lmax", "t2", "=", "nums", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
subarray_with_max_product
arr is list of positive/negative numbers
algorithms/dp/max_product_subarray.py
def subarray_with_max_product(arr): ''' arr is list of positive/negative numbers ''' l = len(arr) product_so_far = max_product_end = 1 max_start_i = 0 so_far_start_i = so_far_end_i = 0 all_negative_flag = True for i in range(l): max_product_end *= arr[i] if arr[i] > 0: ...
def subarray_with_max_product(arr): ''' arr is list of positive/negative numbers ''' l = len(arr) product_so_far = max_product_end = 1 max_start_i = 0 so_far_start_i = so_far_end_i = 0 all_negative_flag = True for i in range(l): max_product_end *= arr[i] if arr[i] > 0: ...
[ "arr", "is", "list", "of", "positive", "/", "negative", "numbers" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/max_product_subarray.py#L40-L67
[ "def", "subarray_with_max_product", "(", "arr", ")", ":", "l", "=", "len", "(", "arr", ")", "product_so_far", "=", "max_product_end", "=", "1", "max_start_i", "=", "0", "so_far_start_i", "=", "so_far_end_i", "=", "0", "all_negative_flag", "=", "True", "for", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
text_justification
:type words: list :type max_width: int :rtype: list
algorithms/strings/text_justification.py
def text_justification(words, max_width): ''' :type words: list :type max_width: int :rtype: list ''' ret = [] # return value row_len = 0 # current length of strs in a row row_words = [] # current words in a row index = 0 # the index of current word in words is_first_word = T...
def text_justification(words, max_width): ''' :type words: list :type max_width: int :rtype: list ''' ret = [] # return value row_len = 0 # current length of strs in a row row_words = [] # current words in a row index = 0 # the index of current word in words is_first_word = T...
[ ":", "type", "words", ":", "list", ":", "type", "max_width", ":", "int", ":", "rtype", ":", "list" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/text_justification.py#L34-L89
[ "def", "text_justification", "(", "words", ",", "max_width", ")", ":", "ret", "=", "[", "]", "# return value", "row_len", "=", "0", "# current length of strs in a row", "row_words", "=", "[", "]", "# current words in a row", "index", "=", "0", "# the index of curren...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
insertion_sort
Insertion Sort Complexity: O(n^2)
algorithms/sort/insertion_sort.py
def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cu...
def insertion_sort(arr, simulation=False): """ Insertion Sort Complexity: O(n^2) """ iteration = 0 if simulation: print("iteration",iteration,":",*arr) for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cu...
[ "Insertion", "Sort", "Complexity", ":", "O", "(", "n^2", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/insertion_sort.py#L1-L25
[ "def", "insertion_sort", "(", "arr", ",", "simulation", "=", "False", ")", ":", "iteration", "=", "0", "if", "simulation", ":", "print", "(", "\"iteration\"", ",", "iteration", ",", "\":\"", ",", "*", "arr", ")", "for", "i", "in", "range", "(", "len", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
cycle_sort
cycle_sort This is based on the idea that the permutations to be sorted can be decomposed into cycles, and the results can be individually sorted by cycling. reference: https://en.wikipedia.org/wiki/Cycle_sort Average time complexity : O(N^2) Worst case time complexity : O(N^2)
algorithms/sort/cycle_sort.py
def cycle_sort(arr): """ cycle_sort This is based on the idea that the permutations to be sorted can be decomposed into cycles, and the results can be individually sorted by cycling. reference: https://en.wikipedia.org/wiki/Cycle_sort Average time complexity : O(N^2) Worst case...
def cycle_sort(arr): """ cycle_sort This is based on the idea that the permutations to be sorted can be decomposed into cycles, and the results can be individually sorted by cycling. reference: https://en.wikipedia.org/wiki/Cycle_sort Average time complexity : O(N^2) Worst case...
[ "cycle_sort", "This", "is", "based", "on", "the", "idea", "that", "the", "permutations", "to", "be", "sorted", "can", "be", "decomposed", "into", "cycles", "and", "the", "results", "can", "be", "individually", "sorted", "by", "cycling", ".", "reference", ":"...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/cycle_sort.py#L1-L46
[ "def", "cycle_sort", "(", "arr", ")", ":", "len_arr", "=", "len", "(", "arr", ")", "# Finding cycle to rotate.", "for", "cur", "in", "range", "(", "len_arr", "-", "1", ")", ":", "item", "=", "arr", "[", "cur", "]", "# Finding an indx to put items in.", "in...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
cocktail_shaker_sort
Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort Worst-case performance: O(N^2)
algorithms/sort/cocktail_shaker_sort.py
def cocktail_shaker_sort(arr): """ Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort Worst-case performance: O(N^2) """ def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swap...
def cocktail_shaker_sort(arr): """ Cocktail_shaker_sort Sorting a given array mutation of bubble sort reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort Worst-case performance: O(N^2) """ def swap(i, j): arr[i], arr[j] = arr[j], arr[i] n = len(arr) swap...
[ "Cocktail_shaker_sort", "Sorting", "a", "given", "array", "mutation", "of", "bubble", "sort" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/cocktail_shaker_sort.py#L1-L30
[ "def", "cocktail_shaker_sort", "(", "arr", ")", ":", "def", "swap", "(", "i", ",", "j", ")", ":", "arr", "[", "i", "]", ",", "arr", "[", "j", "]", "=", "arr", "[", "j", "]", ",", "arr", "[", "i", "]", "n", "=", "len", "(", "arr", ")", "sw...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
reconstruct_queue
:type people: List[List[int]] :rtype: List[List[int]]
algorithms/queues/reconstruct_queue.py
def reconstruct_queue(people): """ :type people: List[List[int]] :rtype: List[List[int]] """ queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
def reconstruct_queue(people): """ :type people: List[List[int]] :rtype: List[List[int]] """ queue = [] people.sort(key=lambda x: (-x[0], x[1])) for h, k in people: queue.insert(k, [h, k]) return queue
[ ":", "type", "people", ":", "List", "[", "List", "[", "int", "]]", ":", "rtype", ":", "List", "[", "List", "[", "int", "]]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/reconstruct_queue.py#L18-L27
[ "def", "reconstruct_queue", "(", "people", ")", ":", "queue", "=", "[", "]", "people", ".", "sort", "(", "key", "=", "lambda", "x", ":", "(", "-", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", ")", "for", "h", ",", "k", "in", "people", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
min_depth
:type root: TreeNode :rtype: int
algorithms/tree/min_height.py
def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) ...
def min_depth(self, root): """ :type root: TreeNode :rtype: int """ if root is None: return 0 if root.left is not None or root.right is not None: return max(self.minDepth(root.left), self.minDepth(root.right))+1 return min(self.minDepth(root.left), self.minDepth(root.right)) ...
[ ":", "type", "root", ":", "TreeNode", ":", "rtype", ":", "int" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/min_height.py#L4-L13
[ "def", "min_depth", "(", "self", ",", "root", ")", ":", "if", "root", "is", "None", ":", "return", "0", "if", "root", ".", "left", "is", "not", "None", "or", "root", ".", "right", "is", "not", "None", ":", "return", "max", "(", "self", ".", "minD...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
is_one_edit
:type s: str :type t: str :rtype: bool
algorithms/strings/one_edit_distance.py
def is_one_edit(s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return is_one_edit(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: return s[i+1:] == t[i+1:] or s[i:] == t[i+1:] ...
def is_one_edit(s, t): """ :type s: str :type t: str :rtype: bool """ if len(s) > len(t): return is_one_edit(t, s) if len(t) - len(s) > 1 or t == s: return False for i in range(len(s)): if s[i] != t[i]: return s[i+1:] == t[i+1:] or s[i:] == t[i+1:] ...
[ ":", "type", "s", ":", "str", ":", "type", "t", ":", "str", ":", "rtype", ":", "bool" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/one_edit_distance.py#L6-L19
[ "def", "is_one_edit", "(", "s", ",", "t", ")", ":", "if", "len", "(", "s", ")", ">", "len", "(", "t", ")", ":", "return", "is_one_edit", "(", "t", ",", "s", ")", "if", "len", "(", "t", ")", "-", "len", "(", "s", ")", ">", "1", "or", "t", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
shell_sort
Shell Sort Complexity: O(n^2)
algorithms/sort/shell_sort.py
def shell_sort(arr): ''' Shell Sort Complexity: O(n^2) ''' n = len(arr) # Initialize size of the gap gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - gap while x_index >= 0 and ...
def shell_sort(arr): ''' Shell Sort Complexity: O(n^2) ''' n = len(arr) # Initialize size of the gap gap = n//2 while gap > 0: y_index = gap while y_index < len(arr): y = arr[y_index] x_index = y_index - gap while x_index >= 0 and ...
[ "Shell", "Sort", "Complexity", ":", "O", "(", "n^2", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/shell_sort.py#L1-L21
[ "def", "shell_sort", "(", "arr", ")", ":", "n", "=", "len", "(", "arr", ")", "# Initialize size of the gap", "gap", "=", "n", "//", "2", "while", "gap", ">", "0", ":", "y_index", "=", "gap", "while", "y_index", "<", "len", "(", "arr", ")", ":", "y"...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
common_prefix
Return prefix common of 2 strings
algorithms/strings/longest_common_prefix.py
def common_prefix(s1, s2): "Return prefix common of 2 strings" if not s1 or not s2: return "" k = 0 while s1[k] == s2[k]: k = k + 1 if k >= len(s1) or k >= len(s2): return s1[0:k] return s1[0:k]
def common_prefix(s1, s2): "Return prefix common of 2 strings" if not s1 or not s2: return "" k = 0 while s1[k] == s2[k]: k = k + 1 if k >= len(s1) or k >= len(s2): return s1[0:k] return s1[0:k]
[ "Return", "prefix", "common", "of", "2", "strings" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/longest_common_prefix.py#L21-L30
[ "def", "common_prefix", "(", "s1", ",", "s2", ")", ":", "if", "not", "s1", "or", "not", "s2", ":", "return", "\"\"", "k", "=", "0", "while", "s1", "[", "k", "]", "==", "s2", "[", "k", "]", ":", "k", "=", "k", "+", "1", "if", "k", ">=", "l...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
euler_totient
Euler's totient function or Phi function. Time Complexity: O(sqrt(n)).
algorithms/maths/euler_totient.py
def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(n)).""" result = n; for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i result -= result // i if n > 1: result -= result // n;...
def euler_totient(n): """Euler's totient function or Phi function. Time Complexity: O(sqrt(n)).""" result = n; for i in range(2, int(n ** 0.5) + 1): if n % i == 0: while n % i == 0: n //= i result -= result // i if n > 1: result -= result // n;...
[ "Euler", "s", "totient", "function", "or", "Phi", "function", ".", "Time", "Complexity", ":", "O", "(", "sqrt", "(", "n", "))", "." ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/euler_totient.py#L7-L18
[ "def", "euler_totient", "(", "n", ")", ":", "result", "=", "n", "for", "i", "in", "range", "(", "2", ",", "int", "(", "n", "**", "0.5", ")", "+", "1", ")", ":", "if", "n", "%", "i", "==", "0", ":", "while", "n", "%", "i", "==", "0", ":", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
is_palindrome_dict
This function builds up a dictionary where the keys are the values of the list, and the values are the positions at which these values occur in the list. We then iterate over the dict and if there is more than one key with an odd number of occurrences, bail out and return False. Otherwise, we want to en...
algorithms/linkedlist/is_palindrome.py
def is_palindrome_dict(head): """ This function builds up a dictionary where the keys are the values of the list, and the values are the positions at which these values occur in the list. We then iterate over the dict and if there is more than one key with an odd number of occurrences, bail out and ...
def is_palindrome_dict(head): """ This function builds up a dictionary where the keys are the values of the list, and the values are the positions at which these values occur in the list. We then iterate over the dict and if there is more than one key with an odd number of occurrences, bail out and ...
[ "This", "function", "builds", "up", "a", "dictionary", "where", "the", "keys", "are", "the", "values", "of", "the", "list", "and", "the", "values", "are", "the", "positions", "at", "which", "these", "values", "occur", "in", "the", "list", ".", "We", "the...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/is_palindrome.py#L52-L89
[ "def", "is_palindrome_dict", "(", "head", ")", ":", "if", "not", "head", "or", "not", "head", ".", "next", ":", "return", "True", "d", "=", "{", "}", "pos", "=", "0", "while", "head", ":", "if", "head", ".", "val", "in", "d", ".", "keys", "(", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
fib_list
[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description]
algorithms/dp/fib.py
def fib_list(n): """[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n m...
def fib_list(n): """[summary] This algorithm computes the n-th fibbonacci number very quick. approximate O(n) The algorithm use dynamic programming. Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n m...
[ "[", "summary", "]", "This", "algorithm", "computes", "the", "n", "-", "th", "fibbonacci", "number", "very", "quick", ".", "approximate", "O", "(", "n", ")", "The", "algorithm", "use", "dynamic", "programming", ".", "Arguments", ":", "n", "{", "[", "int"...
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/fib.py#L24-L43
[ "def", "fib_list", "(", "n", ")", ":", "# precondition", "assert", "n", ">=", "0", ",", "'n must be a positive integer'", "list_results", "=", "[", "0", ",", "1", "]", "for", "i", "in", "range", "(", "2", ",", "n", "+", "1", ")", ":", "list_results", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
fib_iter
[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description]
algorithms/dp/fib.py
def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 sum = 0 if n <= 1: return n ...
def fib_iter(n): """[summary] Works iterative approximate O(n) Arguments: n {[int]} -- [description] Returns: [int] -- [description] """ # precondition assert n >= 0, 'n must be positive integer' fib_1 = 0 fib_2 = 1 sum = 0 if n <= 1: return n ...
[ "[", "summary", "]", "Works", "iterative", "approximate", "O", "(", "n", ")" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/fib.py#L47-L70
[ "def", "fib_iter", "(", "n", ")", ":", "# precondition", "assert", "n", ">=", "0", ",", "'n must be positive integer'", "fib_1", "=", "0", "fib_2", "=", "1", "sum", "=", "0", "if", "n", "<=", "1", ":", "return", "n", "for", "_", "in", "range", "(", ...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
train
subsets
:param nums: List[int] :return: Set[tuple]
algorithms/bit/subsets.py
def subsets(nums): """ :param nums: List[int] :return: Set[tuple] """ n = len(nums) total = 1 << n res = set() for i in range(total): subset = tuple(num for j, num in enumerate(nums) if i & 1 << j) res.add(subset) return res
def subsets(nums): """ :param nums: List[int] :return: Set[tuple] """ n = len(nums) total = 1 << n res = set() for i in range(total): subset = tuple(num for j, num in enumerate(nums) if i & 1 << j) res.add(subset) return res
[ ":", "param", "nums", ":", "List", "[", "int", "]", ":", "return", ":", "Set", "[", "tuple", "]" ]
keon/algorithms
python
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/bit/subsets.py#L21-L34
[ "def", "subsets", "(", "nums", ")", ":", "n", "=", "len", "(", "nums", ")", "total", "=", "1", "<<", "n", "res", "=", "set", "(", ")", "for", "i", "in", "range", "(", "total", ")", ":", "subset", "=", "tuple", "(", "num", "for", "j", ",", "...
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3