INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Toggle favorite stars on Slices and Dashboard
def favstar(self, class_name, obj_id, action): """Toggle favorite stars on Slices and Dashboard""" session = db.session() FavStar = models.FavStar # noqa count = 0 favs = session.query(FavStar).filter_by( class_name=class_name, obj_id=obj_id, user_id=g.us...
Server side rendering for a dashboard
def dashboard(self, dashboard_id): """Server side rendering for a dashboard""" session = db.session() qry = session.query(models.Dashboard) if dashboard_id.isdigit(): qry = qry.filter_by(id=int(dashboard_id)) else: qry = qry.filter_by(slug=dashboard_id) ...
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 ...
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: ...
Returns if a key from cache exist
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)
Serves a key off of the results backend
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( ...
Runs arbitrary sql and returns and json
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( ...
Download the query results as csv.
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...
Get the updated queries.
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...
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
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 ...
Personalized welcome page
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(...
User profile page
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_...
SQL Editor
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...
This method exposes an API endpoint to get the database query string for this slice
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 schema access control settings for csv upload in this database
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...
Provide a transactional scope around a series of operations.
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)
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...
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. ...
Alters the SQL statement to apply a LIMIT clause
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...
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
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...
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...
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...
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.
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...
Need to consider foreign tables for PostgreSQL
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)
Postgres is unable to identify mixed case column names unless they are quoted.
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
Extract error message for queries
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
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>.
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...
Updates progress information
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/...
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...
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 ...
Updates progress information
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, ) ...
Uploads a csv file and creates a superset datasource in Hive.
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...
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 ...
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...
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...
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 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 ...
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 ...
Loading time series data from a zip file in the repo
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...
Imports dashboards from a stream to databases
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 ...
Returns all dashboards metadata as a json dump
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) ...
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").
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...
Local method handling error while processing the SQL
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....
attemps to get the query and retry if it cannot
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...
Provide a transactional scope around a series of operations.
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) ...
Executes the sql query returns the results.
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 a single SQL statement
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 the sql query returns the results.
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( ...
Flask's flash if available, logging call if not
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)
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 ...
Returns l without what is in minus >>> list_minus([1, 2, 3], [2]) [1, 3]
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 ``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...
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...
Function to be passed into json.loads obj_hook parameter Recreates the dashboard object from a json representation.
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...
Returns ``datetime.datetime`` from natural language time deltas >>> parse_human_datetime('now') <= datetime.now() True
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 = ...
Formats datetime to take less room when it is recent
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 '...
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"}'
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
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() *...
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...
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 ...
Utility to find a constraint name in alembic migrations
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 foreign-key constraint name in alembic migrations
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 foreign-key constraint names in alembic migrations
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 a unique constraint name in alembic migrations
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 constraint name in alembic migrations
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
Send an email with html content, eg: send_email_smtp( 'test@example.com', 'foo', '<b>Foo</b> bar',['/dev/null'], dryrun=True)
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...
Setup the flask-cache on a flask app
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
Compress things in a py2/3 safe fashion >>> json_str = '{"test": 1}' >>> blob = zlib_compress(json_str)
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...
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
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): ...
Given a user ORM FAB object, returns a label
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
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...
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...
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
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', '...
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.
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...
Loads an energy related dataset to use with sankey and graphs
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={ ...
Loading random time series data from a zip file in the repo
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...
Starts a Superset web server.
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 ' + ...
Prints the current version number
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...
Refresh druid datasources
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, ...
Import dashboards from JSON
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...
Export dashboards to JSON
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 ...
Import datasources from YAML
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...
Export datasources to YAML
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 datasource YAML schema to stdout
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)
Refresh sqllab datasources cache
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: ...
Starts a Superset worker for async SQL query execution.
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...
Runs a Celery Flower web server Celery Flower is a UI to monitor the Celery operation on a given broker
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}...
Loading random time series data from a zip file in the repo
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 birth name dataset from a zip file in the repo
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...
endpoint that refreshes druid datasources metadata
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...
converts a positive integer into a (reversed) linked list. for example: give 112 result 2 -> 1 -> 1
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 the non-negative number list into a string.
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
:type root: TreeNode :rtype: int
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
:param array: List[int] :return: Set[ Tuple[int, int, int] ]
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...
Time complexity is the same as DFS, which is O(V + E) Space complexity: O(V)
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)
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...
:type nums: List[int] :rtype: int
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)
arr is list of positive/negative numbers
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: ...
:type words: list :type max_width: int :rtype: list
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...
Insertion Sort Complexity: O(n^2)
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...
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)
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...
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 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...
:type people: List[List[int]] :rtype: List[List[int]]
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 root: TreeNode :rtype: int
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 s: str :type t: str :rtype: bool
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:] ...
Shell Sort Complexity: O(n^2)
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 ...
Return prefix common of 2 strings
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]
Euler's totient function or Phi function. Time Complexity: O(sqrt(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;...
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...
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 ...
[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]
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...