Search is not available for this dataset
text stringlengths 75 104k |
|---|
def check_dataset(dataset, mode):
"""Validate we have a good dataset."""
names = [x['name'] for x in dataset.schema]
types = [x['type'] for x in dataset.schema]
if mode == 'train':
if (set(['image_url', 'label']) != set(names) or any(t != 'STRING' for t in types)):
raise ValueError('Invalid dataset. ... |
def get_sources_from_dataset(p, dataset, mode):
"""get pcollection from dataset."""
import apache_beam as beam
import csv
from google.datalab.ml import CsvDataSet, BigQueryDataSet
check_dataset(dataset, mode)
if type(dataset) is CsvDataSet:
source_list = []
for ii, input_path in enumerate(dataset.... |
def decode_and_resize(image_str_tensor):
"""Decodes jpeg string, resizes it and returns a uint8 tensor."""
# These constants are set by Inception v3's expectations.
height = 299
width = 299
channels = 3
image = tf.image.decode_jpeg(image_str_tensor, channels=channels)
# Note resize expects a batch_size,... |
def resize_image(image_str_tensor):
"""Decodes jpeg string, resizes it and re-encode it to jpeg."""
image = decode_and_resize(image_str_tensor)
image = tf.image.encode_jpeg(image, quality=100)
return image |
def load_images(image_files, resize=True):
"""Load images from files and optionally resize it."""
images = []
for image_file in image_files:
with file_io.FileIO(image_file, 'r') as ff:
images.append(ff.read())
if resize is False:
return images
# To resize, run a tf session so we can reuse 'dec... |
def process_prediction_results(results, show_image):
"""Create DataFrames out of prediction results, and display images in IPython if requested."""
import pandas as pd
if (is_in_IPython() and show_image is True):
import IPython
for image_url, image, label_and_score in results:
IPython.display.disp... |
def repackage_to_staging(output_path):
"""Repackage it from local installed location and copy it to GCS."""
import google.datalab.ml as ml
# Find the package root. __file__ is under [package_root]/mltoolbox/image/classification.
package_root = os.path.join(os.path.dirname(__file__), '../../../')
# We deploy... |
def generate_airflow_spec(name, pipeline_spec):
""" Gets the airflow python spec for the Pipeline object.
"""
task_definitions = ''
up_steam_statements = ''
parameters = pipeline_spec.get('parameters')
for (task_id, task_details) in sorted(pipeline_spec['tasks'].items()):
task_def = Pipeli... |
def _get_operator_definition(task_id, task_details, parameters):
""" Internal helper that gets the definition of the airflow operator for the task with the
python parameters. All the parameters are also expanded with the airflow macros.
:param parameters:
"""
operator_type = task_details['type']... |
def _get_dependency_definition(task_id, dependencies):
""" Internal helper collects all the dependencies of the task, and returns
the Airflow equivalent python sytax for specifying them.
"""
set_upstream_statements = ''
for dependency in dependencies:
set_upstream_statements = set_upstream_s... |
def _get_operator_class_name(task_detail_type):
""" Internal helper gets the name of the Airflow operator class. We maintain
this in a map, so this method really returns the enum name, concatenated
with the string "Operator".
"""
# TODO(rajivpb): Rename this var correctly.
task_type_to_opera... |
def _get_operator_param_name_and_values(operator_class_name, task_details):
""" Internal helper gets the name of the python parameter for the Airflow operator class. In
some cases, we do not expose the airflow parameter name in its native form, but choose to
expose a name that's more standard for Datala... |
def size(self):
"""The size of the schema. If the underlying data source changes, it may be outdated.
"""
if self._size is None:
self._size = 0
for csv_file in self.files:
self._size += sum(1 if line else 0 for line in _util.open_local_or_gcs(csv_file, 'r'))
return self._size |
def sample(self, n):
""" Samples data into a Pandas DataFrame.
Args:
n: number of sampled counts.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is larger than number of rows.
"""
row_total_count = 0
row_counts = []
for file in self.files:
w... |
def size(self):
"""The size of the schema. If the underlying data source changes, it may be outdated.
"""
if self._size is None:
self._size = bq.Query('SELECT COUNT(*) FROM %s' %
self._get_source()).execute().result()[0].values()[0]
return self._size |
def sample(self, n):
"""Samples data into a Pandas DataFrame. Note that it calls BigQuery so it will
incur cost.
Args:
n: number of sampled counts. Note that the number of counts returned is approximated.
Returns:
A dataframe containing sampled data.
Raises:
Exception if n is l... |
def size(self):
"""The number of instances in the data. If the underlying data source changes,
it may be outdated.
"""
import tensorflow as tf
if self._size is None:
self._size = 0
options = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.GZIP)
for tfexample_f... |
def list(self, pattern='*'):
"""Returns a list of groups that match the filters.
Args:
pattern: An optional pattern to filter the groups based on their display
name. This can include Unix shell-style wildcards. E.g.
``"Production*"``.
Returns:
A list of Group objects that m... |
def as_dataframe(self, pattern='*', max_rows=None):
"""Creates a pandas dataframe from the groups that match the filters.
Args:
pattern: An optional pattern to further filter the groups. This can
include Unix shell-style wildcards. E.g. ``"Production *"``,
``"*-backend"``.
max_r... |
def _find_recursive_dependencies(sql, values, code, resolved_vars, resolving_vars=None):
""" Recursive helper method for expanding variables including transitive dependencies.
Placeholders in SQL are represented as $<name>. If '$' must appear within
the SQL statement literally, then it can be escaped as '$... |
def format(sql, args=None):
""" Resolve variable references in a query within an environment.
This computes and resolves the transitive dependencies in the query and raises an
exception if that fails due to either undefined or circular references.
Args:
sql: query to format.
args: a dictio... |
def _get_dependencies(sql):
""" Return the list of variables referenced in this SQL. """
dependencies = []
for (_, placeholder, dollar, _) in SqlStatement._get_tokens(sql):
if placeholder:
variable = placeholder[1:]
if variable not in dependencies:
dependencies.append(variabl... |
def pymodule(line, cell=None):
"""Creates and subsequently auto-imports a python module.
"""
parser = _commands.CommandParser.create('pymodule')
parser.add_argument('-n', '--name',
help='the name of the python module to create and import')
parser.set_defaults(func=_pymodule_cell)
retur... |
def set_project_id(self, project_id):
""" Set the project_id for the context. """
self._project_id = project_id
if self == Context._global_context:
try:
from google.datalab import Context as new_context
new_context.default().set_project_id(project_id)
except ImportError:
... |
def default():
"""Retrieves a default Context object, creating it if necessary.
The default Context is a global shared instance used every time the default context is
retrieved.
Attempting to use a Context with no project_id will raise an exception, so on first use
set_project_id must be c... |
def compare_datetimes(d1, d2):
""" Compares two datetimes safely, whether they are timezone-naive or timezone-aware.
If either datetime is naive it is converted to an aware datetime assuming UTC.
Args:
d1: first datetime.
d2: second datetime.
Returns:
-1 if d1 < d2, 0 if they are the same, or +1 ... |
def pick_unused_port():
""" get an unused port on the VM.
Returns:
An unused port.
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('localhost', 0))
addr, port = s.getsockname()
s.close()
return port |
def is_http_running_on(port):
""" Check if an http server runs on a given port.
Args:
The port to check.
Returns:
True if it is used by an http server. False otherwise.
"""
try:
conn = httplib.HTTPConnection('127.0.0.1:' + str(port))
conn.connect()
conn.close()
return True
except Ex... |
def save_project_id(project_id):
""" Save project id to config file.
Args:
project_id: the project_id to save.
"""
# Try gcloud first. If gcloud fails (probably because it does not exist), then
# write to a config file.
try:
subprocess.call(['gcloud', 'config', 'set', 'project', project_id])
exce... |
def get_default_project_id():
""" Get default project id from config or environment var.
Returns: the project id if available, or None.
"""
# Try getting default project id from gcloud. If it fails try config.json.
try:
proc = subprocess.Popen(['gcloud', 'config', 'list', '--format', 'value(core.project)... |
def _construct_context_for_args(args):
"""Construct a new Context for the parsed arguments.
Args:
args: the dictionary of magic arguments.
Returns:
A new Context based on the current default context, but with any explicitly
specified arguments overriding the default's config.
"""
global_default... |
def python_portable_string(string, encoding='utf-8'):
"""Converts bytes into a string type.
Valid string types are retuned without modification. So in Python 2, type str
and unicode are not converted.
In Python 3, type bytes is converted to type str (unicode)
"""
if isinstance(string, six.string_types):
... |
def _extract_storage_api_response_error(message):
""" A helper function to extract user-friendly error messages from service exceptions.
Args:
message: An error message from an exception. If this is from our HTTP client code, it
will actually be a tuple.
Returns:
A modified version of the messag... |
def storage(line, cell=None):
"""Implements the storage cell magic for ipython notebooks.
Args:
line: the contents of the storage line.
Returns:
The results of executing the cell.
"""
parser = datalab.utils.commands.CommandParser(prog='storage', description="""
Execute various storage-related operati... |
def _expand_list(names):
""" Do a wildchar name expansion of object names in a list and return expanded list.
The items are expected to exist as this is used for copy sources or delete targets.
Currently we support wildchars in the key name only.
"""
if names is None:
names = []
elif isinstance(na... |
def _storage_create(args, _):
""" Create one or more buckets. """
buckets = datalab.storage.Buckets(project_id=args['project'])
errs = []
for name in args['bucket']:
try:
bucket, key = datalab.storage._bucket.parse_name(name)
if bucket and not key:
buckets.create(bucket)
else:
... |
def _storage_delete(args, _):
""" Delete one or more buckets or objects. """
items = _expand_list(args['bucket'])
items.extend(_expand_list(args['object']))
errs = []
for item in items:
try:
bucket, key = datalab.storage._bucket.parse_name(item)
if bucket and key:
gcs_item = datalab.st... |
def _storage_list_buckets(project, pattern):
""" List all storage buckets that match a pattern. """
data = [{'Bucket': 'gs://' + bucket.name, 'Created': bucket.metadata.created_on}
for bucket in datalab.storage.Buckets(project_id=project)
if fnmatch.fnmatch(bucket.name, pattern)]
return datala... |
def _storage_get_keys(bucket, pattern):
""" Get names of all storage keys in a specified bucket that match a pattern. """
return [item for item in list(bucket.items()) if fnmatch.fnmatch(item.metadata.name, pattern)] |
def _storage_get_key_names(bucket, pattern):
""" Get names of all storage keys in a specified bucket that match a pattern. """
return [item.metadata.name for item in _storage_get_keys(bucket, pattern)] |
def _storage_list_keys(bucket, pattern):
""" List all storage keys in a specified bucket that match a pattern. """
data = [{'Name': item.metadata.name,
'Type': item.metadata.content_type,
'Size': item.metadata.size,
'Updated': item.metadata.updated_on}
for item in _storage... |
def _storage_list(args, _):
""" List the buckets or the contents of a bucket.
This command is a bit different in that we allow wildchars in the bucket name and will list
the buckets that match.
"""
target = args['object'] if args['object'] else args['bucket']
project = args['project']
if target is None:
... |
def jobs_insert_query(self, sql, table_name=None, append=False,
overwrite=False, dry_run=False, use_cache=True, batch=True,
allow_large_results=False, table_definitions=None, query_params=None):
"""Issues a request to insert a query job.
Args:
sql: the SQL ... |
def jobs_query_results(self, job_id, project_id, page_size, timeout, start_index=0):
"""Issues a request to the jobs/getQueryResults method.
Args:
job_id: the id of job from a previously executed query.
project_id: the project id to use to fetch the results; use None for the default project.
... |
def tables_list(self, dataset_name, max_results=0, page_token=None):
"""Issues a request to retrieve a list of tables.
Args:
dataset_name: the name of the dataset to enumerate.
max_results: an optional maximum number of tables to retrieve.
page_token: an optional token to continue the retriev... |
def _scale(x, min_x_value, max_x_value, output_min, output_max):
"""Scale a column to [output_min, output_max].
Assumes the columns's range is [min_x_value, max_x_value]. If this is not
true at training or prediction time, the output value of this scale could be
outside the range [output_min, output_max].
R... |
def _string_to_int(x, vocab):
"""Given a vocabulary and a string tensor `x`, maps `x` into an int tensor.
Args:
x: A `Column` representing a string value.
vocab: list of strings.
Returns:
A `Column` where each string value is mapped to an integer representing
its index in the vocab. Out of vocab ... |
def _tfidf(x, reduced_term_freq, vocab_size, corpus_size):
"""Maps the terms in x to their (1/doc_length) * inverse document frequency.
Args:
x: A `Column` representing int64 values (most likely that are the result
of calling string_to_int on a tokenized string).
reduced_term_freq: A dense tensor of... |
def _bag_of_words(x):
"""Computes bag of words weights
Note the return type is a float sparse tensor, not a int sparse tensor. This
is so that the output types batch tfidf, and any downstream transformation
in tf layers during training can be applied to both.
"""
def _bow(x):
"""Comptue BOW weights.
... |
def _make_image_to_vec_tito(feature_name, tmp_dir=None, checkpoint=None):
"""Creates a tensor-in-tensor-out function that produces embeddings from image bytes.
Image to embedding is implemented with Tensorflow's inception v3 model and a pretrained
checkpoint. It returns 1x2048 'PreLogits' embeddings for each ima... |
def make_preprocessing_fn(output_dir, features, keep_target):
"""Makes a preprocessing function.
Args:
output_dir: folder path that contains the vocab and stats files.
features: the features dict
Returns:
a function that takes a dict of input tensors
"""
def preprocessing_fn(inputs):
"""Prep... |
def get_transformed_feature_info(features, schema):
"""Returns information about the transformed features.
Returns:
Dict in the from
{transformed_feature_name: {dtype: tf type, size: int or None}}. If the size
is None, then the tensor is a sparse tensor.
"""
info = collections.defaultdict(dict)
... |
def csv_header_and_defaults(features, schema, stats, keep_target):
"""Gets csv header and default lists."""
target_name = get_target_name(features)
if keep_target and not target_name:
raise ValueError('Cannot find target transform')
csv_header = []
record_defaults = []
for col in schema:
if not ke... |
def build_csv_serving_tensors_for_transform_step(analysis_path,
features,
schema,
stats,
keep_target):
"""Builds a serving... |
def build_csv_serving_tensors_for_training_step(analysis_path,
features,
schema,
stats,
keep_target):
"""Builds a serving func... |
def build_csv_transforming_training_input_fn(schema,
features,
stats,
analysis_output_dir,
raw_data_file_pattern,
... |
def build_tfexample_transfored_training_input_fn(schema,
features,
analysis_output_dir,
raw_data_file_pattern,
training_batc... |
def image_feature_engineering(features, feature_tensors_dict):
"""Add a hidden layer on image features.
Args:
features: features dict
feature_tensors_dict: dict of feature-name: tensor
"""
engineered_features = {}
for name, feature_tensor in six.iteritems(feature_tensors_dict):
if name in feature... |
def read_vocab_file(file_path):
"""Reads a vocab file to memeory.
Args:
file_path: Each line of the vocab is in the form "token,example_count"
Returns:
Two lists, one for the vocab, and one for just the example counts.
"""
with file_io.FileIO(file_path, 'r') as f:
vocab_pd = pd.read_csv(
... |
def _to_query_json(self):
""" Return the table as a dictionary to be used as JSON in a query job. """
json = {
'compression': 'GZIP' if self._compressed else 'NONE',
'ignoreUnknownValues': self._ignore_unknown_values,
'maxBadRecords': self._max_bad_records,
'sourceFormat': self._bq_sourc... |
def load_ipython_extension(shell):
"""
Called when the extension is loaded.
Args:
shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.
"""
# Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request.
def _request(self, uri, metho... |
def _get_sql_args(parser, args=None):
""" Parse a set of %%sql arguments or get the default value of the arguments.
Args:
parser: the argument parser to use.
args: the argument flags. May be a string or a list. If omitted the empty string is used so
we can get the default values for the a... |
def get_sql_statement_with_environment(item, args=None):
""" Given a SQLStatement, string or module plus command line args or a dictionary,
return a SqlStatement and final dictionary for variable resolution.
Args:
item: a SqlStatement, %%sql module, or string containing a query.
args: a string... |
def expand(sql, args=None):
""" Expand a SqlStatement, query string or SqlModule with a set of arguments.
Args:
sql: a SqlStatement, %%sql module, or string containing a query.
args: a string of command line arguments or a dictionary of values. If a string, it is
passed to the argument pa... |
def parse_dataset_name(name, project_id=None):
"""Parses a dataset name into its individual parts.
Args:
name: the name to parse, or a tuple, dictionary or array containing the parts.
project_id: the expected project ID. If the name does not contain a project ID,
this will be used; if the name does... |
def parse_table_name(name, project_id=None, dataset_id=None):
"""Parses a table name into its individual parts.
Args:
name: the name to parse, or a tuple, dictionary or array containing the parts.
project_id: the expected project ID. If the name does not contain a project ID,
this will be used; if ... |
def chart(line, cell=None):
""" Generate charts with Google Charts. Use %chart --help for more details. """
parser = _commands.CommandParser(prog='%chart', description="""
Generate an inline chart using Google Charts using the data in a Table, Query, dataframe, or list.
Numerous types of charts are supported. Optio... |
def _make_text_predict_fn(self, labels, instance, column_to_explain):
"""Create a predict_fn that can be used by LIME text explainer. """
def _predict_fn(perturbed_text):
predict_input = []
for x in perturbed_text:
instance_copy = dict(instance)
i... |
def _make_image_predict_fn(self, labels, instance, column_to_explain):
"""Create a predict_fn that can be used by LIME image explainer. """
def _predict_fn(perturbed_image):
predict_input = []
for x in perturbed_image:
instance_copy = dict(instance)
... |
def _get_unique_categories(self, df):
"""Get all categories for each categorical columns from training data."""
categories = []
for col in self._categorical_columns:
categocial = pd.Categorical(df[col])
col_categories = list(map(str, categocial.categories))
c... |
def _preprocess_data_for_tabular_explain(self, df, categories):
"""Get preprocessed training set in numpy array, and categorical names from raw training data.
LIME tabular explainer requires a training set to know the distribution of numeric and
categorical values. The training set has to be nu... |
def _make_tabular_predict_fn(self, labels, instance, categories):
"""Create a predict_fn that can be used by LIME tabular explainer. """
def _predict_fn(np_instance):
df = pd.DataFrame(
np_instance,
columns=(self._categorical_columns + self._numeric_columns)... |
def explain_tabular(self, trainset, labels, instance, num_features=5, kernel_width=3):
"""Explain categorical and numeric features for a prediction.
It analyze the prediction by LIME, and returns a report of the most impactful tabular
features contributing to certain labels.
Args:
... |
def explain_text(self, labels, instance, column_name=None, num_features=10, num_samples=5000):
"""Explain a text field of a prediction.
It analyze the prediction by LIME, and returns a report of which words are most impactful
in contributing to certain labels.
Args:
labels: a... |
def explain_image(self, labels, instance, column_name=None, num_features=100000,
num_samples=300, batch_size=200, hide_color=0):
"""Explain an image of a prediction.
It analyze the prediction by LIME, and returns a report of which words are most impactful
in contributing t... |
def _image_gradients(self, input_csvlines, label, image_column_name):
"""Compute gradients from prob of label to image. Used by integrated gradients (probe)."""
with tf.Graph().as_default() as g, tf.Session() as sess:
logging_level = tf.logging.get_verbosity()
try:
... |
def probe_image(self, labels, instance, column_name=None, num_scaled_images=50,
top_percent=10):
""" Get pixel importance of the image.
It performs pixel sensitivity analysis by showing only the most important pixels to a
certain label in the image. It uses integrated gradie... |
def get_model_details(self, model_name):
"""Get details of the specified model from CloudML Service.
Args:
model_name: the name of the model. It can be a model full name
("projects/[project_id]/models/[model_name]") or just [model_name].
Returns: a dictionary of the model details.
"""... |
def create(self, model_name):
"""Create a model.
Args:
model_name: the short name of the model, such as "iris".
Returns:
If successful, returns informaiton of the model, such as
{u'regions': [u'us-central1'], u'name': u'projects/myproject/models/mymodel'}
Raises:
If the model cr... |
def delete(self, model_name):
"""Delete a model.
Args:
model_name: the name of the model. It can be a model full name
("projects/[project_id]/models/[model_name]") or just [model_name].
"""
full_name = model_name
if not model_name.startswith('projects/'):
full_name = ('project... |
def list(self, count=10):
"""List models under the current project in a table view.
Args:
count: upper limit of the number of models to list.
Raises:
Exception if it is called in a non-IPython environment.
"""
import IPython
data = []
# Add range(count) to loop so it will stop e... |
def describe(self, model_name):
"""Print information of a specified model.
Args:
model_name: the name of the model to print details on.
"""
model_yaml = yaml.safe_dump(self.get_model_details(model_name), default_flow_style=False)
print(model_yaml) |
def get_version_details(self, version_name):
"""Get details of a version.
Args:
version: the name of the version in short form, such as "v1".
Returns: a dictionary containing the version details.
"""
name = ('%s/versions/%s' % (self._full_model_name, version_name))
return self._api.projec... |
def deploy(self, version_name, path, runtime_version=None):
"""Deploy a model version to the cloud.
Args:
version_name: the name of the version in short form, such as "v1".
path: the Google Cloud Storage path (gs://...) which contains the model files.
runtime_version: the ML Engine runtime ve... |
def delete(self, version_name):
"""Delete a version of model.
Args:
version_name: the name of the version in short form, such as "v1".
"""
name = ('%s/versions/%s' % (self._full_model_name, version_name))
response = self._api.projects().models().versions().delete(name=name).execute()
if '... |
def predict(self, version_name, data):
"""Get prediction results from features instances.
Args:
version_name: the name of the version used for prediction.
data: typically a list of instance to be submitted for prediction. The format of the
instance depends on the model. For example, struc... |
def describe(self, version_name):
"""Print information of a specified model.
Args:
version: the name of the version in short form, such as "v1".
"""
version_yaml = yaml.safe_dump(self.get_version_details(version_name),
default_flow_style=False)
print(version_... |
def list(self):
"""List versions under the current model in a table view.
Raises:
Exception if it is called in a non-IPython environment.
"""
import IPython
# "self" is iterable (see __iter__() method).
data = [{'name': version['name'].split()[-1],
'deploymentUri': version['... |
def result(self):
""" Get the table used for the results of the query. If the query is incomplete, this blocks.
Raises:
Exception if we timed out waiting for results or the query failed.
"""
self.wait()
if self.failed:
raise Exception('Query failed: %s' % str(self.errors))
return se... |
def make_preprocessing_fn(output_dir, features, keep_target):
"""Makes a preprocessing function.
Args:
output_dir: folder path that contains the vocab and stats files.
features: the features dict
Returns:
a function that takes a dict of input tensors
"""
def preprocessing_fn(inputs):
"""Prep... |
def get_transformed_feature_indices(features, stats):
"""Returns information about the transformed features.
Returns:
List in the from
[(transformed_feature_name, {size: int, index_start: int})]
"""
feature_indices = []
index_start = 1
for name, transform in sorted(six.iteritems(features)):
tr... |
def create_feature_map(features, feature_indices, output_dir):
"""Returns feature_map about the transformed features.
feature_map includes information such as:
1, cat1=0
2, cat1=1
3, numeric1
...
Returns:
List in the from
[(index, feature_description)]
"""
feature_map = []
for name,... |
def create(self, query):
""" Creates the view with the specified query.
Args:
query: the query to use to for the View; either a string containing a SQL query or
a Query object.
Returns:
The View instance.
Raises:
Exception if the view couldn't be created or already exists an... |
def sample(self, fields=None, count=5, sampling=None, use_cache=True, dialect=None,
billing_tier=None):
"""Retrieves a sampling of data from the view.
Args:
fields: an optional list of field names to retrieve.
count: an optional count of rows to retrieve which is used if a specific
... |
def update(self, friendly_name=None, description=None, query=None):
""" Selectively updates View information.
Any parameters that are None (the default) are not applied in the update.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
... |
def results(self, use_cache=True, dialect=None, billing_tier=None):
"""Materialize the view synchronously.
If you require more control over the execution, use execute() or execute_async().
Args:
use_cache: whether to use cached results or not.
dialect : {'legacy', 'standard'}, default 'legacy'... |
def execute_async(self, table_name=None, table_mode='create', use_cache=True, priority='high',
allow_large_results=False, dialect=None, billing_tier=None):
"""Materialize the View asynchronously.
Args:
table_name: the result table name; if None, then a temporary table will be used.
... |
def get_notebook_item(name):
""" Get an item from the IPython environment. """
env = notebook_environment()
return google.datalab.utils.get_item(env, name) |
def get_field_list(fields, schema):
""" Convert a field list spec into a real list of field names.
For tables, we return only the top-level non-RECORD fields as Google charts
can't handle nested data.
"""
# If the fields weren't supplied get them from the schema.
if schema:
all_fields = [f['nam... |
def _get_data_from_list_of_dicts(source, fields='*', first_row=0, count=-1, schema=None):
""" Helper function for _get_data that handles lists of dicts. """
if schema is None:
schema = google.datalab.bigquery.Schema.from_data(source)
fields = get_field_list(fields, schema)
gen = source[first_row:first_row +... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.