docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Parse command line arguments. Args: argv: includes the script's name. Returns: argparse object
def parse_arguments(argv): parser = argparse.ArgumentParser( description='Runs Prediction inside a beam or Dataflow job.') # cloud options parser.add_argument('--project-id', help='The project to which the job will be submitted.') parser.add_argument('--cloud', ...
436,323
Builds the prediction pipeline. Reads the csv files, prepends a ',' if the target column is missing, run prediction, and then prints the formated results to a file. Args: pipeline: the pipeline args: command line args
def make_prediction_pipeline(pipeline, args): # DF bug: DF does not work with unicode strings predicted_values, errors = ( pipeline | 'Read CSV Files' >> beam.io.ReadFromText(str(args.predict_data), strip_trailing_newlines=True) | 'Batch Input' >> beam.Pa...
436,324
Run batch prediciton on a TF graph. Args: element: list of strings, representing one batch input to the TF graph.
def process(self, element): import collections import apache_beam as beam num_in_batch = 0 try: assert self._session is not None feed_dict = collections.defaultdict(list) for line in element: # Remove trailing newline. if line.endswith('\n'): line = li...
436,329
Encodes the graph json prediction into csv. Args: tf_graph_predictions: python dict. Returns: csv string.
def encode(self, tf_graph_predictions): row = [] for col in self._header: row.append(str(tf_graph_predictions[col])) return ','.join(row)
436,330
Initializes the QueryMetadata given the query object. Args: query: A Query object.
def __init__(self, query): self._timeseries_list = list(query.iter(headers_only=True)) # Note: If self._timeseries_list has even one entry, the metric type # can be extracted from there as well. self._metric_type = query.metric_type
436,333
Creates a pandas dataframe from the query metadata. Args: max_rows: The maximum number of timeseries metadata to return. If None, return all. Returns: A pandas dataframe containing the resource type, resource labels and metric labels. Each row in this dataframe correspo...
def as_dataframe(self, max_rows=None): max_rows = len(self._timeseries_list) if max_rows is None else max_rows headers = [{ 'resource': ts.resource._asdict(), 'metric': ts.metric._asdict()} for ts in self._timeseries_list[:max_rows]] if not headers: return pandas.Da...
436,334
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.
def sample(self, n): row_total_count = 0 row_counts = [] for file in self.files: with _util.open_local_or_gcs(file, 'r') as f: num_lines = sum(1 for line in f) row_total_count += num_lines row_counts.append(num_lines) names = None dtype = None if self._schema...
436,364
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 larger than number of rows.
def sample(self, n): total = bq.Query('select count(*) from %s' % self._get_source()).execute().result()[0].values()[0] if n > total: raise ValueError('sample larger than population') sampling = bq.Sampling.random(percent=n * 100.0 / float(total)) if self._query is not No...
436,368
Initializes the Groups for a Stackdriver project. Args: context: An optional Context object to use instead of the global default.
def __init__(self, context=None): self._context = context or google.datalab.Context.default() self._client = _utils.make_client(self._context) self._group_dict = None
436,371
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 match the filters.
def list(self, pattern='*'): if self._group_dict is None: self._group_dict = collections.OrderedDict( (group.id, group) for group in self._client.list_groups()) return [group for group in self._group_dict.values() if fnmatch.fnmatch(group.display_name, pattern)]
436,372
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_rows: The maximum number of groups to return. If None, retur...
def as_dataframe(self, pattern='*', max_rows=None): data = [] for i, group in enumerate(self.list(pattern)): if max_rows is not None and i >= max_rows: break parent = self._group_dict.get(group.parent_id) parent_display_name = '' if parent is None else parent.display_name da...
436,373
Initializes the SqlStatement. Args: sql: a string containing a SQL query with optional variable references. module: if defined in a %%sql cell, the parent SqlModule object for the SqlStatement.
def __init__(self, sql, module=None): self._sql = sql self._module = module
436,374
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 dictionary of values to use in variable ex...
def format(sql, args=None): resolved_vars = {} code = [] SqlStatement._find_recursive_dependencies(sql, args, code=code, resolved_vars=resolved_vars) # Rebuild the SQL string, substituting just '$' for escaped $ occurrences, # variable references s...
436,376
Initializes an instance of a Context object. Args: project_id: the current cloud project. credentials: the credentials to use to authorize requests.
def __init__(self, project_id, credentials): self._project_id = project_id self._credentials = credentials
436,381
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 is d1 > d2.
def compare_datetimes(d1, d2): if d1.tzinfo is None or d1.tzinfo.utcoffset(d1) is None: d1 = d1.replace(tzinfo=pytz.UTC) if d2.tzinfo is None or d2.tzinfo.utcoffset(d2) is None: d2 = d2.replace(tzinfo=pytz.UTC) if d1 < d2: return -1 elif d1 > d2: return 1 return 0
436,384
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.
def is_http_running_on(port): try: conn = httplib.HTTPConnection('127.0.0.1:' + str(port)) conn.connect() conn.close() return True except Exception: return False
436,386
Save project id to config file. Args: project_id: the project_id to save.
def save_project_id(project_id): # 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]) except: config_file = os.path.join(get_config_dir(), 'config.json') config = {} if...
436,388
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.
def _construct_context_for_args(args): global_default_context = google.datalab.Context.default() config = {} for key in global_default_context.config: config[key] = global_default_context.config[key] billing_tier_arg = args.get('billing', None) if billing_tier_arg: config['bigquery_billing_tier'] ...
436,390
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 message that is less cryptic.
def _extract_storage_api_response_error(message): try: if len(message) == 3: # Try treat the last part as JSON data = json.loads(message[2]) return data['error']['errors'][0]['message'] except Exception: pass return message
436,392
Implements the storage cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
def storage(line, cell=None): parser = datalab.utils.commands.CommandParser(prog='storage', description=) # TODO(gram): consider adding a move command too. I did try this already using the # objects.patch API to change the object name but that fails with an error: # # Value 'newname' in content does not a...
436,393
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 retrieval. Returns: A parsed result object. Raises: Exception i...
def tables_list(self, dataset_name, max_results=0, page_token=None): url = Api._ENDPOINT +\ (Api._TABLES_PATH % (dataset_name.project_id, dataset_name.dataset_id, '', '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: args['pageToken...
436,409
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 values are mapped to len(vocab).
def _string_to_int(x, vocab): def _map_to_int(x): table = lookup.index_table_from_tensor( vocab, default_value=len(vocab)) return table.lookup(x) return _map_to_int(x)
436,411
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 make_preprocessing_fn(output_dir, features, keep_target): def preprocessing_fn(inputs): stats = json.loads( file_io.read_file_to_string( os.path.join(output_dir, STATS_FILE)).decode()) result = {} for name, transform in six.iteritems(features): transform_name = transform...
436,415
Add a hidden layer on image features. Args: features: features dict feature_tensors_dict: dict of feature-name: tensor
def image_feature_engineering(features, feature_tensors_dict): engineered_features = {} for name, feature_tensor in six.iteritems(feature_tensors_dict): if name in features and features[name]['transform'] == IMAGE_TRANSFORM: with tf.name_scope(name, 'Wx_plus_b'): hidden = tf.contrib.layers.full...
436,422
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.
def read_vocab_file(file_path): with file_io.FileIO(file_path, 'r') as f: vocab_pd = pd.read_csv( f, header=None, names=['vocab', 'count'], dtype=str, # Prevent pd from converting numerical categories. na_filter=False) # Prevent pd from converting 'NA' to a NaN. voc...
436,424
Get an item from the cache. Args: key: a string used as the lookup key. Returns: The cached item, if any. Raises: Exception if the key is not a string. KeyError if the key is not found.
def __getitem__(self, key): if not isinstance(key, basestring): raise Exception("LRU cache can only be indexed by strings (%s has type %s)" % (str(key), str(type(key)))) if key in self._cache: entry = self._cache[key] entry['last_used'] = datetime.datetime.now() ...
436,425
Remove an item from the cache. Args: key: a string key for retrieving the item.
def __delitem__(self, key): if not isinstance(key, basestring): raise Exception("LRU cache can only be indexed by strings") del self._cache[key]
436,426
Put an item in the cache. Args: key: a string key for retrieving the item. value: the item to cache. Raises: Exception if the key is not a string.
def __setitem__(self, key, value): if not isinstance(key, basestring): raise Exception("LRU cache can only be indexed by strings") if key in self._cache: entry = self._cache[key] elif len(self._cache) < self._cache_size: # Cache is not full; append an new entry self._cache[key]...
436,427
Called when the extension is loaded. Args: shell - (NotebookWebApplication): handle to the Notebook interactive shell instance.
def load_ipython_extension(shell): # Inject our user agent on all requests by monkey-patching a wrapper around httplib2.Http.request. def _request(self, uri, method="GET", body=None, headers=None, redirections=_httplib2.DEFAULT_MAX_REDIRECTS, connection_type=None): if headers is None: ...
436,431
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 of command line arguments or a dictionary of values. Return...
def get_sql_statement_with_environment(item, args=None): if isinstance(item, basestring): item = _sql_statement.SqlStatement(item) elif not isinstance(item, _sql_statement.SqlStatement): item = SqlModule.get_default_query_from_module(item) if not item: raise Exception('Expected a ...
436,436
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 get_model_details(self, model_name): full_name = model_name if not model_name.startswith('projects/'): full_name = ('projects/%s/models/%s' % (self._project_id, model_name)) return self._api.projects().models().get(name=full_name).execute()
436,458
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 creation failed.
def create(self, model_name): body = {'name': model_name} parent = 'projects/' + self._project_id # Model creation is instant. If anything goes wrong, Exception will be thrown. return self._api.projects().models().create(body=body, parent=parent).execute()
436,459
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].
def delete(self, model_name): full_name = model_name if not model_name.startswith('projects/'): full_name = ('projects/%s/models/%s' % (self._project_id, model_name)) response = self._api.projects().models().delete(name=full_name).execute() if 'name' not in response: raise Exception('In...
436,460
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.
def list(self, count=10): import IPython data = [] # Add range(count) to loop so it will stop either it reaches count, or iteration # on self is exhausted. "self" is iterable (see __iter__() method). for _, model in zip(range(count), self.get_iterator()): element = {'name': model['name']}...
436,461
Print information of a specified model. Args: model_name: the name of the model to print details on.
def describe(self, model_name): model_yaml = yaml.safe_dump(self.get_model_details(model_name), default_flow_style=False) print(model_yaml)
436,462
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.
def get_version_details(self, version_name): name = ('%s/versions/%s' % (self._full_model_name, version_name)) return self._api.projects().models().versions().get(name=name).execute()
436,465
Delete a version of model. Args: version_name: the name of the version in short form, such as "v1".
def delete(self, version_name): name = ('%s/versions/%s' % (self._full_model_name, version_name)) response = self._api.projects().models().versions().delete(name=name).execute() if 'name' not in response: raise Exception('Invalid response from service. "name" is not found.') _util.wait_for_lo...
436,467
Print information of a specified model. Args: version: the name of the version in short form, such as "v1".
def describe(self, version_name): version_yaml = yaml.safe_dump(self.get_version_details(version_name), default_flow_style=False) print(version_yaml)
436,469
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 make_preprocessing_fn(output_dir, features, keep_target): def preprocessing_fn(inputs): stats = json.loads( file_io.read_file_to_string( os.path.join(output_dir, STATS_FILE)).decode()) result = {} for name, transform in six.iteritems(features): transform_name = transform...
436,472
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 and overwrite was False.
def create(self, query): if isinstance(query, _query.Query): query = query.sql try: response = self._table._api.tables_insert(self._table.name, query=query) except Exception as e: raise e if 'selfLink' in response: return self raise Exception("View %s could not be create...
436,476
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. query: if not None, a new query string for the View.
def update(self, friendly_name=None, description=None, query=None): self._table._load_info() if query is not None: if isinstance(query, _query.Query): query = query.sql self._table._info['view'] = {'query': query} self._table.update(friendly_name=friendly_name, description=descripti...
436,478
Provides a simple default sampling strategy which limits the result set by a count. Args: fields: an optional list of field names to retrieve. count: optional number of rows to limit the sampled results to. Returns: A sampling function that can be applied to get a random sampling.
def default(fields=None, count=5): projection = Sampling._create_projection(fields) return lambda sql: 'SELECT %s FROM (%s) LIMIT %d' % (projection, sql, count)
436,492
Provides a sampling strategy that picks from an ordered set of rows. Args: field_name: the name of the field to sort the rows by. ascending: whether to sort in ascending direction or not. fields: an optional list of field names to retrieve. count: optional number of rows to limit the sample...
def sorted(field_name, ascending=True, fields=None, count=5): if field_name is None: raise Exception('Sort field must be specified') direction = '' if ascending else ' DESC' projection = Sampling._create_projection(fields) return lambda sql: 'SELECT %s FROM (%s) ORDER BY %s%s LIMIT %d' % (pro...
436,493
Provides a sampling strategy based on hashing and selecting a percentage of data. Args: field_name: the name of the field to hash. percent: the percentage of the resulting hashes to select. fields: an optional list of field names to retrieve. count: optional maximum count of rows to pick. ...
def hashed(field_name, percent, fields=None, count=0): if field_name is None: raise Exception('Hash field must be specified') def _hashed_sampling(sql): projection = Sampling._create_projection(fields) sql = 'SELECT %s FROM (%s) WHERE MOD(ABS(FARM_FINGERPRINT(CAST(%s AS STRING))), 100) <...
436,494
Initializes the Groups for a Stackdriver project. Args: project_id: An optional project ID or number to override the one provided by the context. context: An optional Context object to use instead of the global default.
def __init__(self, project_id=None, context=None): self._context = context or datalab.context.Context.default() self._project_id = project_id or self._context.project_id self._client = _utils.make_client(project_id, context) self._group_dict = None
436,497
Issues a request to retrieve information about a job. Args: job_id: the id of the job project_id: the project id to use to fetch the results; use None for the default project. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def jobs_get(self, job_id, project_id=None): if project_id is None: project_id = self._project_id url = Api._ENDPOINT + (Api._JOBS_PATH % (project_id, job_id)) return datalab.utils.Http.request(url, credentials=self._credentials)
436,502
Issues a request to create a dataset. Args: dataset_name: the name of the dataset to create. friendly_name: (optional) the friendly name for the dataset description: (optional) a description for the dataset Returns: A parsed result object. Raises: Exception if there is an erro...
def datasets_insert(self, dataset_name, friendly_name=None, description=None): url = Api._ENDPOINT + (Api._DATASETS_PATH % (dataset_name.project_id, '')) data = { 'kind': 'bigquery#dataset', 'datasetReference': { 'projectId': dataset_name.project_id, 'datasetId': dat...
436,503
Issues a request to delete a dataset. Args: dataset_name: the name of the dataset to delete. delete_contents: if True, any tables in the dataset will be deleted. If False and the dataset is non-empty an exception will be raised. Returns: A parsed result object. Raises: Exc...
def datasets_delete(self, dataset_name, delete_contents): url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name) args = {} if delete_contents: args['deleteContents'] = True return datalab.utils.Http.request(url, method='DELETE', args=args, credentials=...
436,504
Updates the Dataset info. Args: dataset_name: the name of the dataset to update as a tuple of components. dataset_info: the Dataset resource with updated fields.
def datasets_update(self, dataset_name, dataset_info): url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name) return datalab.utils.Http.request(url, method='PUT', data=dataset_info, credentials=self._credentials)
436,505
Issues a request to retrieve information about a dataset. Args: dataset_name: the name of the dataset Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def datasets_get(self, dataset_name): url = Api._ENDPOINT + (Api._DATASETS_PATH % dataset_name) return datalab.utils.Http.request(url, credentials=self._credentials)
436,506
Issues a request to list the datasets in the project. Args: project_id: the project id to use to fetch the results; use None for the default project. max_results: an optional maximum number of tables to retrieve. page_token: an optional token to continue the retrieval. Returns: A parsed...
def datasets_list(self, project_id=None, max_results=0, page_token=None): if project_id is None: project_id = self._project_id url = Api._ENDPOINT + (Api._DATASETS_PATH % (project_id, '')) args = {} if max_results != 0: args['maxResults'] = max_results if page_token is not None: ...
436,507
Issues a request to retrieve information about a table. Args: table_name: a tuple representing the full name of the table. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def tables_get(self, table_name): url = Api._ENDPOINT + (Api._TABLES_PATH % table_name) return datalab.utils.Http.request(url, credentials=self._credentials)
436,508
Issues a request to insert data into a table. Args: table_name: the name of the table as a tuple of components. rows: the data to populate the table, as a list of dictionaries. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def tabledata_insert_all(self, table_name, rows): url = Api._ENDPOINT + (Api._TABLES_PATH % table_name) + "/insertAll" data = { 'kind': 'bigquery#tableDataInsertAllRequest', 'rows': rows } return datalab.utils.Http.request(url, data=data, credentials=self._credentials)
436,510
Retrieves the contents of a table. Args: table_name: the name of the table as a tuple of components. start_index: the index of the row at which to start retrieval. max_results: an optional maximum number of rows to retrieve. page_token: an optional token to continue the retrieval. Retur...
def tabledata_list(self, table_name, start_index=None, max_results=None, page_token=None): url = Api._ENDPOINT + (Api._TABLEDATA_PATH % table_name) args = {} if start_index: args['startIndex'] = start_index if max_results: args['maxResults'] = max_results if page_token is not None: ...
436,511
Issues a request to delete a table. Args: table_name: the name of the table as a tuple of components. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
def table_delete(self, table_name): url = Api._ENDPOINT + (Api._TABLES_PATH % table_name) return datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
436,512
Updates the Table info. Args: table_name: the name of the table to update as a tuple of components. table_info: the Table resource with updated fields.
def table_update(self, table_name, table_info): url = Api._ENDPOINT + (Api._TABLES_PATH % table_name) return datalab.utils.Http.request(url, method='PUT', data=table_info, credentials=self._credentials)
436,514
Initializes an instance of a DataFlow Job. Args: runner_results: a DataflowPipelineResult returned from Pipeline.run().
def __init__(self, runner_results): super(DataflowJob, self).__init__(runner_results._job.name) self._runner_results = runner_results
436,515
Extract a local or GCS archive file to a folder. Args: archive_path: local or gcs path to a *.tar.gz or *.tar file dest: local folder the archive will be extracted to
def extract_archive(archive_path, dest): # Make the dest folder if it does not exist if not os.path.isdir(dest): os.makedirs(dest) try: tmpfolder = None if (not tf.gfile.Exists(archive_path)) or tf.gfile.IsDirectory(archive_path): raise ValueError('archive path %s is not a file' % archive_p...
436,517
Return a Query for the given Table object Args: table: the Table object to construct a Query out of fields: the fields to return. If None, all fields will be returned. This can be a string which will be injected into the Query after SELECT, or a list of field names. Returns: A Quer...
def from_table(table, fields=None): if fields is None: fields = '*' elif isinstance(fields, list): fields = ','.join(fields) return Query('SELECT %s FROM %s' % (fields, table._repr_sql_()))
436,525
Merge the given parameters with the airflow macros. Enables macros (like '@_ds') in sql. Args: config_parameters: The user-specified list of parameters in the cell-body. date_time: The timestamp at which the parameters need to be evaluated. E.g. when the table is <project-id>.<dataset-id>.log...
def get_query_parameters(config_parameters, date_time=datetime.datetime.now()): merged_parameters = Query.merge_parameters(config_parameters, date_time=date_time, macros=False, types_and_values=True) # We're exposing a simpler schema format than the one actual...
436,530
Start a process, and have it depend on another specified process. Args: args: the args of the process to start and monitor. pid_to_wait: the process to wait on. If the process ends, also kill the started process. std_out_filter_fn: a filter function which takes a string content from the stdout of the ...
def run_and_monitor(args, pid_to_wait, std_out_filter_fn=None, cwd=None): monitor_process = None try: p = subprocess.Popen(args, cwd=cwd, env=os.environ, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) ...
436,535
Initializes an instance of a Composer object. Args: zone: Zone in which Composer environment has been created. environment: Name of the Composer environment.
def __init__(self, zone, environment): self._zone = zone self._environment = environment self._gcs_dag_location = None
436,539
Initializes a TableMetadata instance. Args: table: the Table object this belongs to. info: The BigQuery information about this table as a Python dictionary.
def __init__(self, table, info): self._table = table self._info = info
436,542
Exports the table to a Pandas dataframe. Args: start_row: the row of the table at which to start the export (default 0) max_rows: an upper limit on the number of rows to export (default None) Returns: A Pandas dataframe containing the table data.
def to_dataframe(self, start_row=0, max_rows=None): fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows, page_size=self._MAX_PAGE_SIZE) count = 0 page_token = None # Collect results of page fetcher in separa...
436,557
Save the results to a local file in CSV format. Args: destination: path on the local filesystem for the saved results. format: the format to use for the exported data; currently only 'csv' is supported. csv_delimiter: for CSV exports, the field delimiter to use. Defaults to ',' csv_header: ...
def to_file(self, destination, format='csv', csv_delimiter=',', csv_header=True): f = codecs.open(destination, 'w', 'utf-8') fieldnames = [] for column in self.schema: fieldnames.append(column.name) if sys.version_info[0] == 2: csv_delimiter = csv_delimiter.encode('unicode_escape') ...
436,558
Makes an instance of data in libsvm format. Args: transformed_json_data: dict of transformed data. features: features config. feature_indices: output of feature_transforms.get_transformed_feature_indices() Returns: The text line representation of an instance in libsvm format.
def serialize_example(transformed_json_data, features, feature_indices, target_name): import six import tensorflow as tf from trainer import feature_transforms line = str(transformed_json_data[target_name][0]) for name, info in feature_indices: if features[name]['transform'] in [feature_transforms.IDE...
436,565
Issues a request to delete the dataset. Args: delete_contents: if True, any tables and views in the dataset will be deleted. If False and the dataset is non-empty an exception will be raised. Returns: None on success. Raises: Exception if the delete fails (including if table was...
def delete(self, delete_contents=False): if not self.exists(): raise Exception('Cannot delete non-existent dataset %s' % self._full_name) try: self._api.datasets_delete(self._name_parts, delete_contents=delete_contents) except Exception as e: raise e self._info = None return N...
436,567
Creates the Dataset with the specified friendly name and description. Args: friendly_name: (optional) the friendly name for the dataset if it is being created. description: (optional) a description for the dataset if it is being created. Returns: The Dataset. Raises: Exception if th...
def create(self, friendly_name=None, description=None): if not self.exists(): try: response = self._api.datasets_insert(self._name_parts, friendly_name=friendly_name, description=description) except Ex...
436,568
Selectively updates Dataset information. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. Returns:
def update(self, friendly_name=None, description=None): self._get_info() if self._info: if friendly_name: self._info['friendlyName'] = friendly_name if description: self._info['description'] = description try: self._api.datasets_update(self._name_parts, self._info...
436,569
Parse command line arguments. Args: argv: list of command line arguments, includeing programe name. Returns: An argparse Namespace object.
def parse_arguments(argv): parser = argparse.ArgumentParser( description='Runs Preprocessing on structured CSV data.') parser.add_argument('--input-file-pattern', type=str, required=True, help='Input CSV file names. May contain a file patter...
436,573
Makes the numerical and categorical analysis files. Args: args: the command line args schema_list: python object of the schema json file. Raises: ValueError: if schema contains unknown column types.
def run_numerical_categorical_analysis(args, schema_list): header = [column['name'] for column in schema_list] input_files = file_io.get_matching_files(args.input_file_pattern) # Check the schema is valid for col_schema in schema_list: col_type = col_schema['type'].lower() if col_type != 'string' an...
436,574
Renders an HTML table with the specified list of objects. Args: items: the iterable collection of objects to render. attributes: the optional list of properties or keys to render. datatype: the type of data; one of 'object' for Python objects, 'dict' for a list of dictionaries, or 'char...
def _render_objects(self, items, attributes=None, datatype='object'): if not items: return if datatype == 'chartdata': if not attributes: attributes = [items['cols'][i]['label'] for i in range(0, len(items['cols']))] items = items['rows'] indices = {attributes[i]: i for i i...
436,578
Renders an HTML formatted text block with the specified text. Args: text: the text to render preformatted: whether the text should be rendered as preformatted
def _render_text(self, text, preformatted=False): tag = 'pre' if preformatted else 'div' self._segments.append('<%s>%s</%s>' % (tag, HtmlBuilder._format(text), tag))
436,579
Renders an HTML list with the specified list of strings. Args: items: the iterable collection of objects to render. empty: what to render if the list is None or empty.
def _render_list(self, items, empty='<pre>&lt;empty&gt;</pre>'): if not items or len(items) == 0: self._segments.append(empty) return self._segments.append('<ul>') for o in items: self._segments.append('<li>') self._segments.append(str(o)) self._segments.append('</li>') ...
436,580
Renders an HTML formatted text block with the specified text. Args: text: the text to render preformatted: whether the text should be rendered as preformatted Returns: The formatted HTML.
def render_text(text, preformatted=False): builder = HtmlBuilder() builder._render_text(text, preformatted=preformatted) return builder._to_html()
436,582
Return a dictionary list formatted as a HTML table. Args: data: a list of dictionaries, one per row. headers: the keys in the dictionary to use as table columns, in order.
def render_table(data, headers=None): builder = HtmlBuilder() builder._render_objects(data, headers, datatype='dict') return builder._to_html()
436,583
Return a dictionary list formatted as a HTML table. Args: data: data in the form consumed by Google Charts.
def render_chart_data(data): builder = HtmlBuilder() builder._render_objects(data, datatype='chartdata') return builder._to_html()
436,584
Get an iterator to iterate through a set of table rows. Args: start_row: the row of the table at which to start the iteration (default 0) max_rows: an upper limit on the number of rows to iterate through (default None) Returns: A row iterator.
def range(self, start_row=0, max_rows=None): fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows) return iter(datalab.utils.Iterator(fetcher))
436,588
Exports the table to a Pandas dataframe. Args: start_row: the row of the table at which to start the export (default 0) max_rows: an upper limit on the number of rows to export (default None) Returns: A Pandas dataframe containing the table data.
def to_dataframe(self, start_row=0, max_rows=None): fetcher = self._get_row_fetcher(start_row=start_row, max_rows=max_rows) count = 0 page_token = None df = None while True: page_rows, page_token = fetcher(page_token, count) if len(page_rows): count += len(page_rows) ...
436,589
Selectively updates Table information. Any parameters that are omitted or None are not updated. Args: friendly_name: if not None, the new friendly name. description: if not None, the new description. expiry: if not None, the new expiry time, either as a DateTime or milliseconds since epoch. ...
def update(self, friendly_name=None, description=None, expiry=None, schema=None): self._load_info() if friendly_name is not None: self._info['friendlyName'] = friendly_name if description is not None: self._info['description'] = description if expiry is not None: if isinstance(exp...
436,591
Return a Query for this Table. Args: fields: the fields to return. If None, all fields will be returned. This can be a string which will be injected into the Query after SELECT, or a list of field names. Returns: A Query object that will return the specified fields from the records in th...
def to_query(self, fields=None): # Do import here to avoid top-level circular dependencies. from . import _query if fields is None: fields = '*' elif isinstance(fields, list): fields = ','.join(fields) return _query.Query('SELECT %s FROM %s' % (fields, self._repr_sql_()), context=se...
436,592
Copies this item to the specified new key. Args: new_key: the new key to copy this item to. bucket: the bucket of the new item; if None (the default) use the same bucket. Returns: An Item corresponding to new key. Raises: Exception if there was an error copying the item.
def copy_to(self, new_key, bucket=None): if bucket is None: bucket = self._bucket try: new_info = self._api.objects_copy(self._bucket, self._key, bucket, new_key) except Exception as e: raise e return Item(bucket, new_key, new_info, context=self._context)
436,595
Writes text content to this item. Args: content: the text content to be written. content_type: the type of text content. Raises: Exception if there was an error requesting the item's content.
def write_to(self, content, content_type): try: self._api.object_upload(self._bucket, self._key, content, content_type) except Exception as e: raise e
436,598
Checks if the specified item exists. Args: key: the key of the item to lookup. Returns: True if the item exists; False otherwise. Raises: Exception if there was an error requesting information about the item.
def contains(self, key): try: self._api.objects_get(self._bucket, key) except datalab.utils.RequestException as e: if e.status == 404: return False raise e except Exception as e: raise e return True
436,600
Implements the datalab cell magic for ipython notebooks. Args: line: the contents of the datalab line. Returns: The results of executing the cell.
def datalab(line, cell=None): parser = google.datalab.utils.commands.CommandParser( prog='%datalab', description=) config_parser = parser.subcommand( 'config', help='List or set API-specific configurations.') config_sub_commands = config_parser.add_subparsers(dest='command') # %%datalab c...
436,603
Implements the pipeline cell create magic used to create Pipeline objects. The supported syntax is: %%pipeline create <args> [<inline YAML>] Args: args: the arguments following '%%pipeline create'. cell_body: the contents of the cell
def _create_cell(args, cell_body): name = args.get('name') if name is None: raise Exception("Pipeline name was not specified.") pipeline_spec = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils.commands.notebook_environment()) airflow_spec = google.datalab.contrib.pipeline._...
436,610
Checks that the transform and schema do not conflict. Args: schema: schema list inverted_features: inverted_features dict Raises: ValueError if transform cannot be applied given schema type.
def check_schema_transforms_match(schema, inverted_features): num_target_transforms = 0 for col_schema in schema: col_name = col_schema['name'] col_type = col_schema['type'].lower() # Check each transform and schema are compatible if col_name in inverted_features: for transform in inverte...
436,618
Use pandas to analyze csv files. Produces a stats file and vocab files. Args: output_dir: output folder csv_file_pattern: list of csv file paths, may contain wildcards schema: CSV schema list features: features config Raises: ValueError: on unknown transfrorms/schemas
def run_local_analysis(output_dir, csv_file_pattern, schema, features): sys.stdout.write('Expanding any file patterns...\n') sys.stdout.flush() header = [column['name'] for column in schema] input_files = [] for file_pattern in csv_file_pattern: input_files.extend(file_io.get_matching_files(file_patter...
436,622
Implements the bigquery sample cell magic for ipython notebooks. Args: args: the optional arguments following '%%bigquery sample'. cell_body: optional contents of the cell interpreted as SQL, YAML or JSON. Returns: The results of executing the sampling query, or a profile of the sample data.
def _sample_cell(args, cell_body): env = datalab.utils.commands.notebook_environment() query = None table = None view = None if args['query']: query = _get_query_argument(args, cell_body, env) elif args['table']: table = _get_table(args['table']) elif args['view']: view = datalab.utils.co...
436,634
Implements the BigQuery cell magic used to create datasets and tables. The supported syntax is: %%bigquery create dataset -n|--name <name> [-f|--friendly <friendlyname>] [<description>] or: %%bigquery create table -n|--name <tablename> [--overwrite] [<YAML or JSON cell_body defining schema...
def _create_cell(args, cell_body): if args['command'] == 'dataset': try: datalab.bigquery.Dataset(args['name']).create(friendly_name=args['friendly'], description=cell_body) except Exception as e: print('Failed to create dataset %s: %s' % (arg...
436,635
Implements the BigQuery cell magic used to delete datasets and tables. The supported syntax is: %%bigquery delete dataset -n|--name <name> or: %%bigquery delete table -n|--name <name> Args: args: the argument following '%bigquery delete <command>'.
def _delete_cell(args, _): # TODO(gram): add support for wildchars and multiple arguments at some point. The latter is # easy, the former a bit more tricky if non-default projects are involved. if args['command'] == 'dataset': try: datalab.bigquery.Dataset(args['name']).delete() except Exception ...
436,636
Implements the BigQuery cell magic used to dry run BQ queries. The supported syntax is: %%bigquery dryrun [-q|--sql <query identifier>] [<YAML or JSON cell_body or inline SQL>] Args: args: the argument following '%bigquery dryrun'. cell_body: optional contents of the cell interpreted as YAML or JSO...
def _dryrun_cell(args, cell_body): query = _get_query_argument(args, cell_body, datalab.utils.commands.notebook_environment()) if args['verbose']: print(query.sql) result = query.execute_dry_run(dialect=args['dialect'], billing_tier=args['billing']) return datalab.bigquery._query_stats.QueryStats(total_...
436,637
Implements the bigquery_udf cell magic for ipython notebooks. The supported syntax is: %%bigquery udf --module <var> <js function> Args: args: the optional arguments following '%%bigquery udf'. js: the UDF declaration (inputs and outputs) and implementation in javascript. Returns: The results of...
def _udf_cell(args, js): variable_name = args['module'] if not variable_name: raise Exception('Declaration must be of the form %%bigquery udf --module <variable name>') # Parse out the input and output specification spec_pattern = r'\{\{([^}]+)\}\}' spec_part_pattern = r'[a-z_][a-z0-9_]*' specs = r...
436,638
Implements the BigQuery cell magic used to execute BQ queries. The supported syntax is: %%bigquery execute [-q|--sql <query identifier>] <other args> [<YAML or JSON cell_body or inline SQL>] Args: args: the arguments following '%bigquery execute'. cell_body: optional contents of the cell interprete...
def _execute_cell(args, cell_body): query = _get_query_argument(args, cell_body, datalab.utils.commands.notebook_environment()) if args['verbose']: print(query.sql) return query.execute(args['target'], table_mode=args['mode'], use_cache=not args['nocache'], allow_large_results=args['...
436,639
Implements the BigQuery cell magic used to validate, execute or deploy BQ pipelines. The supported syntax is: %%bigquery pipeline [-q|--sql <query identifier>] <other args> <action> [<YAML or JSON cell_body or inline SQL>] Args: args: the arguments following '%bigquery pipeline'. cell_body: optiona...
def _pipeline_cell(args, cell_body): if args['action'] == 'deploy': raise Exception('Deploying a pipeline is not yet supported') env = {} for key, value in datalab.utils.commands.notebook_environment().items(): if isinstance(value, datalab.bigquery._udf.UDF): env[key] = value query = _get_que...
436,640
Implements the BigQuery table magic used to display tables. The supported syntax is: %bigquery table -t|--table <name> <other args> Args: args: the arguments following '%bigquery table'. Returns: The HTML rendering for the table.
def _table_line(args): # TODO(gram): It would be good to turn _table_viewer into a class that has a registered # renderer. That would allow this to return a table viewer object which is easier to test. name = args['table'] table = _get_table(name) if table and table.exists(): fields = args['cols'].spli...
436,641
Implements the BigQuery schema magic used to display table/view schemas. Args: args: the arguments following '%bigquery schema'. Returns: The HTML rendering for the schema.
def _schema_line(args): # TODO(gram): surely we could just return the schema itself? name = args['table'] if args['table'] else args['view'] if name is None: raise Exception('No table or view specified; cannot show schema') schema = _get_schema(name) if schema: html = _repr_html_table_schema(schem...
436,643
Implements the BigQuery datasets magic used to display datasets in a project. The supported syntax is: %bigquery datasets [-f <filter>] [-p|--project <project_id>] Args: args: the arguments following '%bigquery datasets'. Returns: The HTML rendering for the table of datasets.
def _datasets_line(args): filter_ = args['filter'] if args['filter'] else '*' return _render_list([str(dataset) for dataset in datalab.bigquery.Datasets(args['project']) if fnmatch.fnmatch(str(dataset), filter_)])
436,645
Implements the BigQuery tables magic used to display tables in a dataset. The supported syntax is: %bigquery tables -p|--project <project_id> -d|--dataset <dataset_id> Args: args: the arguments following '%bigquery tables'. Returns: The HTML rendering for the list of tables.
def _tables_line(args): filter_ = args['filter'] if args['filter'] else '*' if args['dataset']: if args['project'] is None: datasets = [datalab.bigquery.Dataset(args['dataset'])] else: datasets = [datalab.bigquery.Dataset((args['project'], args['dataset']))] else: datasets = datalab.big...
436,646
Implements the BigQuery extract magic used to extract table data to GCS. The supported syntax is: %bigquery extract -S|--source <table> -D|--destination <url> <other_args> Args: args: the arguments following '%bigquery extract'. Returns: A message about whether the extract succeeded or failed.
def _extract_line(args): name = args['source'] source = datalab.utils.commands.get_notebook_item(name) if not source: source = _get_table(name) if not source: raise Exception('No source named %s found' % name) elif isinstance(source, datalab.bigquery.Table) and not source.exists(): raise Excep...
436,647