repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apache/incubator-superset | superset/viz.py | PartitionViz.levels_for | def levels_for(self, time_op, groups, df):
"""
Compute the partition at each `level` from the dataframe.
"""
levels = {}
for i in range(0, len(groups) + 1):
agg_df = df.groupby(groups[:i]) if i else df
levels[i] = (
agg_df.mean() if time_op... | python | def levels_for(self, time_op, groups, df):
"""
Compute the partition at each `level` from the dataframe.
"""
levels = {}
for i in range(0, len(groups) + 1):
agg_df = df.groupby(groups[:i]) if i else df
levels[i] = (
agg_df.mean() if time_op... | [
"def",
"levels_for",
"(",
"self",
",",
"time_op",
",",
"groups",
",",
"df",
")",
":",
"levels",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"groups",
")",
"+",
"1",
")",
":",
"agg_df",
"=",
"df",
".",
"groupby",
"(",
... | Compute the partition at each `level` from the dataframe. | [
"Compute",
"the",
"partition",
"at",
"each",
"level",
"from",
"the",
"dataframe",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L2648-L2658 | train |
apache/incubator-superset | superset/viz.py | PartitionViz.nest_values | def nest_values(self, levels, level=0, metric=None, dims=()):
"""
Nest values at each level on the back-end with
access and setting, instead of summing from the bottom.
"""
if not level:
return [{
'name': m,
'val': levels[0][m],
... | python | def nest_values(self, levels, level=0, metric=None, dims=()):
"""
Nest values at each level on the back-end with
access and setting, instead of summing from the bottom.
"""
if not level:
return [{
'name': m,
'val': levels[0][m],
... | [
"def",
"nest_values",
"(",
"self",
",",
"levels",
",",
"level",
"=",
"0",
",",
"metric",
"=",
"None",
",",
"dims",
"=",
"(",
")",
")",
":",
"if",
"not",
"level",
":",
"return",
"[",
"{",
"'name'",
":",
"m",
",",
"'val'",
":",
"levels",
"[",
"0"... | Nest values at each level on the back-end with
access and setting, instead of summing from the bottom. | [
"Nest",
"values",
"at",
"each",
"level",
"on",
"the",
"back",
"-",
"end",
"with",
"access",
"and",
"setting",
"instead",
"of",
"summing",
"from",
"the",
"bottom",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/viz.py#L2701-L2726 | train |
apache/incubator-superset | superset/connectors/base/models.py | BaseDatasource.short_data | def short_data(self):
"""Data representation of the datasource sent to the frontend"""
return {
'edit_url': self.url,
'id': self.id,
'uid': self.uid,
'schema': self.schema,
'name': self.name,
'type': self.type,
'connecti... | python | def short_data(self):
"""Data representation of the datasource sent to the frontend"""
return {
'edit_url': self.url,
'id': self.id,
'uid': self.uid,
'schema': self.schema,
'name': self.name,
'type': self.type,
'connecti... | [
"def",
"short_data",
"(",
"self",
")",
":",
"return",
"{",
"'edit_url'",
":",
"self",
".",
"url",
",",
"'id'",
":",
"self",
".",
"id",
",",
"'uid'",
":",
"self",
".",
"uid",
",",
"'schema'",
":",
"self",
".",
"schema",
",",
"'name'",
":",
"self",
... | Data representation of the datasource sent to the frontend | [
"Data",
"representation",
"of",
"the",
"datasource",
"sent",
"to",
"the",
"frontend"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L148-L159 | train |
apache/incubator-superset | superset/connectors/base/models.py | BaseDatasource.data | def data(self):
"""Data representation of the datasource sent to the frontend"""
order_by_choices = []
# self.column_names return sorted column_names
for s in self.column_names:
s = str(s or '')
order_by_choices.append((json.dumps([s, True]), s + ' [asc]'))
... | python | def data(self):
"""Data representation of the datasource sent to the frontend"""
order_by_choices = []
# self.column_names return sorted column_names
for s in self.column_names:
s = str(s or '')
order_by_choices.append((json.dumps([s, True]), s + ' [asc]'))
... | [
"def",
"data",
"(",
"self",
")",
":",
"order_by_choices",
"=",
"[",
"]",
"# self.column_names return sorted column_names",
"for",
"s",
"in",
"self",
".",
"column_names",
":",
"s",
"=",
"str",
"(",
"s",
"or",
"''",
")",
"order_by_choices",
".",
"append",
"(",... | Data representation of the datasource sent to the frontend | [
"Data",
"representation",
"of",
"the",
"datasource",
"sent",
"to",
"the",
"frontend"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L166-L215 | train |
apache/incubator-superset | superset/connectors/base/models.py | BaseDatasource.get_fk_many_from_list | def get_fk_many_from_list(
self, object_list, fkmany, fkmany_class, key_attr):
"""Update ORM one-to-many list from object list
Used for syncing metrics and columns using the same code"""
object_dict = {o.get(key_attr): o for o in object_list}
object_keys = [o.get(key_attr) ... | python | def get_fk_many_from_list(
self, object_list, fkmany, fkmany_class, key_attr):
"""Update ORM one-to-many list from object list
Used for syncing metrics and columns using the same code"""
object_dict = {o.get(key_attr): o for o in object_list}
object_keys = [o.get(key_attr) ... | [
"def",
"get_fk_many_from_list",
"(",
"self",
",",
"object_list",
",",
"fkmany",
",",
"fkmany_class",
",",
"key_attr",
")",
":",
"object_dict",
"=",
"{",
"o",
".",
"get",
"(",
"key_attr",
")",
":",
"o",
"for",
"o",
"in",
"object_list",
"}",
"object_keys",
... | Update ORM one-to-many list from object list
Used for syncing metrics and columns using the same code | [
"Update",
"ORM",
"one",
"-",
"to",
"-",
"many",
"list",
"from",
"object",
"list"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L281-L316 | train |
apache/incubator-superset | superset/connectors/base/models.py | BaseDatasource.update_from_object | def update_from_object(self, obj):
"""Update datasource from a data structure
The UI's table editor crafts a complex data structure that
contains most of the datasource's properties as well as
an array of metrics and columns objects. This method
receives the object from the UI a... | python | def update_from_object(self, obj):
"""Update datasource from a data structure
The UI's table editor crafts a complex data structure that
contains most of the datasource's properties as well as
an array of metrics and columns objects. This method
receives the object from the UI a... | [
"def",
"update_from_object",
"(",
"self",
",",
"obj",
")",
":",
"for",
"attr",
"in",
"self",
".",
"update_from_object_fields",
":",
"setattr",
"(",
"self",
",",
"attr",
",",
"obj",
".",
"get",
"(",
"attr",
")",
")",
"self",
".",
"owners",
"=",
"obj",
... | Update datasource from a data structure
The UI's table editor crafts a complex data structure that
contains most of the datasource's properties as well as
an array of metrics and columns objects. This method
receives the object from the UI and syncs the datasource to
match it. S... | [
"Update",
"datasource",
"from",
"a",
"data",
"structure"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/base/models.py#L318-L341 | train |
apache/incubator-superset | superset/common/query_context.py | QueryContext.get_query_result | def get_query_result(self, query_object):
"""Returns a pandas dataframe based on the query object"""
# Here, we assume that all the queries will use the same datasource, which is
# is a valid assumption for current setting. In a long term, we may or maynot
# support multiple queries fro... | python | def get_query_result(self, query_object):
"""Returns a pandas dataframe based on the query object"""
# Here, we assume that all the queries will use the same datasource, which is
# is a valid assumption for current setting. In a long term, we may or maynot
# support multiple queries fro... | [
"def",
"get_query_result",
"(",
"self",
",",
"query_object",
")",
":",
"# Here, we assume that all the queries will use the same datasource, which is",
"# is a valid assumption for current setting. In a long term, we may or maynot",
"# support multiple queries from different data source.",
"ti... | Returns a pandas dataframe based on the query object | [
"Returns",
"a",
"pandas",
"dataframe",
"based",
"on",
"the",
"query",
"object"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L67-L110 | train |
apache/incubator-superset | superset/common/query_context.py | QueryContext.df_metrics_to_num | def df_metrics_to_num(self, df, query_object):
"""Converting metrics to numeric when pandas.read_sql cannot"""
metrics = [metric for metric in query_object.metrics]
for col, dtype in df.dtypes.items():
if dtype.type == np.object_ and col in metrics:
df[col] = pd.to_nu... | python | def df_metrics_to_num(self, df, query_object):
"""Converting metrics to numeric when pandas.read_sql cannot"""
metrics = [metric for metric in query_object.metrics]
for col, dtype in df.dtypes.items():
if dtype.type == np.object_ and col in metrics:
df[col] = pd.to_nu... | [
"def",
"df_metrics_to_num",
"(",
"self",
",",
"df",
",",
"query_object",
")",
":",
"metrics",
"=",
"[",
"metric",
"for",
"metric",
"in",
"query_object",
".",
"metrics",
"]",
"for",
"col",
",",
"dtype",
"in",
"df",
".",
"dtypes",
".",
"items",
"(",
")",... | Converting metrics to numeric when pandas.read_sql cannot | [
"Converting",
"metrics",
"to",
"numeric",
"when",
"pandas",
".",
"read_sql",
"cannot"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L112-L117 | train |
apache/incubator-superset | superset/common/query_context.py | QueryContext.get_single_payload | def get_single_payload(self, query_obj):
"""Returns a payload of metadata and data"""
payload = self.get_df_payload(query_obj)
df = payload.get('df')
status = payload.get('status')
if status != utils.QueryStatus.FAILED:
if df is not None and df.empty:
... | python | def get_single_payload(self, query_obj):
"""Returns a payload of metadata and data"""
payload = self.get_df_payload(query_obj)
df = payload.get('df')
status = payload.get('status')
if status != utils.QueryStatus.FAILED:
if df is not None and df.empty:
... | [
"def",
"get_single_payload",
"(",
"self",
",",
"query_obj",
")",
":",
"payload",
"=",
"self",
".",
"get_df_payload",
"(",
"query_obj",
")",
"df",
"=",
"payload",
".",
"get",
"(",
"'df'",
")",
"status",
"=",
"payload",
".",
"get",
"(",
"'status'",
")",
... | Returns a payload of metadata and data | [
"Returns",
"a",
"payload",
"of",
"metadata",
"and",
"data"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L122-L134 | train |
apache/incubator-superset | superset/common/query_context.py | QueryContext.get_df_payload | def get_df_payload(self, query_obj, **kwargs):
"""Handles caching around the df paylod retrieval"""
cache_key = query_obj.cache_key(
datasource=self.datasource.uid, **kwargs) if query_obj else None
logging.info('Cache key: {}'.format(cache_key))
is_loaded = False
stac... | python | def get_df_payload(self, query_obj, **kwargs):
"""Handles caching around the df paylod retrieval"""
cache_key = query_obj.cache_key(
datasource=self.datasource.uid, **kwargs) if query_obj else None
logging.info('Cache key: {}'.format(cache_key))
is_loaded = False
stac... | [
"def",
"get_df_payload",
"(",
"self",
",",
"query_obj",
",",
"*",
"*",
"kwargs",
")",
":",
"cache_key",
"=",
"query_obj",
".",
"cache_key",
"(",
"datasource",
"=",
"self",
".",
"datasource",
".",
"uid",
",",
"*",
"*",
"kwargs",
")",
"if",
"query_obj",
... | Handles caching around the df paylod retrieval | [
"Handles",
"caching",
"around",
"the",
"df",
"paylod",
"retrieval"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/common/query_context.py#L152-L237 | train |
apache/incubator-superset | superset/models/core.py | Slice.data | def data(self):
"""Data used to render slice in templates"""
d = {}
self.token = ''
try:
d = self.viz.data
self.token = d.get('token')
except Exception as e:
logging.exception(e)
d['error'] = str(e)
return {
'dat... | python | def data(self):
"""Data used to render slice in templates"""
d = {}
self.token = ''
try:
d = self.viz.data
self.token = d.get('token')
except Exception as e:
logging.exception(e)
d['error'] = str(e)
return {
'dat... | [
"def",
"data",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"self",
".",
"token",
"=",
"''",
"try",
":",
"d",
"=",
"self",
".",
"viz",
".",
"data",
"self",
".",
"token",
"=",
"d",
".",
"get",
"(",
"'token'",
")",
"except",
"Exception",
"as",
"e... | Data used to render slice in templates | [
"Data",
"used",
"to",
"render",
"slice",
"in",
"templates"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L226-L248 | train |
apache/incubator-superset | superset/models/core.py | Slice.get_viz | def get_viz(self, force=False):
"""Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
"""
slice_params = json.loads(self.... | python | def get_viz(self, force=False):
"""Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz
"""
slice_params = json.loads(self.... | [
"def",
"get_viz",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"slice_params",
"=",
"json",
".",
"loads",
"(",
"self",
".",
"params",
")",
"slice_params",
"[",
"'slice_id'",
"]",
"=",
"self",
".",
"id",
"slice_params",
"[",
"'json'",
"]",
"=",
... | Creates :py:class:viz.BaseViz object from the url_params_multidict.
:return: object of the 'viz_type' type that is taken from the
url_params_multidict or self.params.
:rtype: :py:class:viz.BaseViz | [
"Creates",
":",
"py",
":",
"class",
":",
"viz",
".",
"BaseViz",
"object",
"from",
"the",
"url_params_multidict",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L305-L322 | train |
apache/incubator-superset | superset/models/core.py | Slice.import_obj | def import_obj(cls, slc_to_import, slc_to_override, import_time=None):
"""Inserts or overrides slc in the database.
remote_id and import_time fields in params_dict are set to track the
slice origin and ensure correct overrides for multiple imports.
Slice.perm is used to find the datasou... | python | def import_obj(cls, slc_to_import, slc_to_override, import_time=None):
"""Inserts or overrides slc in the database.
remote_id and import_time fields in params_dict are set to track the
slice origin and ensure correct overrides for multiple imports.
Slice.perm is used to find the datasou... | [
"def",
"import_obj",
"(",
"cls",
",",
"slc_to_import",
",",
"slc_to_override",
",",
"import_time",
"=",
"None",
")",
":",
"session",
"=",
"db",
".",
"session",
"make_transient",
"(",
"slc_to_import",
")",
"slc_to_import",
".",
"dashboards",
"=",
"[",
"]",
"s... | Inserts or overrides slc in the database.
remote_id and import_time fields in params_dict are set to track the
slice origin and ensure correct overrides for multiple imports.
Slice.perm is used to find the datasources and connect them.
:param Slice slc_to_import: Slice object to import... | [
"Inserts",
"or",
"overrides",
"slc",
"in",
"the",
"database",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L336-L366 | train |
apache/incubator-superset | superset/models/core.py | Dashboard.import_obj | def import_obj(cls, dashboard_to_import, import_time=None):
"""Imports the dashboard from the object to the database.
Once dashboard is imported, json_metadata field is extended and stores
remote_id and import_time. It helps to decide if the dashboard has to
be overridden or just cop... | python | def import_obj(cls, dashboard_to_import, import_time=None):
"""Imports the dashboard from the object to the database.
Once dashboard is imported, json_metadata field is extended and stores
remote_id and import_time. It helps to decide if the dashboard has to
be overridden or just cop... | [
"def",
"import_obj",
"(",
"cls",
",",
"dashboard_to_import",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"alter_positions",
"(",
"dashboard",
",",
"old_to_new_slc_id_dict",
")",
":",
"\"\"\" Updates slice_ids in the position json.\n\n Sample position_json dat... | Imports the dashboard from the object to the database.
Once dashboard is imported, json_metadata field is extended and stores
remote_id and import_time. It helps to decide if the dashboard has to
be overridden or just copies over. Slices that belong to this
dashboard will be wired t... | [
"Imports",
"the",
"dashboard",
"from",
"the",
"object",
"to",
"the",
"database",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L488-L615 | train |
apache/incubator-superset | superset/models/core.py | Database.get_effective_user | def get_effective_user(self, url, user_name=None):
"""
Get the effective user, especially during impersonation.
:param url: SQL Alchemy URL object
:param user_name: Default username
:return: The effective username
"""
effective_username = None
if self.impe... | python | def get_effective_user(self, url, user_name=None):
"""
Get the effective user, especially during impersonation.
:param url: SQL Alchemy URL object
:param user_name: Default username
:return: The effective username
"""
effective_username = None
if self.impe... | [
"def",
"get_effective_user",
"(",
"self",
",",
"url",
",",
"user_name",
"=",
"None",
")",
":",
"effective_username",
"=",
"None",
"if",
"self",
".",
"impersonate_user",
":",
"effective_username",
"=",
"url",
".",
"username",
"if",
"user_name",
":",
"effective_... | Get the effective user, especially during impersonation.
:param url: SQL Alchemy URL object
:param user_name: Default username
:return: The effective username | [
"Get",
"the",
"effective",
"user",
"especially",
"during",
"impersonation",
".",
":",
"param",
"url",
":",
"SQL",
"Alchemy",
"URL",
"object",
":",
"param",
"user_name",
":",
"Default",
"username",
":",
"return",
":",
"The",
"effective",
"username"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L776-L793 | train |
apache/incubator-superset | superset/models/core.py | Database.select_star | def select_star(
self, table_name, schema=None, limit=100, show_cols=False,
indent=True, latest_partition=False, cols=None):
"""Generates a ``select *`` statement in the proper dialect"""
eng = self.get_sqla_engine(
schema=schema, source=utils.sources.get('sql_lab', N... | python | def select_star(
self, table_name, schema=None, limit=100, show_cols=False,
indent=True, latest_partition=False, cols=None):
"""Generates a ``select *`` statement in the proper dialect"""
eng = self.get_sqla_engine(
schema=schema, source=utils.sources.get('sql_lab', N... | [
"def",
"select_star",
"(",
"self",
",",
"table_name",
",",
"schema",
"=",
"None",
",",
"limit",
"=",
"100",
",",
"show_cols",
"=",
"False",
",",
"indent",
"=",
"True",
",",
"latest_partition",
"=",
"False",
",",
"cols",
"=",
"None",
")",
":",
"eng",
... | Generates a ``select *`` statement in the proper dialect | [
"Generates",
"a",
"select",
"*",
"statement",
"in",
"the",
"proper",
"dialect"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L908-L917 | train |
apache/incubator-superset | superset/models/core.py | Database.all_table_names_in_database | def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""
if not self.allow_multi_schema_metadata_fetch:
return []
return self.db_engine_spec.fetch_result_sets(self... | python | def all_table_names_in_database(self, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments."""
if not self.allow_multi_schema_metadata_fetch:
return []
return self.db_engine_spec.fetch_result_sets(self... | [
"def",
"all_table_names_in_database",
"(",
"self",
",",
"cache",
"=",
"False",
",",
"cache_timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"allow_multi_schema_metadata_fetch",
":",
"return",
"[",
"]",
"return",
"self",
... | Parameters need to be passed as keyword arguments. | [
"Parameters",
"need",
"to",
"be",
"passed",
"as",
"keyword",
"arguments",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L933-L938 | train |
apache/incubator-superset | superset/models/core.py | Database.all_table_names_in_schema | def all_table_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema nam... | python | def all_table_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema nam... | [
"def",
"all_table_names_in_schema",
"(",
"self",
",",
"schema",
",",
"cache",
"=",
"False",
",",
"cache_timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"tables",
"=",
"[",
"]",
"try",
":",
"tables",
"=",
"self",
".",
"db_engine_spec",
".",
... | Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema name
:type schema: str
:param cache: whether cache is enabled for the function
:type cache: bool
:param cac... | [
"Parameters",
"need",
"to",
"be",
"passed",
"as",
"keyword",
"arguments",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L954-L978 | train |
apache/incubator-superset | superset/models/core.py | Database.all_view_names_in_schema | def all_view_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema name
... | python | def all_view_names_in_schema(self, schema, cache=False,
cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema name
... | [
"def",
"all_view_names_in_schema",
"(",
"self",
",",
"schema",
",",
"cache",
"=",
"False",
",",
"cache_timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"views",
"=",
"[",
"]",
"try",
":",
"views",
"=",
"self",
".",
"db_engine_spec",
".",
"g... | Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param schema: schema name
:type schema: str
:param cache: whether cache is enabled for the function
:type cache: bool
:param cac... | [
"Parameters",
"need",
"to",
"be",
"passed",
"as",
"keyword",
"arguments",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L984-L1008 | train |
apache/incubator-superset | superset/models/core.py | Database.all_schema_names | def all_schema_names(self, cache=False, cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param cache: whether cache is enabled for the function
:type cache:... | python | def all_schema_names(self, cache=False, cache_timeout=None, force=False):
"""Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param cache: whether cache is enabled for the function
:type cache:... | [
"def",
"all_schema_names",
"(",
"self",
",",
"cache",
"=",
"False",
",",
"cache_timeout",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"return",
"self",
".",
"db_engine_spec",
".",
"get_schema_names",
"(",
"self",
".",
"inspector",
")"
] | Parameters need to be passed as keyword arguments.
For unused parameters, they are referenced in
cache_util.memoized_func decorator.
:param cache: whether cache is enabled for the function
:type cache: bool
:param cache_timeout: timeout in seconds for the cache
:type ca... | [
"Parameters",
"need",
"to",
"be",
"passed",
"as",
"keyword",
"arguments",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1013-L1028 | train |
apache/incubator-superset | superset/models/core.py | Database.grains_dict | def grains_dict(self):
"""Allowing to lookup grain by either label or duration
For backward compatibility"""
d = {grain.duration: grain for grain in self.grains()}
d.update({grain.label: grain for grain in self.grains()})
return d | python | def grains_dict(self):
"""Allowing to lookup grain by either label or duration
For backward compatibility"""
d = {grain.duration: grain for grain in self.grains()}
d.update({grain.label: grain for grain in self.grains()})
return d | [
"def",
"grains_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"grain",
".",
"duration",
":",
"grain",
"for",
"grain",
"in",
"self",
".",
"grains",
"(",
")",
"}",
"d",
".",
"update",
"(",
"{",
"grain",
".",
"label",
":",
"grain",
"for",
"grain",
"in... | Allowing to lookup grain by either label or duration
For backward compatibility | [
"Allowing",
"to",
"lookup",
"grain",
"by",
"either",
"label",
"or",
"duration"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1050-L1056 | train |
apache/incubator-superset | superset/models/core.py | Log.log_this | def log_this(cls, f):
"""Decorator to log user actions"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
user_id = None
if g.user:
user_id = g.user.get_id()
d = request.form.to_dict() or {}
# request parameters can overwrite pos... | python | def log_this(cls, f):
"""Decorator to log user actions"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
user_id = None
if g.user:
user_id = g.user.get_id()
d = request.form.to_dict() or {}
# request parameters can overwrite pos... | [
"def",
"log_this",
"(",
"cls",
",",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"None",
"if",
"g",
".",
"user",
":",
"user_id",
"=",
"g",
... | Decorator to log user actions | [
"Decorator",
"to",
"log",
"user",
"actions"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/core.py#L1143-L1200 | train |
apache/incubator-superset | superset/views/base.py | api | def api(f):
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
logging.exception(e)
... | python | def api(f):
"""
A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
logging.exception(e)
... | [
"def",
"api",
"(",
"f",
")",
":",
"def",
"wraps",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"Exception",
"as",
"e",
":",... | A decorator to label an endpoint as an API. Catches uncaught exceptions and
return the response in the JSON format | [
"A",
"decorator",
"to",
"label",
"an",
"endpoint",
"as",
"an",
"API",
".",
"Catches",
"uncaught",
"exceptions",
"and",
"return",
"the",
"response",
"in",
"the",
"JSON",
"format"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L96-L108 | train |
apache/incubator-superset | superset/views/base.py | handle_api_exception | def handle_api_exception(f):
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions.
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
... | python | def handle_api_exception(f):
"""
A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions.
"""
def wraps(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
... | [
"def",
"handle_api_exception",
"(",
"f",
")",
":",
"def",
"wraps",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"SupersetSecurity... | A decorator to catch superset exceptions. Use it after the @api decorator above
so superset exception handler is triggered before the handler for generic exceptions. | [
"A",
"decorator",
"to",
"catch",
"superset",
"exceptions",
".",
"Use",
"it",
"after",
"the"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L111-L134 | train |
apache/incubator-superset | superset/views/base.py | check_ownership | def check_ownership(obj, raise_if_false=True):
"""Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be ... | python | def check_ownership(obj, raise_if_false=True):
"""Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be ... | [
"def",
"check_ownership",
"(",
"obj",
",",
"raise_if_false",
"=",
"True",
")",
":",
"if",
"not",
"obj",
":",
"return",
"False",
"security_exception",
"=",
"SupersetSecurityException",
"(",
"\"You don't have the rights to alter [{}]\"",
".",
"format",
"(",
"obj",
")"... | Meant to be used in `pre_update` hooks on models to enforce ownership
Admin have all access, and other users need to be referenced on either
the created_by field that comes with the ``AuditMixin``, or in a field
named ``owners`` which is expected to be a one-to-many with the User
model. It is meant to ... | [
"Meant",
"to",
"be",
"used",
"in",
"pre_update",
"hooks",
"on",
"models",
"to",
"enforce",
"ownership"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L331-L374 | train |
apache/incubator-superset | superset/views/base.py | bind_field | def bind_field(
self,
form: DynamicForm,
unbound_field: UnboundField,
options: Dict[Any, Any],
) -> Field:
"""
Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field opti... | python | def bind_field(
self,
form: DynamicForm,
unbound_field: UnboundField,
options: Dict[Any, Any],
) -> Field:
"""
Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field opti... | [
"def",
"bind_field",
"(",
"self",
",",
"form",
":",
"DynamicForm",
",",
"unbound_field",
":",
"UnboundField",
",",
"options",
":",
"Dict",
"[",
"Any",
",",
"Any",
"]",
",",
")",
"->",
"Field",
":",
"filters",
"=",
"unbound_field",
".",
"kwargs",
".",
"... | Customize how fields are bound by stripping all whitespace.
:param form: The form
:param unbound_field: The unbound field
:param options: The field options
:returns: The bound field | [
"Customize",
"how",
"fields",
"are",
"bound",
"by",
"stripping",
"all",
"whitespace",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L377-L394 | train |
apache/incubator-superset | superset/views/base.py | BaseSupersetView.common_bootsrap_payload | def common_bootsrap_payload(self):
"""Common data always sent to the client"""
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
return {
'flash_messages': messages,
'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS},
'... | python | def common_bootsrap_payload(self):
"""Common data always sent to the client"""
messages = get_flashed_messages(with_categories=True)
locale = str(get_locale())
return {
'flash_messages': messages,
'conf': {k: conf.get(k) for k in FRONTEND_CONF_KEYS},
'... | [
"def",
"common_bootsrap_payload",
"(",
"self",
")",
":",
"messages",
"=",
"get_flashed_messages",
"(",
"with_categories",
"=",
"True",
")",
"locale",
"=",
"str",
"(",
"get_locale",
"(",
")",
")",
"return",
"{",
"'flash_messages'",
":",
"messages",
",",
"'conf'... | Common data always sent to the client | [
"Common",
"data",
"always",
"sent",
"to",
"the",
"client"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L156-L166 | train |
apache/incubator-superset | superset/views/base.py | DeleteMixin._delete | def _delete(self, pk):
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete
"""
item = self.datamodel.get(pk, self._base_filters)
if not item:
... | python | def _delete(self, pk):
"""
Delete function logic, override to implement diferent logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete
"""
item = self.datamodel.get(pk, self._base_filters)
if not item:
... | [
"def",
"_delete",
"(",
"self",
",",
"pk",
")",
":",
"item",
"=",
"self",
".",
"datamodel",
".",
"get",
"(",
"pk",
",",
"self",
".",
"_base_filters",
")",
"if",
"not",
"item",
":",
"abort",
"(",
"404",
")",
"try",
":",
"self",
".",
"pre_delete",
"... | Delete function logic, override to implement diferent logic
deletes the record with primary_key = pk
:param pk:
record primary key to delete | [
"Delete",
"function",
"logic",
"override",
"to",
"implement",
"diferent",
"logic",
"deletes",
"the",
"record",
"with",
"primary_key",
"=",
"pk"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L207-L251 | train |
apache/incubator-superset | superset/views/base.py | SupersetFilter.get_all_permissions | def get_all_permissions(self):
"""Returns a set of tuples with the perm name and view menu name"""
perms = set()
for role in self.get_user_roles():
for perm_view in role.permissions:
t = (perm_view.permission.name, perm_view.view_menu.name)
perms.add(t... | python | def get_all_permissions(self):
"""Returns a set of tuples with the perm name and view menu name"""
perms = set()
for role in self.get_user_roles():
for perm_view in role.permissions:
t = (perm_view.permission.name, perm_view.view_menu.name)
perms.add(t... | [
"def",
"get_all_permissions",
"(",
"self",
")",
":",
"perms",
"=",
"set",
"(",
")",
"for",
"role",
"in",
"self",
".",
"get_user_roles",
"(",
")",
":",
"for",
"perm_view",
"in",
"role",
".",
"permissions",
":",
"t",
"=",
"(",
"perm_view",
".",
"permissi... | Returns a set of tuples with the perm name and view menu name | [
"Returns",
"a",
"set",
"of",
"tuples",
"with",
"the",
"perm",
"name",
"and",
"view",
"menu",
"name"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L286-L293 | train |
apache/incubator-superset | superset/views/base.py | SupersetFilter.get_view_menus | def get_view_menus(self, permission_name):
"""Returns the details of view_menus for a perm name"""
vm = set()
for perm_name, vm_name in self.get_all_permissions():
if perm_name == permission_name:
vm.add(vm_name)
return vm | python | def get_view_menus(self, permission_name):
"""Returns the details of view_menus for a perm name"""
vm = set()
for perm_name, vm_name in self.get_all_permissions():
if perm_name == permission_name:
vm.add(vm_name)
return vm | [
"def",
"get_view_menus",
"(",
"self",
",",
"permission_name",
")",
":",
"vm",
"=",
"set",
"(",
")",
"for",
"perm_name",
",",
"vm_name",
"in",
"self",
".",
"get_all_permissions",
"(",
")",
":",
"if",
"perm_name",
"==",
"permission_name",
":",
"vm",
".",
"... | Returns the details of view_menus for a perm name | [
"Returns",
"the",
"details",
"of",
"view_menus",
"for",
"a",
"perm",
"name"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/base.py#L306-L312 | train |
apache/incubator-superset | superset/tasks/schedules.py | destroy_webdriver | def destroy_webdriver(driver):
"""
Destroy a driver
"""
# This is some very flaky code in selenium. Hence the retries
# and catch-all exceptions
try:
retry_call(driver.close, tries=2)
except Exception:
pass
try:
driver.quit()
except Exception:
pass | python | def destroy_webdriver(driver):
"""
Destroy a driver
"""
# This is some very flaky code in selenium. Hence the retries
# and catch-all exceptions
try:
retry_call(driver.close, tries=2)
except Exception:
pass
try:
driver.quit()
except Exception:
pass | [
"def",
"destroy_webdriver",
"(",
"driver",
")",
":",
"# This is some very flaky code in selenium. Hence the retries",
"# and catch-all exceptions",
"try",
":",
"retry_call",
"(",
"driver",
".",
"close",
",",
"tries",
"=",
"2",
")",
"except",
"Exception",
":",
"pass",
... | Destroy a driver | [
"Destroy",
"a",
"driver"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L190-L204 | train |
apache/incubator-superset | superset/tasks/schedules.py | deliver_dashboard | def deliver_dashboard(schedule):
"""
Given a schedule, delivery the dashboard as an email report
"""
dashboard = schedule.dashboard
dashboard_url = _get_url_path(
'Superset.dashboard',
dashboard_id=dashboard.id,
)
# Create a driver, fetch the page, wait for the page to rend... | python | def deliver_dashboard(schedule):
"""
Given a schedule, delivery the dashboard as an email report
"""
dashboard = schedule.dashboard
dashboard_url = _get_url_path(
'Superset.dashboard',
dashboard_id=dashboard.id,
)
# Create a driver, fetch the page, wait for the page to rend... | [
"def",
"deliver_dashboard",
"(",
"schedule",
")",
":",
"dashboard",
"=",
"schedule",
".",
"dashboard",
"dashboard_url",
"=",
"_get_url_path",
"(",
"'Superset.dashboard'",
",",
"dashboard_id",
"=",
"dashboard",
".",
"id",
",",
")",
"# Create a driver, fetch the page, w... | Given a schedule, delivery the dashboard as an email report | [
"Given",
"a",
"schedule",
"delivery",
"the",
"dashboard",
"as",
"an",
"email",
"report"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L207-L258 | train |
apache/incubator-superset | superset/tasks/schedules.py | deliver_slice | def deliver_slice(schedule):
"""
Given a schedule, delivery the slice as an email report
"""
if schedule.email_format == SliceEmailReportFormat.data:
email = _get_slice_data(schedule)
elif schedule.email_format == SliceEmailReportFormat.visualization:
email = _get_slice_visualization... | python | def deliver_slice(schedule):
"""
Given a schedule, delivery the slice as an email report
"""
if schedule.email_format == SliceEmailReportFormat.data:
email = _get_slice_data(schedule)
elif schedule.email_format == SliceEmailReportFormat.visualization:
email = _get_slice_visualization... | [
"def",
"deliver_slice",
"(",
"schedule",
")",
":",
"if",
"schedule",
".",
"email_format",
"==",
"SliceEmailReportFormat",
".",
"data",
":",
"email",
"=",
"_get_slice_data",
"(",
"schedule",
")",
"elif",
"schedule",
".",
"email_format",
"==",
"SliceEmailReportForma... | Given a schedule, delivery the slice as an email report | [
"Given",
"a",
"schedule",
"delivery",
"the",
"slice",
"as",
"an",
"email",
"report"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L356-L373 | train |
apache/incubator-superset | superset/tasks/schedules.py | schedule_window | def schedule_window(report_type, start_at, stop_at, resolution):
"""
Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule)
"""
model_cls = get_scheduler_model(report_type)
dbsession = db.create_scop... | python | def schedule_window(report_type, start_at, stop_at, resolution):
"""
Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule)
"""
model_cls = get_scheduler_model(report_type)
dbsession = db.create_scop... | [
"def",
"schedule_window",
"(",
"report_type",
",",
"start_at",
",",
"stop_at",
",",
"resolution",
")",
":",
"model_cls",
"=",
"get_scheduler_model",
"(",
"report_type",
")",
"dbsession",
"=",
"db",
".",
"create_scoped_session",
"(",
")",
"schedules",
"=",
"dbses... | Find all active schedules and schedule celery tasks for
each of them with a specific ETA (determined by parsing
the cron schedule for the schedule) | [
"Find",
"all",
"active",
"schedules",
"and",
"schedule",
"celery",
"tasks",
"for",
"each",
"of",
"them",
"with",
"a",
"specific",
"ETA",
"(",
"determined",
"by",
"parsing",
"the",
"cron",
"schedule",
"for",
"the",
"schedule",
")"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L419-L440 | train |
apache/incubator-superset | superset/tasks/schedules.py | schedule_hourly | def schedule_hourly():
""" Celery beat job meant to be invoked hourly """
if not config.get('ENABLE_SCHEDULED_EMAIL_REPORTS'):
logging.info('Scheduled email reports not enabled in config')
return
resolution = config.get('EMAIL_REPORTS_CRON_RESOLUTION', 0) * 60
# Get the top of the hou... | python | def schedule_hourly():
""" Celery beat job meant to be invoked hourly """
if not config.get('ENABLE_SCHEDULED_EMAIL_REPORTS'):
logging.info('Scheduled email reports not enabled in config')
return
resolution = config.get('EMAIL_REPORTS_CRON_RESOLUTION', 0) * 60
# Get the top of the hou... | [
"def",
"schedule_hourly",
"(",
")",
":",
"if",
"not",
"config",
".",
"get",
"(",
"'ENABLE_SCHEDULED_EMAIL_REPORTS'",
")",
":",
"logging",
".",
"info",
"(",
"'Scheduled email reports not enabled in config'",
")",
"return",
"resolution",
"=",
"config",
".",
"get",
"... | Celery beat job meant to be invoked hourly | [
"Celery",
"beat",
"job",
"meant",
"to",
"be",
"invoked",
"hourly"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/schedules.py#L444-L457 | train |
apache/incubator-superset | superset/dataframe.py | dedup | def dedup(l, suffix='__', case_sensitive=True):
"""De-duplicates a list of string by suffixing a counter
Always returns the same number of entries as provided, and always returns
unique values. Case sensitive comparison by default.
>>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar'])))
fo... | python | def dedup(l, suffix='__', case_sensitive=True):
"""De-duplicates a list of string by suffixing a counter
Always returns the same number of entries as provided, and always returns
unique values. Case sensitive comparison by default.
>>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar'])))
fo... | [
"def",
"dedup",
"(",
"l",
",",
"suffix",
"=",
"'__'",
",",
"case_sensitive",
"=",
"True",
")",
":",
"new_l",
"=",
"[",
"]",
"seen",
"=",
"{",
"}",
"for",
"s",
"in",
"l",
":",
"s_fixed_case",
"=",
"s",
"if",
"case_sensitive",
"else",
"s",
".",
"lo... | De-duplicates a list of string by suffixing a counter
Always returns the same number of entries as provided, and always returns
unique values. Case sensitive comparison by default.
>>> print(','.join(dedup(['foo', 'bar', 'bar', 'bar', 'Bar'])))
foo,bar,bar__1,bar__2,Bar
>>> print(','.join(dedup(['... | [
"De",
"-",
"duplicates",
"a",
"list",
"of",
"string",
"by",
"suffixing",
"a",
"counter"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/dataframe.py#L39-L60 | train |
apache/incubator-superset | superset/dataframe.py | SupersetDataFrame.db_type | def db_type(cls, dtype):
"""Given a numpy dtype, Returns a generic database type"""
if isinstance(dtype, ExtensionDtype):
return cls.type_map.get(dtype.kind)
elif hasattr(dtype, 'char'):
return cls.type_map.get(dtype.char) | python | def db_type(cls, dtype):
"""Given a numpy dtype, Returns a generic database type"""
if isinstance(dtype, ExtensionDtype):
return cls.type_map.get(dtype.kind)
elif hasattr(dtype, 'char'):
return cls.type_map.get(dtype.char) | [
"def",
"db_type",
"(",
"cls",
",",
"dtype",
")",
":",
"if",
"isinstance",
"(",
"dtype",
",",
"ExtensionDtype",
")",
":",
"return",
"cls",
".",
"type_map",
".",
"get",
"(",
"dtype",
".",
"kind",
")",
"elif",
"hasattr",
"(",
"dtype",
",",
"'char'",
")"... | Given a numpy dtype, Returns a generic database type | [
"Given",
"a",
"numpy",
"dtype",
"Returns",
"a",
"generic",
"database",
"type"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/dataframe.py#L122-L127 | train |
apache/incubator-superset | superset/dataframe.py | SupersetDataFrame.columns | def columns(self):
"""Provides metadata about columns for data visualization.
:return: dict, with the fields name, type, is_date, is_dim and agg.
"""
if self.df.empty:
return None
columns = []
sample_size = min(INFER_COL_TYPES_SAMPLE_SIZE, len(self.df.index)... | python | def columns(self):
"""Provides metadata about columns for data visualization.
:return: dict, with the fields name, type, is_date, is_dim and agg.
"""
if self.df.empty:
return None
columns = []
sample_size = min(INFER_COL_TYPES_SAMPLE_SIZE, len(self.df.index)... | [
"def",
"columns",
"(",
"self",
")",
":",
"if",
"self",
".",
"df",
".",
"empty",
":",
"return",
"None",
"columns",
"=",
"[",
"]",
"sample_size",
"=",
"min",
"(",
"INFER_COL_TYPES_SAMPLE_SIZE",
",",
"len",
"(",
"self",
".",
"df",
".",
"index",
")",
")"... | Provides metadata about columns for data visualization.
:return: dict, with the fields name, type, is_date, is_dim and agg. | [
"Provides",
"metadata",
"about",
"columns",
"for",
"data",
"visualization",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/dataframe.py#L177-L229 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | TableColumn.get_timestamp_expression | def get_timestamp_expression(self, time_grain):
"""Getting the time component of the query"""
label = utils.DTTM_ALIAS
db = self.table.database
pdf = self.python_date_format
is_epoch = pdf in ('epoch_s', 'epoch_ms')
if not self.expression and not time_grain and not is_ep... | python | def get_timestamp_expression(self, time_grain):
"""Getting the time component of the query"""
label = utils.DTTM_ALIAS
db = self.table.database
pdf = self.python_date_format
is_epoch = pdf in ('epoch_s', 'epoch_ms')
if not self.expression and not time_grain and not is_ep... | [
"def",
"get_timestamp_expression",
"(",
"self",
",",
"time_grain",
")",
":",
"label",
"=",
"utils",
".",
"DTTM_ALIAS",
"db",
"=",
"self",
".",
"table",
".",
"database",
"pdf",
"=",
"self",
".",
"python_date_format",
"is_epoch",
"=",
"pdf",
"in",
"(",
"'epo... | Getting the time component of the query | [
"Getting",
"the",
"time",
"component",
"of",
"the",
"query"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L143-L162 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | TableColumn.dttm_sql_literal | def dttm_sql_literal(self, dttm, is_epoch_in_utc):
"""Convert datetime object to a SQL expression string
If database_expression is empty, the internal dttm
will be parsed as the string with the pattern that
the user inputted (python_date_format)
If database_expression is not emp... | python | def dttm_sql_literal(self, dttm, is_epoch_in_utc):
"""Convert datetime object to a SQL expression string
If database_expression is empty, the internal dttm
will be parsed as the string with the pattern that
the user inputted (python_date_format)
If database_expression is not emp... | [
"def",
"dttm_sql_literal",
"(",
"self",
",",
"dttm",
",",
"is_epoch_in_utc",
")",
":",
"tf",
"=",
"self",
".",
"python_date_format",
"if",
"self",
".",
"database_expression",
":",
"return",
"self",
".",
"database_expression",
".",
"format",
"(",
"dttm",
".",
... | Convert datetime object to a SQL expression string
If database_expression is empty, the internal dttm
will be parsed as the string with the pattern that
the user inputted (python_date_format)
If database_expression is not empty, the internal dttm
will be parsed as the sql senten... | [
"Convert",
"datetime",
"object",
"to",
"a",
"SQL",
"expression",
"string"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L172-L198 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.make_sqla_column_compatible | def make_sqla_column_compatible(self, sqla_col, label=None):
"""Takes a sql alchemy column object and adds label info if supported by engine.
:param sqla_col: sql alchemy column instance
:param label: alias/label that column is expected to have
:return: either a sql alchemy column or lab... | python | def make_sqla_column_compatible(self, sqla_col, label=None):
"""Takes a sql alchemy column object and adds label info if supported by engine.
:param sqla_col: sql alchemy column instance
:param label: alias/label that column is expected to have
:return: either a sql alchemy column or lab... | [
"def",
"make_sqla_column_compatible",
"(",
"self",
",",
"sqla_col",
",",
"label",
"=",
"None",
")",
":",
"label_expected",
"=",
"label",
"or",
"sqla_col",
".",
"name",
"db_engine_spec",
"=",
"self",
".",
"database",
".",
"db_engine_spec",
"if",
"db_engine_spec",... | Takes a sql alchemy column object and adds label info if supported by engine.
:param sqla_col: sql alchemy column instance
:param label: alias/label that column is expected to have
:return: either a sql alchemy column or label instance if supported by engine | [
"Takes",
"a",
"sql",
"alchemy",
"column",
"object",
"and",
"adds",
"label",
"info",
"if",
"supported",
"by",
"engine",
".",
":",
"param",
"sqla_col",
":",
"sql",
"alchemy",
"column",
"instance",
":",
"param",
"label",
":",
"alias",
"/",
"label",
"that",
... | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L302-L314 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.values_for_column | def values_for_column(self, column_name, limit=10000):
"""Runs query against sqla to retrieve some
sample values for the given column.
"""
cols = {col.column_name: col for col in self.columns}
target_col = cols[column_name]
tp = self.get_template_processor()
qry ... | python | def values_for_column(self, column_name, limit=10000):
"""Runs query against sqla to retrieve some
sample values for the given column.
"""
cols = {col.column_name: col for col in self.columns}
target_col = cols[column_name]
tp = self.get_template_processor()
qry ... | [
"def",
"values_for_column",
"(",
"self",
",",
"column_name",
",",
"limit",
"=",
"10000",
")",
":",
"cols",
"=",
"{",
"col",
".",
"column_name",
":",
"col",
"for",
"col",
"in",
"self",
".",
"columns",
"}",
"target_col",
"=",
"cols",
"[",
"column_name",
... | Runs query against sqla to retrieve some
sample values for the given column. | [
"Runs",
"query",
"against",
"sqla",
"to",
"retrieve",
"some",
"sample",
"values",
"for",
"the",
"given",
"column",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L437-L464 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.mutate_query_from_config | def mutate_query_from_config(self, sql):
"""Apply config's SQL_QUERY_MUTATOR
Typically adds comments to the query with context"""
SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
if SQL_QUERY_MUTATOR:
username = utils.get_username()
sql = SQL_QUERY_MUTATOR(sql... | python | def mutate_query_from_config(self, sql):
"""Apply config's SQL_QUERY_MUTATOR
Typically adds comments to the query with context"""
SQL_QUERY_MUTATOR = config.get('SQL_QUERY_MUTATOR')
if SQL_QUERY_MUTATOR:
username = utils.get_username()
sql = SQL_QUERY_MUTATOR(sql... | [
"def",
"mutate_query_from_config",
"(",
"self",
",",
"sql",
")",
":",
"SQL_QUERY_MUTATOR",
"=",
"config",
".",
"get",
"(",
"'SQL_QUERY_MUTATOR'",
")",
"if",
"SQL_QUERY_MUTATOR",
":",
"username",
"=",
"utils",
".",
"get_username",
"(",
")",
"sql",
"=",
"SQL_QUE... | Apply config's SQL_QUERY_MUTATOR
Typically adds comments to the query with context | [
"Apply",
"config",
"s",
"SQL_QUERY_MUTATOR"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L466-L474 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.adhoc_metric_to_sqla | def adhoc_metric_to_sqla(self, metric, cols):
"""
Turn an adhoc metric into a sqlalchemy column.
:param dict metric: Adhoc metric definition
:param dict cols: Columns for the current table
:returns: The metric defined as a sqlalchemy column
:rtype: sqlalchemy.sql.column
... | python | def adhoc_metric_to_sqla(self, metric, cols):
"""
Turn an adhoc metric into a sqlalchemy column.
:param dict metric: Adhoc metric definition
:param dict cols: Columns for the current table
:returns: The metric defined as a sqlalchemy column
:rtype: sqlalchemy.sql.column
... | [
"def",
"adhoc_metric_to_sqla",
"(",
"self",
",",
"metric",
",",
"cols",
")",
":",
"expression_type",
"=",
"metric",
".",
"get",
"(",
"'expressionType'",
")",
"label",
"=",
"utils",
".",
"get_metric_name",
"(",
"metric",
")",
"if",
"expression_type",
"==",
"u... | Turn an adhoc metric into a sqlalchemy column.
:param dict metric: Adhoc metric definition
:param dict cols: Columns for the current table
:returns: The metric defined as a sqlalchemy column
:rtype: sqlalchemy.sql.column | [
"Turn",
"an",
"adhoc",
"metric",
"into",
"a",
"sqlalchemy",
"column",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L509-L534 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.get_sqla_query | def get_sqla_query( # sqla
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=15,
timeseries_limit_metric=None,
row_limit=None,
inner_f... | python | def get_sqla_query( # sqla
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=15,
timeseries_limit_metric=None,
row_limit=None,
inner_f... | [
"def",
"get_sqla_query",
"(",
"# sqla",
"self",
",",
"groupby",
",",
"metrics",
",",
"granularity",
",",
"from_dttm",
",",
"to_dttm",
",",
"filter",
"=",
"None",
",",
"# noqa",
"is_timeseries",
"=",
"True",
",",
"timeseries_limit",
"=",
"15",
",",
"timeserie... | Querying any sqla table from this common interface | [
"Querying",
"any",
"sqla",
"table",
"from",
"this",
"common",
"interface"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L536-L808 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.fetch_metadata | def fetch_metadata(self):
"""Fetches the metadata for the table and merges it in"""
try:
table = self.get_sqla_table_object()
except Exception as e:
logging.exception(e)
raise Exception(_(
"Table [{}] doesn't seem to exist in the specified data... | python | def fetch_metadata(self):
"""Fetches the metadata for the table and merges it in"""
try:
table = self.get_sqla_table_object()
except Exception as e:
logging.exception(e)
raise Exception(_(
"Table [{}] doesn't seem to exist in the specified data... | [
"def",
"fetch_metadata",
"(",
"self",
")",
":",
"try",
":",
"table",
"=",
"self",
".",
"get_sqla_table_object",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"logging",
".",
"exception",
"(",
"e",
")",
"raise",
"Exception",
"(",
"_",
"(",
"\"Table [{}... | Fetches the metadata for the table and merges it in | [
"Fetches",
"the",
"metadata",
"for",
"the",
"table",
"and",
"merges",
"it",
"in"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L875-L930 | train |
apache/incubator-superset | superset/connectors/sqla/models.py | SqlaTable.import_obj | def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata is... | python | def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata is... | [
"def",
"import_obj",
"(",
"cls",
",",
"i_datasource",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"lookup_sqlatable",
"(",
"table",
")",
":",
"return",
"db",
".",
"session",
".",
"query",
"(",
"SqlaTable",
")",
".",
"join",
"(",
"Database",
")",
... | Imports the datasource from the object to the database.
Metrics and columns and datasource will be overrided if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata isn't copies over. | [
"Imports",
"the",
"datasource",
"from",
"the",
"object",
"to",
"the",
"database",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/models.py#L933-L952 | train |
apache/incubator-superset | superset/data/long_lat.py | load_long_lat_data | def load_long_lat_data():
"""Loading lat/long data from a csv file in the repo"""
data = get_example_data('san_francisco.csv.gz', make_bytes=True)
pdf = pd.read_csv(data, encoding='utf-8')
start = datetime.datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0)
pdf['datetime'] = [... | python | def load_long_lat_data():
"""Loading lat/long data from a csv file in the repo"""
data = get_example_data('san_francisco.csv.gz', make_bytes=True)
pdf = pd.read_csv(data, encoding='utf-8')
start = datetime.datetime.now().replace(
hour=0, minute=0, second=0, microsecond=0)
pdf['datetime'] = [... | [
"def",
"load_long_lat_data",
"(",
")",
":",
"data",
"=",
"get_example_data",
"(",
"'san_francisco.csv.gz'",
",",
"make_bytes",
"=",
"True",
")",
"pdf",
"=",
"pd",
".",
"read_csv",
"(",
"data",
",",
"encoding",
"=",
"'utf-8'",
")",
"start",
"=",
"datetime",
... | Loading lat/long data from a csv file in the repo | [
"Loading",
"lat",
"/",
"long",
"data",
"from",
"a",
"csv",
"file",
"in",
"the",
"repo"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/long_lat.py#L36-L110 | train |
apache/incubator-superset | superset/views/datasource.py | Datasource.external_metadata | def external_metadata(self, datasource_type=None, datasource_id=None):
"""Gets column info from the source system"""
if datasource_type == 'druid':
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session)
elif datasource_type == 'tabl... | python | def external_metadata(self, datasource_type=None, datasource_id=None):
"""Gets column info from the source system"""
if datasource_type == 'druid':
datasource = ConnectorRegistry.get_datasource(
datasource_type, datasource_id, db.session)
elif datasource_type == 'tabl... | [
"def",
"external_metadata",
"(",
"self",
",",
"datasource_type",
"=",
"None",
",",
"datasource_id",
"=",
"None",
")",
":",
"if",
"datasource_type",
"==",
"'druid'",
":",
"datasource",
"=",
"ConnectorRegistry",
".",
"get_datasource",
"(",
"datasource_type",
",",
... | Gets column info from the source system | [
"Gets",
"column",
"info",
"from",
"the",
"source",
"system"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/datasource.py#L70-L89 | train |
apache/incubator-superset | superset/forms.py | filter_not_empty_values | def filter_not_empty_values(value):
"""Returns a list of non empty values or None"""
if not value:
return None
data = [x for x in value if x]
if not data:
return None
return data | python | def filter_not_empty_values(value):
"""Returns a list of non empty values or None"""
if not value:
return None
data = [x for x in value if x]
if not data:
return None
return data | [
"def",
"filter_not_empty_values",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"None",
"data",
"=",
"[",
"x",
"for",
"x",
"in",
"value",
"if",
"x",
"]",
"if",
"not",
"data",
":",
"return",
"None",
"return",
"data"
] | Returns a list of non empty values or None | [
"Returns",
"a",
"list",
"of",
"non",
"empty",
"values",
"or",
"None"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/forms.py#L50-L57 | train |
apache/incubator-superset | superset/forms.py | CsvToDatabaseForm.at_least_one_schema_is_allowed | def at_least_one_schema_is_allowed(database):
"""
If the user has access to the database or all datasource
1. if schemas_allowed_for_csv_upload is empty
a) if database does not support schema
user is able to upload csv without specifying schema name
... | python | def at_least_one_schema_is_allowed(database):
"""
If the user has access to the database or all datasource
1. if schemas_allowed_for_csv_upload is empty
a) if database does not support schema
user is able to upload csv without specifying schema name
... | [
"def",
"at_least_one_schema_is_allowed",
"(",
"database",
")",
":",
"if",
"(",
"security_manager",
".",
"database_access",
"(",
"database",
")",
"or",
"security_manager",
".",
"all_datasource_access",
"(",
")",
")",
":",
"return",
"True",
"schemas",
"=",
"database... | If the user has access to the database or all datasource
1. if schemas_allowed_for_csv_upload is empty
a) if database does not support schema
user is able to upload csv without specifying schema name
b) if database supports schema
user ... | [
"If",
"the",
"user",
"has",
"access",
"to",
"the",
"database",
"or",
"all",
"datasource",
"1",
".",
"if",
"schemas_allowed_for_csv_upload",
"is",
"empty",
"a",
")",
"if",
"database",
"does",
"not",
"support",
"schema",
"user",
"is",
"able",
"to",
"upload",
... | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/forms.py#L73-L106 | train |
apache/incubator-superset | superset/views/sql_lab.py | QueryFilter.apply | def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:
"""
Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query
"""
if security_manager.can_only_access_owned_q... | python | def apply(
self,
query: BaseQuery,
func: Callable) -> BaseQuery:
"""
Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query
"""
if security_manager.can_only_access_owned_q... | [
"def",
"apply",
"(",
"self",
",",
"query",
":",
"BaseQuery",
",",
"func",
":",
"Callable",
")",
"->",
"BaseQuery",
":",
"if",
"security_manager",
".",
"can_only_access_owned_queries",
"(",
")",
":",
"query",
"=",
"(",
"query",
".",
"filter",
"(",
"Query",
... | Filter queries to only those owned by current user if
can_only_access_owned_queries permission is set.
:returns: query | [
"Filter",
"queries",
"to",
"only",
"those",
"owned",
"by",
"current",
"user",
"if",
"can_only_access_owned_queries",
"permission",
"is",
"set",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/sql_lab.py#L34-L49 | train |
apache/incubator-superset | superset/connectors/sqla/views.py | TableModelView.edit | def edit(self, pk):
"""Simple hack to redirect to explore view after saving"""
resp = super(TableModelView, self).edit(pk)
if isinstance(resp, str):
return resp
return redirect('/superset/explore/table/{}/'.format(pk)) | python | def edit(self, pk):
"""Simple hack to redirect to explore view after saving"""
resp = super(TableModelView, self).edit(pk)
if isinstance(resp, str):
return resp
return redirect('/superset/explore/table/{}/'.format(pk)) | [
"def",
"edit",
"(",
"self",
",",
"pk",
")",
":",
"resp",
"=",
"super",
"(",
"TableModelView",
",",
"self",
")",
".",
"edit",
"(",
"pk",
")",
"if",
"isinstance",
"(",
"resp",
",",
"str",
")",
":",
"return",
"resp",
"return",
"redirect",
"(",
"'/supe... | Simple hack to redirect to explore view after saving | [
"Simple",
"hack",
"to",
"redirect",
"to",
"explore",
"view",
"after",
"saving"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/sqla/views.py#L305-L310 | train |
apache/incubator-superset | superset/translations/utils.py | get_language_pack | def get_language_pack(locale):
"""Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords"
"""
pack = ALL_LANGUAGE_PACKS.get(locale)
if not pack:
filename = DIR + '/{}/LC_MESSAGES/me... | python | def get_language_pack(locale):
"""Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords"
"""
pack = ALL_LANGUAGE_PACKS.get(locale)
if not pack:
filename = DIR + '/{}/LC_MESSAGES/me... | [
"def",
"get_language_pack",
"(",
"locale",
")",
":",
"pack",
"=",
"ALL_LANGUAGE_PACKS",
".",
"get",
"(",
"locale",
")",
"if",
"not",
"pack",
":",
"filename",
"=",
"DIR",
"+",
"'/{}/LC_MESSAGES/messages.json'",
".",
"format",
"(",
"locale",
")",
"try",
":",
... | Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords" | [
"Get",
"/",
"cache",
"a",
"language",
"pack"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/translations/utils.py#L27-L45 | train |
apache/incubator-superset | superset/tasks/cache.py | get_form_data | def get_form_data(chart_id, dashboard=None):
"""
Build `form_data` for chart GET request from dashboard's `default_filters`.
When a dashboard has `default_filters` they need to be added as extra
filters in the GET request for charts.
"""
form_data = {'slice_id': chart_id}
if dashboard is... | python | def get_form_data(chart_id, dashboard=None):
"""
Build `form_data` for chart GET request from dashboard's `default_filters`.
When a dashboard has `default_filters` they need to be added as extra
filters in the GET request for charts.
"""
form_data = {'slice_id': chart_id}
if dashboard is... | [
"def",
"get_form_data",
"(",
"chart_id",
",",
"dashboard",
"=",
"None",
")",
":",
"form_data",
"=",
"{",
"'slice_id'",
":",
"chart_id",
"}",
"if",
"dashboard",
"is",
"None",
"or",
"not",
"dashboard",
".",
"json_metadata",
":",
"return",
"form_data",
"json_me... | Build `form_data` for chart GET request from dashboard's `default_filters`.
When a dashboard has `default_filters` they need to be added as extra
filters in the GET request for charts. | [
"Build",
"form_data",
"for",
"chart",
"GET",
"request",
"from",
"dashboard",
"s",
"default_filters",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/cache.py#L40-L75 | train |
apache/incubator-superset | superset/tasks/cache.py | get_url | def get_url(params):
"""Return external URL for warming up a given chart/table cache."""
baseurl = 'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'.format(
**app.config)
with app.test_request_context():
return urllib.parse.urljoin(
baseurl,
url_for('Su... | python | def get_url(params):
"""Return external URL for warming up a given chart/table cache."""
baseurl = 'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'.format(
**app.config)
with app.test_request_context():
return urllib.parse.urljoin(
baseurl,
url_for('Su... | [
"def",
"get_url",
"(",
"params",
")",
":",
"baseurl",
"=",
"'http://{SUPERSET_WEBSERVER_ADDRESS}:{SUPERSET_WEBSERVER_PORT}/'",
".",
"format",
"(",
"*",
"*",
"app",
".",
"config",
")",
"with",
"app",
".",
"test_request_context",
"(",
")",
":",
"return",
"urllib",
... | Return external URL for warming up a given chart/table cache. | [
"Return",
"external",
"URL",
"for",
"warming",
"up",
"a",
"given",
"chart",
"/",
"table",
"cache",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/cache.py#L78-L86 | train |
apache/incubator-superset | superset/tasks/cache.py | cache_warmup | def cache_warmup(strategy_name, *args, **kwargs):
"""
Warm up cache.
This task periodically hits charts to warm up the cache.
"""
logger.info('Loading strategy')
class_ = None
for class_ in strategies:
if class_.name == strategy_name:
break
else:
message = f... | python | def cache_warmup(strategy_name, *args, **kwargs):
"""
Warm up cache.
This task periodically hits charts to warm up the cache.
"""
logger.info('Loading strategy')
class_ = None
for class_ in strategies:
if class_.name == strategy_name:
break
else:
message = f... | [
"def",
"cache_warmup",
"(",
"strategy_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
".",
"info",
"(",
"'Loading strategy'",
")",
"class_",
"=",
"None",
"for",
"class_",
"in",
"strategies",
":",
"if",
"class_",
".",
"name",
"==",
... | Warm up cache.
This task periodically hits charts to warm up the cache. | [
"Warm",
"up",
"cache",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/tasks/cache.py#L280-L316 | train |
apache/incubator-superset | superset/db_engines/hive.py | fetch_logs | def fetch_logs(self, max_rows=1024,
orientation=None):
"""Mocked. Retrieve the logs produced by the execution of the query.
Can be called multiple times to fetch the logs produced after
the previous call.
:returns: list<str>
:raises: ``ProgrammingError`` when no query has been started... | python | def fetch_logs(self, max_rows=1024,
orientation=None):
"""Mocked. Retrieve the logs produced by the execution of the query.
Can be called multiple times to fetch the logs produced after
the previous call.
:returns: list<str>
:raises: ``ProgrammingError`` when no query has been started... | [
"def",
"fetch_logs",
"(",
"self",
",",
"max_rows",
"=",
"1024",
",",
"orientation",
"=",
"None",
")",
":",
"from",
"pyhive",
"import",
"hive",
"from",
"TCLIService",
"import",
"ttypes",
"from",
"thrift",
"import",
"Thrift",
"orientation",
"=",
"orientation",
... | Mocked. Retrieve the logs produced by the execution of the query.
Can be called multiple times to fetch the logs produced after
the previous call.
:returns: list<str>
:raises: ``ProgrammingError`` when no query has been started
.. note::
This is not a part of DB-API. | [
"Mocked",
".",
"Retrieve",
"the",
"logs",
"produced",
"by",
"the",
"execution",
"of",
"the",
"query",
".",
"Can",
"be",
"called",
"multiple",
"times",
"to",
"fetch",
"the",
"logs",
"produced",
"after",
"the",
"previous",
"call",
".",
":",
"returns",
":",
... | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/db_engines/hive.py#L21-L61 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidCluster.refresh_datasources | def refresh_datasources(
self,
datasource_name=None,
merge_flag=True,
refreshAll=True):
"""Refresh metadata of all datasources in the cluster
If ``datasource_name`` is specified, only that datasource is updated
"""
ds_list = self.get_dataso... | python | def refresh_datasources(
self,
datasource_name=None,
merge_flag=True,
refreshAll=True):
"""Refresh metadata of all datasources in the cluster
If ``datasource_name`` is specified, only that datasource is updated
"""
ds_list = self.get_dataso... | [
"def",
"refresh_datasources",
"(",
"self",
",",
"datasource_name",
"=",
"None",
",",
"merge_flag",
"=",
"True",
",",
"refreshAll",
"=",
"True",
")",
":",
"ds_list",
"=",
"self",
".",
"get_datasources",
"(",
")",
"blacklist",
"=",
"conf",
".",
"get",
"(",
... | Refresh metadata of all datasources in the cluster
If ``datasource_name`` is specified, only that datasource is updated | [
"Refresh",
"metadata",
"of",
"all",
"datasources",
"in",
"the",
"cluster",
"If",
"datasource_name",
"is",
"specified",
"only",
"that",
"datasource",
"is",
"updated"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L165-L182 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidCluster.refresh | def refresh(self, datasource_names, merge_flag, refreshAll):
"""
Fetches metadata for the specified datasources and
merges to the Superset database
"""
session = db.session
ds_list = (
session.query(DruidDatasource)
.filter(DruidDatasource.cluster_... | python | def refresh(self, datasource_names, merge_flag, refreshAll):
"""
Fetches metadata for the specified datasources and
merges to the Superset database
"""
session = db.session
ds_list = (
session.query(DruidDatasource)
.filter(DruidDatasource.cluster_... | [
"def",
"refresh",
"(",
"self",
",",
"datasource_names",
",",
"merge_flag",
",",
"refreshAll",
")",
":",
"session",
"=",
"db",
".",
"session",
"ds_list",
"=",
"(",
"session",
".",
"query",
"(",
"DruidDatasource",
")",
".",
"filter",
"(",
"DruidDatasource",
... | Fetches metadata for the specified datasources and
merges to the Superset database | [
"Fetches",
"metadata",
"for",
"the",
"specified",
"datasources",
"and",
"merges",
"to",
"the",
"Superset",
"database"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L184-L248 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidColumn.refresh_metrics | def refresh_metrics(self):
"""Refresh metrics based on the column metadata"""
metrics = self.get_metrics()
dbmetrics = (
db.session.query(DruidMetric)
.filter(DruidMetric.datasource_id == self.datasource_id)
.filter(DruidMetric.metric_name.in_(metrics.keys()))... | python | def refresh_metrics(self):
"""Refresh metrics based on the column metadata"""
metrics = self.get_metrics()
dbmetrics = (
db.session.query(DruidMetric)
.filter(DruidMetric.datasource_id == self.datasource_id)
.filter(DruidMetric.metric_name.in_(metrics.keys()))... | [
"def",
"refresh_metrics",
"(",
"self",
")",
":",
"metrics",
"=",
"self",
".",
"get_metrics",
"(",
")",
"dbmetrics",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"DruidMetric",
")",
".",
"filter",
"(",
"DruidMetric",
".",
"datasource_id",
"==",
"sel... | Refresh metrics based on the column metadata | [
"Refresh",
"metrics",
"based",
"on",
"the",
"column",
"metadata"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L309-L326 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.import_obj | def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overridden if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata i... | python | def import_obj(cls, i_datasource, import_time=None):
"""Imports the datasource from the object to the database.
Metrics and columns and datasource will be overridden if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata i... | [
"def",
"import_obj",
"(",
"cls",
",",
"i_datasource",
",",
"import_time",
"=",
"None",
")",
":",
"def",
"lookup_datasource",
"(",
"d",
")",
":",
"return",
"db",
".",
"session",
".",
"query",
"(",
"DruidDatasource",
")",
".",
"filter",
"(",
"DruidDatasource... | Imports the datasource from the object to the database.
Metrics and columns and datasource will be overridden if exists.
This function can be used to import/export dashboards between multiple
superset instances. Audit metadata isn't copies over. | [
"Imports",
"the",
"datasource",
"from",
"the",
"object",
"to",
"the",
"database",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L514-L532 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.sync_to_db_from_config | def sync_to_db_from_config(
cls,
druid_config,
user,
cluster,
refresh=True):
"""Merges the ds config from druid_config into one stored in the db."""
session = db.session
datasource = (
session.query(cls)
.filter_... | python | def sync_to_db_from_config(
cls,
druid_config,
user,
cluster,
refresh=True):
"""Merges the ds config from druid_config into one stored in the db."""
session = db.session
datasource = (
session.query(cls)
.filter_... | [
"def",
"sync_to_db_from_config",
"(",
"cls",
",",
"druid_config",
",",
"user",
",",
"cluster",
",",
"refresh",
"=",
"True",
")",
":",
"session",
"=",
"db",
".",
"session",
"datasource",
"=",
"(",
"session",
".",
"query",
"(",
"cls",
")",
".",
"filter_by"... | Merges the ds config from druid_config into one stored in the db. | [
"Merges",
"the",
"ds",
"config",
"from",
"druid_config",
"into",
"one",
"stored",
"in",
"the",
"db",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L590-L671 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.get_post_agg | def get_post_agg(mconf):
"""
For a metric specified as `postagg` returns the
kind of post aggregation for pydruid.
"""
if mconf.get('type') == 'javascript':
return JavascriptPostAggregator(
name=mconf.get('name', ''),
field_names=mconf.... | python | def get_post_agg(mconf):
"""
For a metric specified as `postagg` returns the
kind of post aggregation for pydruid.
"""
if mconf.get('type') == 'javascript':
return JavascriptPostAggregator(
name=mconf.get('name', ''),
field_names=mconf.... | [
"def",
"get_post_agg",
"(",
"mconf",
")",
":",
"if",
"mconf",
".",
"get",
"(",
"'type'",
")",
"==",
"'javascript'",
":",
"return",
"JavascriptPostAggregator",
"(",
"name",
"=",
"mconf",
".",
"get",
"(",
"'name'",
",",
"''",
")",
",",
"field_names",
"=",
... | For a metric specified as `postagg` returns the
kind of post aggregation for pydruid. | [
"For",
"a",
"metric",
"specified",
"as",
"postagg",
"returns",
"the",
"kind",
"of",
"post",
"aggregation",
"for",
"pydruid",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L731-L770 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.find_postaggs_for | def find_postaggs_for(postagg_names, metrics_dict):
"""Return a list of metrics that are post aggregations"""
postagg_metrics = [
metrics_dict[name] for name in postagg_names
if metrics_dict[name].metric_type == POST_AGG_TYPE
]
# Remove post aggregations that were... | python | def find_postaggs_for(postagg_names, metrics_dict):
"""Return a list of metrics that are post aggregations"""
postagg_metrics = [
metrics_dict[name] for name in postagg_names
if metrics_dict[name].metric_type == POST_AGG_TYPE
]
# Remove post aggregations that were... | [
"def",
"find_postaggs_for",
"(",
"postagg_names",
",",
"metrics_dict",
")",
":",
"postagg_metrics",
"=",
"[",
"metrics_dict",
"[",
"name",
"]",
"for",
"name",
"in",
"postagg_names",
"if",
"metrics_dict",
"[",
"name",
"]",
".",
"metric_type",
"==",
"POST_AGG_TYPE... | Return a list of metrics that are post aggregations | [
"Return",
"a",
"list",
"of",
"metrics",
"that",
"are",
"post",
"aggregations"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L773-L782 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.values_for_column | def values_for_column(self,
column_name,
limit=10000):
"""Retrieve some values for the given column"""
logging.info(
'Getting values for columns [{}] limited to [{}]'
.format(column_name, limit))
# TODO: Use Lexicographi... | python | def values_for_column(self,
column_name,
limit=10000):
"""Retrieve some values for the given column"""
logging.info(
'Getting values for columns [{}] limited to [{}]'
.format(column_name, limit))
# TODO: Use Lexicographi... | [
"def",
"values_for_column",
"(",
"self",
",",
"column_name",
",",
"limit",
"=",
"10000",
")",
":",
"logging",
".",
"info",
"(",
"'Getting values for columns [{}] limited to [{}]'",
".",
"format",
"(",
"column_name",
",",
"limit",
")",
")",
"# TODO: Use Lexicographic... | Retrieve some values for the given column | [
"Retrieve",
"some",
"values",
"for",
"the",
"given",
"column"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L857-L883 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.get_aggregations | def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]):
"""
Returns a dictionary of aggregation metric names to aggregation json objects
:param metrics_dict: dictionary of all the metrics
:param saved_metrics: list of saved metric names
:param adhoc_... | python | def get_aggregations(metrics_dict, saved_metrics, adhoc_metrics=[]):
"""
Returns a dictionary of aggregation metric names to aggregation json objects
:param metrics_dict: dictionary of all the metrics
:param saved_metrics: list of saved metric names
:param adhoc_... | [
"def",
"get_aggregations",
"(",
"metrics_dict",
",",
"saved_metrics",
",",
"adhoc_metrics",
"=",
"[",
"]",
")",
":",
"aggregations",
"=",
"OrderedDict",
"(",
")",
"invalid_metric_names",
"=",
"[",
"]",
"for",
"metric_name",
"in",
"saved_metrics",
":",
"if",
"m... | Returns a dictionary of aggregation metric names to aggregation json objects
:param metrics_dict: dictionary of all the metrics
:param saved_metrics: list of saved metric names
:param adhoc_metrics: list of adhoc metric names
:raise SupersetException: if one or more metr... | [
"Returns",
"a",
"dictionary",
"of",
"aggregation",
"metric",
"names",
"to",
"aggregation",
"json",
"objects"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L940-L970 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource._dimensions_to_values | def _dimensions_to_values(dimensions):
"""
Replace dimensions specs with their `dimension`
values, and ignore those without
"""
values = []
for dimension in dimensions:
if isinstance(dimension, dict):
if 'extractionFn' in dimension:
... | python | def _dimensions_to_values(dimensions):
"""
Replace dimensions specs with their `dimension`
values, and ignore those without
"""
values = []
for dimension in dimensions:
if isinstance(dimension, dict):
if 'extractionFn' in dimension:
... | [
"def",
"_dimensions_to_values",
"(",
"dimensions",
")",
":",
"values",
"=",
"[",
"]",
"for",
"dimension",
"in",
"dimensions",
":",
"if",
"isinstance",
"(",
"dimension",
",",
"dict",
")",
":",
"if",
"'extractionFn'",
"in",
"dimension",
":",
"values",
".",
"... | Replace dimensions specs with their `dimension`
values, and ignore those without | [
"Replace",
"dimensions",
"specs",
"with",
"their",
"dimension",
"values",
"and",
"ignore",
"those",
"without"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L1010-L1025 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.run_query | def run_query( # noqa / druid
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=None,
timeseries_limit_metric=None,
row_limit=None,
in... | python | def run_query( # noqa / druid
self,
groupby, metrics,
granularity,
from_dttm, to_dttm,
filter=None, # noqa
is_timeseries=True,
timeseries_limit=None,
timeseries_limit_metric=None,
row_limit=None,
in... | [
"def",
"run_query",
"(",
"# noqa / druid",
"self",
",",
"groupby",
",",
"metrics",
",",
"granularity",
",",
"from_dttm",
",",
"to_dttm",
",",
"filter",
"=",
"None",
",",
"# noqa",
"is_timeseries",
"=",
"True",
",",
"timeseries_limit",
"=",
"None",
",",
"time... | Runs a query against Druid and returns a dataframe. | [
"Runs",
"a",
"query",
"against",
"Druid",
"and",
"returns",
"a",
"dataframe",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L1039-L1268 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.homogenize_types | def homogenize_types(df, groupby_cols):
"""Converting all GROUPBY columns to strings
When grouping by a numeric (say FLOAT) column, pydruid returns
strings in the dataframe. This creates issues downstream related
to having mixed types in the dataframe
Here we replace None with ... | python | def homogenize_types(df, groupby_cols):
"""Converting all GROUPBY columns to strings
When grouping by a numeric (say FLOAT) column, pydruid returns
strings in the dataframe. This creates issues downstream related
to having mixed types in the dataframe
Here we replace None with ... | [
"def",
"homogenize_types",
"(",
"df",
",",
"groupby_cols",
")",
":",
"for",
"col",
"in",
"groupby_cols",
":",
"df",
"[",
"col",
"]",
"=",
"df",
"[",
"col",
"]",
".",
"fillna",
"(",
"'<NULL>'",
")",
".",
"astype",
"(",
"'unicode'",
")",
"return",
"df"... | Converting all GROUPBY columns to strings
When grouping by a numeric (say FLOAT) column, pydruid returns
strings in the dataframe. This creates issues downstream related
to having mixed types in the dataframe
Here we replace None with <NULL> and make the whole series a
str inst... | [
"Converting",
"all",
"GROUPBY",
"columns",
"to",
"strings"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L1271-L1283 | train |
apache/incubator-superset | superset/connectors/druid/models.py | DruidDatasource.get_filters | def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa
"""Given Superset filter data structure, returns pydruid Filter(s)"""
filters = None
for flt in raw_filters:
col = flt.get('col')
op = flt.get('op')
eq = flt.get('val')
if (
... | python | def get_filters(cls, raw_filters, num_cols, columns_dict): # noqa
"""Given Superset filter data structure, returns pydruid Filter(s)"""
filters = None
for flt in raw_filters:
col = flt.get('col')
op = flt.get('op')
eq = flt.get('val')
if (
... | [
"def",
"get_filters",
"(",
"cls",
",",
"raw_filters",
",",
"num_cols",
",",
"columns_dict",
")",
":",
"# noqa",
"filters",
"=",
"None",
"for",
"flt",
"in",
"raw_filters",
":",
"col",
"=",
"flt",
".",
"get",
"(",
"'col'",
")",
"op",
"=",
"flt",
".",
"... | Given Superset filter data structure, returns pydruid Filter(s) | [
"Given",
"Superset",
"filter",
"data",
"structure",
"returns",
"pydruid",
"Filter",
"(",
"s",
")"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/models.py#L1361-L1484 | train |
apache/incubator-superset | contrib/docker/superset_config.py | get_env_variable | def get_env_variable(var_name, default=None):
"""Get the environment variable or raise exception."""
try:
return os.environ[var_name]
except KeyError:
if default is not None:
return default
else:
error_msg = 'The environment variable {} was missing, abort...'\... | python | def get_env_variable(var_name, default=None):
"""Get the environment variable or raise exception."""
try:
return os.environ[var_name]
except KeyError:
if default is not None:
return default
else:
error_msg = 'The environment variable {} was missing, abort...'\... | [
"def",
"get_env_variable",
"(",
"var_name",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"var_name",
"]",
"except",
"KeyError",
":",
"if",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"else",
":",
... | Get the environment variable or raise exception. | [
"Get",
"the",
"environment",
"variable",
"or",
"raise",
"exception",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/contrib/docker/superset_config.py#L20-L30 | train |
apache/incubator-superset | superset/connectors/connector_registry.py | ConnectorRegistry.get_eager_datasource | def get_eager_datasource(cls, session, datasource_type, datasource_id):
"""Returns datasource with columns and metrics."""
datasource_class = ConnectorRegistry.sources[datasource_type]
return (
session.query(datasource_class)
.options(
subqueryload(datasou... | python | def get_eager_datasource(cls, session, datasource_type, datasource_id):
"""Returns datasource with columns and metrics."""
datasource_class = ConnectorRegistry.sources[datasource_type]
return (
session.query(datasource_class)
.options(
subqueryload(datasou... | [
"def",
"get_eager_datasource",
"(",
"cls",
",",
"session",
",",
"datasource_type",
",",
"datasource_id",
")",
":",
"datasource_class",
"=",
"ConnectorRegistry",
".",
"sources",
"[",
"datasource_type",
"]",
"return",
"(",
"session",
".",
"query",
"(",
"datasource_c... | Returns datasource with columns and metrics. | [
"Returns",
"datasource",
"with",
"columns",
"and",
"metrics",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/connector_registry.py#L76-L87 | train |
apache/incubator-superset | superset/data/misc_dashboard.py | load_misc_dashboard | def load_misc_dashboard():
"""Loading a dashboard featuring misc charts"""
print('Creating the dashboard')
db.session.expunge_all()
dash = db.session.query(Dash).filter_by(slug=DASH_SLUG).first()
if not dash:
dash = Dash()
js = textwrap.dedent("""\
{
"CHART-BkeVbh8ANQ": {
"... | python | def load_misc_dashboard():
"""Loading a dashboard featuring misc charts"""
print('Creating the dashboard')
db.session.expunge_all()
dash = db.session.query(Dash).filter_by(slug=DASH_SLUG).first()
if not dash:
dash = Dash()
js = textwrap.dedent("""\
{
"CHART-BkeVbh8ANQ": {
"... | [
"def",
"load_misc_dashboard",
"(",
")",
":",
"print",
"(",
"'Creating the dashboard'",
")",
"db",
".",
"session",
".",
"expunge_all",
"(",
")",
"dash",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Dash",
")",
".",
"filter_by",
"(",
"slug",
"=",
"DASH_S... | Loading a dashboard featuring misc charts | [
"Loading",
"a",
"dashboard",
"featuring",
"misc",
"charts"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/misc_dashboard.py#L32-L228 | train |
apache/incubator-superset | superset/data/world_bank.py | load_world_bank_health_n_pop | def load_world_bank_health_n_pop():
"""Loads the world bank health dataset, slices and a dashboard"""
tbl_name = 'wb_health_population'
data = get_example_data('countries.json.gz')
pdf = pd.read_json(data)
pdf.columns = [col.replace('.', '_') for col in pdf.columns]
pdf.year = pd.to_datetime(pdf... | python | def load_world_bank_health_n_pop():
"""Loads the world bank health dataset, slices and a dashboard"""
tbl_name = 'wb_health_population'
data = get_example_data('countries.json.gz')
pdf = pd.read_json(data)
pdf.columns = [col.replace('.', '_') for col in pdf.columns]
pdf.year = pd.to_datetime(pdf... | [
"def",
"load_world_bank_health_n_pop",
"(",
")",
":",
"tbl_name",
"=",
"'wb_health_population'",
"data",
"=",
"get_example_data",
"(",
"'countries.json.gz'",
")",
"pdf",
"=",
"pd",
".",
"read_json",
"(",
"data",
")",
"pdf",
".",
"columns",
"=",
"[",
"col",
"."... | Loads the world bank health dataset, slices and a dashboard | [
"Loads",
"the",
"world",
"bank",
"health",
"dataset",
"slices",
"and",
"a",
"dashboard"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/world_bank.py#L43-L507 | train |
apache/incubator-superset | superset/data/country_map.py | load_country_map_data | def load_country_map_data():
"""Loading data for map with country map"""
csv_bytes = get_example_data(
'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True)
data = pd.read_csv(csv_bytes, encoding='utf-8')
data['dttm'] = datetime.datetime.now().date()
data.to_sql( # pylint... | python | def load_country_map_data():
"""Loading data for map with country map"""
csv_bytes = get_example_data(
'birth_france_data_for_country_map.csv', is_gzip=False, make_bytes=True)
data = pd.read_csv(csv_bytes, encoding='utf-8')
data['dttm'] = datetime.datetime.now().date()
data.to_sql( # pylint... | [
"def",
"load_country_map_data",
"(",
")",
":",
"csv_bytes",
"=",
"get_example_data",
"(",
"'birth_france_data_for_country_map.csv'",
",",
"is_gzip",
"=",
"False",
",",
"make_bytes",
"=",
"True",
")",
"data",
"=",
"pd",
".",
"read_csv",
"(",
"csv_bytes",
",",
"en... | Loading data for map with country map | [
"Loading",
"data",
"for",
"map",
"with",
"country",
"map"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/country_map.py#L35-L110 | train |
apache/incubator-superset | superset/sql_parse.py | ParsedQuery.get_statements | def get_statements(self):
"""Returns a list of SQL statements as strings, stripped"""
statements = []
for statement in self._parsed:
if statement:
sql = str(statement).strip(' \n;\t')
if sql:
statements.append(sql)
return st... | python | def get_statements(self):
"""Returns a list of SQL statements as strings, stripped"""
statements = []
for statement in self._parsed:
if statement:
sql = str(statement).strip(' \n;\t')
if sql:
statements.append(sql)
return st... | [
"def",
"get_statements",
"(",
"self",
")",
":",
"statements",
"=",
"[",
"]",
"for",
"statement",
"in",
"self",
".",
"_parsed",
":",
"if",
"statement",
":",
"sql",
"=",
"str",
"(",
"statement",
")",
".",
"strip",
"(",
"' \\n;\\t'",
")",
"if",
"sql",
"... | Returns a list of SQL statements as strings, stripped | [
"Returns",
"a",
"list",
"of",
"SQL",
"statements",
"as",
"strings",
"stripped"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_parse.py#L67-L75 | train |
apache/incubator-superset | superset/sql_parse.py | ParsedQuery.as_create_table | def as_create_table(self, table_name, overwrite=False):
"""Reformats the query into the create table as query.
Works only for the single select SQL statements, in all other cases
the sql query is not modified.
:param superset_query: string, sql query that will be executed
:param... | python | def as_create_table(self, table_name, overwrite=False):
"""Reformats the query into the create table as query.
Works only for the single select SQL statements, in all other cases
the sql query is not modified.
:param superset_query: string, sql query that will be executed
:param... | [
"def",
"as_create_table",
"(",
"self",
",",
"table_name",
",",
"overwrite",
"=",
"False",
")",
":",
"exec_sql",
"=",
"''",
"sql",
"=",
"self",
".",
"stripped",
"(",
")",
"if",
"overwrite",
":",
"exec_sql",
"=",
"f'DROP TABLE IF EXISTS {table_name};\\n'",
"exec... | Reformats the query into the create table as query.
Works only for the single select SQL statements, in all other cases
the sql query is not modified.
:param superset_query: string, sql query that will be executed
:param table_name: string, will contain the results of the
qu... | [
"Reformats",
"the",
"query",
"into",
"the",
"create",
"table",
"as",
"query",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_parse.py#L105-L121 | train |
apache/incubator-superset | superset/sql_parse.py | ParsedQuery.get_query_with_new_limit | def get_query_with_new_limit(self, new_limit):
"""returns the query with the specified limit"""
"""does not change the underlying query"""
if not self._limit:
return self.sql + ' LIMIT ' + str(new_limit)
limit_pos = None
tokens = self._parsed[0].tokens
# Add a... | python | def get_query_with_new_limit(self, new_limit):
"""returns the query with the specified limit"""
"""does not change the underlying query"""
if not self._limit:
return self.sql + ' LIMIT ' + str(new_limit)
limit_pos = None
tokens = self._parsed[0].tokens
# Add a... | [
"def",
"get_query_with_new_limit",
"(",
"self",
",",
"new_limit",
")",
":",
"\"\"\"does not change the underlying query\"\"\"",
"if",
"not",
"self",
".",
"_limit",
":",
"return",
"self",
".",
"sql",
"+",
"' LIMIT '",
"+",
"str",
"(",
"new_limit",
")",
"limit_pos",... | returns the query with the specified limit | [
"returns",
"the",
"query",
"with",
"the",
"specified",
"limit"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/sql_parse.py#L166-L189 | train |
apache/incubator-superset | superset/jinja_context.py | url_param | def url_param(param, default=None):
"""Read a url or post parameter and use it in your SQL Lab query
When in SQL Lab, it's possible to add arbitrary URL "query string"
parameters, and use those in your SQL code. For instance you can
alter your url and add `?foo=bar`, as in
`{domain}/superset/sqllab... | python | def url_param(param, default=None):
"""Read a url or post parameter and use it in your SQL Lab query
When in SQL Lab, it's possible to add arbitrary URL "query string"
parameters, and use those in your SQL code. For instance you can
alter your url and add `?foo=bar`, as in
`{domain}/superset/sqllab... | [
"def",
"url_param",
"(",
"param",
",",
"default",
"=",
"None",
")",
":",
"if",
"request",
".",
"args",
".",
"get",
"(",
"param",
")",
":",
"return",
"request",
".",
"args",
".",
"get",
"(",
"param",
",",
"default",
")",
"# Supporting POST as well as get"... | Read a url or post parameter and use it in your SQL Lab query
When in SQL Lab, it's possible to add arbitrary URL "query string"
parameters, and use those in your SQL code. For instance you can
alter your url and add `?foo=bar`, as in
`{domain}/superset/sqllab?foo=bar`. Then if your query is something ... | [
"Read",
"a",
"url",
"or",
"post",
"parameter",
"and",
"use",
"it",
"in",
"your",
"SQL",
"Lab",
"query"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/jinja_context.py#L44-L70 | train |
apache/incubator-superset | superset/jinja_context.py | filter_values | def filter_values(column, default=None):
""" Gets a values for a particular filter as a list
This is useful if:
- you want to use a filter box to filter a query where the name of filter box
column doesn't match the one in the select statement
- you want to have the ability for filter ... | python | def filter_values(column, default=None):
""" Gets a values for a particular filter as a list
This is useful if:
- you want to use a filter box to filter a query where the name of filter box
column doesn't match the one in the select statement
- you want to have the ability for filter ... | [
"def",
"filter_values",
"(",
"column",
",",
"default",
"=",
"None",
")",
":",
"form_data",
"=",
"json",
".",
"loads",
"(",
"request",
".",
"form",
".",
"get",
"(",
"'form_data'",
",",
"'{}'",
")",
")",
"return_val",
"=",
"[",
"]",
"for",
"filter_type",... | Gets a values for a particular filter as a list
This is useful if:
- you want to use a filter box to filter a query where the name of filter box
column doesn't match the one in the select statement
- you want to have the ability for filter inside the main query for speed purposes
Thi... | [
"Gets",
"a",
"values",
"for",
"a",
"particular",
"filter",
"as",
"a",
"list"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/jinja_context.py#L85-L125 | train |
apache/incubator-superset | superset/jinja_context.py | BaseTemplateProcessor.process_template | def process_template(self, sql, **kwargs):
"""Processes a sql template
>>> sql = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'"
>>> process_template(sql)
"SELECT '2017-01-01T00:00:00'"
"""
template = self.env.from_string(sql)
kwargs.update(self.context)
... | python | def process_template(self, sql, **kwargs):
"""Processes a sql template
>>> sql = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'"
>>> process_template(sql)
"SELECT '2017-01-01T00:00:00'"
"""
template = self.env.from_string(sql)
kwargs.update(self.context)
... | [
"def",
"process_template",
"(",
"self",
",",
"sql",
",",
"*",
"*",
"kwargs",
")",
":",
"template",
"=",
"self",
".",
"env",
".",
"from_string",
"(",
"sql",
")",
"kwargs",
".",
"update",
"(",
"self",
".",
"context",
")",
"return",
"template",
".",
"re... | Processes a sql template
>>> sql = "SELECT '{{ datetime(2017, 1, 1).isoformat() }}'"
>>> process_template(sql)
"SELECT '2017-01-01T00:00:00'" | [
"Processes",
"a",
"sql",
"template"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/jinja_context.py#L165-L174 | train |
apache/incubator-superset | superset/views/utils.py | get_datasource_info | def get_datasource_info(datasource_id, datasource_type, form_data):
"""Compatibility layer for handling of datasource info
datasource_id & datasource_type used to be passed in the URL
directory, now they should come as part of the form_data,
This function allows supporting both without duplicating code... | python | def get_datasource_info(datasource_id, datasource_type, form_data):
"""Compatibility layer for handling of datasource info
datasource_id & datasource_type used to be passed in the URL
directory, now they should come as part of the form_data,
This function allows supporting both without duplicating code... | [
"def",
"get_datasource_info",
"(",
"datasource_id",
",",
"datasource_type",
",",
"form_data",
")",
":",
"datasource",
"=",
"form_data",
".",
"get",
"(",
"'datasource'",
",",
"''",
")",
"if",
"'__'",
"in",
"datasource",
":",
"datasource_id",
",",
"datasource_type... | Compatibility layer for handling of datasource info
datasource_id & datasource_type used to be passed in the URL
directory, now they should come as part of the form_data,
This function allows supporting both without duplicating code | [
"Compatibility",
"layer",
"for",
"handling",
"of",
"datasource",
"info"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/utils.py#L170-L186 | train |
apache/incubator-superset | superset/security.py | SupersetSecurityManager.can_access | def can_access(self, permission_name, view_name):
"""Protecting from has_access failing from missing perms/view"""
user = g.user
if user.is_anonymous:
return self.is_item_public(permission_name, view_name)
return self._has_view_access(user, permission_name, view_name) | python | def can_access(self, permission_name, view_name):
"""Protecting from has_access failing from missing perms/view"""
user = g.user
if user.is_anonymous:
return self.is_item_public(permission_name, view_name)
return self._has_view_access(user, permission_name, view_name) | [
"def",
"can_access",
"(",
"self",
",",
"permission_name",
",",
"view_name",
")",
":",
"user",
"=",
"g",
".",
"user",
"if",
"user",
".",
"is_anonymous",
":",
"return",
"self",
".",
"is_item_public",
"(",
"permission_name",
",",
"view_name",
")",
"return",
"... | Protecting from has_access failing from missing perms/view | [
"Protecting",
"from",
"has_access",
"failing",
"from",
"missing",
"perms",
"/",
"view"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/security.py#L106-L111 | train |
apache/incubator-superset | superset/security.py | SupersetSecurityManager.create_missing_perms | def create_missing_perms(self):
"""Creates missing perms for datasources, schemas and metrics"""
from superset import db
from superset.models import core as models
logging.info(
'Fetching a set of all perms to lookup which ones are missing')
all_pvs = set()
f... | python | def create_missing_perms(self):
"""Creates missing perms for datasources, schemas and metrics"""
from superset import db
from superset.models import core as models
logging.info(
'Fetching a set of all perms to lookup which ones are missing')
all_pvs = set()
f... | [
"def",
"create_missing_perms",
"(",
"self",
")",
":",
"from",
"superset",
"import",
"db",
"from",
"superset",
".",
"models",
"import",
"core",
"as",
"models",
"logging",
".",
"info",
"(",
"'Fetching a set of all perms to lookup which ones are missing'",
")",
"all_pvs"... | Creates missing perms for datasources, schemas and metrics | [
"Creates",
"missing",
"perms",
"for",
"datasources",
"schemas",
"and",
"metrics"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/security.py#L287-L322 | train |
apache/incubator-superset | superset/security.py | SupersetSecurityManager.clean_perms | def clean_perms(self):
"""FAB leaves faulty permissions that need to be cleaned up"""
logging.info('Cleaning faulty perms')
sesh = self.get_session
pvms = (
sesh.query(ab_models.PermissionView)
.filter(or_(
ab_models.PermissionView.permission == No... | python | def clean_perms(self):
"""FAB leaves faulty permissions that need to be cleaned up"""
logging.info('Cleaning faulty perms')
sesh = self.get_session
pvms = (
sesh.query(ab_models.PermissionView)
.filter(or_(
ab_models.PermissionView.permission == No... | [
"def",
"clean_perms",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"'Cleaning faulty perms'",
")",
"sesh",
"=",
"self",
".",
"get_session",
"pvms",
"=",
"(",
"sesh",
".",
"query",
"(",
"ab_models",
".",
"PermissionView",
")",
".",
"filter",
"(",
"... | FAB leaves faulty permissions that need to be cleaned up | [
"FAB",
"leaves",
"faulty",
"permissions",
"that",
"need",
"to",
"be",
"cleaned",
"up"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/security.py#L324-L338 | train |
apache/incubator-superset | superset/security.py | SupersetSecurityManager.sync_role_definitions | def sync_role_definitions(self):
"""Inits the Superset application with security roles and such"""
from superset import conf
logging.info('Syncing role definition')
self.create_custom_permissions()
# Creating default roles
self.set_role('Admin', self.is_admin_pvm)
... | python | def sync_role_definitions(self):
"""Inits the Superset application with security roles and such"""
from superset import conf
logging.info('Syncing role definition')
self.create_custom_permissions()
# Creating default roles
self.set_role('Admin', self.is_admin_pvm)
... | [
"def",
"sync_role_definitions",
"(",
"self",
")",
":",
"from",
"superset",
"import",
"conf",
"logging",
".",
"info",
"(",
"'Syncing role definition'",
")",
"self",
".",
"create_custom_permissions",
"(",
")",
"# Creating default roles",
"self",
".",
"set_role",
"(",
... | Inits the Superset application with security roles and such | [
"Inits",
"the",
"Superset",
"application",
"with",
"security",
"roles",
"and",
"such"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/security.py#L340-L361 | train |
apache/incubator-superset | superset/utils/dict_import_export.py | export_schema_to_dict | def export_schema_to_dict(back_references):
"""Exports the supported import/export schema to a dictionary"""
databases = [Database.export_schema(recursive=True,
include_parent_ref=back_references)]
clusters = [DruidCluster.export_schema(recursive=True,
include_parent_ref=bac... | python | def export_schema_to_dict(back_references):
"""Exports the supported import/export schema to a dictionary"""
databases = [Database.export_schema(recursive=True,
include_parent_ref=back_references)]
clusters = [DruidCluster.export_schema(recursive=True,
include_parent_ref=bac... | [
"def",
"export_schema_to_dict",
"(",
"back_references",
")",
":",
"databases",
"=",
"[",
"Database",
".",
"export_schema",
"(",
"recursive",
"=",
"True",
",",
"include_parent_ref",
"=",
"back_references",
")",
"]",
"clusters",
"=",
"[",
"DruidCluster",
".",
"exp... | Exports the supported import/export schema to a dictionary | [
"Exports",
"the",
"supported",
"import",
"/",
"export",
"schema",
"to",
"a",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/dict_import_export.py#L28-L39 | train |
apache/incubator-superset | superset/utils/dict_import_export.py | export_to_dict | def export_to_dict(session,
recursive,
back_references,
include_defaults):
"""Exports databases and druid clusters to a dictionary"""
logging.info('Starting export')
dbs = session.query(Database)
databases = [database.export_to_dict(recursive=recu... | python | def export_to_dict(session,
recursive,
back_references,
include_defaults):
"""Exports databases and druid clusters to a dictionary"""
logging.info('Starting export')
dbs = session.query(Database)
databases = [database.export_to_dict(recursive=recu... | [
"def",
"export_to_dict",
"(",
"session",
",",
"recursive",
",",
"back_references",
",",
"include_defaults",
")",
":",
"logging",
".",
"info",
"(",
"'Starting export'",
")",
"dbs",
"=",
"session",
".",
"query",
"(",
"Database",
")",
"databases",
"=",
"[",
"da... | Exports databases and druid clusters to a dictionary | [
"Exports",
"databases",
"and",
"druid",
"clusters",
"to",
"a",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/dict_import_export.py#L42-L63 | train |
apache/incubator-superset | superset/utils/dict_import_export.py | import_from_dict | def import_from_dict(session, data, sync=[]):
"""Imports databases and druid clusters from dictionary"""
if isinstance(data, dict):
logging.info('Importing %d %s',
len(data.get(DATABASES_KEY, [])),
DATABASES_KEY)
for database in data.get(DATABASES_KEY, [... | python | def import_from_dict(session, data, sync=[]):
"""Imports databases and druid clusters from dictionary"""
if isinstance(data, dict):
logging.info('Importing %d %s',
len(data.get(DATABASES_KEY, [])),
DATABASES_KEY)
for database in data.get(DATABASES_KEY, [... | [
"def",
"import_from_dict",
"(",
"session",
",",
"data",
",",
"sync",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"logging",
".",
"info",
"(",
"'Importing %d %s'",
",",
"len",
"(",
"data",
".",
"get",
"(",
"DATABAS... | Imports databases and druid clusters from dictionary | [
"Imports",
"databases",
"and",
"druid",
"clusters",
"from",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/utils/dict_import_export.py#L66-L82 | train |
apache/incubator-superset | superset/views/api.py | Api.query | def query(self):
"""
Takes a query_obj constructed in the client and returns payload data response
for the given query_obj.
params: query_context: json_blob
"""
query_context = QueryContext(**json.loads(request.form.get('query_context')))
security_manager.assert_d... | python | def query(self):
"""
Takes a query_obj constructed in the client and returns payload data response
for the given query_obj.
params: query_context: json_blob
"""
query_context = QueryContext(**json.loads(request.form.get('query_context')))
security_manager.assert_d... | [
"def",
"query",
"(",
"self",
")",
":",
"query_context",
"=",
"QueryContext",
"(",
"*",
"*",
"json",
".",
"loads",
"(",
"request",
".",
"form",
".",
"get",
"(",
"'query_context'",
")",
")",
")",
"security_manager",
".",
"assert_datasource_permission",
"(",
... | Takes a query_obj constructed in the client and returns payload data response
for the given query_obj.
params: query_context: json_blob | [
"Takes",
"a",
"query_obj",
"constructed",
"in",
"the",
"client",
"and",
"returns",
"payload",
"data",
"response",
"for",
"the",
"given",
"query_obj",
".",
"params",
":",
"query_context",
":",
"json_blob"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/api.py#L38-L51 | train |
apache/incubator-superset | superset/views/api.py | Api.query_form_data | def query_form_data(self):
"""
Get the formdata stored in the database for existing slice.
params: slice_id: integer
"""
form_data = {}
slice_id = request.args.get('slice_id')
if slice_id:
slc = db.session.query(models.Slice).filter_by(id=slice_id).one... | python | def query_form_data(self):
"""
Get the formdata stored in the database for existing slice.
params: slice_id: integer
"""
form_data = {}
slice_id = request.args.get('slice_id')
if slice_id:
slc = db.session.query(models.Slice).filter_by(id=slice_id).one... | [
"def",
"query_form_data",
"(",
"self",
")",
":",
"form_data",
"=",
"{",
"}",
"slice_id",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'slice_id'",
")",
"if",
"slice_id",
":",
"slc",
"=",
"db",
".",
"session",
".",
"query",
"(",
"models",
".",
"Slic... | Get the formdata stored in the database for existing slice.
params: slice_id: integer | [
"Get",
"the",
"formdata",
"stored",
"in",
"the",
"database",
"for",
"existing",
"slice",
".",
"params",
":",
"slice_id",
":",
"integer"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/views/api.py#L58-L72 | train |
apache/incubator-superset | superset/data/css_templates.py | load_css_templates | def load_css_templates():
"""Loads 2 css templates to demonstrate the feature"""
print('Creating default CSS templates')
obj = db.session.query(CssTemplate).filter_by(template_name='Flat').first()
if not obj:
obj = CssTemplate(template_name='Flat')
css = textwrap.dedent("""\
.gridster d... | python | def load_css_templates():
"""Loads 2 css templates to demonstrate the feature"""
print('Creating default CSS templates')
obj = db.session.query(CssTemplate).filter_by(template_name='Flat').first()
if not obj:
obj = CssTemplate(template_name='Flat')
css = textwrap.dedent("""\
.gridster d... | [
"def",
"load_css_templates",
"(",
")",
":",
"print",
"(",
"'Creating default CSS templates'",
")",
"obj",
"=",
"db",
".",
"session",
".",
"query",
"(",
"CssTemplate",
")",
".",
"filter_by",
"(",
"template_name",
"=",
"'Flat'",
")",
".",
"first",
"(",
")",
... | Loads 2 css templates to demonstrate the feature | [
"Loads",
"2",
"css",
"templates",
"to",
"demonstrate",
"the",
"feature"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/css_templates.py#L23-L119 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin._parent_foreign_key_mappings | def _parent_foreign_key_mappings(cls):
"""Get a mapping of foreign name to the local name of foreign keys"""
parent_rel = cls.__mapper__.relationships.get(cls.export_parent)
if parent_rel:
return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs}
return {} | python | def _parent_foreign_key_mappings(cls):
"""Get a mapping of foreign name to the local name of foreign keys"""
parent_rel = cls.__mapper__.relationships.get(cls.export_parent)
if parent_rel:
return {l.name: r.name for (l, r) in parent_rel.local_remote_pairs}
return {} | [
"def",
"_parent_foreign_key_mappings",
"(",
"cls",
")",
":",
"parent_rel",
"=",
"cls",
".",
"__mapper__",
".",
"relationships",
".",
"get",
"(",
"cls",
".",
"export_parent",
")",
"if",
"parent_rel",
":",
"return",
"{",
"l",
".",
"name",
":",
"r",
".",
"n... | Get a mapping of foreign name to the local name of foreign keys | [
"Get",
"a",
"mapping",
"of",
"foreign",
"name",
"to",
"the",
"local",
"name",
"of",
"foreign",
"keys"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L60-L65 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin._unique_constrains | def _unique_constrains(cls):
"""Get all (single column and multi column) unique constraints"""
unique = [{c.name for c in u.columns} for u in cls.__table_args__
if isinstance(u, UniqueConstraint)]
unique.extend({c.name} for c in cls.__table__.columns if c.unique)
return... | python | def _unique_constrains(cls):
"""Get all (single column and multi column) unique constraints"""
unique = [{c.name for c in u.columns} for u in cls.__table_args__
if isinstance(u, UniqueConstraint)]
unique.extend({c.name} for c in cls.__table__.columns if c.unique)
return... | [
"def",
"_unique_constrains",
"(",
"cls",
")",
":",
"unique",
"=",
"[",
"{",
"c",
".",
"name",
"for",
"c",
"in",
"u",
".",
"columns",
"}",
"for",
"u",
"in",
"cls",
".",
"__table_args__",
"if",
"isinstance",
"(",
"u",
",",
"UniqueConstraint",
")",
"]",... | Get all (single column and multi column) unique constraints | [
"Get",
"all",
"(",
"single",
"column",
"and",
"multi",
"column",
")",
"unique",
"constraints"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L68-L73 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin.export_schema | def export_schema(cls, recursive=True, include_parent_ref=False):
"""Export schema as a dictionary"""
parent_excludes = {}
if not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get(cls.export_parent)
if parent_ref:
parent_excludes = {c.name ... | python | def export_schema(cls, recursive=True, include_parent_ref=False):
"""Export schema as a dictionary"""
parent_excludes = {}
if not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get(cls.export_parent)
if parent_ref:
parent_excludes = {c.name ... | [
"def",
"export_schema",
"(",
"cls",
",",
"recursive",
"=",
"True",
",",
"include_parent_ref",
"=",
"False",
")",
":",
"parent_excludes",
"=",
"{",
"}",
"if",
"not",
"include_parent_ref",
":",
"parent_ref",
"=",
"cls",
".",
"__mapper__",
".",
"relationships",
... | Export schema as a dictionary | [
"Export",
"schema",
"as",
"a",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L76-L96 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin.import_from_dict | def import_from_dict(cls, session, dict_rep, parent=None,
recursive=True, sync=[]):
"""Import obj from a dictionary"""
parent_refs = cls._parent_foreign_key_mappings()
export_fields = set(cls.export_fields) | set(parent_refs.keys())
new_children = {c: dict_rep.ge... | python | def import_from_dict(cls, session, dict_rep, parent=None,
recursive=True, sync=[]):
"""Import obj from a dictionary"""
parent_refs = cls._parent_foreign_key_mappings()
export_fields = set(cls.export_fields) | set(parent_refs.keys())
new_children = {c: dict_rep.ge... | [
"def",
"import_from_dict",
"(",
"cls",
",",
"session",
",",
"dict_rep",
",",
"parent",
"=",
"None",
",",
"recursive",
"=",
"True",
",",
"sync",
"=",
"[",
"]",
")",
":",
"parent_refs",
"=",
"cls",
".",
"_parent_foreign_key_mappings",
"(",
")",
"export_field... | Import obj from a dictionary | [
"Import",
"obj",
"from",
"a",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L99-L184 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin.export_to_dict | def export_to_dict(self, recursive=True, include_parent_ref=False,
include_defaults=False):
"""Export obj to dictionary"""
cls = self.__class__
parent_excludes = {}
if recursive and not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get(c... | python | def export_to_dict(self, recursive=True, include_parent_ref=False,
include_defaults=False):
"""Export obj to dictionary"""
cls = self.__class__
parent_excludes = {}
if recursive and not include_parent_ref:
parent_ref = cls.__mapper__.relationships.get(c... | [
"def",
"export_to_dict",
"(",
"self",
",",
"recursive",
"=",
"True",
",",
"include_parent_ref",
"=",
"False",
",",
"include_defaults",
"=",
"False",
")",
":",
"cls",
"=",
"self",
".",
"__class__",
"parent_excludes",
"=",
"{",
"}",
"if",
"recursive",
"and",
... | Export obj to dictionary | [
"Export",
"obj",
"to",
"dictionary"
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L186-L217 | train |
apache/incubator-superset | superset/models/helpers.py | ImportMixin.override | def override(self, obj):
"""Overrides the plain fields of the dashboard."""
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field)) | python | def override(self, obj):
"""Overrides the plain fields of the dashboard."""
for field in obj.__class__.export_fields:
setattr(self, field, getattr(obj, field)) | [
"def",
"override",
"(",
"self",
",",
"obj",
")",
":",
"for",
"field",
"in",
"obj",
".",
"__class__",
".",
"export_fields",
":",
"setattr",
"(",
"self",
",",
"field",
",",
"getattr",
"(",
"obj",
",",
"field",
")",
")"
] | Overrides the plain fields of the dashboard. | [
"Overrides",
"the",
"plain",
"fields",
"of",
"the",
"dashboard",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/models/helpers.py#L219-L222 | train |
apache/incubator-superset | superset/legacy.py | update_time_range | def update_time_range(form_data):
"""Move since and until to time_range."""
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(
form_data.pop('since', '') or '',
form_data.pop('until', '') or '',
) | python | def update_time_range(form_data):
"""Move since and until to time_range."""
if 'since' in form_data or 'until' in form_data:
form_data['time_range'] = '{} : {}'.format(
form_data.pop('since', '') or '',
form_data.pop('until', '') or '',
) | [
"def",
"update_time_range",
"(",
"form_data",
")",
":",
"if",
"'since'",
"in",
"form_data",
"or",
"'until'",
"in",
"form_data",
":",
"form_data",
"[",
"'time_range'",
"]",
"=",
"'{} : {}'",
".",
"format",
"(",
"form_data",
".",
"pop",
"(",
"'since'",
",",
... | Move since and until to time_range. | [
"Move",
"since",
"and",
"until",
"to",
"time_range",
"."
] | ca2996c78f679260eb79c6008e276733df5fb653 | https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/legacy.py#L21-L27 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.